]>
src.bluestatic.org Git - isso.git/blob - kernel.php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework [#]issoversion[#]
5 || # Copyright ©2002-[#]year[#] Blue Static
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 * Blue Static ISSO Framework Kernel
29 if (!function_exists('stripos'))
31 trigger_error('You need PHP version 5.0.0 or newer to run ISSO', E_USER_ERROR
);
35 if ((bool)ini_get('register_globals') === true)
37 $superglobals = array('_GET', '_COOKIE', '_FILES', '_POST', '_SERVER', '_ENV');
38 foreach ($superglobals AS $global)
40 if (is_array(${$global}))
42 foreach (${$global} AS $_key => $_val)
53 $oldlevel = ini_get('error_reporting');
54 $newlevel = $oldlevel;
55 $levels = array(E_ERROR
=> E_USER_ERROR
, E_WARNING
=> E_USER_WARNING
, E_NOTICE
=> E_USER_NOTICE
);
56 foreach ($levels AS $php => $isso)
60 if (!($oldlevel & $isso))
67 if ($oldlevel & $isso)
73 error_reporting($newlevel);
76 * Input cleaning type constant
81 define('TYPE_INT', 1);
86 define('TYPE_UINT', 2);
91 define('TYPE_FLOAT', 4);
96 define('TYPE_BOOL', 8);
101 define('TYPE_STR', 16);
104 * String - deliberate unclean
106 define('TYPE_STRUN', 32);
109 * No cleaning - here for use in API
111 define('TYPE_NONE', 64);
114 * Macro for using DB->escape_binary() without cleaning - used in API
116 define('TYPE_BIN', 128);
122 define('REQ_YES', 1);
130 * Blue Static ISSO Framework (ISSO)
132 * This framework allows a common backend to be used amongst all Blue
133 * Static applications and is built to be abstract and flexible.
134 * The base framework handles all loading and module management.
137 * ISSO_NO_INPUT_SANITIZE - Disables the automatic input sanitizer
138 * ISSO_CHECK_POST_REFERER - Will check to make sure that on POSTed
139 * data, the referer matches the host
140 * ISSO_MT_START - Define the microtime() value at the top of your
141 * script and this will calculate the total execution
143 * SVN - Place SVN keywords (like $Id) to display the information on output
145 * @author Blue Static
146 * @copyright Copyright ©2002 - [#]year[#], Blue Static
147 * @version $Revision$
157 private $version = '[#]issoversion[#]';
160 * List of all active debug messages
163 private $debuginfo = array();
166 * List of loaded modules
169 private $modules = array();
172 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
175 public $in = array();
178 * If we are running with magic_quotes_gpc on or off
181 private $magicquotes = 0;
183 // ###################################################################
187 public function __construct()
189 $GLOBALS['isso:callback'] = null;
192 set_error_handler(array(&$this, '_error_handler'));
195 $this->magicquotes
= get_magic_quotes_gpc();
196 set_magic_quotes_runtime(0);
198 // some debug info that's always useful
199 $this->debug('magic_quotes_gpc = ' . $this->magicquotes
);
200 $this->debug('register_globals = ' . ini_get('register_globals'));
202 // start input sanitize using variable_order GPC
203 if (!defined('ISSO_NO_INPUT_SANITIZE'))
205 $this->exec_sanitize_data();
208 if (defined('ISSO_CHECK_POST_REFERER'))
210 $this->exec_referer_check();
214 // ###################################################################
216 * Prepares a path for being set as the sourcepath
218 * @param string Source path or URL
220 * @return string Prepared source path
222 public function fetch_sourcepath($source)
224 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
226 $source .= DIRECTORY_SEPARATOR
;
231 // ###################################################################
233 * Loads a framework module
235 * @param string Name of the framework file to load
236 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
237 * @param bool Globalize the internal variable?
239 * @return object Instantiated instance
241 public function &load($framework, $asobject, $globalize = false)
243 $this->check_isso_fields(null);
245 // set the object interlock
246 if (!method_exists($GLOBALS['isso:callback'], 'load'))
248 $GLOBALS['isso:callback'] =& $this;
249 $this->modules
['isso'] =& $this;
252 if ($this->is_loaded($framework))
254 return $this->modules
["$framework"];
257 if ($this->sourcepath == '')
259 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
262 if (file_exists($this->sourcepath . $framework . '.php'))
264 require_once($this->sourcepath . $framework . '.php');
268 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
271 if ($asobject === null)
276 if (isset($this->$asobject))
278 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
281 $this->$asobject = new $framework($this);
283 $this->modules["$framework"] =& $this->$asobject;
287 $GLOBALS["$asobject"] =& $this->$asobject;
290 // allow for init_as_package to link
291 if (method_exists($this->modules["$framework"], 'init_as_package'))
293 $this->modules
[ $this->modules
["$framework"]->init_as_package() ] =& $this->modules["$framework"];
296 return $this->$asobject;
299 // ###################################################################
301 * Prints a list of all currently loaded framework modules
303 * @param bool Return the data as an array?
305 * @return mixed HTML output or an array of loaded modules
307 public function show_modules($return = false)
310 foreach ($this->modules
AS $object)
312 $module = get_class($object);
313 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
315 $module = $object->init_as_package() . " - ($module)";
318 $modules[] = $module;
327 $output = "\n\n<ul>\n\t<li>";
328 $output .= implode("</li>\n\t<li>", $modules);
329 $output .= "</li>\n</ul>\n\n";
330 $this->message('Loaded Modules', $output, 1);
334 // ###################################################################
336 * Verifies to see if a framework has been loaded
338 * @param string Framework name
340 * @return bool Whether or not the framework has been loaded
342 public function is_loaded($framework)
344 if (isset($this->modules
["$framework"]))
354 // ###################################################################
356 * Prints an ISSO message
358 * @param string The title of the message
359 * @param string The content of the message
360 * @param integer Type of message to be printed
361 * @param bool Return the output?
362 * @param bool Show the debug stack?
363 * @param integer Message width
365 * @return mixed Output or null
367 public function message($title, $message, $type, $return = false, $stack = true, $width = 500)
392 $backtrace = debug_backtrace();
393 array_shift($backtrace);
395 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
397 array_shift($backtrace);
400 $trace = $this->format_debug_trace($backtrace);
402 $output = "\n
<br
/>\n<table cellpadding
=\"4\" cellspacing
=\"1\" border
=\"0\" width
=\"$width\" style
=\"background
-color
: $color; color
: black
; font
-family
: Verdana
, sans
-serif
; font
-size
: 12px
;\">";
403 $output .= "\n
<tr style
=\"color
: $font; text
-align
: left\"
>\n\t<td
><strong
>$prefix: $title</strong
></td
>\n</tr
>";
404 $output .= "\n
<tr style
=\"background
-color
: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
405 $output .= (($stack AND $GLOBALS['isso:callback']->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>" : '');
406 $output .= "\n</table>\n<br />\n";
418 // ###################################################################
420 * Prepares a debug_backtrace() array for output to the browser by
421 * compressing the array into visible text
423 * @param array debug_backtrace() array
425 * @return array Formatted trace output
427 public function format_debug_trace($backtrace)
430 foreach ($backtrace AS $i => $step)
433 $file = $step['file'] . ':' . $step['line'];
434 $funct = (isset($step['class']) ? $step['class'] . '::' . $step['function'] : $step['function']);
436 if (isset($step['args']) AND is_array($step['args']))
438 // we need to do this so we don't get "Array to string conversion" notices
439 foreach ($step['args'] AS $id => $arg)
443 $step['args']["$id"] = 'Array';
446 $args = implode(', ', $step['args']);
449 $trace[] = "#$i $funct($args) called at [$file]";
455 // ###################################################################
457 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
458 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
460 * @param integer Error number
461 * @param string Error message string
462 * @param string File that contains the error
463 * @param string The line number of the error
464 * @param string The active symbol table at which point the error occurred
466 public function _error_handler($errno, $errstr, $errfile, $errline, $errcontext)
468 $level = ini_get('error_reporting');
476 if (!($level & E_USER_ERROR
))
487 if (! (($level & E_USER_WARNING
) AND ($level & E_WARNING
)) )
499 if (! (($level & E_USER_NOTICE
) AND ($level & E_NOTICE
)) )
506 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
508 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
510 $this->message($title, $errstr, $mode);
512 if ($errno == E_USER_ERROR
)
518 // ###################################################################
520 * Creates a table that explains the error reporting levels and their
523 public function explain_error_reporting()
526 'E_ERROR' => E_ERROR
,
527 'E_WARNING' => E_WARNING
,
528 'E_PARSE' => E_PARSE
,
529 'E_NOTICE' => E_NOTICE
,
530 'E_CORE_ERROR' => E_CORE_ERROR
,
531 'E_CORE_WARNING' => E_CORE_WARNING
,
532 'E_COMPILE_ERROR' => E_COMPILE_ERROR
,
533 'E_COMPILE_WARNING' => E_COMPILE_WARNING
,
534 'E_USER_ERROR' => E_USER_ERROR
,
535 'E_USER_WARNING' => E_USER_WARNING
,
536 'E_USER_NOTICE' => E_USER_NOTICE
,
538 'E_STRICT' => E_STRICT
541 $table = '<table cellspacing="0" cellpadding="2" border="0">';
543 foreach ($levels AS $name => $value)
547 <td>' . $name . '</td>
548 <td>' . (ini_get('error_reporting') & $value) . '</td>
555 $this->message('Error Reporting', $table, 1);
558 // ###################################################################
560 * Logs a debug message for verbose output
562 * @param string Message
564 public function debug($message)
566 $this->debuginfo
[] = $message;
569 // ###################################################################
571 * Recursive XSS cleaner
573 * @param mixed Unsanitized REQUEST data
575 * @return mixed Sanitized data
577 public function _sanitize_input_recursive($data)
579 foreach ($data AS $key => $value)
581 if (is_array($value))
583 $data["$key"] = $this->_sanitize_input_recursive($value);
587 if ($this->magicquotes)
589 $value = str_replace("\'
", "'", $value);
591 $data["$key"] = $this->sanitize($value);
597 // ###################################################################
599 * Simple way to protect against HTML attacks with Unicode support
601 * @param string Unsanitzed text
603 * @return string Properly protected text that only encodes potential threats
605 public function sanitize($text)
607 if ($this->magicquotes)
609 return str_replace(array('<', '>', '\"
', '"'), array('<', '>', '"', '"'), $text);
613 return str_replace(array('<', '>', '"'), array('<
;', '>
;', '"
;'), $text);
617 // ###################################################################
619 * Unicode-safe entity encoding system; similar to sanitize()
621 * @param string Unsanitized text
623 * @return string Unicode-safe sanitized text with entities preserved
625 public function entity_encode($text)
627 $text = str_replace('&', '&
;', $text);
628 $text = $this->sanitize($text);
632 // ###################################################################
634 * Takes text that has been processed for HTML and unsanitizes it
636 * @param string Text that needs to be turned back into HTML
638 * @return string Unsanitized text
640 public function unsanitize($text)
642 return str_replace(array('<
;', '>
;', '"
;'), array('<', '>', '"'), $text);
645 // ###################################################################
647 * Smart addslashes() that only applies itself it the Magic Quotes GPC
648 * is off. This should only be run on database query values that come
649 * from ISSO->in[] input; data that needs sanitization should be run
650 * through ISSO->DB->escape_string()
652 * @param string Some string
653 * @param bool Force magic quotes to be off
655 * @return string String that has slashes added
657 public function escape($str, $force = true)
659 if ($this->magicquotes AND !$force)
661 if (isset($this->modules[ISSO_DB_LAYER]))
663 return $this->modules[ISSO_DB_LAYER]->escape_string(str_replace(array("\'
", '\"'), array("'", '"'), $str));
669 if (isset($this->modules[ISSO_DB_LAYER]))
671 return $this->modules[ISSO_DB_LAYER]->escape_string($str);
673 return addslashes($str);
677 // ###################################################################
679 * Runs through all of the input data and sanitizes it.
681 private function exec_sanitize_data()
683 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
686 // ###################################################################
688 * Sanitize function for something other than a string (which
689 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
690 * data is placed back into $isso->in; this makes it so you don't have
691 * to constantly intval() [etc.] data.
693 * @param array Array of elements to clean as varname => type
695 public function input_clean_array($vars)
697 foreach ($vars AS $varname => $type)
699 $this->input_clean($varname, $type);
703 // ###################################################################
705 * Sanitize function that does a single variable as oppoesd to an array
706 * (see input_clean_array() for more details)
708 * @param string Variable name in $isso->in[]
709 * @param integer Sanitization type constant
711 public function input_clean($varname, $type)
713 if (isset($this->in["$varname"]))
715 $this->in
["$varname"] = $this->clean($this->in["$varname"], $type);
719 $this->in
["$varname"] = $this->clean(null, $type);
722 return $this->in["$varname"];
725 // ###################################################################
727 * Runs ISSO->escape() on a variable on ISSO->in[]. This is just a
728 * short-hand wrapper so that queries can be shortened. When this is used,
729 * the actual value in ISSO->in[] is not changed, only the return value
732 * @param string Input variable
734 * @return string Escaped input
736 public function input_escape($varname)
738 if (isset($this->in
["$varname"]))
740 return $this->escape($this->in["$varname"]);
744 return $this->escape(null);
748 // ###################################################################
750 * Cleaning function that does the work for input_clean(); this is
751 * moved here so it can be used to clean things that aren't in
755 * @param integer Sanitization type constant
757 * @return mixed Cleaned data
759 public function clean($value, $type)
761 if (is_array($value))
763 return $this->clean_array($value, $type);
766 if ($type == TYPE_INT
)
768 $value = intval($value);
770 else if ($type == TYPE_UINT
)
772 $value = (($val = intval($value)) < 0 ? 0 : $val);
774 else if ($type == TYPE_FLOAT
)
776 $value = floatval($value);
778 else if ($type == TYPE_BOOL
)
780 $value = (bool)$value;
782 else if ($type == TYPE_STR
)
786 else if ($type == TYPE_STRUN
)
788 $value = $this->unsanitize($value);
790 else if ($type == TYPE_NOCLEAN
)
792 if ($this->magicquotes
)
794 $value = str_replace(array('\"', "\'"), array('"', "'"), $value);
801 else if ($type == TYPE_BIN
)
807 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR
);
813 // ###################################################################
815 * Recursion function for ISSO->clean()
817 * @param array Uncleaned array
818 * @param integer Sanitization type constant
820 * @return array Cleaned array of data
822 private function clean_array($array, $type)
824 foreach ($array AS $key => $value)
826 $array["$key"] = $this->clean($value, $type);
832 // ###################################################################
834 * Checks to see if a POST refer is actually from us
836 public function exec_referer_check()
838 if ($_SERVER['REQUEST_METHOD'] == 'POST')
840 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
842 if ($host AND $_SERVER['HTTP_REFERER'])
844 $parts = parse_url($_SERVER['HTTP_REFERER']);
845 $ourhost = $parts['host'] . (isset($parts['port']) ? ":$parts[port
]" : '');
847 if ($ourhost != $host)
849 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
851 $this->debug('remote post check = ok');
855 $this->debug('remote post check = FAILED');
860 // ###################################################################
862 * Constructs a debug information box that contains various debugging
865 * @param bool Show template information?
867 * @return string Debugging block
869 public function construct_debug_block($dotemplates)
882 foreach ($this->modules['template']->usage AS $name => $count)
884 if (in_array($name, $this->modules['template']->uncached))
886 $optlist[] = $name . '[' . $count . ']';
888 $usage[] = $name . " ($count)";
891 $sizeof = sizeof($this->modules['template']->uncached);
894 $debug .= "\n\t
<li
><strong style
=\"color
: red\"
>Uncached
Template(s
):</strong
> $sizeof ( " . implode(' ', $optlist) . " )</li
>";
899 $scinfo = 'Not Under Source Control';
902 $scinfo = constant('SVN');
904 if (preg_match('#\$Id:?\s*\$#', $scinfo))
906 $scinfo = 'Not Under Source Control';
910 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
911 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
912 $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);
916 $scinfo = trim($scinfo);
917 $debug .= "\n\t
<li
><strong
>Source Control
:</strong
> $scinfo</li
>";
920 if (is_object($this->modules[ISSO_DB_LAYER]))
922 $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
>";
925 // total execution time
926 if (defined('ISSO_MT_START'))
928 $this->load('functions', 'functions');
929 $debug .= "\n\t
<li
><strong
>Total Execution Time
:</strong
> " . round($this->modules['functions']->fetch_microtime_diff(ISSO_MT_START), 10) . "</li
>";
933 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Debug
Notices (" . sizeof($this->debuginfo) . ")</option
>";
934 foreach ((array)$this->debuginfo AS $msg)
936 $debug .= "\n\t\t\t
<option
>--- $msg</option
>";
938 $debug .= "\n\t\t
</select
>\n\t</li
>";
941 $modules = $this->show_modules(true);
942 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Loaded
Modules (" . sizeof($modules) . ")</option
>";
943 foreach ($modules AS $mod)
945 $debug .= "\n\t\t\t
<option
>--- $mod</option
>";
947 $debug .= "\n\t\t
</select
>\n\t</li
>";
952 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Template
Usage (" . array_sum($this->modules['template']->usage) . ")</option
>";
953 foreach ($usage AS $tpl)
955 $debug .= "\n\t\t\t
<option
>--- $tpl</option
>";
957 $debug .= "\n\t\t
</select
>\n\t</li
>";
962 $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";
969 /*=====================================================================*\
970 || ###################################################################
973 || ###################################################################
974 \*=====================================================================*/