Location: PHPKode > projects > mediaIndex > includes/init.php
<?php
/**
  * $Id: init.php,v 1.4 2004/12/02 04:15:47 openface Exp $      
  *
  *               _ _        _         _                 
  *  _ __  ___ __| (_)__ _  (_)_ _  __| |_____ _____ _ _ 
  * | '  \/ -_) _` | / _` | | | ' \/ _` / -_) \ / -_) '_|
  * |_|_|_\___\__,_|_\__,_| |_|_||_\__,_\___/_\_\___|_|  
  *                                                     
  *     Standalone Indexer Script for Media Files
  *        jason hines, <hide@address.com>
  *
  * This library is free software; you can redistribute it and/or modify
  * it under the terms of the GNU Library General Public License as
  * published by the Free Software Foundation; either version 2 of the
  * License, or (at your option) any later version.
  *
  * This library is distributed in the hope that it will be useful, but
  * WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library
  * General Public License for more details.
  */

/**
 * Internal use only
 */
define("_VERSION",    "0.10");

/**
 * Some initialization
 */
error_reporting(E_ALL);
set_exception_handler('_exception_handler');
$time_start = _getmicrotime();

if (phpversion() < 5) {
  die("This script requires PHP 5 or higher.  You are running version " . phpversion());
}

if (!is_writable(_CACHEPATH)) {
  throw new Exception("Cache directory '"._CACHEPATH."' must be writable by webserver!");
}

/**
 * Main Functions
 */

/**
 * Initializes database, create new tables if they don't exist
 */
function _initDatabase() {
  if (!file_exists(_DATAFILE)) {
      touch(_DATAFILE);
  }
  $gDb = sqlite_open(_DATAFILE);
  if (!sqlite_table_exists($gDb,"files")) {
      _addMessage("Files database not found. Creating...");
      sqlite_query($gDb,"CREATE TABLE files (
          hash VARCHAR(255) PRIMARY KEY,
          title VARCHAR(255) NOT NULL,
          desc TEXT,
          hits INTEGER NOT NULL DEFAULT 0);");
  }
  if (!sqlite_table_exists($gDb,"dirs")) {
      _addMessage("Directory database not found. Creating...");
      sqlite_query($gDb,"CREATE TABLE dirs (
          path VARCHAR(255) PRIMARY KEY,
          title VARCHAR(255) NOT NULL,
          image VARCHAR(255) NOT NULL,
          desc TEXT);");
  }
  if (!sqlite_table_exists($gDb,"mirrors")) {
      _addMessage("Mirrors database not found. Creating...");
      sqlite_query($gDb,"CREATE TABLE mirrors (
          id INTEGER PRIMARY KEY,
          hash VARCHAR(255) NOT NULL,
          url VARCHAR(255) NOT NULL);");
  }
  if (!sqlite_table_exists($gDb,"comments") && _ENABLECOMMENTS == TRUE) {
      _addMessage("Comments database not found. Creating...");
      sqlite_query($gDb,"CREATE TABLE comments (
          id INTEGER PRIMARY KEY,
          hash VARCHAR(255) NOT NULL,
          name VARCHAR(24) NOT NULL,
          body TEXT,
          time TIMESTAMP);");
  }
  if (0) { // use this to reset the files database manually.
    sqlite_query($gDb,"DROP TABLE files;"); // reset
    _addMessage("Files database has been reset. Everything is gone.");
  }
  if (0) { // use this to reset the dirs database manually.
    sqlite_query($gDb,"DROP TABLE dirs;"); // reset
    _addMessage("Directories database has been reset. Everything is gone.");
  }
  if (0) { // use this to reset the mirrors database manually.
    sqlite_query($gDb,"DROP TABLE mirrors;"); // reset
    _addMessage("Mirrors database has been reset.");
  }
  if (0 && _ENABLECOMMENTS == TRUE) { // reset comments database
    sqlite_query($gDb,"DROP TABLE comments;"); // reset
    _addMessage("Comments database has been reset.");
  }
  return $gDb;
}

/**
 * Callback for zipdir(tm) feature
 */
function callback_zipdir() {
  $tempname = md5(stripslashes($_GET['dir'])) . ".zip";
  $filename = basename(str_replace(" ","_",$_GET['dir'])) . ".zip";
  $target = _ZIPDIRPATH . "/" . $tempname;
  $path = dirname(realpath(_MEDIAPATH . stripslashes($_GET['dir'])));
  $base = basename(realpath(_MEDIAPATH . stripslashes($_GET['dir'])));
  $source = escapeshellarg($base) . "/*";
  if (!is_writable(_ZIPDIRPATH)) mkdir(_ZIPDIRPATH);

  $cwd = getcwd();
  chdir($path);

  $cmd = _ZIP . " -1D {$target} {$source}";
  exec($cmd,$out,$ret);

  chdir($cwd);
  if ($ret != 0) die("Error generating zip file.");

  $size = filesize($target);

  header("Content-type: application/octet-stream");
  header("Content-Transfer-Encoding: binary");
  header("Content-length: ".$size);
  header("Content-Disposition: attachment; filename=$filename");

  readfile($target);

  // clean up
  unlink($target);
}

