]>
src.bluestatic.org Git - bugdar.git/blob - framework/kernel.php
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 $this->setSourcePath(dirname(__FILE__
));
225 // start input sanitize using variable_order GPC
226 if (!defined('ISSO_NO_INPUT_SANITIZE'))
228 $this->exec_sanitize_data();
231 if (defined('ISSO_CHECK_POST_REFERER'))
233 $this->exec_referer_check();
237 // ###################################################################
239 * (PHP 4) Constructor
243 $this->__construct();
246 // ###################################################################
248 * Sets the sourcepath
252 * @param string Source path
254 function setSourcePath($path)
256 $this->sourcepath
= $this->fetch_sourcepath($path);
259 // ###################################################################
261 * Gets the sourcepath
265 * @return string Source path
267 function getSourcePath()
269 return $this->sourcepath
;
272 // ###################################################################
278 * @param string Application path
280 function setAppPath($path)
282 $this->apppath
= $this->fetch_sourcepath($path);
285 // ###################################################################
291 * @return string Source path
293 function getAppPath()
295 return $this->apppath
;
298 // ###################################################################
304 * @param string Web path
306 function setWebPath($path)
308 $this->webpath
= $this->fetch_sourcepath($path);
311 // ###################################################################
317 * @return string Web path
319 function getWebPath()
321 return $this->webpath
;
324 // ###################################################################
326 * Sets the applicaiton
330 * @param string Applicaiton
332 function setApplication($app)
334 $this->application
= $app;
337 // ###################################################################
339 * Gets the application
343 * @return string Application
345 function getApplication()
347 return $this->application
;
350 // ###################################################################
352 * Sets the appverison
356 * @param string Applicaiton version
358 function setAppVersion($version)
360 $this->appversion
= $version;
363 // ###################################################################
365 * Gets the appversion
369 * @return string Application version
371 function getAppVersion()
373 return $this->appversion
;
376 // ###################################################################
382 * @param boolean Debug?
384 function setDebug($debug)
386 $this->debug
= $debug;
389 // ###################################################################
391 * Gets debug mode state
395 * @return boolean Debug?
402 // ###################################################################
404 * Prepares a path for being set as the sourcepath
408 * @param string Source path or URL
410 * @return string Prepared source path
412 function fetch_sourcepath($source)
414 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
416 $source .= DIRECTORY_SEPARATOR
;
421 // ###################################################################
423 * Loads a framework module
427 * @param string Name of the framework file to load
428 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
429 * @param bool Globalize the internal variable?
431 * @return object Instantiated instance
433 function &load($framework, $asobject, $globalize = false)
435 // set the object interlock
436 if (!method_exists($GLOBALS['isso:callback'], 'load'))
438 $GLOBALS['isso:callback'] =& $this;
439 $this->modules
['isso'] =& $this;
442 if ($this->is_loaded($framework))
444 return $this->modules
["$framework"];
447 if ($this->sourcepath == '')
449 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
452 if (file_exists($this->sourcepath . $framework . '.php'))
454 require_once($this->sourcepath . $framework . '.php');
458 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
461 if ($asobject === null)
466 if (isset($this->$asobject))
468 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
471 $this->$asobject = new $framework($this);
473 $this->modules["$framework"] =& $this->$asobject;
477 $GLOBALS["$asobject"] =& $this->$asobject;
480 // allow for init_as_package to link
481 if (method_exists($this->modules["$framework"], 'init_as_package'))
483 $this->modules
[ $this->modules
["$framework"]->init_as_package() ] =& $this->modules["$framework"];
486 return $this->$asobject;
489 // ###################################################################
491 * Prints a list of all currently loaded framework modules
495 * @param bool Return the data as an array?
497 * @return mixed HTML output or an array of loaded modules
499 function show_modules($return = false)
502 foreach ($this->modules
AS $object)
504 $module = get_class($object);
505 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
507 $module = $object->init_as_package() . " - ($module)";
510 $modules[] = $module;
519 $output = "\n\n<ul>\n\t<li>";
520 $output .= implode("</li>\n\t<li>", $modules);
521 $output .= "</li>\n</ul>\n\n";
522 $this->message('Loaded Modules', $output, 1);
526 // ###################################################################
528 * Verifies to see if a framework has been loaded
532 * @param string Framework name
534 * @return bool Whether or not the framework has been loaded
536 function is_loaded($framework)
538 if (isset($this->modules
["$framework"]))
548 // ###################################################################
550 * Prints an ISSO message
554 * @param string The title of the message
555 * @param string The content of the message
556 * @param integer Type of message to be printed
557 * @param bool Return the output?
558 * @param bool Show the debug stack?
559 * @param integer Message width
561 * @return mixed Output or null
563 function message($title, $message, $type, $return = false, $stack = true, $width = 500)
588 $backtrace = debug_backtrace();
589 array_shift($backtrace);
591 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
593 array_shift($backtrace);
596 $trace = $this->format_debug_trace($backtrace);
598 $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
;\">";
599 $output .= "\n
<tr style
=\"color
: $font; text
-align
: left\"
>\n\t<td
><strong
>$prefix: $title</strong
></td
>\n</tr
>";
600 $output .= "\n
<tr style
=\"background
-color
: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
601 $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>" : '');
602 $output .= "\n</table>\n<br />\n";
614 // ###################################################################
616 * Prepares a debug_backtrace() array for output to the browser by
617 * compressing the array into visible text
621 * @param array debug_backtrace() array
623 * @return array Formatted trace output
625 function format_debug_trace($backtrace)
628 foreach ($backtrace AS $i => $step)
630 $file = $step['file'] . ':' . $step['line'];
631 $funct = (isset($step['class']) ? $step['class'] . '::' . $step['function'] : $step['function']);
632 $trace[] = "#$i $funct() $file";
638 // ###################################################################
640 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
641 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
645 * @param integer Error number
646 * @param string Error message string
647 * @param string File that contains the error
648 * @param string The line number of the error
649 * @param string The active symbol table at which point the error occurred
651 function _error_handler($errno, $errstr, $errfile, $errline, $errcontext)
653 $level = ini_get('error_reporting');
661 if (!($level & E_USER_ERROR))
672 if (! (($level & E_USER_WARNING) AND ($level & E_WARNING)) )
684 if (! (($level & E_USER_NOTICE) AND ($level & E_NOTICE)) )
691 $errstr .= " in
<strong
>$errfile</strong
> on line
<strong
>$errline</strong
>";
693 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
695 $this->message($title, $errstr, $mode);
697 if ($errno == E_USER_ERROR)
703 // ###################################################################
705 * Creates a table that explains the error reporting levels and their
710 function explain_error_reporting()
713 'E_ERROR' => E_ERROR,
714 'E_WARNING' => E_WARNING,
715 'E_PARSE' => E_PARSE,
716 'E_NOTICE' => E_NOTICE,
717 'E_CORE_ERROR' => E_CORE_ERROR,
718 'E_CORE_WARNING' => E_CORE_WARNING,
719 'E_COMPILE_ERROR' => 64,
720 'E_COMPILE_WARNING' => 128,
721 'E_USER_ERROR' => E_USER_ERROR,
722 'E_USER_WARNING' => E_USER_WARNING,
723 'E_USER_NOTICE' => E_USER_NOTICE,
728 $table = '<table cellspacing="0" cellpadding="2" border="0">';
730 foreach ($levels AS $name => $value)
734 <td>' . $name . '</td>
735 <td>' . (ini_get('error_reporting') & $value) . '</td>
742 $this->message('Error Reporting', $table, 1);
745 // ###################################################################
747 * Logs a debug message for verbose output
751 * @param string Message
753 function debug($message)
755 $this->debuginfo[] = $message;
758 // ###################################################################
760 * Recursive XSS cleaner
764 * @param mixed Unsanitized REQUEST data
766 * @return mixed Sanitized data
768 function _sanitize_input_recursive($data)
770 foreach ($data AS $key => $value)
772 if (is_array($value))
774 $data["$key"] = $this->_sanitize_input_recursive($value);
778 $data["$key"] = $this->sanitize($value);
784 // ###################################################################
786 * Simple way to protect against HTML attacks with Unicode support
790 * @param string Unsanitzed text
792 * @return string Properly protected text that only encodes potential threats
794 function sanitize($text)
796 return str_replace(array('<', '>', '"'), array('<
;', '>
;', '"
;'), $text);
799 // ###################################################################
801 * Unicode-safe entity encoding system; similar to sanitize()
805 * @param string Unsanitized text
807 * @return string Unicode-safe sanitized text with entities preserved
809 function entity_encode($text)
811 $text = str_replace('&', '&
;', $text);
812 $text = $this->sanitize($text);
816 // ###################################################################
818 * Takes text that has been processed for HTML and unsanitizes it
822 * @param string Text that needs to be turned back into HTML
824 * @return string Unsanitized text
826 function unsanitize($text)
828 return str_replace(array('<
;', '>
;', '"
;'), array('<', '>', '"'), $text);
831 // ###################################################################
833 * Smart addslashes() that only applies itself it the Magic Quotes GPC
834 * is off. This should only be run on database query values that come
835 * from ISSO->in[] input; data that needs sanitization should be run
836 * through ISSO->DB->escape_string()
840 * @param string Some string
841 * @param bool ignored
843 * @return string String that has slashes added
845 function escape($str, $force = true)
847 if (isset($this->modules[ISSO_DB_LAYER]))
849 return $this->modules[ISSO_DB_LAYER]->escape_string($str);
851 return addslashes($str);
854 // ###################################################################
856 * Runs through all of the input data and sanitizes it.
860 function exec_sanitize_data()
862 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
865 // ###################################################################
867 * Sanitize function for something other than a string (which
868 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
869 * data is placed back into $isso->in; this makes it so you don't have
870 * to constantly intval() [etc.] data.
874 * @param array Array of elements to clean as varname => type
876 function input_clean_array($vars)
878 foreach ($vars AS $varname => $type)
880 $this->input_clean($varname, $type);
884 // ###################################################################
886 * Sanitize function that does a single variable as oppoesd to an array
887 * (see input_clean_array() for more details)
891 * @param string Variable name in $isso->in[]
892 * @param integer Sanitization type constant
894 function input_clean($varname, $type)
896 if (isset($this->in["$varname"]))
898 $this->in
["$varname"] = $this->clean($this->in["$varname"], $type);
902 $this->in
["$varname"] = $this->clean(null, $type);
905 return $this->in["$varname"];
908 // ###################################################################
910 * Runs ISSO->escape() on a variable on ISSO->in[]. This is just a
911 * short-hand wrapper so that queries can be shortened. When this is used,
912 * the actual value in ISSO->in[] is not changed, only the return value
917 * @param string Input variable
919 * @return string Escaped input
921 function input_escape($varname)
923 if (isset($this->in
["$varname"]))
925 return $this->escape($this->in["$varname"]);
929 return $this->escape(null);
933 // ###################################################################
935 * Cleaning function that does the work for input_clean(); this is
936 * moved here so it can be used to clean things that aren't in
942 * @param integer Sanitization type constant
944 * @return mixed Cleaned data
946 function clean($value, $type)
948 if (is_array($value))
950 return $this->clean_array($value, $type);
953 if ($type == TYPE_INT
)
955 $value = intval($value);
957 else if ($type == TYPE_UINT
)
959 $value = (($val = intval($value)) < 0 ? 0 : $val);
961 else if ($type == TYPE_FLOAT
)
963 $value = floatval($value);
965 else if ($type == TYPE_BOOL
)
967 $value = (bool)$value;
969 else if ($type == TYPE_STR
)
973 else if ($type == TYPE_STRUN
)
975 $value = $this->unsanitize($value);
977 else if ($type == TYPE_NOCLEAN
)
981 else if ($type == TYPE_BIN
)
987 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR
);
993 // ###################################################################
995 * Recursion function for ISSO->clean()
999 * @param array Uncleaned array
1000 * @param integer Sanitization type constant
1002 * @return array Cleaned array of data
1004 function clean_array($array, $type)
1006 foreach ($array AS $key => $value)
1008 $array["$key"] = $this->clean($value, $type);
1014 // ###################################################################
1016 * Checks to see if a POST refer is actually from us
1020 function exec_referer_check()
1022 if ($_SERVER['REQUEST_METHOD'] == 'POST')
1024 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
1026 if ($host AND $_SERVER['HTTP_REFERER'])
1028 $parts = parse_url($_SERVER['HTTP_REFERER']);
1029 $ourhost = $parts['host'] . (isset($parts['port']) ? ":$parts[port
]" : '');
1031 if ($ourhost != $host)
1033 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
1035 $this->debug('remote post check = ok');
1039 $this->debug('remote post check = FAILED');
1044 // ###################################################################
1046 * Constructs a debug information box that contains various debugging
1047 * information points
1051 * @param bool Show template information?
1053 * @return string Debugging block
1055 function construct_debug_block($dotemplates)
1068 foreach ($this->modules['template']->usage AS $name => $count)
1070 if (in_array($name, $this->modules['template']->uncached))
1072 $optlist[] = $name . '[' . $count . ']';
1074 $usage[] = $name . " ($count)";
1077 $sizeof = sizeof($this->modules['template']->uncached);
1080 $debug .= "\n\t
<li
><strong style
=\"color
: red\"
>Uncached
Template(s
):</strong
> $sizeof ( " . implode(' ', $optlist) . " )</li
>";
1085 $scinfo = 'Not Under Source Control';
1086 $debug .= "\n\t
<li
><strong
>Source Control
:</strong
> $scinfo</li
>";
1088 // query information
1089 if (is_object($this->modules[ISSO_DB_LAYER]))
1091 $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
>";
1093 $queries = $this->modules[ISSO_DB_LAYER]->history;
1094 $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>';
1095 foreach ($queries AS $query)
1097 $querydebug .= "\n\t
<tr style
=\"background
-color
: rgb(230, 230, 230); color
: black\"
>";
1098 $querydebug .= "\n\t\t
<td
>";
1099 $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
>";
1102 $querydebug .= "\n
</table
>\n\n\n";
1105 // total execution time
1106 if (defined('ISSO_MT_START'))
1108 $this->load('functions', 'functions');
1109 $debug .= "\n\t
<li
><strong
>Total Execution Time
:</strong
> " . round($this->modules['functions']->fetch_microtime_diff(ISSO_MT_START), 10) . "</li
>";
1112 // total memory usage KB
1113 if (defined('ISSO_MEMORY_START'))
1115 $end = memory_get_usage(true);
1116 $debug .= "\n\t
<li
><strong
>Total Memory Usage
:</strong
> " . ($end - ISSO_MEMORY_START)/1024 . " KB
</li
>";
1120 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Debug
Notices (" . sizeof($this->debuginfo) . ")</option
>";
1121 foreach ((array)$this->debuginfo AS $msg)
1123 $debug .= "\n\t\t\t
<option
>--- $msg</option
>";
1125 $debug .= "\n\t\t
</select
>\n\t</li
>";
1128 $modules = $this->show_modules(true);
1129 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Loaded
Modules (" . sizeof($modules) . ")</option
>";
1130 foreach ($modules AS $mod)
1132 $debug .= "\n\t\t\t
<option
>--- $mod</option
>";
1134 $debug .= "\n\t\t
</select
>\n\t</li
>";
1139 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Template
Usage (" . array_sum($this->modules['template']->usage) . ")</option
>";
1140 foreach ($usage AS $tpl)
1142 $debug .= "\n\t\t\t
<option
>--- $tpl</option
>";
1144 $debug .= "\n\t\t
</select
>\n\t</li
>";
1147 $debug .= "\n
</ul
>";
1149 $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";