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 // when we are PHP5-nat instead of PHP5-compat, we can remove this
30 if (version_compare(PHP_VERSION
, '5.0.0', '>='))
32 if (ini_get('error_reporting') & E_NOTICE
)
34 error_reporting(ini_get('error_reporting') - E_NOTICE
);
36 if (ini_get('error_reporting') & E_USER_NOTICE
)
38 error_reporting(ini_get('error_reporting') - E_USER_NOTICE
);
42 $oldlevel = ini_get('error_reporting');
43 $newlevel = $oldlevel;
44 $levels = array(E_ERROR
=> E_USER_ERROR
, E_WARNING
=> E_USER_WARNING
, E_NOTICE
=> E_USER_NOTICE
);
45 foreach ($levels AS $php => $isso)
49 if (!($oldlevel & $isso))
56 if ($oldlevel & $isso)
62 error_reporting($newlevel);
65 * Input cleaning type constant
70 define('TYPE_INT', 1);
75 define('TYPE_UINT', 2);
80 define('TYPE_FLOAT', 4);
85 define('TYPE_BOOL', 8);
90 define('TYPE_STR', 16);
93 * String - deliberate unclean
95 define('TYPE_STRUN', 32);
98 * No cleaning - here for use in API
100 define('TYPE_NOCLEAN', 64);
103 * Duplicate of TYPE_NOCLEAN, but shorter
105 define('TYPE_NONE', TYPE_NOCLEAN
);
108 * Macro for using DB->escape_binary() without cleaning - used in API
110 define('TYPE_BIN', 128);
116 define('REQ_YES', 1);
124 * Blue Static ISSO Framework (ISSO)
126 * This framework allows a common backend to be used amongst all Blue
127 * Static applications and is built to be abstract and flexible.
128 * The base framework handles all loading and module management.
131 * ISSO_NO_INPUT_SANITIZE - Disables the automatic input sanitizer
132 * ISSO_CHECK_POST_REFERER - Will check to make sure that on POSTed
133 * data, the referer matches the host
134 * ISSO_MT_START - Define the microtime() value at the top of your
135 * script and this will calculate the total execution
137 * ISSO_MEMORY_START - The result of memory_get_usage(true) at the start of
139 * SVN - Place SVN keywords (like $Id) to display the information on output
141 * @author Blue Static
142 * @copyright Copyright (c)2002 - [#]year[#], Blue Static
143 * @version $Revision$
150 * Location of ISSO, used for internal linking
154 var $sourcepath = '';
157 * Path of the current application
164 * Web path used to get the web location of the installation of ISSO; only used for Printer module
171 * Name of the current application
175 var $application = '';
178 * Version of the current application
182 var $appversion = '';
185 * Whether debug mode is on or off
192 * List of all active debug messages
196 var $debuginfo = array();
199 * List of loaded modules
203 var $modules = array();
206 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
212 // ###################################################################
216 function __construct()
218 $GLOBALS['isso:callback'] = null
;
221 set_error_handler(array(&$this, '_error_handler'));
223 // attempt to set the sourcepath
224 $path = call_user_func('debug_backtrace');
225 $this->setSourcePath(str_replace('kernel.php', '', $path[0]['file']));
227 // start input sanitize using variable_order GPC
228 if (!defined('ISSO_NO_INPUT_SANITIZE'))
230 $this->exec_sanitize_data();
233 if (defined('ISSO_CHECK_POST_REFERER'))
235 $this->exec_referer_check();
239 // ###################################################################
241 * (PHP 4) Constructor
245 $this->__construct();
248 // ###################################################################
250 * Sets the sourcepath
254 * @param string Source path
256 function setSourcePath($path)
258 $this->sourcepath
= $this->fetch_sourcepath($path);
261 // ###################################################################
263 * Gets the sourcepath
267 * @return string Source path
269 function getSourcePath()
271 return $this->sourcepath
;
274 // ###################################################################
280 * @param string Application path
282 function setAppPath($path)
284 $this->apppath
= $this->fetch_sourcepath($path);
287 // ###################################################################
293 * @return string Source path
295 function getAppPath()
297 return $this->apppath
;
300 // ###################################################################
306 * @param string Web path
308 function setWebPath($path)
310 $this->webpath
= $this->fetch_sourcepath($path);
313 // ###################################################################
319 * @return string Web path
321 function getWebPath()
323 return $this->webpath
;
326 // ###################################################################
328 * Sets the applicaiton
332 * @param string Applicaiton
334 function setApplication($app)
336 $this->application
= $app;
339 // ###################################################################
341 * Gets the application
345 * @return string Application
347 function getApplication()
349 return $this->application
;
352 // ###################################################################
354 * Sets the appverison
358 * @param string Applicaiton version
360 function setAppVersion($version)
362 $this->appversion
= $version;
365 // ###################################################################
367 * Gets the appversion
371 * @return string Application version
373 function getAppVersion()
375 return $this->appversion
;
378 // ###################################################################
384 * @param boolean Debug?
386 function setDebug($debug)
388 $this->debug
= $debug;
391 // ###################################################################
393 * Gets debug mode state
397 * @return boolean Debug?
404 // ###################################################################
406 * Prepares a path for being set as the sourcepath
410 * @param string Source path or URL
412 * @return string Prepared source path
414 function fetch_sourcepath($source)
416 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
418 $source .= DIRECTORY_SEPARATOR
;
423 // ###################################################################
425 * Loads a framework module
429 * @param string Name of the framework file to load
430 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
431 * @param bool Globalize the internal variable?
433 * @return object Instantiated instance
435 function &load($framework, $asobject, $globalize = false
)
437 // set the object interlock
438 if (!method_exists($GLOBALS['isso:callback'], 'load'))
440 $GLOBALS['isso:callback'] =& $this;
441 $this->modules
['isso'] =& $this;
444 if ($this->is_loaded($framework))
446 return $this->modules
["$framework"];
449 if ($this->sourcepath
== '')
451 trigger_error('Invalid sourcepath specified', E_USER_ERROR
);
454 if (file_exists($this->sourcepath
. $framework . '.php'))
456 require_once($this->sourcepath
. $framework . '.php');
460 trigger_error('Could not find the framework ' . $this->sourcepath
. $framework . '.php', E_USER_ERROR
);
463 if ($asobject === null
)
468 if (isset($this->$asobject))
470 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR
);
473 $this->$asobject = new $framework($this);
475 $this->modules
["$framework"] =& $this->$asobject;
479 $GLOBALS["$asobject"] =& $this->$asobject;
482 // allow for init_as_package to link
483 if (method_exists($this->modules
["$framework"], 'init_as_package'))
485 $this->modules
[ $this->modules
["$framework"]->init_as_package() ] =& $this->modules
["$framework"];
488 return $this->$asobject;
491 // ###################################################################
493 * Prints a list of all currently loaded framework modules
497 * @param bool Return the data as an array?
499 * @return mixed HTML output or an array of loaded modules
501 function show_modules($return = false
)
504 foreach ($this->modules
AS $object)
506 $module = get_class($object);
507 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
509 $module = $object->init_as_package() . " - ($module)";
512 $modules[] = $module;
521 $output = "\n\n<ul>\n\t<li>";
522 $output .= implode("</li>\n\t<li>", $modules);
523 $output .= "</li>\n</ul>\n\n";
524 $this->message('Loaded Modules', $output, 1);
528 // ###################################################################
530 * Verifies to see if a framework has been loaded
534 * @param string Framework name
536 * @return bool Whether or not the framework has been loaded
538 function is_loaded($framework)
540 if (isset($this->modules
["$framework"]))
550 // ###################################################################
552 * Prints an ISSO message
556 * @param string The title of the message
557 * @param string The content of the message
558 * @param integer Type of message to be printed
559 * @param bool Return the output?
560 * @param bool Show the debug stack?
561 * @param integer Message width
563 * @return mixed Output or null
565 function message($title, $message, $type, $return = false
, $stack = true
, $width = 500)
590 $backtrace = debug_backtrace();
591 array_shift($backtrace);
593 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
595 array_shift($backtrace);
598 $trace = $this->format_debug_trace($backtrace);
600 $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;\">";
601 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
602 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
603 $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>" : '');
604 $output .= "\n</table>\n<br />\n";
616 // ###################################################################
618 * Prepares a debug_backtrace() array for output to the browser by
619 * compressing the array into visible text
623 * @param array debug_backtrace() array
625 * @return array Formatted trace output
627 function format_debug_trace($backtrace)
630 foreach ($backtrace AS $i => $step)
633 $file = $step['file'] . ':' . $step['line'];
634 $funct = (isset($step['class']) ?
$step['class'] . '::' . $step['function'] : $step['function']);
636 if (isset($step['args']) AND is_array($step['args']))
638 // we need to do this so we don't get "Array to string conversion" notices
639 foreach ($step['args'] AS $id => $arg)
643 $step['args']["$id"] = 'Array';
646 $args = implode(', ', $step['args']);
649 $trace[] = "#$i $funct($args) called at [$file]";
655 // ###################################################################
657 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
658 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
662 * @param integer Error number
663 * @param string Error message string
664 * @param string File that contains the error
665 * @param string The line number of the error
666 * @param string The active symbol table at which point the error occurred
668 function _error_handler($errno, $errstr, $errfile, $errline, $errcontext)
670 $level = ini_get('error_reporting');
678 if (!($level & E_USER_ERROR
))
689 if (! (($level & E_USER_WARNING
) AND ($level & E_WARNING
)) )
701 if (! (($level & E_USER_NOTICE
) AND ($level & E_NOTICE
)) )
708 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
710 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
712 $this->message($title, $errstr, $mode);
714 if ($errno == E_USER_ERROR
)
720 // ###################################################################
722 * Creates a table that explains the error reporting levels and their
727 function explain_error_reporting()
730 'E_ERROR' => E_ERROR
,
731 'E_WARNING' => E_WARNING
,
732 'E_PARSE' => E_PARSE
,
733 'E_NOTICE' => E_NOTICE
,
734 'E_CORE_ERROR' => E_CORE_ERROR
,
735 'E_CORE_WARNING' => E_CORE_WARNING
,
736 'E_COMPILE_ERROR' => 64,
737 'E_COMPILE_WARNING' => 128,
738 'E_USER_ERROR' => E_USER_ERROR
,
739 'E_USER_WARNING' => E_USER_WARNING
,
740 'E_USER_NOTICE' => E_USER_NOTICE
,
745 $table = '<table cellspacing="0" cellpadding="2" border="0">';
747 foreach ($levels AS $name => $value)
751 <td>' . $name . '</td>
752 <td>' . (ini_get('error_reporting') & $value) . '</td>
759 $this->message('Error Reporting', $table, 1);
762 // ###################################################################
764 * Logs a debug message for verbose output
768 * @param string Message
770 function debug($message)
772 $this->debuginfo
[] = $message;
775 // ###################################################################
777 * Recursive XSS cleaner
781 * @param mixed Unsanitized REQUEST data
783 * @return mixed Sanitized data
785 function _sanitize_input_recursive($data)
787 foreach ($data AS $key => $value)
789 if (is_array($value))
791 $data["$key"] = $this->_sanitize_input_recursive($value);
795 $data["$key"] = $this->sanitize($value);
801 // ###################################################################
803 * Simple way to protect against HTML attacks with Unicode support
807 * @param string Unsanitzed text
809 * @return string Properly protected text that only encodes potential threats
811 function sanitize($text)
813 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
816 // ###################################################################
818 * Unicode-safe entity encoding system; similar to sanitize()
822 * @param string Unsanitized text
824 * @return string Unicode-safe sanitized text with entities preserved
826 function entity_encode($text)
828 $text = str_replace('&', '&', $text);
829 $text = $this->sanitize($text);
833 // ###################################################################
835 * Takes text that has been processed for HTML and unsanitizes it
839 * @param string Text that needs to be turned back into HTML
841 * @return string Unsanitized text
843 function unsanitize($text)
845 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
848 // ###################################################################
850 * Smart addslashes() that only applies itself it the Magic Quotes GPC
851 * is off. This should only be run on database query values that come
852 * from ISSO->in[] input; data that needs sanitization should be run
853 * through ISSO->DB->escape_string()
857 * @param string Some string
858 * @param bool ignored
860 * @return string String that has slashes added
862 function escape($str, $force = true
)
864 if (isset($this->modules
[ISSO_DB_LAYER
]))
866 return $this->modules
[ISSO_DB_LAYER
]->escape_string($str);
868 return addslashes($str);
871 // ###################################################################
873 * Runs through all of the input data and sanitizes it.
877 function exec_sanitize_data()
879 $this->in
= $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
882 // ###################################################################
884 * Sanitize function for something other than a string (which
885 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
886 * data is placed back into $isso->in; this makes it so you don't have
887 * to constantly intval() [etc.] data.
891 * @param array Array of elements to clean as varname => type
893 function input_clean_array($vars)
895 foreach ($vars AS $varname => $type)
897 $this->input_clean($varname, $type);
901 // ###################################################################
903 * Sanitize function that does a single variable as oppoesd to an array
904 * (see input_clean_array() for more details)
908 * @param string Variable name in $isso->in[]
909 * @param integer Sanitization type constant
911 function input_clean($varname, $type)
913 if (isset($this->in
["$varname"]))
915 $this->in
["$varname"] = $this->clean($this->in
["$varname"], $type);
919 $this->in
["$varname"] = $this->clean(null
, $type);
922 return $this->in
["$varname"];
925 // ###################################################################
927 * Runs ISSO->escape() on a variable on ISSO->in[]. This is just a
928 * short-hand wrapper so that queries can be shortened. When this is used,
929 * the actual value in ISSO->in[] is not changed, only the return value
934 * @param string Input variable
936 * @return string Escaped input
938 function input_escape($varname)
940 if (isset($this->in
["$varname"]))
942 return $this->escape($this->in
["$varname"]);
946 return $this->escape(null
);
950 // ###################################################################
952 * Cleaning function that does the work for input_clean(); this is
953 * moved here so it can be used to clean things that aren't in
959 * @param integer Sanitization type constant
961 * @return mixed Cleaned data
963 function clean($value, $type)
965 if (is_array($value))
967 return $this->clean_array($value, $type);
970 if ($type == TYPE_INT
)
972 $value = intval($value);
974 else if ($type == TYPE_UINT
)
976 $value = (($val = intval($value)) < 0 ?
0 : $val);
978 else if ($type == TYPE_FLOAT
)
980 $value = floatval($value);
982 else if ($type == TYPE_BOOL
)
984 $value = (bool
)$value;
986 else if ($type == TYPE_STR
)
990 else if ($type == TYPE_STRUN
)
992 $value = $this->unsanitize($value);
994 else if ($type == TYPE_NOCLEAN
)
998 else if ($type == TYPE_BIN
)
1004 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR
);
1010 // ###################################################################
1012 * Recursion function for ISSO->clean()
1016 * @param array Uncleaned array
1017 * @param integer Sanitization type constant
1019 * @return array Cleaned array of data
1021 function clean_array($array, $type)
1023 foreach ($array AS $key => $value)
1025 $array["$key"] = $this->clean($value, $type);
1031 // ###################################################################
1033 * Checks to see if a POST refer is actually from us
1037 function exec_referer_check()
1039 if ($_SERVER['REQUEST_METHOD'] == 'POST')
1041 $host = ($_SERVER['HTTP_HOST']) ?
$_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
1043 if ($host AND $_SERVER['HTTP_REFERER'])
1045 $parts = parse_url($_SERVER['HTTP_REFERER']);
1046 $ourhost = $parts['host'] . (isset($parts['port']) ?
":$parts[port]" : '');
1048 if ($ourhost != $host)
1050 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR
);
1052 $this->debug('remote post check = ok');
1056 $this->debug('remote post check = FAILED');
1061 // ###################################################################
1063 * Constructs a debug information box that contains various debugging
1064 * information points
1068 * @param bool Show template information?
1070 * @return string Debugging block
1072 function construct_debug_block($dotemplates)
1085 foreach ($this->modules
['template']->usage
AS $name => $count)
1087 if (in_array($name, $this->modules
['template']->uncached
))
1089 $optlist[] = $name . '[' . $count . ']';
1091 $usage[] = $name . " ($count)";
1094 $sizeof = sizeof($this->modules
['template']->uncached
);
1097 $debug .= "\n\t<li><strong style=\"color: red\">Uncached Template(s):</strong> $sizeof ( " . implode(' ', $optlist) . " )</li>";
1102 $scinfo = 'Not Under Source Control';
1105 $scinfo = constant('SVN');
1107 if (preg_match('#\$Id:?\s*\$#', $scinfo))
1109 $scinfo = 'Not Under Source Control';
1113 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
1114 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
1115 $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);
1119 $scinfo = trim($scinfo);
1120 $debug .= "\n\t<li><strong>Source Control:</strong> $scinfo</li>";
1122 // query information
1123 if (is_object($this->modules
[ISSO_DB_LAYER
]))
1125 $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>";
1127 $queries = $this->modules
[ISSO_DB_LAYER
]->history
;
1128 $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>';
1129 foreach ($queries AS $query)
1131 $querydebug .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
1132 $querydebug .= "\n\t\t<td>";
1133 $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>";
1136 $querydebug .= "\n</table>\n\n\n";
1139 // total execution time
1140 if (defined('ISSO_MT_START'))
1142 $this->load('functions', 'functions');
1143 $debug .= "\n\t<li><strong>Total Execution Time:</strong> " . round($this->modules
['functions']->fetch_microtime_diff(ISSO_MT_START
), 10) . "</li>";
1146 // total memory usage KB
1147 if (defined('ISSO_MEMORY_START'))
1149 $end = memory_get_usage(true
);
1150 $debug .= "\n\t<li><strong>Total Memory Usage:</strong> " . ($end - ISSO_MEMORY_USAGE
)/1024 . " KB</li>";
1154 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Debug Notices (" . sizeof($this->debuginfo
) . ")</option>";
1155 foreach ((array)$this->debuginfo
AS $msg)
1157 $debug .= "\n\t\t\t<option>--- $msg</option>";
1159 $debug .= "\n\t\t</select>\n\t</li>";
1162 $modules = $this->show_modules(true
);
1163 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Loaded Modules (" . sizeof($modules) . ")</option>";
1164 foreach ($modules AS $mod)
1166 $debug .= "\n\t\t\t<option>--- $mod</option>";
1168 $debug .= "\n\t\t</select>\n\t</li>";
1173 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Template Usage (" . array_sum($this->modules
['template']->usage
) . ")</option>";
1174 foreach ($usage AS $tpl)
1176 $debug .= "\n\t\t\t<option>--- $tpl</option>";
1178 $debug .= "\n\t\t</select>\n\t</li>";
1181 $debug .= "\n</ul>";
1183 $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";