/**
 * Handles an uploaded file gracefully, returns filename or false on error
 */
function _handleFileUpload($path,$A) {
  if (!is_writable($path)) mkdir($path);
  $tofile = $path . "/" . $A['name'];
  if (move_uploaded_file($A['tmp_name'], $tofile)) {
      return $A['name'];
  } else {
      return false;
  }
}

/**
 * Authenticates login attempt, returns false on failure
 */
function _authenticated() {
  if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_USER'])) {
      return false;
  }
  $username = $_SERVER['PHP_AUTH_USER'];
  $password = $_SERVER['PHP_AUTH_PW'];

  foreach ($GLOBALS['_USERS']['admin'] as $A) {
    if ($A[0] = $username && $A[1] == $password) return true;
  }
  
  return false;
}

/**
 * Callback sorting function
 */
function _key_compare($a, $b) {
    switch (_SORTMETHOD) {
      case NAME_ASC: return strcmp($a->title, $b->title); break;
      case NAME_DESC: return strcmp($b->title, $a->title); break;

      case MTIME_ASC: return ($a->_filemtime - $b->_filemtime); break;
      case MTIME_DESC: return ($b->_filemtime - $a->_filemtime); break;

      case CTIME_ASC: return ($a->_filectime - $b->_filectime); break;
      case CTIME_DESC: return ($b->_filectime - $a->_filectime); break;

      default: throw new Exception("Invalid _SORTMETHOD."); break;
    }
}

/**
 * Includes a file (typically an HTML file)
 */
function _includeFile($filepath) {
  if (is_file($filepath)) {
    include($filepath);
  }
}

/**
 * Formats a filesize pretty-like
 */
function _filesize($size, $dec = 1) {
    $sizes = array('B', 'KB', 'MB', 'GB');
    $count = count($sizes);
    $i = 0;
    while ($size >= 1024 && ($i < $count - 1)) {
        $size /= 1024; $i++;
    }
    return round($size, $dec) . $sizes[$i];
}

/**
 * Checks if a SQLite table exists, returns boolean
 */
function sqlite_table_exists($dblink, $table) {
  $sql = "SELECT count(name) FROM sqlite_master WHERE ((type = 'table') and (name = '$table'))";
  if ($res = sqlite_query ($dblink, $sql)) {
    return sqlite_fetch_single($res) > 0;
  } else {
    return false; // or throw exception
  }
}

/**
 * Add a message to message stack
 */
function _addMessage($msg) {
  $GLOBALS['messages'][] = $msg;
}  

/**
 * Truncates a string at a given length
 */
function _truncate($string,$length=255) { 
  if (strlen($string) > $length) {
    $string = substr($string, 0, $length) . "&nbsp;<img src=\""._BASEURL."/img/para.gif\" border=\"0\" alt=\"More...\">";
  }
  return $string;
}

/**
 * Escapes a string for a SQLite SQL query
 */
function _escape($string) {
    return str_replace("'","''",$string);
}

/**
 * Checks if a filename is to be excluded
 */
function _isExcluded($filename) {
    foreach ($GLOBALS['_EXCLUDES'] as $pattern) {
        if (fnmatch($pattern, $filename)) {
            return true;
        }
    }
    return false;
}

/**
 * Print string via parser (markdown library)
 */
function _parseText($string) {
  return markdown(htmlentities(stripslashes($string)));
}

/**
 * Returns the file extension of a given file path
 */
function _getExtension($filepath) { 
  $pathinfo = pathinfo($filepath);
  return isset($pathinfo['extension']) ? $pathinfo['extension'] : "";
}   

/**
 * Returns current time in microseconds
 */
function _getmicrotime() {
    list($msec, $sec) = explode(" ", microtime());
    return ((float)$msec + (float)$sec);
}

/**
 * Prints a subtitle
 */
function _printSubtitle($string) {
    echo "<div class=\"subtitle\">"._truncate(stripslashes($string),70)."</div><br />\n";
}

/**
 * Encodes a URL properly
 */
function _encodeuri($uri) {
   $parts = explode('/', $uri);
   for ($i = 0; $i < count($parts); $i++) {
     $parts[$i] = rawurlencode($parts[$i]);
   }
   return implode('/', $parts);
}

/**
 * Callback function for streaming a playlist (for audio handler)
 */
