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('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 ©2002 - [#]year[#], Blue Static
165 * @version $Revision$
176 var $version = '[#]issoversion[#]';
179 * Location of ISSO, used for internal linking
183 var $sourcepath = '';
186 * Path of the current application
193 * Web path used to get the web location of the installation of ISSO; only used for Printer module
200 * Name of the current application
204 var $application = '';
207 * Version of the current application
211 var $appversion = '';
214 * Whether debug mode is on or off
221 * List of all active debug messages
225 var $debuginfo = array();
228 * List of loaded modules
232 var $modules = array();
235 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
242 * If we are running with magic_quotes_gpc on or off
246 var $magicquotes = 0;
248 // ###################################################################
252 function __construct()
254 $GLOBALS['isso:callback'] = null
;
257 set_error_handler(array(&$this, '_error_handler'));
260 $this->magicquotes
= get_magic_quotes_gpc();
261 set_magic_quotes_runtime(0);
263 // some debug info that's always useful
264 $this->debug('magic_quotes_gpc = ' . $this->magicquotes
);
265 $this->debug('register_globals = ' . ini_get('register_globals'));
267 // attempt to set the sourcepath
268 $path = call_user_func('debug_backtrace');
269 $this->setSourcePath(str_replace('kernel.php', '', $path[0]['file']));
271 // start input sanitize using variable_order GPC
272 if (!defined('ISSO_NO_INPUT_SANITIZE'))
274 $this->exec_sanitize_data();
277 if (defined('ISSO_CHECK_POST_REFERER'))
279 $this->exec_referer_check();
283 // ###################################################################
285 * (PHP 4) Constructor
289 $this->__construct();
292 // ###################################################################
294 * Sets the sourcepath
298 * @param string Source path
300 function setSourcePath($path)
302 $this->sourcepath
= $this->fetch_sourcepath($path);
305 // ###################################################################
307 * Gets the sourcepath
311 * @return string Source path
313 function getSourcePath()
315 return $this->sourcepath
;
318 // ###################################################################
324 * @param string Application path
326 function setAppPath($path)
328 $this->apppath
= $this->fetch_sourcepath($path);
331 // ###################################################################
337 * @return string Source path
339 function getAppPath()
341 return $this->apppath
;
344 // ###################################################################
350 * @param string Web path
352 function setWebPath($path)
354 $this->webpath
= $this->fetch_sourcepath($path);
357 // ###################################################################
363 * @return string Web path
365 function getWebPath()
367 return $this->webpath
;
370 // ###################################################################
372 * Sets the applicaiton
376 * @param string Applicaiton
378 function setApplication($app)
380 $this->application
= $app;
383 // ###################################################################
385 * Gets the application
389 * @return string Application
391 function getApplication()
393 return $this->application
;
396 // ###################################################################
398 * Sets the appverison
402 * @param string Applicaiton version
404 function getAppVersion($version)
406 $this->appversion
= $version;
409 // ###################################################################
411 * Gets the appversion
415 * @return string Application version
417 function getAppVersion()
419 return $this->appversion
;
422 // ###################################################################
428 * @param boolean Debug?
430 function setDebug($debug)
432 $this->debug
= $debug;
435 // ###################################################################
437 * Gets debug mode state
441 * @return boolean Debug?
448 // ###################################################################
450 * Prepares a path for being set as the sourcepath
454 * @param string Source path or URL
456 * @return string Prepared source path
458 function fetch_sourcepath($source)
460 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
462 $source .= DIRECTORY_SEPARATOR
;
467 // ###################################################################
469 * Loads a framework module
473 * @param string Name of the framework file to load
474 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
475 * @param bool Globalize the internal variable?
477 * @return object Instantiated instance
479 function &load($framework, $asobject, $globalize = false
)
481 $this->check_isso_fields(null
);
483 // set the object interlock
484 if (!method_exists($GLOBALS['isso:callback'], 'load'))
486 $GLOBALS['isso:callback'] =& $this;
487 $this->modules
['isso'] =& $this;
490 if ($this->is_loaded($framework))
492 return $this->modules
["$framework"];
495 if ($this->sourcepath
== '')
497 trigger_error('Invalid sourcepath specified', E_USER_ERROR
);
500 if (file_exists($this->sourcepath
. $framework . '.php'))
502 require_once($this->sourcepath
. $framework . '.php');
506 trigger_error('Could not find the framework ' . $this->sourcepath
. $framework . '.php', E_USER_ERROR
);
509 if ($asobject === null
)
514 if (isset($this->$asobject))
516 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR
);
519 $this->$asobject = new $framework($this);
521 $this->modules
["$framework"] =& $this->$asobject;
525 $GLOBALS["$asobject"] =& $this->$asobject;
528 // allow for init_as_package to link
529 if (method_exists($this->modules
["$framework"], 'init_as_package'))
531 $this->modules
[ $this->modules
["$framework"]->init_as_package() ] =& $this->modules
["$framework"];
534 return $this->$asobject;
537 // ###################################################################
539 * Prints a list of all currently loaded framework modules
543 * @param bool Return the data as an array?
545 * @return mixed HTML output or an array of loaded modules
547 function show_modules($return = false
)
550 foreach ($this->modules
AS $object)
552 $module = get_class($object);
553 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
555 $module = $object->init_as_package() . " - ($module)";
558 $modules[] = $module;
567 $output = "\n\n<ul>\n\t<li>";
568 $output .= implode("</li>\n\t<li>", $modules);
569 $output .= "</li>\n</ul>\n\n";
570 $this->message('Loaded Modules', $output, 1);
574 // ###################################################################
576 * Verifies to see if a framework has been loaded
580 * @param string Framework name
582 * @return bool Whether or not the framework has been loaded
584 function is_loaded($framework)
586 if (isset($this->modules
["$framework"]))
596 // ###################################################################
598 * Prints an ISSO message
602 * @param string The title of the message
603 * @param string The content of the message
604 * @param integer Type of message to be printed
605 * @param bool Return the output?
606 * @param bool Show the debug stack?
607 * @param integer Message width
609 * @return mixed Output or null
611 function message($title, $message, $type, $return = false
, $stack = true
, $width = 500)
636 $backtrace = debug_backtrace();
637 array_shift($backtrace);
639 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
641 array_shift($backtrace);
644 $trace = $this->format_debug_trace($backtrace);
646 $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;\">";
647 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
648 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
649 $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>" : '');
650 $output .= "\n</table>\n<br />\n";
662 // ###################################################################
664 * Prepares a debug_backtrace() array for output to the browser by
665 * compressing the array into visible text
669 * @param array debug_backtrace() array
671 * @return array Formatted trace output
673 function format_debug_trace($backtrace)
676 foreach ($backtrace AS $i => $step)
679 $file = $step['file'] . ':' . $step['line'];
680 $funct = (isset($step['class']) ?
$step['class'] . '::' . $step['function'] : $step['function']);
682 if (isset($step['args']) AND is_array($step['args']))
684 // we need to do this so we don't get "Array to string conversion" notices
685 foreach ($step['args'] AS $id => $arg)
689 $step['args']["$id"] = 'Array';
692 $args = implode(', ', $step['args']);
695 $trace[] = "#$i $funct($args) called at [$file]";
701 // ###################################################################
703 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
704 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
708 * @param integer Error number
709 * @param string Error message string
710 * @param string File that contains the error
711 * @param string The line number of the error
712 * @param string The active symbol table at which point the error occurred
714 function _error_handler($errno, $errstr, $errfile, $errline, $errcontext)
716 $level = ini_get('error_reporting');
724 if (!($level & E_USER_ERROR
))
735 if (! (($level & E_USER_WARNING
) AND ($level & E_WARNING
)) )
747 if (! (($level & E_USER_NOTICE
) AND ($level & E_NOTICE
)) )
754 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
756 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
758 $this->message($title, $errstr, $mode);
760 if ($errno == E_USER_ERROR
)
766 // ###################################################################
768 * Creates a table that explains the error reporting levels and their
773 function explain_error_reporting()
776 'E_ERROR' => E_ERROR
,
777 'E_WARNING' => E_WARNING
,
778 'E_PARSE' => E_PARSE
,
779 'E_NOTICE' => E_NOTICE
,
780 'E_CORE_ERROR' => E_CORE_ERROR
,
781 'E_CORE_WARNING' => E_CORE_WARNING
,
782 'E_COMPILE_ERROR' => 64,
783 'E_COMPILE_WARNING' => 128,
784 'E_USER_ERROR' => E_USER_ERROR
,
785 'E_USER_WARNING' => E_USER_WARNING
,
786 'E_USER_NOTICE' => E_USER_NOTICE
,
791 $table = '<table cellspacing="0" cellpadding="2" border="0">';
793 foreach ($levels AS $name => $value)
797 <td>' . $name . '</td>
798 <td>' . (ini_get('error_reporting') & $value) . '</td>
805 $this->message('Error Reporting', $table, 1);
808 // ###################################################################
810 * Logs a debug message for verbose output
814 * @param string Message
816 function debug($message)
818 $this->debuginfo
[] = $message;
821 // ###################################################################
823 * Recursive XSS cleaner
827 * @param mixed Unsanitized REQUEST data
829 * @return mixed Sanitized data
831 function _sanitize_input_recursive($data)
833 foreach ($data AS $key => $value)
835 if (is_array($value))
837 $data["$key"] = $this->_sanitize_input_recursive($value);
841 if ($this->magicquotes
)
843 $value = str_replace("\'", "'", $value);
845 $data["$key"] = $this->sanitize($value);
851 // ###################################################################
853 * Simple way to protect against HTML attacks with Unicode support
857 * @param string Unsanitzed text
859 * @return string Properly protected text that only encodes potential threats
861 function sanitize($text)
863 if ($this->magicquotes
)
865 return str_replace(array('<', '>', '\"', '"'), array('<', '>', '"', '"'), $text);
869 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
873 // ###################################################################
875 * Unicode-safe entity encoding system; similar to sanitize()
879 * @param string Unsanitized text
881 * @return string Unicode-safe sanitized text with entities preserved
883 function entity_encode($text)
885 $text = str_replace('&', '&', $text);
886 $text = $this->sanitize($text);
890 // ###################################################################
892 * Takes text that has been processed for HTML and unsanitizes it
896 * @param string Text that needs to be turned back into HTML
898 * @return string Unsanitized text
900 function unsanitize($text)
902 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
905 // ###################################################################
907 * Smart addslashes() that only applies itself it the Magic Quotes GPC
908 * is off. This should only be run on database query values that come
909 * from ISSO->in[] input; data that needs sanitization should be run
910 * through ISSO->DB->escape_string()
914 * @param string Some string
915 * @param bool Force magic quotes to be off
917 * @return string String that has slashes added
919 function escape($str, $force = true
)
921 if ($this->magicquotes
AND !$force)
923 if (isset($this->modules
[ISSO_DB_LAYER
]))
925 return $this->modules
[ISSO_DB_LAYER
]->escape_string(str_replace(array("\'", '\"'), array("'", '"'), $str));
931 if (isset($this->modules
[ISSO_DB_LAYER
]))
933 return $this->modules
[ISSO_DB_LAYER
]->escape_string($str);
935 return addslashes($str);
939 // ###################################################################
941 * Runs through all of the input data and sanitizes it.
945 function exec_sanitize_data()
947 $this->in
= $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
950 // ###################################################################
952 * Sanitize function for something other than a string (which
953 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
954 * data is placed back into $isso->in; this makes it so you don't have
955 * to constantly intval() [etc.] data.
959 * @param array Array of elements to clean as varname => type
961 function input_clean_array($vars)
963 foreach ($vars AS $varname => $type)
965 $this->input_clean($varname, $type);
969 // ###################################################################
971 * Sanitize function that does a single variable as oppoesd to an array
972 * (see input_clean_array() for more details)
976 * @param string Variable name in $isso->in[]
977 * @param integer Sanitization type constant
979 function input_clean($varname, $type)
981 if (isset($this->in
["$varname"]))
983 $this->in
["$varname"] = $this->clean($this->in
["$varname"], $type);
987 $this->in
["$varname"] = $this->clean(null
, $type);
990 return $this->in
["$varname"];
993 // ###################################################################
995 * Runs ISSO->escape() on a variable on ISSO->in[]. This is just a
996 * short-hand wrapper so that queries can be shortened. When this is used,
997 * the actual value in ISSO->in[] is not changed, only the return value
1002 * @param string Input variable
1004 * @return string Escaped input
1006 function input_escape($varname)
1008 if (isset($this->in
["$varname"]))
1010 return $this->escape($this->in
["$varname"]);
1014 return $this->escape(null
);
1018 // ###################################################################
1020 * Cleaning function that does the work for input_clean(); this is
1021 * moved here so it can be used to clean things that aren't in
1027 * @param integer Sanitization type constant
1029 * @return mixed Cleaned data
1031 function clean($value, $type)
1033 if (is_array($value))
1035 return $this->clean_array($value, $type);
1038 if ($type == TYPE_INT
)
1040 $value = intval($value);
1042 else if ($type == TYPE_UINT
)
1044 $value = (($val = intval($value)) < 0 ?
0 : $val);
1046 else if ($type == TYPE_FLOAT
)
1048 $value = floatval($value);
1050 else if ($type == TYPE_BOOL
)
1052 $value = (bool
)$value;
1054 else if ($type == TYPE_STR
)
1058 else if ($type == TYPE_STRUN
)
1060 $value = $this->unsanitize($value);
1062 else if ($type == TYPE_NOCLEAN
)
1064 if ($this->magicquotes
)
1066 $value = str_replace(array('\"', "\'"), array('"', "'"), $value);
1073 else if ($type == TYPE_BIN
)
1079 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR
);
1085 // ###################################################################
1087 * Recursion function for ISSO->clean()
1091 * @param array Uncleaned array
1092 * @param integer Sanitization type constant
1094 * @return array Cleaned array of data
1096 function clean_array($array, $type)
1098 foreach ($array AS $key => $value)
1100 $array["$key"] = $this->clean($value, $type);
1106 // ###################################################################
1108 * Checks to see if a POST refer is actually from us
1112 function exec_referer_check()
1114 if ($_SERVER['REQUEST_METHOD'] == 'POST')
1116 $host = ($_SERVER['HTTP_HOST']) ?
$_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
1118 if ($host AND $_SERVER['HTTP_REFERER'])
1120 $parts = parse_url($_SERVER['HTTP_REFERER']);
1121 $ourhost = $parts['host'] . (isset($parts['port']) ?
":$parts[port]" : '');
1123 if ($ourhost != $host)
1125 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR
);
1127 $this->debug('remote post check = ok');
1131 $this->debug('remote post check = FAILED');
1136 // ###################################################################
1138 * Constructs a debug information box that contains various debugging
1139 * information points
1143 * @param bool Show template information?
1145 * @return string Debugging block
1147 function construct_debug_block($dotemplates)
1160 foreach ($this->modules
['template']->usage
AS $name => $count)
1162 if (in_array($name, $this->modules
['template']->uncached
))
1164 $optlist[] = $name . '[' . $count . ']';
1166 $usage[] = $name . " ($count)";
1169 $sizeof = sizeof($this->modules
['template']->uncached
);
1172 $debug .= "\n\t<li><strong style=\"color: red\">Uncached Template(s):</strong> $sizeof ( " . implode(' ', $optlist) . " )</li>";
1177 $scinfo = 'Not Under Source Control';
1180 $scinfo = constant('SVN');
1182 if (preg_match('#\$Id:?\s*\$#', $scinfo))
1184 $scinfo = 'Not Under Source Control';
1188 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
1189 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
1190 $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);
1194 $scinfo = trim($scinfo);
1195 $debug .= "\n\t<li><strong>Source Control:</strong> $scinfo</li>";
1197 // query information
1198 if (is_object($this->modules
[ISSO_DB_LAYER
]))
1200 $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>";
1203 // total execution time
1204 if (defined('ISSO_MT_START'))
1206 $this->load('functions', 'functions');
1207 $debug .= "\n\t<li><strong>Total Execution Time:</strong> " . round($this->modules
['functions']->fetch_microtime_diff(ISSO_MT_START
), 10) . "</li>";
1211 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Debug Notices (" . sizeof($this->debuginfo
) . ")</option>";
1212 foreach ((array)$this->debuginfo
AS $msg)
1214 $debug .= "\n\t\t\t<option>--- $msg</option>";
1216 $debug .= "\n\t\t</select>\n\t</li>";
1219 $modules = $this->show_modules(true
);
1220 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Loaded Modules (" . sizeof($modules) . ")</option>";
1221 foreach ($modules AS $mod)
1223 $debug .= "\n\t\t\t<option>--- $mod</option>";
1225 $debug .= "\n\t\t</select>\n\t</li>";
1230 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Template Usage (" . array_sum($this->modules
['template']->usage
) . ")</option>";
1231 foreach ($usage AS $tpl)
1233 $debug .= "\n\t\t\t<option>--- $tpl</option>";
1235 $debug .= "\n\t\t</select>\n\t</li>";
1238 $debug .= "\n</ul>";
1240 $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";
1247 /*=====================================================================*\
1248 || ###################################################################
1251 || ###################################################################
1252 \*=====================================================================*/