]>
src.bluestatic.org Git - isso.git/blob - kernel.php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version [#]gpl[#] of the License.
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
23 * Iris Studios Shared Object Framework Kernel
29 if (!function_exists('version_compare'))
31 trigger_error('You need PHP version 4.1.0 or newer to run ISSO', E_USER_ERROR
);
35 // when we are PHP5-nat instead of PHP5-compat, we can remove this
36 if (version_compare(PHP_VERSION
, '5.0.0', '>='))
38 if (ini_get('error_reporting') & E_NOTICE
)
40 error_reporting(ini_get('error_reporting') - E_NOTICE
);
42 if (ini_get('error_reporting') & E_USER_NOTICE
)
44 error_reporting(ini_get('error_reporting') - E_USER_NOTICE
);
48 $oldlevel = ini_get('error_reporting');
49 $newlevel = $oldlevel;
50 $levels = array(E_ERROR
=> E_USER_ERROR
, E_WARNING
=> E_USER_WARNING
, E_NOTICE
=> E_USER_NOTICE
);
51 foreach ($levels AS $php => $isso)
55 if (!($oldlevel & $isso))
62 if ($oldlevel & $isso)
68 error_reporting($newlevel);
70 if ((bool)ini_get('register_globals') === true)
72 $superglobals = array('_GET', '_COOKIE', '_FILES', '_POST', '_SERVER', '_ENV');
73 foreach ($superglobals AS $global)
75 if (is_array(${$global}))
77 foreach (${$global} AS $_key => $_val)
89 * Input cleaning type constant
94 define('TYPE_INT', 1);
99 define('TYPE_UINT', 2);
104 define('TYPE_FLOAT', 4);
109 define('TYPE_BOOL', 8);
114 define('TYPE_STR', 16);
117 * String - deliberate unclean
119 define('TYPE_STRUN', 32);
122 * No cleaning - here for use in API
124 define('TYPE_NOCLEAN', 64);
130 define('REQ_YES', 1);
138 * Iris Studios Shared Object Framework (ISSO)
140 * This framework allows a common backend to be used amongst all Iris
141 * Studios applications and is built to be abstract and flexible.
142 * The base framework handles all loading and module management.
145 * ISSO_NO_INPUT_SANITIZE - Disables the automatic input sanitizer
146 * ISSO_CHECK_POST_REFERER - Will check to make sure that on POSTed
147 * data, the referer matches the host
149 * @author Iris Studios, Inc.
150 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
151 * @version $Revision$
162 var $version = '[#]version[#]';
165 * Location of ISSO, used for internal linking
169 var $sourcepath = '';
172 * Path of the current application
179 * Web path used to get the web location of the installation of ISSO; only used for Printer module
186 * Name of the current application
190 var $application = '';
193 * Version of the current application
197 var $appversion = '';
200 * Whether debug mode is on or off
207 * List of all active debug messages
211 var $debuginfo = array();
214 * List of loaded modules
218 var $modules = array();
221 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
228 * If we are running with magic_quotes_gpc on or off
232 var $magicquotes = 0;
235 * Array of user-specified fields that are required for ISSO initialization
236 * fieldname => array(REQUIRED, CALLBACK PARSER, SET)
241 'sourcepath' => array(REQ_YES
, 'fetch_sourcepath', false),
242 'apppath' => array(REQ_YES
, 'fetch_sourcepath', false),
243 'webpath' => array(REQ_NO
, 'fetch_sourcepath', false),
244 'application' => array(REQ_YES
, null, false),
245 'appversion' => array(REQ_NO
, null, false),
246 'debug' => array(REQ_NO
, null, false)
249 // ###################################################################
253 function __construct()
255 $GLOBALS['isso:null-framework'] = null;
258 set_error_handler(array(&$this, '_error_handler'));
261 $this->magicquotes
= get_magic_quotes_gpc();
262 set_magic_quotes_runtime(0);
264 // attempt to set the sourcepath
265 $path = debug_backtrace();
266 $this->set('sourcepath', str_replace('kernel.php', '', $path[0]['file']));
268 // start input sanitize using variable_order GPC
269 if (!defined('ISSO_NO_INPUT_SANITIZE'))
271 $this->exec_sanitize_data();
274 if (defined('ISSO_CHECK_POST_REFERER'))
276 $this->exec_referer_check();
280 // ###################################################################
282 * (PHP 4) Constructor
286 $this->__construct();
289 // ###################################################################
291 * Sets a specified field in the ISSO. This is used to set all the
292 * required fields that ISSO uses for linking. It replaces the old
293 * method of setting the instance variables directly.
297 * @param string Field name
298 * @param mixed Value of the field
300 function set($fieldname, $value)
302 $this->do_set($fieldname, $value, null);
305 // ###################################################################
307 * Does the actual setting of the field. set() is defined in each
308 * module, but this controls the actual data. This is done so that
309 * there isn't an extra parameter in set() that controls module spaces
313 * @param string Field name
315 * @param string Module name (as referred to in ISSO->modules[]) to place in
317 function do_set($fieldname, $value, $module)
321 $field =& $this->fields
["$fieldname"];
325 $field =& $this->modules["$module"]->fields
["$fieldname"];
328 if (is_array($field))
330 if ($field[1] != null)
332 if (preg_match('#^\$(.*)#', $field[1]))
334 $caller = preg_replace('#^\$(.*)->([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$#', 'array(&$\1, "\
2")', $field[1]);
335 eval('$caller = ' . $caller . ';');
339 $caller = array(&$this, $field[1]);
342 $value = call_user_func($caller, $value);
347 $this->$fieldname = $value;
351 $this->modules["$module"]->$fieldname = $value;
358 trigger_error('Invalid field `' . $module . '.' . $fieldname . '` specified in ISSO->do_set()', E_USER_ERROR
);
362 // ###################################################################
364 * Fetches the value of a field. This is protected because get() should
365 * be defined in each module to make a call to this function.
369 * @param string Field name
370 * @param string Module name (as referred to in ISSO->modules[]) to fetch from
372 function do_get($fieldname, $module)
376 $field =& $this->fields
["$fieldname"];
380 $field =& $this->modules["$module"]->fields
["$fieldname"];
383 if (is_array($field))
385 if ($field[2] == false)
387 trigger_error('Field ' . $module . ':: ' . $filedname . ' is not set and therefore cannot be get()', E_USER_ERROR);
392 return $this->$fieldname;
396 return $this->modules["$module"]->$fieldname;
403 trigger_error('Invalid field `' . $module . '.' . $fieldname . '` specified in ISSO->do_get()', E_USER_ERROR
);
407 // ###################################################################
409 * Returns the value of an ISSO field. You should not access any instance
410 * variables directly, use this instead.
414 * @param string Field name
416 * @return mixed Value of the field
418 function get($fieldname)
420 return $this->do_get($fieldname, null);
423 // ###################################################################
425 * Makes sure that all of the required fields in ISSO are set before
426 * any action is done. This will throw an error block describing
427 * the fields that need to be set if any are missing.
431 * @param string Module to check for; null is kernel, string is a module name, false is all
432 * @param bool Is this a non-error environment that should display all fields?
434 function check_isso_fields($module = null, $called = false)
438 if ($module === false)
440 $modules = $this->show_modules(true);
442 else if ($module === null)
444 $modules = array(get_class($this));
448 $modules = array($module);
451 foreach ($modules AS $module)
453 if (empty($this->modules
["$module"]->fields))
458 foreach ($this->modules["$module"]->fields
AS $name => $field)
460 if ($field[0] == REQ_YES
AND $field[2] == false AND $called == false)
462 $missing[] = $module . ':: ' . $name;
464 else if ($called == true AND $field[2] == false)
466 $missing[] = $module . ':: ' . $name . ($field[0] == REQ_YES
? ' <strong>(REQUIRED)</strong>' : '');
471 if (count($missing) > 0)
473 $error = ($called ? 'The following fields are not set:' : 'You are missing required ISSO fields. Please make sure you have set:');
477 foreach ($missing AS $field)
479 $error .= "\n\t" . '<li>' . $field . '</li>';
482 $error .= "\n" . '</ul>';
484 $this->message(($called ? '' : 'Missing ') . 'Fields', $error, ($called ? 1 : 3));
486 if ($called == false)
493 // ###################################################################
495 * Prepares a path for being set as the sourcepath
499 * @param string Source path or URL
501 * @return string Prepared source path
503 function fetch_sourcepath($source)
505 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
507 $source .= DIRECTORY_SEPARATOR
;
512 // ###################################################################
514 * Loads a framework module
518 * @param string Name of the framework file to load
519 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
520 * @param bool Globalize the internal variable?
522 * @return object Instantiated instance
524 function &load($framework, $asobject, $globalize = false)
526 $this->check_isso_fields(null);
528 // set the object interlock
529 if (!method_exists($GLOBALS['isso:null-framework'], 'load'))
531 $GLOBALS['isso:null-framework'] =& $this;
532 $this->modules
['isso'] =& $this;
535 if ($this->is_loaded($framework))
537 return $this->modules
["$framework"];
540 if ($this->sourcepath == '')
542 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
545 if (file_exists($this->sourcepath . $framework . '.php'))
547 require_once($this->sourcepath . $framework . '.php');
551 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
554 if ($asobject === null)
559 if (isset($this->$asobject))
561 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
564 $this->$asobject = new $framework($this);
566 $this->modules["$framework"] =& $this->$asobject;
570 $GLOBALS["$asobject"] =& $this->$asobject;
573 // allow for init_as_package to link
574 if (method_exists($this->modules["$framework"], 'init_as_package'))
576 $this->modules
[ $this->modules
["$framework"]->init_as_package() ] =& $this->modules["$framework"];
579 return $this->$asobject;
582 // ###################################################################
584 * Prints a list of all currently loaded framework modules
588 * @param bool Return the data as an array?
590 * @return mixed HTML output or an array of loaded modules
592 function show_modules($return = false)
595 foreach ($this->modules
AS $object)
597 $module = get_class($object);
598 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
600 $module = $object->init_as_package() . " - ($module)";
603 $modules[] = $module;
612 $output = "\n\n<ul>\n\t<li>";
613 $output .= implode("</li>\n\t<li>", $modules);
614 $output .= "</li>\n</ul>\n\n";
615 $this->message('Loaded Modules', $output, 1);
619 // ###################################################################
621 * Verifies to see if a framework has been loaded
625 * @param string Framework name
627 * @return bool Whether or not the framework has been loaded
629 function is_loaded($framework)
631 if (isset($this->modules
["$framework"]))
641 // ###################################################################
643 * Prints an ISSO message
647 * @param string The title of the message
648 * @param string The content of the message
649 * @param integer Type of message to be printed
650 * @param bool Return the output?
651 * @param bool Show the debug stack?
653 * @return mixed Output or null
655 function message($title, $message, $type, $return = false, $stack = true)
680 $backtrace = debug_backtrace();
681 array_shift($backtrace);
683 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
685 array_shift($backtrace);
689 foreach ($backtrace AS $i => $step)
691 $file = $step['file'] . ':' . $step['line'];
692 $funct = (isset($step['class']) ? $step['class'] . '::' . $step['function'] : $step['function']);
693 $args = (is_array($step['args']) ? implode(', ', $step['args']) : '');
695 $trace[] = "#$i $funct($args) called at [$file]";
698 $output = "\n<br />\n<table cellpadding=\"4\" cellspacing=\"1\" border=\"0\" width=\"500\" style=\"background-color: $color; color: black; font-family: Verdana, sans-serif; font-size: 12px;\">";
699 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
700 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
701 $output .= (($stack AND $GLOBALS['isso:null-framework']->debug
) ? "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td><strong>Debug Stack:</strong> <pre>" . implode("\n", $trace) . "</pre></td>\n</tr>" : '');
702 $output .= "\n</table>\n<br />\n";
714 // ###################################################################
716 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
717 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
721 * @param integer Error number
722 * @param string Error message string
723 * @param string File that contains the error
724 * @param string The line number of the error
725 * @param string The active symbol table at which point the error occurred
727 function _error_handler($errno, $errstr, $errfile, $errline)
735 if (!(ini_get('error_reporting') & E_USER_ERROR
))
745 if (!(ini_get('error_reporting') & E_USER_WARNING
) AND !(ini_get('error_reporting') & E_WARNING
))
756 if (!(ini_get('error_reporting') & E_USER_NOTICE
) AND !(ini_get('error_reporting') & E_NOTICE
))
763 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
765 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
767 $this->message($title, $errstr, $level);
769 if ($errno == E_USER_ERROR
)
775 // ###################################################################
777 * Creates a table that explains the error reporting levels and their
782 function explain_error_reporting()
785 'E_ERROR' => E_ERROR
,
786 'E_WARNING' => E_WARNING
,
787 'E_PARSE' => E_PARSE
,
788 'E_NOTICE' => E_NOTICE
,
789 'E_CORE_ERROR' => E_CORE_ERROR
,
790 'E_CORE_WARNING' => E_CORE_WARNING
,
791 'E_COMPILE_ERROR' => 64,
792 'E_COMPILE_WARNING' => 128,
793 'E_USER_ERROR' => E_USER_ERROR
,
794 'E_USER_WARNING' => E_USER_WARNING
,
795 'E_USER_NOTICE' => E_USER_NOTICE
,
800 $table = '<table cellspacing="0" cellpadding="2" border="0">';
802 foreach ($levels AS $name => $value)
806 <td>' . $name . '</td>
807 <td>' . (ini_get('error_reporting') & $value) . '</td>
814 $this->message('Error Reporting', $table, 1);
817 // ###################################################################
819 * Logs a debug message for verbose output
823 * @param string Message
825 function debug($message)
827 $this->debuginfo
[] = $message;
830 // ###################################################################
832 * Recursive XSS cleaner
836 * @param mixed Unsanitized REQUEST data
838 * @return mixed Sanitized data
840 function _sanitize_input_recursive($data)
842 foreach ($data AS $key => $value)
844 if (is_array($value))
846 $data["$key"] = $this->_sanitize_input_recursive($value);
850 $data["$key"] = $this->sanitize($value);
856 // ###################################################################
858 * Simple way to protect against HTML attacks with Unicode support
862 * @param string Unsanitzed text
864 * @return string Properly protected text that only encodes potential threats
866 function sanitize($text)
868 if ($this->magicquotes
)
870 return str_replace(array('<', '>', '\"', '"'), array('<', '>', '"', '"'), $text);
874 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
878 // ###################################################################
880 * Unicode-safe entity encoding system; similar to sanitize()
884 * @param string Unsanitized text
886 * @return string Unicode-safe sanitized text with entities preserved
888 function entity_encode($text)
890 $text = str_replace('&', '&', $text);
891 $text = $this->sanitize($text);
895 // ###################################################################
897 * Takes text that has been processed for HTML and unsanitizes it
901 * @param string Text that needs to be turned back into HTML
903 * @return string Unsanitized text
905 function unsanitize($text)
907 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
910 // ###################################################################
912 * Smart addslashes() that only applies itself it the Magic Quotes GPC
913 * is off. This should only be run on database query values.
917 * @param string Some string
918 * @param bool If the data is binary; if so it'll be run through DB::escape_stringing()
919 * @param bool Force magic quotes to be off
921 * @return string String that has slashes added
923 function escape($str, $binary = false, $force = true)
925 if ($this->magicquotes
AND !$force)
927 if (isset($this->modules
[ISSO_DB_LAYER
]) AND $binary)
929 return $this->modules
[ISSO_DB_LAYER
]->escape_string(str_replace(array("\'", '\"'), array("'", '"'), $str));
935 if (isset($this->modules
[ISSO_DB_LAYER
]) AND $binary)
937 return $this->modules
[ISSO_DB_LAYER
]->escape_string($str);
939 return addslashes($str);
943 // ###################################################################
945 * Runs through all of the input data and sanitizes it.
949 function exec_sanitize_data()
951 $this->in
= $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
954 // ###################################################################
956 * Sanitize function for something other than a string (which
957 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
958 * data is placed back into $isso->in; this makes it so you don't have
959 * to constantly intval() [etc.] data.
963 * @param array Array of elements to clean as varname => type
965 function input_clean_array($vars)
967 foreach ($vars AS $varname => $type)
969 $this->input_clean($varname, $type);
973 // ###################################################################
975 * Sanitize function that does a single variable as oppoesd to an array
976 * (see input_clean_array() for more details)
980 * @param string Variable name in $isso->in[]
981 * @param integer Sanitization type constant
983 function input_clean($varname, $type)
985 if (isset($this->in
["$varname"]))
987 $this->in["$varname"] = $this->clean($this->in
["$varname"], $type);
991 $this->in["$varname"] = null;
994 return $this->in
["$varname"];
997 // ###################################################################
999 * Cleaning function that does the work for input_clean(); this is
1000 * moved here so it can be used to clean things that aren't in
1006 * @param integer Sanitization type constant
1008 * @return mixed Cleaned data
1010 function clean($value, $type)
1012 if ($type == TYPE_INT)
1014 $value = intval($value);
1016 else if ($type == TYPE_UINT)
1018 $value = abs(intval($value));
1020 else if ($type == TYPE_FLOAT)
1022 $value = floatval($value);
1024 else if ($type == TYPE_BOOL)
1026 $value = (bool)$value;
1028 else if ($type == TYPE_STR)
1032 else if ($type == TYPE_STRUN)
1034 $value = $this->unsanitize($value);
1036 else if ($type == TYPE_NOCLEAN)
1042 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR);
1048 // ###################################################################
1050 * Checks to see if a POST refer is actually from us
1054 function exec_referer_check()
1056 if ($_SERVER['REQUEST_METHOD'] == 'POST')
1058 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
1060 if ($host AND $_SERVER['HTTP_REFERER'])
1062 $parts = parse_url($_SERVER['HTTP_REFERER']);
1063 $ourhost = $parts['host'] . (isset($parts['port']) ? ":$parts[port
]" : '');
1065 if ($ourhost != $host)
1067 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
1069 $this->debug('remote post check = ok');
1073 $this->debug('remote post check = FAILED');
1078 // ###################################################################
1080 * Constructs a debug information box that contains various debugging
1081 * information points
1085 * @param bool Show template information?
1087 * @return string Debugging block
1089 function construct_debug_block($dotemplates)
1102 foreach ($this->modules['template']->usage AS $name => $count)
1104 if (in_array($name, $this->modules['template']->uncached))
1106 $optlist[] = $name . '[' . $count . ']';
1108 $usage[] = $name . " ($count)";
1111 $sizeof = sizeof($this->modules['template']->uncached);
1114 $debug .= "\n\t
<li
><strong style
=\"color
: red\"
>Uncached
Template(s
):</strong
> $sizeof ( " . implode(' ', $optlist) . " )</li
>";
1119 $scinfo = 'Not Under Source Control';
1122 $scinfo = constant('SVN');
1124 if (preg_match('#\$Id:?\s*\$#', $scinfo))
1126 $scinfo = 'Not Under Source Control';
1130 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
1131 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
1132 $scinfo = preg_replace('#\$' . 'Id: (.+?) ([0-9].+?) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(.+?) (.+?) \$#', '\\1 - SVN \\2', $scinfo);
1136 $scinfo = trim($scinfo);
1137 $debug .= "\n\t
<li
><strong
>Source Control
:</strong
> $scinfo</li
>";
1139 // query information
1140 if (is_object($this->modules[ISSO_DB_LAYER]))
1142 $debug .= "\n\t
<li
><strong
>Total Queries
:</strong
> " . sizeof($this->modules[ISSO_DB_LAYER]->history) . " (<a href
=\"" . $this->sanitize($_SERVER['REQUEST_URI']) . ((strpos($_SERVER['REQUEST_URI'], '?') !== false) ? '&query=1' : '?query=1') . "\"
>?</a
>)</li
>";
1145 // total execution time
1146 if (defined('ISSO_MT_START'))
1148 $this->load('functions', 'functions');
1149 $debug .= "\n\t
<li
><strong
>Total Execution Time
:</strong
> " . round($this->modules['functions']->fetch_microtime_diff(ISSO_MT_START), 10) . "</li
>";
1153 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Debug
Notices (" . sizeof($this->debuginfo) . ")</option
>";
1154 foreach ((array)$this->debuginfo AS $msg)
1156 $debug .= "\n\t\t\t
<option
>--- $msg</option
>";
1158 $debug .= "\n\t\t
</select
>\n\t</li
>";
1161 $modules = $this->show_modules(true);
1162 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Loaded
Modules (" . sizeof($modules) . ")</option
>";
1163 foreach ($modules AS $mod)
1165 $debug .= "\n\t\t\t
<option
>--- $mod</option
>";
1167 $debug .= "\n\t\t
</select
>\n\t</li
>";
1172 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Template
Usage (" . array_sum($this->modules['template']->usage) . ")</option
>";
1173 foreach ($usage AS $tpl)
1175 $debug .= "\n\t\t\t
<option
>--- $tpl</option
>";
1177 $debug .= "\n\t\t
</select
>\n\t</li
>";
1180 $debug .= "\n
</ul
>";
1182 $debug = "\n\n
<!-- dev debug
-->\n<div align
=\"center\"
>\n\n<hr
/>\n" . $this->message('Debug Information', $debug, 1, true, false) . "\n
</div
>\n<!-- / dev debug
-->\n\n";
1189 /*=====================================================================*\
1190 || ###################################################################
1193 || ###################################################################
1194 \*=====================================================================*/