function callback_playlist() {
  if (empty($_POST['playlist'])) { die("Unexpected Error."); }

  header("Content-type: audio/x-mpegurl");

  foreach ($_POST['playlist'] as $url) {
      echo $url . "\n";
  }
}

/**
 * Simple exception handler
 */
function _exception_handler($e) {
  echo "<h3>Fatal Error!</h3>";
  die("<pre>" . $e->__tostring() . "</pre>");
}

/**
 * Includes
 */

// include required classes
include_once(_BASEPATH . "/classes/class.dir.php");
include_once(_BASEPATH . "/classes/class.file.php");

// include base group / handler classes
include_once(_BASEPATH . "/classes/handler.default.php");
include_once(_BASEPATH . "/classes/group.default.php");

// include libraries
include_once(_BASEPATH . "/lib/php-markdown/markdown.php");

/**
 * Special controller class
 */
class mediaIndexer {

    function execute() {
        // admin mode requested, check for authorization
        if (!empty($_GET['mode']) && $_GET['mode']=='admin') {
            if (!_authenticated()) {
                header('WWW-Authenticate: Basic realm="'._SITENAME.'"');
                header('HTTP/1.0 401 Unauthorized');
                _addMessage("Login failed - You entered incorrect credentials.");
            } else {
                _addMessage("Administration mode enabled.");
            }
        }

        // create a database connection
        $GLOBALS['gDb'] = _initDatabase();

        // setup the controller data based on request, or redirect to default root path
        if (!empty($_GET['do'])) { // do callback
            $callable = "callback_".$_GET['do'];
            if (!is_callable($callable)) {
                throw new Exception("Unable to callback '{$callable}'");
            }
            call_user_func($callable);
            exit();
        } elseif (!empty($_POST['match']) && !empty($_POST['query'])) {
            $GLOBALS['action'] = "search";
            $GLOBALS['path'] = stripslashes(rawurldecode($_GET['dir']));
            if (strpos($GLOBALS['path'],'..') !== false || !is_dir(_MEDIAPATH.$GLOBALS['path'])) {
                throw new Exception("Directory {$GLOBALS['path']} not valid!");
                return;
            }
            $GLOBALS['title'] = "Search";
            $GLOBALS['dir'] = new dir($GLOBALS['path']);
        } elseif (!empty($_GET['file'])) {
            $GLOBALS['action'] = "file";
            $GLOBALS['path'] = stripslashes(rawurldecode($_GET['file']));
            if (strpos($GLOBALS['path'],'..') !== false || !is_file(_MEDIAPATH.$GLOBALS['path'])) {
                throw new Exception("File {$GLOBALS['path']} not valid!");
                return;
            }
            $GLOBALS['title'] = ucwords(stripslashes(basename($_GET['file'])));
            $GLOBALS['file'] = new file($GLOBALS['path']);
        } elseif (!empty($_GET['dir'])) {
            $GLOBALS['action'] = "dir";
            $GLOBALS['path'] = stripslashes(rawurldecode($_GET['dir']));
            if (strpos($GLOBALS['path'],'..') !== false || !is_dir(_MEDIAPATH.$GLOBALS['path'])) {
                throw new Exception("Directory {$GLOBALS['path']} not valid!");
                return;
            }
            $GLOBALS['title'] = ucwords(stripslashes(basename($_GET['dir'])));
            $GLOBALS['dir'] = new dir($GLOBALS['path']);
        } else {
            header("location: ".$_SERVER['SCRIPT_NAME']."?dir=/");
        }

        // execute administrative logic first, buffer output and assign to controller
        if (_authenticated() && $GLOBALS['action'] != "search") {
            ob_start();
            if ($GLOBALS['action'] == "file") {
                include(_BASEPATH."/includes/editFile.php");
            }
            elseif ($GLOBALS['action'] == "dir") {
                include(_BASEPATH."/includes/editDir.php");
            }
            $adminOutput = ob_get_contents();
            ob_end_clean();
        } else {
            $adminOutput = "";
        }

        ob_start();
        if ($GLOBALS['action'] == "search") { // Search
            include(_BASEPATH."/includes/viewSearch.php");
        } elseif ($GLOBALS['action'] == "file") { // File
            include(_BASEPATH."/includes/viewFile.php");
        } elseif ($GLOBALS['action'] == "dir") { // Directory
            include(_BASEPATH."/includes/viewDir.php");
        }
            
        $mainOutput = ob_get_contents();
        ob_end_clean();
              
        include_once(_BASEPATH."/includes/layout.php");
    }

}

$mdx = new MediaIndexer;
$mdx->execute();

// show elapsed time of script execution
$time_end = _getmicrotime();
$ltime = $time_end - $time_start;
printf("<!-- Page generated in %0.5f seconds -->\n", $ltime);
?>
Return current item: mediaIndex