Sources for file onyx.class.php in version 2.0



Click on a comment to hide it. Click here to show all comments.

/*
 * Project:     Onyx: PHP Application Backend
 * File:        onyx.class.php
 *              Main Onyx Class
 *
 * Version:     2.0
 * CVS tag:     $Id: onyx.class.php,v 1.61 2003/05/31 08:29:26 bok Exp $
 * Author:      Robert Amos <bok[at]ausmac.net>
 *              Andrew Wellington <proton[at]wiretapped.net>
 * Copyright:   2001,2002 odynia.org.
*/
// set the constants first
// directory seperator (for compatibility with windows)
define('DIRSEP'DIRECTORY_SEPARATOR);

// main onyx dir
if (!defined('ONYXDIR')) {
    
define('ONYXDIR'dirname(__FILE__).DIRSEP);
    
define('ONYX_DIR'dirname(__FILE__).DIRSEP);
}

// main smarty dir
if (!defined('SMARTY_DIR')) {
    
define('SMARTY_DIR'ONYXDIR.'smarty'.DIRSEP);
}

// main script dir
if (!defined('SCRIPT_DIR')) {
    
define('SCRIPT_DIR'dirname($_SERVER['SCRIPT_FILENAME']).DIRSEP);
}

// simplified error stuff
define('ERROR'E_USER_ERROR);
define('WARNING'E_USER_WARNING);
define('NOTICE'E_USER_NOTICE);



// are we running from the command line?
$web false;
if (
count($_ENV))
{
    foreach (
$_ENV as $key => $var)
        if (!isset(
$_SERVER[$key]))
        {
            
$web true;
            break;
        }
} else {
    
$web true;
}

if (
$web) {
    if (!
defined('CLI')) define ('CLI'false);
    if (!
defined('WEB')) define ('WEB'true);
} else {
    if (!
defined('CLI')) define ('CLI'true);
    if (!
defined('WEB')) define ('WEB'false);
}

// set the include path to include ONYXDIR
ini_set("include_path"ini_get("include_path").":".ONYXDIR.":".SCRIPT_DIR);

