]>
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 * Location of ISSO, used for internal linking
163 private $sourcepath = '';
166 * Path of the current application
169 private $apppath = '';
172 * Web path used to get the web location of the installation of ISSO; only used for Printer module
175 private $webpath = '';
178 * Name of the current application
181 private $application = '';
184 * Version of the current application
187 private $appversion = '';
190 * Whether debug mode is on or off
193 private $debug = false;
196 * List of all active debug messages
199 private $debuginfo = array();
202 * List of loaded modules
205 private $modules = array();
208 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
211 public $in = array();
214 * If we are running with magic_quotes_gpc on or off
217 private $magicquotes = 0;
220 * Array of user-specified fields that are required for ISSO initialization
221 * fieldname => array(REQUIRED, CALLBACK PARSER, SET)
224 private $fields = array(
225 'sourcepath' => array(REQ_YES
, 'fetch_sourcepath', false),
226 'apppath' => array(REQ_YES
, 'fetch_sourcepath', false),
227 'webpath' => array(REQ_NO
, 'fetch_sourcepath', false),
228 'application' => array(REQ_YES
, null, false),
229 'appversion' => array(REQ_NO
, null, false),
230 'debug' => array(REQ_NO
, null, false)
233 // ###################################################################
237 public function __construct()
239 $GLOBALS['isso:callback'] = null;
242 set_error_handler(array(&$this, '_error_handler'));
245 $this->magicquotes
= get_magic_quotes_gpc();
246 set_magic_quotes_runtime(0);
248 // some debug info that's always useful
249 $this->debug('magic_quotes_gpc = ' . $this->magicquotes
);
250 $this->debug('register_globals = ' . ini_get('register_globals'));
252 // attempt to set the sourcepath
253 $path = call_user_func('debug_backtrace');
254 $this->set('sourcepath', str_replace('kernel.php', '', $path[0]['file']));
256 // start input sanitize using variable_order GPC
257 if (!defined('ISSO_NO_INPUT_SANITIZE'))
259 $this->exec_sanitize_data();
262 if (defined('ISSO_CHECK_POST_REFERER'))
264 $this->exec_referer_check();
268 // ###################################################################
270 * Prepares a path for being set as the sourcepath
272 * @param string Source path or URL
274 * @return string Prepared source path
276 public function fetch_sourcepath($source)
278 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
280 $source .= DIRECTORY_SEPARATOR
;
285 // ###################################################################
287 * Loads a framework module
289 * @param string Name of the framework file to load
290 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
291 * @param bool Globalize the internal variable?
293 * @return object Instantiated instance
295 public function &load($framework, $asobject, $globalize = false)
297 $this->check_isso_fields(null);
299 // set the object interlock
300 if (!method_exists($GLOBALS['isso:callback'], 'load'))
302 $GLOBALS['isso:callback'] =& $this;
303 $this->modules
['isso'] =& $this;
306 if ($this->is_loaded($framework))
308 return $this->modules
["$framework"];
311 if ($this->sourcepath == '')
313 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
316 if (file_exists($this->sourcepath . $framework . '.php'))
318 require_once($this->sourcepath . $framework . '.php');
322 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
325 if ($asobject === null)
330 if (isset($this->$asobject))
332 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
335 $this->$asobject = new $framework($this);
337 $this->modules["$framework"] =& $this->$asobject;
341 $GLOBALS["$asobject"] =& $this->$asobject;
344 // allow for init_as_package to link
345 if (method_exists($this->modules["$framework"], 'init_as_package'))
347 $this->modules
[ $this->modules
["$framework"]->init_as_package() ] =& $this->modules["$framework"];
350 return $this->$asobject;
353 // ###################################################################
355 * Prints a list of all currently loaded framework modules
357 * @param bool Return the data as an array?
359 * @return mixed HTML output or an array of loaded modules
361 public function show_modules($return = false)
364 foreach ($this->modules
AS $object)
366 $module = get_class($object);
367 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
369 $module = $object->init_as_package() . " - ($module)";
372 $modules[] = $module;
381 $output = "\n\n<ul>\n\t<li>";
382 $output .= implode("</li>\n\t<li>", $modules);
383 $output .= "</li>\n</ul>\n\n";
384 $this->message('Loaded Modules', $output, 1);
388 // ###################################################################
390 * Verifies to see if a framework has been loaded
392 * @param string Framework name
394 * @return bool Whether or not the framework has been loaded
396 public function is_loaded($framework)
398 if (isset($this->modules
["$framework"]))
408 // ###################################################################
410 * Prints an ISSO message
412 * @param string The title of the message
413 * @param string The content of the message
414 * @param integer Type of message to be printed
415 * @param bool Return the output?
416 * @param bool Show the debug stack?
417 * @param integer Message width
419 * @return mixed Output or null
421 public function message($title, $message, $type, $return = false, $stack = true, $width = 500)
446 $backtrace = debug_backtrace();
447 array_shift($backtrace);
449 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
451 array_shift($backtrace);
454 $trace = $this->format_debug_trace($backtrace);
456 $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
;\">";
457 $output .= "\n
<tr style
=\"color
: $font; text
-align
: left\"
>\n\t<td
><strong
>$prefix: $title</strong
></td
>\n</tr
>";
458 $output .= "\n
<tr style
=\"background
-color
: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
459 $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>" : '');
460 $output .= "\n</table>\n<br />\n";
472 // ###################################################################
474 * Prepares a debug_backtrace() array for output to the browser by
475 * compressing the array into visible text
477 * @param array debug_backtrace() array
479 * @return array Formatted trace output
481 public function format_debug_trace($backtrace)
484 foreach ($backtrace AS $i => $step)
487 $file = $step['file'] . ':' . $step['line'];
488 $funct = (isset($step['class']) ? $step['class'] . '::' . $step['function'] : $step['function']);
490 if (isset($step['args']) AND is_array($step['args']))
492 // we need to do this so we don't get "Array to string conversion" notices
493 foreach ($step['args'] AS $id => $arg)
497 $step['args']["$id"] = 'Array';
500 $args = implode(', ', $step['args']);
503 $trace[] = "#$i $funct($args) called at [$file]";
509 // ###################################################################
511 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
512 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
514 * @param integer Error number
515 * @param string Error message string
516 * @param string File that contains the error
517 * @param string The line number of the error
518 * @param string The active symbol table at which point the error occurred
520 public function _error_handler($errno, $errstr, $errfile, $errline, $errcontext)
522 $level = ini_get('error_reporting');
530 if (!($level & E_USER_ERROR
))
541 if (! (($level & E_USER_WARNING
) AND ($level & E_WARNING
)) )
553 if (! (($level & E_USER_NOTICE
) AND ($level & E_NOTICE
)) )
560 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
562 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
564 $this->message($title, $errstr, $mode);
566 if ($errno == E_USER_ERROR
)
572 // ###################################################################
574 * Creates a table that explains the error reporting levels and their
577 public function explain_error_reporting()
580 'E_ERROR' => E_ERROR
,
581 'E_WARNING' => E_WARNING
,
582 'E_PARSE' => E_PARSE
,
583 'E_NOTICE' => E_NOTICE
,
584 'E_CORE_ERROR' => E_CORE_ERROR
,
585 'E_CORE_WARNING' => E_CORE_WARNING
,
586 'E_COMPILE_ERROR' => E_COMPILE_ERROR
,
587 'E_COMPILE_WARNING' => E_COMPILE_WARNING
,
588 'E_USER_ERROR' => E_USER_ERROR
,
589 'E_USER_WARNING' => E_USER_WARNING
,
590 'E_USER_NOTICE' => E_USER_NOTICE
,
592 'E_STRICT' => E_STRICT
595 $table = '<table cellspacing="0" cellpadding="2" border="0">';
597 foreach ($levels AS $name => $value)
601 <td>' . $name . '</td>
602 <td>' . (ini_get('error_reporting') & $value) . '</td>
609 $this->message('Error Reporting', $table, 1);
612 // ###################################################################
614 * Logs a debug message for verbose output
616 * @param string Message
618 public function debug($message)
620 $this->debuginfo
[] = $message;
623 // ###################################################################
625 * Recursive XSS cleaner
627 * @param mixed Unsanitized REQUEST data
629 * @return mixed Sanitized data
631 public function _sanitize_input_recursive($data)
633 foreach ($data AS $key => $value)
635 if (is_array($value))
637 $data["$key"] = $this->_sanitize_input_recursive($value);
641 if ($this->magicquotes)
643 $value = str_replace("\'
", "'", $value);
645 $data["$key"] = $this->sanitize($value);
651 // ###################################################################
653 * Simple way to protect against HTML attacks with Unicode support
655 * @param string Unsanitzed text
657 * @return string Properly protected text that only encodes potential threats
659 public function sanitize($text)
661 if ($this->magicquotes)
663 return str_replace(array('<', '>', '\"
', '"'), array('<', '>', '"', '"'), $text);
667 return str_replace(array('<', '>', '"'), array('<
;', '>
;', '"
;'), $text);
671 // ###################################################################
673 * Unicode-safe entity encoding system; similar to sanitize()
675 * @param string Unsanitized text
677 * @return string Unicode-safe sanitized text with entities preserved
679 public function entity_encode($text)
681 $text = str_replace('&', '&
;', $text);
682 $text = $this->sanitize($text);
686 // ###################################################################
688 * Takes text that has been processed for HTML and unsanitizes it
690 * @param string Text that needs to be turned back into HTML
692 * @return string Unsanitized text
694 public function unsanitize($text)
696 return str_replace(array('<
;', '>
;', '"
;'), array('<', '>', '"'), $text);
699 // ###################################################################
701 * Smart addslashes() that only applies itself it the Magic Quotes GPC
702 * is off. This should only be run on database query values that come
703 * from ISSO->in[] input; data that needs sanitization should be run
704 * through ISSO->DB->escape_string()
706 * @param string Some string
707 * @param bool Force magic quotes to be off
709 * @return string String that has slashes added
711 public function escape($str, $force = true)
713 if ($this->magicquotes AND !$force)
715 if (isset($this->modules[ISSO_DB_LAYER]))
717 return $this->modules[ISSO_DB_LAYER]->escape_string(str_replace(array("\'
", '\"'), array("'", '"'), $str));
723 if (isset($this->modules[ISSO_DB_LAYER]))
725 return $this->modules[ISSO_DB_LAYER]->escape_string($str);
727 return addslashes($str);
731 // ###################################################################
733 * Runs through all of the input data and sanitizes it.
735 private function exec_sanitize_data()
737 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
740 // ###################################################################
742 * Sanitize function for something other than a string (which
743 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
744 * data is placed back into $isso->in; this makes it so you don't have
745 * to constantly intval() [etc.] data.
747 * @param array Array of elements to clean as varname => type
749 public function input_clean_array($vars)
751 foreach ($vars AS $varname => $type)
753 $this->input_clean($varname, $type);
757 // ###################################################################
759 * Sanitize function that does a single variable as oppoesd to an array
760 * (see input_clean_array() for more details)
762 * @param string Variable name in $isso->in[]
763 * @param integer Sanitization type constant
765 public function input_clean($varname, $type)
767 if (isset($this->in["$varname"]))
769 $this->in
["$varname"] = $this->clean($this->in["$varname"], $type);
773 $this->in
["$varname"] = $this->clean(null, $type);
776 return $this->in["$varname"];
779 // ###################################################################
781 * Runs ISSO->escape() on a variable on ISSO->in[]. This is just a
782 * short-hand wrapper so that queries can be shortened. When this is used,
783 * the actual value in ISSO->in[] is not changed, only the return value
786 * @param string Input variable
788 * @return string Escaped input
790 public function input_escape($varname)
792 if (isset($this->in
["$varname"]))
794 return $this->escape($this->in["$varname"]);
798 return $this->escape(null);
802 // ###################################################################
804 * Cleaning function that does the work for input_clean(); this is
805 * moved here so it can be used to clean things that aren't in
809 * @param integer Sanitization type constant
811 * @return mixed Cleaned data
813 public function clean($value, $type)
815 if (is_array($value))
817 return $this->clean_array($value, $type);
820 if ($type == TYPE_INT
)
822 $value = intval($value);
824 else if ($type == TYPE_UINT
)
826 $value = (($val = intval($value)) < 0 ? 0 : $val);
828 else if ($type == TYPE_FLOAT
)
830 $value = floatval($value);
832 else if ($type == TYPE_BOOL
)
834 $value = (bool)$value;
836 else if ($type == TYPE_STR
)
840 else if ($type == TYPE_STRUN
)
842 $value = $this->unsanitize($value);
844 else if ($type == TYPE_NOCLEAN
)
846 if ($this->magicquotes
)
848 $value = str_replace(array('\"', "\'"), array('"', "'"), $value);
855 else if ($type == TYPE_BIN
)
861 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR
);
867 // ###################################################################
869 * Recursion function for ISSO->clean()
871 * @param array Uncleaned array
872 * @param integer Sanitization type constant
874 * @return array Cleaned array of data
876 private function clean_array($array, $type)
878 foreach ($array AS $key => $value)
880 $array["$key"] = $this->clean($value, $type);
886 // ###################################################################
888 * Checks to see if a POST refer is actually from us
890 public function exec_referer_check()
892 if ($_SERVER['REQUEST_METHOD'] == 'POST')
894 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
896 if ($host AND $_SERVER['HTTP_REFERER'])
898 $parts = parse_url($_SERVER['HTTP_REFERER']);
899 $ourhost = $parts['host'] . (isset($parts['port']) ? ":$parts[port
]" : '');
901 if ($ourhost != $host)
903 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
905 $this->debug('remote post check = ok');
909 $this->debug('remote post check = FAILED');
914 // ###################################################################
916 * Constructs a debug information box that contains various debugging
919 * @param bool Show template information?
921 * @return string Debugging block
923 public function construct_debug_block($dotemplates)
936 foreach ($this->modules['template']->usage AS $name => $count)
938 if (in_array($name, $this->modules['template']->uncached))
940 $optlist[] = $name . '[' . $count . ']';
942 $usage[] = $name . " ($count)";
945 $sizeof = sizeof($this->modules['template']->uncached);
948 $debug .= "\n\t
<li
><strong style
=\"color
: red\"
>Uncached
Template(s
):</strong
> $sizeof ( " . implode(' ', $optlist) . " )</li
>";
953 $scinfo = 'Not Under Source Control';
956 $scinfo = constant('SVN');
958 if (preg_match('#\$Id:?\s*\$#', $scinfo))
960 $scinfo = 'Not Under Source Control';
964 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
965 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
966 $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);
970 $scinfo = trim($scinfo);
971 $debug .= "\n\t
<li
><strong
>Source Control
:</strong
> $scinfo</li
>";
974 if (is_object($this->modules[ISSO_DB_LAYER]))
976 $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
>";
979 // total execution time
980 if (defined('ISSO_MT_START'))
982 $this->load('functions', 'functions');
983 $debug .= "\n\t
<li
><strong
>Total Execution Time
:</strong
> " . round($this->modules['functions']->fetch_microtime_diff(ISSO_MT_START), 10) . "</li
>";
987 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Debug
Notices (" . sizeof($this->debuginfo) . ")</option
>";
988 foreach ((array)$this->debuginfo AS $msg)
990 $debug .= "\n\t\t\t
<option
>--- $msg</option
>";
992 $debug .= "\n\t\t
</select
>\n\t</li
>";
995 $modules = $this->show_modules(true);
996 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Loaded
Modules (" . sizeof($modules) . ")</option
>";
997 foreach ($modules AS $mod)
999 $debug .= "\n\t\t\t
<option
>--- $mod</option
>";
1001 $debug .= "\n\t\t
</select
>\n\t</li
>";
1006 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Template
Usage (" . array_sum($this->modules['template']->usage) . ")</option
>";
1007 foreach ($usage AS $tpl)
1009 $debug .= "\n\t\t\t
<option
>--- $tpl</option
>";
1011 $debug .= "\n\t\t
</select
>\n\t</li
>";
1014 $debug .= "\n
</ul
>";
1016 $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";
1023 /*=====================================================================*\
1024 || ###################################################################
1027 || ###################################################################
1028 \*=====================================================================*/