<?PHP
/**
* General functions
*
* Contains global available tool functions. It is included in every
* page and sets up some defaults like error reporting, environment
* setups, session initialisation and config loading
*
* @package functions
* @version $Id: functions.php,v 1.1.1.1 2004/07/28 12:09:05 pbworks Exp $
*/
/* This is needed to make sure we have our very own namespace without
interfering Environment variables */
foreach (array_keys($_ENV) as $key){
unset($GLOBALS[$key]);
}
require_once ("config.inc.php");
require_once ("template.php");
require_once ("smarty/Smarty.class.php");
/* --------------------------------------------------------------------*/
// Set up some defaults
checkcache_or_die();
if($config['debug']){
error_reporting (E_ALL ^ E_NOTICE);
}else{
error_reporting (E_ERROR + E_PARSE);
}
if (get_magic_quotes_gpc()) {
if (!empty($_GET)) remove_magic_quotes($_GET);
if (!empty($_POST)) remove_magic_quotes($_POST);
if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
// $_SESSION is handled in session.php
ini_set('magic_quotes_gpc', 0);
}
set_magic_quotes_runtime(0);
//register_globals off? Well i like it...
if (!empty($_GET)) {
extract($_GET);
}
elseif (!empty($HTTP_GET_VARS)) {
extract($HTTP_GET_VARS);
}
if (!empty($_POST)) {
extract($_POST);
}
elseif (!empty($HTTP_POST_VARS)) {
extract($HTTP_POST_VARS);
}
//create smarty object
$smarty = new Smarty;
$smarty->compile_dir = './cache/smarty/';
$smarty->use_sub_dirs = 0;
//load config
loadconfig();
//check authentification data for multiuser
if(basename($_SERVER[PHP_SELF]) != 'login.php') authcheck();
/* --------------------------------------------------------------------*/
// functions follow
/**
* Used to remove magic quotes from the $_GET, $_POST, $_COOKIE and
* $_SESSION super global arrays. It's automatically called in
* functions.php
*
* @param array &$array Reference to an array
*/
function remove_magic_quotes(&$array) {
foreach (array_keys($array) as $key) {
if (is_array($array[$key])) {
remove_magic_quotes($array[$key]);
}
else {
$array[$key] = stripslashes($array[$key]);
}
}
}
/**
* magicquote safe formoutputter
*
* Strips slashes when magic_quotes_gpc is set.
*
* @param string $name The input string
* @return string The cleaned string
*/
function formvar ($name) {
if (get_magic_quotes_gpc()) {
$name = stripslashes($name);
}
return htmlspecialchars($name);
}
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
/**
* SQL function
*
* Wrapper for all Database accesses.
*
* @param string $sql_string The SQL-Statement to execute
* @return mixed either the resultset as an array with hashes or the insertid
*/
function runSQL($sql_string) {
global $config;
if($config['debug']){
echo "\n\n<!-- $sql_string -->\n\n";
$timestamp = getmicrotime();
}
$link = mysql_connect ($config['db_server'], $config['db_user'], $config['db_password']) or
errorpage("DB Connection Error","<p>Edit the database settings in <code>config.inc.php</code>.</p>" );
$result = mysql_db_query($config['db_database'],$sql_string,$link) or
errorpage("Database Problem",mysql_error($link)."\n<br />\n".$sql_string);
//mysql_db_query returns 1 on a insert statement -> no need to ask for results
if ($result != 1) {
for($i=0; $i< mysql_num_rows($result); $i++) {
$temparray = mysql_fetch_assoc($result);
$resultarray[]=$temparray;
}
mysql_free_result ($result);
}
if (mysql_insert_id($link)) {
$resultarray = mysql_insert_id($link); #give back ID on insert
}
if($config['debug']){
$timestamp = getmicrotime() - $timestamp;
echo "\n\n<!-- time: $timestamp -->\n\n";
}
mysql_close ($link);
return $resultarray;
}
//dbquery
function dbquery($sql_string) {
global $config;
$link = mysql_connect ($config['db_server'], $config['db_user'], $config['db_password']) or
errorpage("DB Connection Error","<p>Edit the database settings in <code>config.inc.php</code>.</p>" );
$result = mysql_db_query($config['db_database'],$sql_string,$link) or
errorpage("Database Problem",mysql_error($link)."\n<br />\n".$sql_string);
mysql_close ($link);
return $result;
}
/**
* decodes HTML entities
*
* @author <hide@address.com>
* @param string $string HTML encoded string
* @return string HTML decoded string
*/
function decodeHTML($string) {
$string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
$string = preg_replace("/&#([0-9]+);/me", "chr('\\1')", $string);
return $string;
}
/**
* checks if the page is accessed from within the local net. If not displays
* a simple error page and exits
*/
function localnet_or_die(){
global $config;
if (localnet()) {
return;
}
errorpage('Forbidden','You are not allowed to visit this page');
}
/**
* checks if the page is accessed from within the local net.
*
* @return bool true if localnet
*/
function localnet(){
global $config;
return (preg_match('/'.$config['localnet'].'/',$_SERVER['REMOTE_ADDR']));
}
/**
* checks if the cachedirectories exist and are writable by the webserver. If
* they don't exist it tries to create them. If this fails, too a simple
* error page is displayed.
*/
function checkcache_or_die(){
$isok=true;
foreach (array('cache','cache/smarty') as $dir ){
if(!is_dir($dir)){
if(!@mkdir($dir, 0700)){
$isok = false;
$error .= "Directory <code>$dir</code> does not exist.<br />";
}
}else{
if(!is_writable($dir)){
$isok = false;
$error .= "Directory <code>$dir</code> is not writable.<br />";
}
}
}
if($isok) return;
$body = "
<p>The cache directories have to be writable by the webserver!</p>
<p>Please fix the following errors:</p>
<p>$error</p>
</body>
</html>
";
errorpage('Cachedirectories not writable',$body);
}
/**
* load config options from the database and setup sane defaults
*/
function loadconfig(){
global $config;
global $lang;
global $smarty;
//prepare som options for later use
$config[style] = './templates/default.css';
$config[templatedir] = './templates/';
$smarty->template_dir = $config[templatedir];
if($config[recompile]){
$smarty->force_compile=1;
}
}
/**
* Downloads an URL to the given local file
*
* @param string $url URL to download
* @param string $local Full path to save to
* @return bool true on succes else false
*/
function download($url, $local){
$resp = httpClient($url);
if (!$resp[success]) return false;
$writefile = @fopen($local, "wb");
if(!$writefile) return false;
//print "<pre>".htmlspecialchars($data)."</pre>";
if(!fwrite($writefile, $resp[data], strlen($resp[data]))) return false;
fclose($writefile);
return true;
}
/**
* reads filecontents into a string - fixes problems with join('',file()) and
* windows systems (it's binary safe)
*
* @author <hide@address.com>
* @param string $filename file to read
*/
function getfile($filename) {
$fd = fopen("$filename", "rb");
$content = fread($fd, filesize($filename));
fclose($fd);
return $content;
}
/**
* Reads a saved HTTP response from a cachefile.
*
* @param string $url URL of the cached response
* @return mixed HTTP Response, false on errors
*/
function getHTTPcache($url){
global $config;
$cfile='cache/imdb/'.md5($url);
if(file_exists($cfile) && (time()-filemtime($cfile) < $config[IMDBage]) ){
$resp = unserialize(getfile($cfile));
return $resp;
}else{
return false;
}
}
/**
* Saves a HTTP resonse to a cachfile
*
* @param string $url URL of the response
* @param mixed $resp HTTP Response
*/
function saveHTTPcache($url,$resp){
$cfile='cache/imdb/'.md5($url);
$string=serialize($resp);
@fwrite(@fopen("$cfile", "w"),$string,strlen($string));
}
/**
* Displays an errorpage and exits
*
* @param string $title The pages headline
* @param string $body An additional message
*/
function errorpage($title='An error occured',$body=''){
print '<?xml version="1.0" encoding="en"?>'."\n";
print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">'."\n";
print '<head>'."\n";
print ' <title>VideoDB - ERROR</title>'."\n";
print ' <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />'."\n";
print ' <meta name="description" content="VideoDB" />'."\n";
print "</head>\n";
print "<body>\n";
print "<h1>$title</h1>\n";
print $body;
print "</body>\n";
print "</html>\n";
exit;
}
/**
* Used to check permissions on a user for a page
*
* @author Mike Clark <hide@address.com>
* @param integer $permission Permission to check
* @return boolean True if permission exists else false
*/
function check_permission($permission) {
global $config;
if (!$config[multiuser]) {
return true;
}
$user = $_COOKIE['VDBusername'];
$result = runSQL("SELECT permissions FROM users WHERE user='$user'");
//check permissionbits
if($result[0][permissions] & $permission){
return true;
}else{
return false;
}
}
/**
* Check permissions on a user for a page and display error message on failure
*
* @param integer $permission Permission to check (admin,write,writeall)
*/
function permission_or_die($permission) {
if(!check_permission($permission)){
errorpage("Access denied",'You don\'t have enough permissions to access this
page try to <a href="login.php">login</a> first.');
}
}
/**
* This function checks if the user was authenticated and if the received
* auth cookie is valid. This function is called for every page except login.php!
*/
function authcheck(){
global $config;
//auth check only in multiuser mode
if ($config[multiuser]){
//already logged in?
$user = $_COOKIE["VDBusername"];
$pass = $_COOKIE["VDBpassword"];
if(!empty($user) || !empty($passwd)){
//There are some auth cookies - we need to check if they are valid
if (!eregi ("[a-z]", $user)) header("Location: login.php");
if (!eregi ("[0-9]", $pass)) header("Location: login.php");
// This is the crucial bit, lets just test the cookiecode with SQL
// again.
$row = runSQL("SELECT cookiecode FROM users WHERE user='$user'");
if ($row[0][cookiecode] !== $pass) header("location:login.php");
}else{
//No auth yet
if ($config[denyguest]){
//guests are not allowed here!
header("Location: login.php");
}
}
}
}
/**
* Function to get the owner from videodata table
*
* @author Mike Clark <hide@address.com>
* @param integer $id videodata id
* @param boolean $diskid is the given ID a disk ID instead of videoID?
* @return string Returns the owner of the given Video or Disk
*/
function get_owner($id,$diskid=false) {
if($diskid) {
$se = ("SELECT owner FROM videodata WHERE diskid='$id'");
} else {
$se = ("SELECT owner FROM videodata WHERE id='$id'");
}
$result = runSQL($se);
return $result[0][owner];
}
?>