// start session now to avoid it bitching about the cache firing before it does
if (WEBsession_start();

// start the class
class Onyx {

    
// initialise variables

    /**
     * Configuration File Handler
    **/
    
var $config_handler "file";

    
/**
     * Cache File Handler
    **/
    
var $cache_handler "file";
    
    
/**
     * Error Handler
    **/
    
var $error_handler;
    
    
/**
     * Construction and destruction functions
    **/
    
var $constructor;
    var 
$destructor;

    
/**
     * To cache, or not to cache, that is the question.
    **/
    
var $cache TRUE;

    
/**
     * Date/Time (as unix timestamp) that cache file should expire
    **/
    
var $cache_expire NULL;

    
/**
     * How many seconds a cache file should be valid for, ignored if
     * $cache_expire != NULL
    **/
    
var $cache_lifetime 86400;

    
/**
     * Location to store cached data.
    **/
    
var $cache_location "cache";

    
/**
     * Filename (if using file cache handler) to output cache data to.
     * This is part of the website generation system.
    **/
    
var $cache_filename '';

    
/**
     * Automatic Variable Filter
    **/
    
var $filter_vars TRUE;

    
/**
     * Whether to translate $_GET['bleh'] to $bleh after input filtering
    **/
    
var $global_vars FALSE;

    
/**
     * How many seconds until a session expires
    **/
    
var $session_lifetime 86400;

    
/**
     * Database Type. See the manual for valid options.
    **/
    
var $database_type "pgsql";

    
/**
     * These are for connecting to the database server.
    **/
    
var $db_host;
    var 
$db_port;
    var 
$db_user;
    var 
$db_passwd;

    
/**
     * Whether to use persistent connections to the database.
    **/
    
var $use_persistent_db_conns TRUE;

    
/**
     * Authention module to use
    **/
    
var $auth_type "sql";

    
/**
     * Parameters to pass to the authentication module.
    **/
    
var $auth_params = array();

    
/**
     * URL to redirect users to who have been forcefully logged out.
    **/
    
var $logout_redirect_url '';

    
/**
     * URL to redirect users to who are trying to access a page
     * thats restricted to a different location.
    **/
    
var $location_redirect_url '';
    
    
/**
     * Set location?
    **/
    
var $set_location true;

    
/**
     * Plugin Directories
    **/
    
var $plugin_dirs = array ("plugins");

    
/**
     * Whether to trim all extra whitespaces from HTML before transmit.
    **/
    
var $trim_html false;

    
/**
     * What to call the smarty object
    **/
    
var $smarty_obj 'smarty';

    
/**
     * Smarty configuration options..
     * See the smarty manual http://smarty.php.net/manual/en/
    **/
    
var $smarty_config = array ();

    
/*******************************************************************
    *******************************************************************/

    /**
     * These variables should all be set in your scripts via
     * $onyx->varname = 'bleh';
    **/


    /**
     * Page specific configuration, such as access controls, etc
    **/
    
var $page = array();

    
/**
     * Automatic Input Filter arrays, use these to filter variables,
     * see the manual.
    **/
    
var $get_vars = array();
    var 
$post_vars = array();
    var 
$argv_vars = array();

    
/******************************************************************/

    /**
     * Dont touch these!!
    **/
    
var $_loaded_plugins = array();
    var 
$_input_modified = array();
    
    
/*******************************************************************
    **
    * End Variable Configuration
    **
    *******************************************************************/
    
    /**
     * Method:            start
     * Description:    start the function parsing and stuff0r
     * Arguments:        none
     * Returns:            true
    **/
    
function start () {

        
// set global $onyx_parent variable
        
$GLOBALS['onyx_parent'] =& $this;

        
// fetched cache'd copy if we have one
        
if ($this->cache && WEB) {
            
$this->_fetch_cache();
        }

        
// start the output buffer (no caching for CLI)
        
if (WEBob_start("onyx_ob_cache_handler");

        
// log errors
        
if (CLI) {
            
ini_set("display_errors"true);
        } else {
            if (
$this->log_errors && ini_get("log_errors") == false) {
                
ini_set("error_log"$this->error_log);
                
ini_set("log_errors"true);
            }
        }

        
// load the default plugins
        
$this->load_plugin($this->database_type'database');
        
$this->load_plugin('input');
        
$this->load_plugin('access');

        global 
$access;
        
// do auth type checking
        
if (!$access->sess_check()) {
            
header("Location: ".$this->logout_redirect_url);
            exit;
        }
        
        
// Parse our variables
        
if ($this->filter_vars) {
            if (
WEB) {
                if (
count($_GET) > 0)
                    
$this->_filter_input_vars ($this->get_vars1);
                if (
count($_POST) > 0)
                    
$this->_filter_input_vars ($this->post_vars2);
            } else {
                
// cant exactly global argv...
                
$this->global_vars false;
                if (
count($_SERVER['argv']) > 0)
                    
$this->_filter_input_vars ($this->argv_vars3);
            }
        }

        
// load smarty
        
include_once SMARTY_DIR.'/Smarty.class.php';
        
$GLOBALS[$this->smarty_obj] = new Smarty;

        
// load our smarty configuration over it's..
        
if (is_array($this->smarty_config) && count($this->smarty_config) > 0)
            foreach (
$this->smarty_config as $key => $var)
                
$GLOBALS[$this->smarty_obj]->$key $var;

        
// set plugin directories for smarty
        
foreach ($this->plugin_dirs as $dir) {
            
$smarty_dirs[] = $dir.'/smarty';
        }
        
$onyx_smarty_var = array (
                    
"page" => &$this->page,
                    
'colours' => &$this->colours,
                    
'config' => &$this->config,
                );

        
$GLOBALS[$this->smarty_obj]->plugins_dir $smarty_dirs;
        
$GLOBALS[$this->smarty_obj]->assign_by_ref('onyx'$onyx_smarty_var);
        
        
// run the construction functions, if we have specified one
        
if (!empty($this->constructor) && function_exists($this->constructor))
        {
            
$func $this->constructor;
            
$func();
        }

    }

    
/**
     * Method:            load_plugin
     * Description:    Load a plugin into the system
     * Arguments:        string    - plugin name
     *                        string    - plugin type (optional)
     * Returns:            true on success, false on failure
    **/
    
function load_plugin($plugin$type=NULL) {

        
// set default type
        
if (is_null($type)) {
            
$type "class";
        }

        
// do we have this plugin in the return list?
        
if (isset($this->_return_plugins[$plugin]))
            return 
$this->_return_plugins[$plugin];

        
// return true if we've already loaded this plugin
        
if ($this->_loaded_plugins[$type][$plugin]) {
            return 
true;
        }

        
// no plugin name?
        
if (empty($plugin))
        {
            
$this->trigger_error("Empty plugin name specified."NOTICE);
            return 
false;
        }

        
// check for the plugin file
        
foreach ($this->plugin_dirs as $dir) {

            
// check the path
            
$dir $this->_transform_path($dir.DIRSEP.$type).DIRSEP;

            
// try it with ONYXDIR prepended if its not in teh include_path..
            
if (!file_exists($dir.$plugin.'.php') && file_exists(ONYXDIR.$dir.$plugin.".php"))
                
$dir ONYXDIR.$dir;

            
// load the plugin if we have it
            
if (file_exists($dir.$plugin.".php")) {
                include_once(
$dir.$plugin.".php");

                
// loaded successfully
                
$this->_loaded_plugins[$type][$plugin] = true;

                
// our action variables
                
$global FALSE;
                
$return FALSE;

                
// start the magic
                
switch ($type) {
                    case 
'class':
                        
$class $plugin."_plugin";
                        
$objname strtolower($plugin);
                        
$global TRUE;
                        break;
                    case 
'database':
                        
$class "db_plugin";
                        
$objname "db";
                        
$global TRUE;
                        break;
                    case 
'auth':
                        
$class "auth_".$plugin."_plugin";
                        
$objname "_auth_".strtolower($plugin)."_handler";
                        break;
                    case 
'config':
                        
$class "config_".$plugin."_plugin";
                        
$objname "_config_".strtolower($plugin)."_handler";
                        break;
                    case 
'cache':
                        
$class "cache_".$plugin."_plugin";
                        
$objname "_cache_".strtolower($plugin)."_handler";
                        break;
                    case 
'error':
                        
$class "error_".$plugin."_plugin";
                        
$objname "_error_handler";
                        break;
                    case 
'dbspec':
                        
$class "dbspec_".$plugin;
                        
$return TRUE;
                        break;
                    default:
                        
$this->trigger_error("Invalid plugin type: $type (plugin: $plugin)"WARNING);
                        return 
false;
                }

                
// check
                
if (!class_exists($class))
                {
                    
$this->trigger_error('Invalid plugin: '.$plugin.' ('.$type.'), class '.$class.' not found',
WARNING);
                    return 
false;
                }


                
// Make the object i guess
                
if ($global) {
                    
$GLOBALS[$objname] = new $class;
                } elseif (
$return) {
                    
$this->_return_plugins[$plugin] = new $class;
                    return 
$this->_return_plugins[$plugin];
                } else
                    
$this->$objname = new $class;

                
// finished teh juarez
                
return true;
            }

        }

        
// guess we fucked up...
        
$this->trigger_error("Unable to locate plugin: $plugin ($type)"WARNING);
        return 
false;
    }

    
/**
     * Method:            _filter_input_vars
     * Description:    Automatically filter input variables
     * Arguments:        array        - variables to filter
     *                        integer    - type
     * Returns:            true on success, false on failure
    **/
    
function _filter_input_vars ($vars$type=1) {

        
// load input juarez
        
global $input;

        
// best double check everything
        
if (!is_array($vars) || count($vars) == 0) {
            switch(
$type) {
                case 
3:
                    
$_SERVER['argv'] = array();
                    break;
                case 
2:
                    
$_POST = array();
                    break;
                case 
1:
                default:
                    
$_GET = array();
            }
            return 
true;
        }

        
// set variable stuffs
        
switch($type) {
            case 
3$parse $_SERVER['argv'];
                break;
            case 
2:
                
$parse $_POST;
                break;
            case 
1:
            default:
                
$parse $_GET;
        }

        
// do the filtering
        
foreach ($parse as $key => $var) {
            if (isset(
$vars[$key])) {
                
// deal with arrays

                
if (is_array($vars[$key])) {

                    
$array_type $vars[$key][0];

                    
$vars[$key] = "_array";
                }

                if (
method_exists($input$vars[$key])) {
                    
$method $vars[$key];

                    
// again our arrays
                    
if (!empty($array_type)) {
                        
$parsed[$key] = $input->$method($var$array_type);
                    } else {
                        
$parsed[$key] = $input->$method($var);
                    }

                    
// dear god, more arrays
                    
if (is_array($parse[$key])) {
                        foreach (
$parse[$key] as $k => $v)
                            
$this->_input_modified[$key][$k] = $parse[$key][$k] != $parsed[$key][$k];
                    } else {
                        
$this->_input_modified[$key] = $parse[$key] != $parsed[$key];
                    }
                    if (
$this->global && !isset($GLOBALS[$key]))
                        
$GLOBALS[$key] = $var;
                }
            }
        }

        switch(
$type) {
            case 
3:
                
$_SERVER['argv'] = $parsed;
                break;
            case 
2:
                
$_POST $parsed;
                break;
            case 
1:
            default:
                
$_GET $parsed;
        }

        return 
true;

    }

    
/**
     * Method:            parse_config
     * Description:    Parse Configuration Stuffs
     * Arguments:        string    - config identifier to parse
     * Returns:            array on success, false on failure
    **/
    
function parse_config ($var=NULL) {

        if (
is_null($var))
        {
            
$this->trigger_error('Failed to parse_config for NULL config variable'NOTICE);
            return 
false;
        }
        
        
// no handler? we're screwed!
        
if (empty($this->config_handler))
        {
            
$this->trigger_error('Failed to parse_config for '.$var.' because there is no configuration
handler specified'
NOTICE);
            return 
false;
        }
        
        
// load it first, to be sure
        
if (!$this->load_plugin($this->config_handler'config'))
        {
            
$this->trigger_error('Unable to load configuration handler '.$this->config_handlerNOTICE);
            return 
false;
        }

        
// do the warez
        
$obj_name "_config_".$this->config_handler."_handler";

        
// check to make sure the config handler is valid
        
if (!is_object($this->$obj_name))
        {
            
$this->trigger_error('Invalid configuration handler '.$this->config_handler.'. Unable to access
object $this->'
.$obj_name.'->parse'NOTICE);
            return 
false;
        }
        
        
$config $this->$obj_name->parse($var);

        return 
$config;

    }

    
/**
     * Method:            _fetch_cache
     * Description:    Fetch a cached file
     * Arguments:        none
     * Returns:            exits or false when no cached page found
    **/
    
function _fetch_cache () {

        
// ok, first things first, last things last, you know the drill

        // do security checking
        
if (isset($_SESSION["user"]) && $_SESSION["expiry"] <= time()) {
            return 
false;
        }

        
// no handler? we're screwed!
        
if (empty($this->cache_handler)) {
            
$this->trigger_error('No cache handler set, but caching is on!'WARNING);
            return 
false;
        }

        
// load it first, to be sure
        
if (!$this->load_plugin($this->cache_handler'cache')) {
            
$this->trigger_error('Unable to load configured cache handler '.$this->cache_handlerWARNING);
            return 
false;
        }

        
// do the warez
        
$method_name "_cache_".$this->cache_handler."_handler";
        if (
$this->$method_name->read()) {
            exit;
        }
        return 
false;
    }

    
/**
     * Method:            _transform_path
     * Description:    Seucrity check and clean a filesystem path
     * Arguments:        string    - file system path
     * Returns:            nice clean path
    **/
    
function _transform_path ($path) {

        
// nor do we allow directory transversals
        
$path preg_replace("/\.\./"""$path);

        
// clean up nicely
        
$path preg_replace("/\/\//"""$path);

        
// all done
        
return $path;
    }
    
    
/**
     * Method:            trigger_error
     * Description:    Triggers the predefined error handlers
     * Arguments:        string    - error message
     *                     integer    - error type, constants exist for accessing this (ERROR, WARNING, NOTICE)
     * Returns:            true
    **/
    
function trigger_error ($errmsg$type=WARNING) {
        
        
// easy enough
        
        // if it doesnt exist dont do anything
        
if (empty($this->error_handler) || !$this->load_plugin($this->error_handler'error'))
        {
            
trigger_error($errmsg$type);
            return 
true;
        }
        
        
// load the plugin
        // run the handler function
        
$this->_error_handler->error($errmsg$type);
        
        
// done
        
return true;
    }
    

}

/**
 * Function:        onyx_ob_cache_handler
 * Description:    Cache output of file
 * Arguments:        output to cache
 * Returns:            unchanged browser output
**/
function onyx_ob_cache_handler ($buffer) {

    global 
$onyx_parent;
    
    
// destruction functions
    
if (!empty($onyx_parent->destructor) && function_exists($onyx_parent->destructor))
    {
        
$func $onyx_parent->destructor;
        
$func();
    }

    if (
$onyx_parent->trim_html) {
        
$buffer onyx_ob_trimwhitespace($buffer);
    }

    
// output a content-length header, we never modify the data, so do it
    
header('Content-Length: '.strlen($buffer));

    
// not caching? fine with me
    
if (!$onyx_parent->cache)
        return 
$buffer;

    
// no handler? we're screwed!
    
if (empty($onyx_parent->cache_handler)) {
        
$this->trigger_error('No caching handler set but caching is on'WARNING);
        return 
$buffer;
    }

    
// load it first, to be sure
    
if (!$onyx_parent->load_plugin($onyx_parent->cache_handler'cache')) {
        
$this->trigger_error('Couldnt load configured cache handler.'WARNING);
        return 
$buffer;
    }

    
// do the warez
    
$method_name "_cache_".$onyx_parent->cache_handler."_handler";
    
$onyx_parent->$method_name->write($buffer);

    return 
$buffer;
}

/**
 * Function:        onyx_ob_trimwhitespace
 * Description:    Trim Extra Whitespaces, compacting the HTML
 * Syntax:            onyx_ob_cache_handler($source);
 * Returns:            trim'd browser output
 * Credits:            Originally from the Smarty template engine
 *    Author:             Monty Ohrt <monte[at]ispi.net>
 *    Date:             April 30, 2002
 *    Version:         1.2
 * Note:                slight changes have been made
 **/
function onyx_ob_trimwhitespace($source) {

    
$_blocks_match "script|pre|style|textarea";

    
// Pull out the blocks
    
preg_match_all("!<($_blocks_match)[^>]+>.*?</($_blocks_match)>!is"$source$match);
    
$_blocks $match[0];
    
$source preg_replace("!<($_blocks_match)[^>]+>.*?</($_blocks_match)>!is"'@@@ONYX:TRIM@@@',
$source);

    
// clean up all whitespaces from the start of a line to the start of a HTML tag
    
$source preg_replace('/^[\s]+?</m''<'$source);

    
// remove multiple lines/empty lines
    
$source preg_replace('/>[\s\t\n]{2,}?</m'">\n<"$source);

    
// replace blocks
    
foreach($_blocks as $curr_block)
        
$source preg_replace("!@@@ONYX:TRIM@@@!",$curr_block,$source,1);

    return 
$source
}

?>


Website is Copyright © Odynia.org 2000-2005 - Xnyo is released under a BSD license.