2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)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('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 if ((bool
)ini_get('register_globals') === true
)
50 $superglobals = array('_GET', '_COOKIE', '_FILES', '_POST', '_SERVER', '_ENV');
51 foreach ($superglobals AS $global)
53 if (is_array($
{$global}))
55 foreach ($
{$global} AS $_key => $_val)
66 $oldlevel = ini_get('error_reporting');
67 $newlevel = $oldlevel;
68 $levels = array(E_ERROR
=> E_USER_ERROR
, E_WARNING
=> E_USER_WARNING
, E_NOTICE
=> E_USER_NOTICE
);
69 foreach ($levels AS $php => $isso)
73 if (!($oldlevel & $isso))
80 if ($oldlevel & $isso)
86 error_reporting($newlevel);
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);
127 * Duplicate of TYPE_NOCLEAN, but shorter
129 define('TYPE_NONE', TYPE_NOCLEAN
);
132 * Macro for using DB->escape_binary() without cleaning - used in API
134 define('TYPE_BIN', 128);
140 define('REQ_YES', 1);
148 * Blue Static ISSO Framework (ISSO)
150 * This framework allows a common backend to be used amongst all Blue
151 * Static applications and is built to be abstract and flexible.
152 * The base framework handles all loading and module management.
155 * ISSO_NO_INPUT_SANITIZE - Disables the automatic input sanitizer
156 * ISSO_CHECK_POST_REFERER - Will check to make sure that on POSTed
157 * data, the referer matches the host
158 * ISSO_MT_START - Define the microtime() value at the top of your
159 * script and this will calculate the total execution
161 * SVN - Place SVN keywords (like $Id) to display the information on output
163 * @author Blue Static
164 * @copyright Copyright (c)2002 - [#]year[#], Blue Static
165 * @version $Revision$
172 * Location of ISSO, used for internal linking
176 var $sourcepath = '';
179 * Path of the current application
186 * Web path used to get the web location of the installation of ISSO; only used for Printer module
193 * Name of the current application
197 var $application = '';
200 * Version of the current application
204 var $appversion = '';
207 * Whether debug mode is on or off
214 * List of all active debug messages
218 var $debuginfo = array();
221 * List of loaded modules
225 var $modules = array();
228 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
235 * If we are running with magic_quotes_gpc on or off
239 var $magicquotes = 0;
241 // ###################################################################
245 function __construct()
247 $GLOBALS['isso:callback'] = null
;
250 set_error_handler(array(&$this, '_error_handler'));
253 $this->magicquotes
= get_magic_quotes_gpc();
254 set_magic_quotes_runtime(0);
256 // some debug info that's always useful
257 $this->debug('magic_quotes_gpc = ' . $this->magicquotes
);
258 $this->debug('register_globals = ' . ini_get('register_globals'));
260 // attempt to set the sourcepath
261 $path = call_user_func('debug_backtrace');
262 $this->setSourcePath(str_replace('kernel.php', '', $path[0]['file']));
264 // start input sanitize using variable_order GPC
265 if (!defined('ISSO_NO_INPUT_SANITIZE'))
267 $this->exec_sanitize_data();
270 if (defined('ISSO_CHECK_POST_REFERER'))
272 $this->exec_referer_check();
276 // ###################################################################
278 * (PHP 4) Constructor
282 $this->__construct();
285 // ###################################################################
287 * Sets the sourcepath
291 * @param string Source path
293 function setSourcePath($path)
295 $this->sourcepath
= $this->fetch_sourcepath($path);
298 // ###################################################################
300 * Gets the sourcepath
304 * @return string Source path
306 function getSourcePath()
308 return $this->sourcepath
;
311 // ###################################################################
317 * @param string Application path
319 function setAppPath($path)
321 $this->apppath
= $this->fetch_sourcepath($path);
324 // ###################################################################
330 * @return string Source path
332 function getAppPath()
334 return $this->apppath
;
337 // ###################################################################
343 * @param string Web path
345 function setWebPath($path)
347 $this->webpath
= $this->fetch_sourcepath($path);
350 // ###################################################################
356 * @return string Web path
358 function getWebPath()
360 return $this->webpath
;
363 // ###################################################################
365 * Sets the applicaiton
369 * @param string Applicaiton
371 function setApplication($app)
373 $this->application
= $app;
376 // ###################################################################
378 * Gets the application
382 * @return string Application
384 function getApplication()
386 return $this->application
;
389 // ###################################################################
391 * Sets the appverison
395 * @param string Applicaiton version
397 function setAppVersion($version)
399 $this->appversion
= $version;
402 // ###################################################################
404 * Gets the appversion
408 * @return string Application version
410 function getAppVersion()
412 return $this->appversion
;
415 // ###################################################################
421 * @param boolean Debug?
423 function setDebug($debug)
425 $this->debug
= $debug;
428 // ###################################################################
430 * Gets debug mode state
434 * @return boolean Debug?
441 // ###################################################################
443 * Prepares a path for being set as the sourcepath
447 * @param string Source path or URL
449 * @return string Prepared source path
451 function fetch_sourcepath($source)
453 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
455 $source .= DIRECTORY_SEPARATOR
;
460 // ###################################################################
462 * Loads a framework module
466 * @param string Name of the framework file to load
467 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
468 * @param bool Globalize the internal variable?
470 * @return object Instantiated instance
472 function &load($framework, $asobject, $globalize = false
)
474 // set the object interlock
475 if (!method_exists($GLOBALS['isso:callback'], 'load'))
477 $GLOBALS['isso:callback'] =& $this;
478 $this->modules
['isso'] =& $this;
481 if ($this->is_loaded($framework))
483 return $this->modules
["$framework"];
486 if ($this->sourcepath
== '')
488 trigger_error('Invalid sourcepath specified', E_USER_ERROR
);
491 if (file_exists($this->sourcepath
. $framework . '.php'))
493 require_once($this->sourcepath
. $framework . '.php');
497 trigger_error('Could not find the framework ' . $this->sourcepath
. $framework . '.php', E_USER_ERROR
);
500 if ($asobject === null
)
505 if (isset($this->$asobject))
507 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR
);
510 $this->$asobject = new $framework($this);
512 $this->modules
["$framework"] =& $this->$asobject;
516 $GLOBALS["$asobject"] =& $this->$asobject;
519 // allow for init_as_package to link
520 if (method_exists($this->modules
["$framework"], 'init_as_package'))
522 $this->modules
[ $this->modules
["$framework"]->init_as_package() ] =& $this->modules
["$framework"];
525 return $this->$asobject;
528 // ###################################################################
530 * Prints a list of all currently loaded framework modules
534 * @param bool Return the data as an array?
536 * @return mixed HTML output or an array of loaded modules
538 function show_modules($return = false
)
541 foreach ($this->modules
AS $object)
543 $module = get_class($object);
544 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
546 $module = $object->init_as_package() . " - ($module)";
549 $modules[] = $module;
558 $output = "\n\n<ul>\n\t<li>";
559 $output .= implode("</li>\n\t<li>", $modules);
560 $output .= "</li>\n</ul>\n\n";
561 $this->message('Loaded Modules', $output, 1);
565 // ###################################################################
567 * Verifies to see if a framework has been loaded
571 * @param string Framework name
573 * @return bool Whether or not the framework has been loaded
575 function is_loaded($framework)
577 if (isset($this->modules
["$framework"]))
587 // ###################################################################
589 * Prints an ISSO message
593 * @param string The title of the message
594 * @param string The content of the message
595 * @param integer Type of message to be printed
596 * @param bool Return the output?
597 * @param bool Show the debug stack?
598 * @param integer Message width
600 * @return mixed Output or null
602 function message($title, $message, $type, $return = false
, $stack = true
, $width = 500)
627 $backtrace = debug_backtrace();
628 array_shift($backtrace);
630 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
632 array_shift($backtrace);
635 $trace = $this->format_debug_trace($backtrace);
637 $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;\">";
638 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
639 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
640 $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>" : '');
641 $output .= "\n</table>\n<br />\n";
653 // ###################################################################
655 * Prepares a debug_backtrace() array for output to the browser by
656 * compressing the array into visible text
660 * @param array debug_backtrace() array
662 * @return array Formatted trace output
664 function format_debug_trace($backtrace)
667 foreach ($backtrace AS $i => $step)
670 $file = $step['file'] . ':' . $step['line'];
671 $funct = (isset($step['class']) ?
$step['class'] . '::' . $step['function'] : $step['function']);
673 if (isset($step['args']) AND is_array($step['args']))
675 // we need to do this so we don't get "Array to string conversion" notices
676 foreach ($step['args'] AS $id => $arg)
680 $step['args']["$id"] = 'Array';
683 $args = implode(', ', $step['args']);
686 $trace[] = "#$i $funct($args) called at [$file]";
692 // ###################################################################
694 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
695 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
699 * @param integer Error number
700 * @param string Error message string
701 * @param string File that contains the error
702 * @param string The line number of the error
703 * @param string The active symbol table at which point the error occurred
705 function _error_handler($errno, $errstr, $errfile, $errline, $errcontext)
707 $level = ini_get('error_reporting');
715 if (!($level & E_USER_ERROR
))
726 if (! (($level & E_USER_WARNING
) AND ($level & E_WARNING
)) )
738 if (! (($level & E_USER_NOTICE
) AND ($level & E_NOTICE
)) )
745 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
747 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
749 $this->message($title, $errstr, $mode);
751 if ($errno == E_USER_ERROR
)
757 // ###################################################################
759 * Creates a table that explains the error reporting levels and their
764 function explain_error_reporting()
767 'E_ERROR' => E_ERROR
,
768 'E_WARNING' => E_WARNING
,
769 'E_PARSE' => E_PARSE
,
770 'E_NOTICE' => E_NOTICE
,
771 'E_CORE_ERROR' => E_CORE_ERROR
,
772 'E_CORE_WARNING' => E_CORE_WARNING
,
773 'E_COMPILE_ERROR' => 64,
774 'E_COMPILE_WARNING' => 128,
775 'E_USER_ERROR' => E_USER_ERROR
,
776 'E_USER_WARNING' => E_USER_WARNING
,
777 'E_USER_NOTICE' => E_USER_NOTICE
,
782 $table = '<table cellspacing="0" cellpadding="2" border="0">';
784 foreach ($levels AS $name => $value)
788 <td>' . $name . '</td>
789 <td>' . (ini_get('error_reporting') & $value) . '</td>
796 $this->message('Error Reporting', $table, 1);
799 // ###################################################################
801 * Logs a debug message for verbose output
805 * @param string Message
807 function debug($message)
809 $this->debuginfo
[] = $message;
812 // ###################################################################
814 * Recursive XSS cleaner
818 * @param mixed Unsanitized REQUEST data
820 * @return mixed Sanitized data
822 function _sanitize_input_recursive($data)
824 foreach ($data AS $key => $value)
826 if (is_array($value))
828 $data["$key"] = $this->_sanitize_input_recursive($value);
832 if ($this->magicquotes
)
834 $value = str_replace("\'", "'", $value);
836 $data["$key"] = $this->sanitize($value);
842 // ###################################################################
844 * Simple way to protect against HTML attacks with Unicode support
848 * @param string Unsanitzed text
850 * @return string Properly protected text that only encodes potential threats
852 function sanitize($text)
854 if ($this->magicquotes
)
856 return str_replace(array('<', '>', '\"', '"'), array('<', '>', '"', '"'), $text);
860 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
864 // ###################################################################
866 * Unicode-safe entity encoding system; similar to sanitize()
870 * @param string Unsanitized text
872 * @return string Unicode-safe sanitized text with entities preserved
874 function entity_encode($text)
876 $text = str_replace('&', '&', $text);
877 $text = $this->sanitize($text);
881 // ###################################################################
883 * Takes text that has been processed for HTML and unsanitizes it
887 * @param string Text that needs to be turned back into HTML
889 * @return string Unsanitized text
891 function unsanitize($text)
893 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
896 // ###################################################################
898 * Smart addslashes() that only applies itself it the Magic Quotes GPC
899 * is off. This should only be run on database query values that come
900 * from ISSO->in[] input; data that needs sanitization should be run
901 * through ISSO->DB->escape_string()
905 * @param string Some string
906 * @param bool Force magic quotes to be off
908 * @return string String that has slashes added
910 function escape($str, $force = true
)
912 if ($this->magicquotes
AND !$force)
914 if (isset($this->modules
[ISSO_DB_LAYER
]))
916 return $this->modules
[ISSO_DB_LAYER
]->escape_string(str_replace(array("\'", '\"'), array("'", '"'), $str));
922 if (isset($this->modules
[ISSO_DB_LAYER
]))
924 return $this->modules
[ISSO_DB_LAYER
]->escape_string($str);
926 return addslashes($str);
930 // ###################################################################
932 * Runs through all of the input data and sanitizes it.
936 function exec_sanitize_data()
938 $this->in
= $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
941 // ###################################################################
943 * Sanitize function for something other than a string (which
944 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
945 * data is placed back into $isso->in; this makes it so you don't have
946 * to constantly intval() [etc.] data.
950 * @param array Array of elements to clean as varname => type
952 function input_clean_array($vars)
954 foreach ($vars AS $varname => $type)
956 $this->input_clean($varname, $type);
960 // ###################################################################
962 * Sanitize function that does a single variable as oppoesd to an array
963 * (see input_clean_array() for more details)
967 * @param string Variable name in $isso->in[]
968 * @param integer Sanitization type constant
970 function input_clean($varname, $type)
972 if (isset($this->in
["$varname"]))
974 $this->in
["$varname"] = $this->clean($this->in
["$varname"], $type);
978 $this->in
["$varname"] = $this->clean(null
, $type);
981 return $this->in
["$varname"];
984 // ###################################################################
986 * Runs ISSO->escape() on a variable on ISSO->in[]. This is just a
987 * short-hand wrapper so that queries can be shortened. When this is used,
988 * the actual value in ISSO->in[] is not changed, only the return value
993 * @param string Input variable
995 * @return string Escaped input
997 function input_escape($varname)
999 if (isset($this->in
["$varname"]))
1001 return $this->escape($this->in
["$varname"]);
1005 return $this->escape(null
);
1009 // ###################################################################
1011 * Cleaning function that does the work for input_clean(); this is
1012 * moved here so it can be used to clean things that aren't in
1018 * @param integer Sanitization type constant
1020 * @return mixed Cleaned data
1022 function clean($value, $type)
1024 if (is_array($value))
1026 return $this->clean_array($value, $type);
1029 if ($type == TYPE_INT
)
1031 $value = intval($value);
1033 else if ($type == TYPE_UINT
)
1035 $value = (($val = intval($value)) < 0 ?
0 : $val);
1037 else if ($type == TYPE_FLOAT
)
1039 $value = floatval($value);
1041 else if ($type == TYPE_BOOL
)
1043 $value = (bool
)$value;
1045 else if ($type == TYPE_STR
)
1049 else if ($type == TYPE_STRUN
)
1051 $value = $this->unsanitize($value);
1053 else if ($type == TYPE_NOCLEAN
)
1055 if ($this->magicquotes
)
1057 $value = str_replace(array('\"', "\'"), array('"', "'"), $value);
1064 else if ($type == TYPE_BIN
)
1070 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR
);
1076 // ###################################################################
1078 * Recursion function for ISSO->clean()
1082 * @param array Uncleaned array
1083 * @param integer Sanitization type constant
1085 * @return array Cleaned array of data
1087 function clean_array($array, $type)
1089 foreach ($array AS $key => $value)
1091 $array["$key"] = $this->clean($value, $type);
1097 // ###################################################################
1099 * Checks to see if a POST refer is actually from us
1103 function exec_referer_check()
1105 if ($_SERVER['REQUEST_METHOD'] == 'POST')
1107 $host = ($_SERVER['HTTP_HOST']) ?
$_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
1109 if ($host AND $_SERVER['HTTP_REFERER'])
1111 $parts = parse_url($_SERVER['HTTP_REFERER']);
1112 $ourhost = $parts['host'] . (isset($parts['port']) ?
":$parts[port]" : '');
1114 if ($ourhost != $host)
1116 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR
);
1118 $this->debug('remote post check = ok');
1122 $this->debug('remote post check = FAILED');
1127 // ###################################################################
1129 * Constructs a debug information box that contains various debugging
1130 * information points
1134 * @param bool Show template information?
1136 * @return string Debugging block
1138 function construct_debug_block($dotemplates)
1151 foreach ($this->modules
['template']->usage
AS $name => $count)
1153 if (in_array($name, $this->modules
['template']->uncached
))
1155 $optlist[] = $name . '[' . $count . ']';
1157 $usage[] = $name . " ($count)";
1160 $sizeof = sizeof($this->modules
['template']->uncached
);
1163 $debug .= "\n\t<li><strong style=\"color: red\">Uncached Template(s):</strong> $sizeof ( " . implode(' ', $optlist) . " )</li>";
1168 $scinfo = 'Not Under Source Control';
1171 $scinfo = constant('SVN');
1173 if (preg_match('#\$Id:?\s*\$#', $scinfo))
1175 $scinfo = 'Not Under Source Control';
1179 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
1180 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
1181 $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);
1185 $scinfo = trim($scinfo);
1186 $debug .= "\n\t<li><strong>Source Control:</strong> $scinfo</li>";
1188 // query information
1189 if (is_object($this->modules
[ISSO_DB_LAYER
]))
1191 $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>";
1193 $queries = $this->modules
[ISSO_DB_LAYER
]->history
;
1194 $querydebug = "<br />\n" . '<table cellpadding="4" cellspacing="1" border="0" align="center" width="30%" style="background-color: rgb(60, 60, 60); color: white">' . "\n\t" . '<tr><td><strong>Query Debug</strong></td></tr>';
1195 foreach ($queries AS $query)
1197 $querydebug .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
1198 $querydebug .= "\n\t\t<td>";
1199 $querydebug .= "\n\t\t\t$query[query]\n\n\t\t\t<div style=\"font-size: 9px;\">($query[time])</div>\n<!--\n" . implode("\n", $query[trace
]) . "\n-->\n\t\t</td>\n\t</tr>";
1202 $querydebug .= "\n</table>\n\n\n";
1205 // total execution time
1206 if (defined('ISSO_MT_START'))
1208 $this->load('functions', 'functions');
1209 $debug .= "\n\t<li><strong>Total Execution Time:</strong> " . round($this->modules
['functions']->fetch_microtime_diff(ISSO_MT_START
), 10) . "</li>";
1213 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Debug Notices (" . sizeof($this->debuginfo
) . ")</option>";
1214 foreach ((array)$this->debuginfo
AS $msg)
1216 $debug .= "\n\t\t\t<option>--- $msg</option>";
1218 $debug .= "\n\t\t</select>\n\t</li>";
1221 $modules = $this->show_modules(true
);
1222 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Loaded Modules (" . sizeof($modules) . ")</option>";
1223 foreach ($modules AS $mod)
1225 $debug .= "\n\t\t\t<option>--- $mod</option>";
1227 $debug .= "\n\t\t</select>\n\t</li>";
1232 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Template Usage (" . array_sum($this->modules
['template']->usage
) . ")</option>";
1233 foreach ($usage AS $tpl)
1235 $debug .= "\n\t\t\t<option>--- $tpl</option>";
1237 $debug .= "\n\t\t</select>\n\t</li>";
1240 $debug .= "\n</ul>";
1242 $debug = "\n\n<!-- dev debug -->\n<div align=\"center\">\n\n<hr />\n" . $this->message('Debug Information', $debug, 1, true
, false
) . "\n</div>$querydebug\n<!-- / dev debug -->\n\n";