]>
src.bluestatic.org Git - isso.git/blob - kernel.php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
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 * Iris Studios Shared Object 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 if (version_compare(PHP_VERSION
, '5.0.0', '>='))
37 if (ini_get('error_reporting') & E_NOTICE
)
39 error_reporting(ini_get('error_reporting') - E_NOTICE
);
41 if (ini_get('error_reporting') & E_USER_NOTICE
)
43 error_reporting(ini_get('error_reporting') - E_USER_NOTICE
);
47 $oldlevel = ini_get('error_reporting');
48 $newlevel = $oldlevel;
49 $levels = array(E_ERROR
=> E_USER_ERROR
, E_WARNING
=> E_USER_WARNING
, E_NOTICE
=> E_USER_NOTICE
);
50 foreach ($levels AS $php => $isso)
54 if (!($oldlevel & $isso))
61 if ($oldlevel & $isso)
67 error_reporting($newlevel);
69 if ((bool)ini_get('register_globals') === true)
71 $superglobals = array('_GET', '_COOKIE', '_FILES', '_POST', '_SERVER', '_ENV');
72 foreach ($superglobals AS $global)
74 if (is_array(${$global}))
76 foreach (${$global} AS $_key => $_val)
88 * Input cleaning type constant
93 define('TYPE_INT', 1);
98 define('TYPE_UINT', 2);
103 define('TYPE_FLOAT', 4);
108 define('TYPE_BOOL', 8);
113 define('TYPE_STR', 16);
116 * String - deliberate unclean
118 define('TYPE_STRUN', 32);
121 * No cleaning - here for use in API
123 define('TYPE_NOCLEAN', 64);
129 define('REQ_YES', 1);
137 * Iris Studios Shared Object Framework (ISSO)
139 * This framework allows a common backend to be used amongst all Iris
140 * Studios applications and is built to be abstract and flexible.
141 * The base framework handles all loading and module management.
144 * ISSO_NO_INPUT_SANITIZE - Disables the automatic input sanitizer
145 * ISSO_CHECK_POST_REFERER - Will check to make sure that on POSTed
146 * data, the referer matches the host
148 * @author Iris Studios, Inc.
149 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
150 * @version $Revision$
154 class Shared_Object_Framework
161 var $version = '[#]version[#]';
164 * Location of ISSO, used for internal linking
168 var $sourcepath = '';
171 * Path of the current application
178 * Web path used to get the web location of the installation of ISSO; only used for Printer module
185 * Name of the current application
189 var $application = '';
192 * Version of the current application
196 var $appversion = '';
199 * Whether debug mode is on or off
206 * List of all active debug messages
210 var $debuginfo = array();
213 * List of loaded modules
217 var $modules = array();
220 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
227 * If we are running with magic_quotes_gpc on or off
231 var $magicquotes = 0;
234 * Array of user-specified fields that are required for ISSO initialization
235 * fieldname => array(REQUIRED, CALLBACK PARSER, SET)
240 'sourcepath' => array(REQ_YES
, 'fetch_sourcepath', false),
241 'apppath' => array(REQ_YES
, 'fetch_sourcepath', false),
242 'webpath' => array(REQ_NO
, 'fetch_sourcepath', false),
243 'application' => array(REQ_YES
, null, false),
244 'appversion' => array(REQ_NO
, null, false),
245 'debug' => array(REQ_NO
, null, false)
248 // ###################################################################
252 function __construct()
254 $GLOBALS['isso:null-framework'] = null;
257 set_error_handler(array(&$this, '_error_handler'));
260 $this->magicquotes
= get_magic_quotes_gpc();
261 set_magic_quotes_runtime(0);
263 // start input sanitize using variable_order GPC
264 if (!defined('ISSO_NO_INPUT_SANITIZE'))
266 $this->exec_sanitize_data();
269 if (defined('ISSO_CHECK_POST_REFERER'))
271 $this->exec_referer_check();
275 // ###################################################################
277 * (PHP 4) Constructor
279 function Shared_Object_Framework()
281 $this->__construct();
284 // ###################################################################
286 * Sets a specified field in the ISSO. This is used to set all the
287 * required fields that ISSO uses for linking. It replaces the old
288 * method of setting the instance variables directly.
292 * @param string Field name
293 * @param mixed Value of the field
295 function set($fieldname, $value)
297 if (is_array($this->fields
["$fieldname"]))
299 if (method_exists($this, $this->fields["$fieldname"][1]))
301 $value = $this->{$this
->fields
["$fieldname"][1]}($value);
304 $this->$fieldname = $value;
306 $this->fields
["$fieldname"][2] = true;
310 trigger_error('Invalid field `' . $fieldname . '` specified in ISSO->set()', E_USER_ERROR);
314 // ###################################################################
316 * Returns the value of an ISSO field. You should not access any instance
317 * variables directly, use this instead.
321 * @param string Field name
323 * @return mixed Value of the field
325 function get($fieldname)
327 if (is_array($this->fields["$fieldname"]))
329 if ($this->fields
["$fieldname"][2] == false)
331 trigger_error('Field `' . $fieldname . '` is not set and therefore cannot ISSO->get()', E_USER_ERROR);
334 return $this->$fieldname;
338 trigger_error('Invalid field `' . $fieldname . '` specified in ISSO->get()', E_USER_ERROR);
342 // ###################################################################
344 * Makes sure that all of the required fields in ISSO are set before
345 * any action is done. This will throw an error block describing
346 * the fields that need to be set if any are missing.
350 * @param bool Is this a non-error environment that should display all fields?
352 function check_isso_fields($called = false)
355 foreach ($this->fields AS $name => $field)
357 if ($field[0] == REQ_YES AND $field[2] == false)
361 else if ($called == true AND $field[2] == false)
363 $missing[] = $name . ($field[0] == REQ_YES ? ' (REQUIRED)' : '');
367 if (count($missing) > 0)
369 $error = ($called ? 'The following fields are not set:' : 'You are missing required ISSO fields. Please make sure you have set:');
373 foreach ($missing AS $field)
375 $error .= "\n\t
" . '<li>' . $field . '</li>';
378 $error .= "\n
" . '</ul>';
380 $this->message(($called ? '' : 'Missing ') . 'Fields', $error, ($called ? 1 : 3));
382 if ($called == false)
389 // ###################################################################
391 * Prepares a path for being set as the sourcepath
395 * @param string Source path or URL
397 * @return string Prepared source path
399 function fetch_sourcepath($source)
401 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
403 $source .= DIRECTORY_SEPARATOR;
408 // ###################################################################
410 * Loads a framework module
414 * @param string Name of the framework file to load
415 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
416 * @param bool Globalize the internal variable?
418 * @return object Instantiated instance
420 function &load($framework, $asobject, $globalize = false)
422 $this->check_isso_fields();
424 // set the object interlock
425 if (!method_exists($GLOBALS['isso:null-framework'], 'load'))
427 $GLOBALS['isso:null-framework'] =& $this;
430 if ($this->is_loaded($framework))
432 return $this->modules["$framework"];
435 if ($this->sourcepath
== '')
437 trigger_error('Invalid sourcepath specified', E_USER_ERROR
);
440 if (file_exists($this->sourcepath
. $framework . '.php'))
442 require_once($this->sourcepath
. $framework . '.php');
446 trigger_error('Could not find the framework ' . $this->sourcepath
. $framework . '.php', E_USER_ERROR
);
449 if ($asobject === null)
454 if (isset($this->$asobject))
456 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR
);
459 $this->$asobject = new $framework($this);
461 $this->modules
["$framework"] =& $this->$asobject;
465 $GLOBALS["$asobject"] =& $this->$asobject;
468 return $this->$asobject;
471 // ###################################################################
473 * Prints a list of all currently loaded framework modules
477 * @param bool Return the data as an array?
479 * @return mixed HTML output or an array of loaded modules
481 function show_modules($return = false)
483 foreach ($this->modules
AS $object)
485 $modules[] = get_class($object);
494 $output = "\n\n<ul>\n\t<li>";
495 $output .= implode("</li>\n\t<li>", $modules);
496 $output .= "</li>\n</ul>\n\n";
497 $this->message('Loaded Modules', $output, 1);
501 // ###################################################################
503 * Verifies to see if a framework has been loaded
507 * @param string Framework name
509 * @return bool Whether or not the framework has been loaded
511 function is_loaded($framework)
513 if (isset($this->modules
["$framework"]))
523 // ###################################################################
525 * Prints an ISSO message
529 * @param string The title of the message
530 * @param string The content of the message
531 * @param integer Type of message to be printed
532 * @param bool Return the output?
533 * @param bool Show the debug stack?
535 * @return mixed Output or null
537 function message($title, $message, $type, $return = false, $stack = true)
562 $backtrace = debug_backtrace();
563 unset($backtrace[0]);
565 $output = "\n
<br
/>\n<table cellpadding
=\"4\" cellspacing
=\"1\" border
=\"0\" width
=\"500\" style
=\"background
-color
: $color; color
: black
; font
-family
: Verdana
, sans
-serif
; font
-size
: 12px
;\">";
566 $output .= "\n
<tr style
=\"color
: $font; text
-align
: left\"
>\n\t<td
><strong
>$prefix: $title</strong
></td
>\n</tr
>";
567 $output .= "\n
<tr style
=\"background
-color
: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
568 $output .= (($stack AND $GLOBALS['isso:null-framework']->debug
) ? "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td><strong>Debug Stack:</strong> <pre>" . print_r($backtrace, true) . "</pre></td>\n</tr>" : '');
569 $output .= "\n</table>\n<br />\n";
581 // ###################################################################
583 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
584 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
588 * @param integer Error number
589 * @param string Error message string
590 * @param string File that contains the error
591 * @param string The line number of the error
592 * @param string The active symbol table at which point the error occurred
594 function _error_handler($errno, $errstr, $errfile, $errline)
602 if (!(ini_get('error_reporting') & E_USER_ERROR
))
612 if (!(ini_get('error_reporting') & E_USER_WARNING
) AND !(ini_get('error_reporting') & E_WARNING
))
623 if (!(ini_get('error_reporting') & E_USER_NOTICE
) AND !(ini_get('error_reporting') & E_NOTICE
))
630 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
632 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
634 $this->message($title, $errstr, $level);
636 if ($errno == E_USER_ERROR
)
642 // ###################################################################
644 * Creates a table that explains the error reporting levels and their
649 function explain_error_reporting()
652 'E_ERROR' => E_ERROR
,
653 'E_WARNING' => E_WARNING
,
654 'E_PARSE' => E_PARSE
,
655 'E_NOTICE' => E_NOTICE
,
656 'E_CORE_ERROR' => E_CORE_ERROR
,
657 'E_CORE_WARNING' => E_CORE_WARNING
,
658 'E_COMPILE_ERROR' => 64,
659 'E_COMPILE_WARNING' => 128,
660 'E_USER_ERROR' => E_USER_ERROR
,
661 'E_USER_WARNING' => E_USER_WARNING
,
662 'E_USER_NOTICE' => E_USER_NOTICE
,
667 $table = '<table cellspacing="0" cellpadding="2" border="0">';
669 foreach ($levels AS $name => $value)
673 <td>' . $name . '</td>
674 <td>' . (ini_get('error_reporting') & $value) . '</td>
681 $this->message('Error Reporting', $table, 1);
684 // ###################################################################
686 * Logs a debug message for verbose output
690 * @param string Message
692 function debug($message)
694 $this->debuginfo
[] = $message;
697 // ###################################################################
699 * Recursive XSS cleaner
703 * @param mixed Unsanitized REQUEST data
705 * @return mixed Sanitized data
707 function _sanitize_input_recursive($data)
709 foreach ($data AS $key => $value)
711 if (is_array($value))
713 $data["$key"] = $this->_sanitize_input_recursive($value);
717 $data["$key"] = $this->sanitize($value);
723 // ###################################################################
725 * Simple way to protect against HTML attacks with Unicode support
729 * @param string Unsanitzed text
731 * @return string Properly protected text that only encodes potential threats
733 function sanitize($text)
735 if ($this->magicquotes
)
737 return str_replace(array('<', '>', '\"', '"'), array('<', '>', '"', '"'), $text);
741 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
745 // ###################################################################
747 * Unicode-safe entity encoding system; similar to sanitize()
751 * @param string Unsanitized text
753 * @return string Unicode-safe sanitized text with entities preserved
755 function entity_encode($text)
757 $text = str_replace('&', '&', $text);
758 $text = $this->sanitize($text);
762 // ###################################################################
764 * Takes text that has been processed for HTML and unsanitizes it
768 * @param string Text that needs to be turned back into HTML
770 * @return string Unsanitized text
772 function unsanitize($text)
774 return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
777 // ###################################################################
779 * Smart addslashes() that only applies itself it the Magic Quotes GPC
780 * is off. This should only be run on database query values.
784 * @param string Some string
785 * @param bool If the data is binary; if so it'll be run through DB::escape_stringing()
786 * @param bool Force magic quotes to be off
788 * @return string String that has slashes added
790 function escape($str, $binary = false, $force = true)
792 if ($this->magicquotes
AND !$force)
794 if (isset($this->modules
[ISSO_DB_LAYER
]) AND $binary)
796 return $this->modules
[ISSO_DB_LAYER
]->escape_string(str_replace(array("\'", '\"'), array("'", '"'), $str));
802 if (isset($this->modules
[ISSO_DB_LAYER
]) AND $binary)
804 return $this->modules
[ISSO_DB_LAYER
]->escape_string($str);
806 return addslashes($str);
810 // ###################################################################
812 * Runs through all of the input data and sanitizes it.
816 function exec_sanitize_data()
818 $this->in
= $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
821 // ###################################################################
823 * Sanitize function for something other than a string (which
824 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
825 * data is placed back into $isso->in; this makes it so you don't have
826 * to constantly intval() [etc.] data.
830 * @param array Array of elements to clean as varname => type
832 function input_clean_array($vars)
834 foreach ($vars AS $varname => $type)
836 $this->input_clean($varname, $type);
840 // ###################################################################
842 * Sanitize function that does a single variable as oppoesd to an array
843 * (see input_clean_array() for more details)
847 * @param string Variable name in $isso->in[]
848 * @param integer Sanitization type constant
850 function input_clean($varname, $type)
852 if (isset($this->in
["$varname"]))
854 $this->in["$varname"] = $this->clean($this->in
["$varname"], $type);
858 $this->in["$varname"] = null;
861 return $this->in
["$varname"];
864 // ###################################################################
866 * Cleaning function that does the work for input_clean(); this is
867 * moved here so it can be used to clean things that aren't in
873 * @param integer Sanitization type constant
875 * @return mixed Cleaned data
877 function clean($value, $type)
879 if ($type == TYPE_INT)
881 $value = intval($value);
883 else if ($type == TYPE_UINT)
885 $value = abs(intval($value));
887 else if ($type == TYPE_FLOAT)
889 $value = floatval($value);
891 else if ($type == TYPE_BOOL)
893 $value = (bool)$value;
895 else if ($type == TYPE_STR)
899 else if ($type == TYPE_STRUN)
901 $value = $this->unsanitize($value);
903 else if ($type == TYPE_NOCLEAN)
909 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR);
915 // ###################################################################
917 * Checks to see if a POST refer is actually from us
921 function exec_referer_check()
923 if ($_SERVER['REQUEST_METHOD'] == 'POST')
925 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
927 if ($host AND $_SERVER['HTTP_REFERER'])
929 $parts = parse_url($_SERVER['HTTP_REFERER']);
930 $ourhost = $parts['host'] . (isset($parts['port']) ? ":$parts[port
]" : '');
932 if ($ourhost != $host)
934 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
936 $this->debug('remote post check = ok');
940 $this->debug('remote post check = FAILED');
945 // ###################################################################
947 * Constructs a debug information box that contains various debugging
952 * @param bool Show template information?
954 * @return string Debugging block
956 function construct_debug_block($dotemplates)
967 // both template and template_fs are viable, so we need to determine the right one
968 if ($this->is_loaded('template'))
970 $tpl_obj =& $this->modules['template'];
972 else if ($this->is_loaded('template_fs'))
974 $tpl_obj =& $this->modules['template_fs'];
983 foreach ($tpl_obj->usage AS $name => $count)
985 if (in_array($name, $tpl_obj->uncached))
987 $optlist[] = $name . '[' . $count . ']';
989 $usage[] = $name . " ($count)";
992 $sizeof = sizeof($tpl_obj->uncached);
995 $debug .= "\n\t
<li
><strong style
=\"color
: red\"
>Uncached
Template(s
):</strong
> $sizeof ( " . implode(' ', $optlist) . " )</li
>";
1000 $scinfo = 'Not Under Source Control';
1003 $scinfo = constant('SVN');
1005 if (preg_match('#\$Id:?\s*\$#', $scinfo))
1007 $scinfo = 'Not Under Source Control';
1011 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
1012 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
1013 $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);
1017 $scinfo = trim($scinfo);
1018 $debug .= "\n\t
<li
><strong
>Source Control
:</strong
> $scinfo</li
>";
1020 // query information
1021 if (is_object($this->modules[ISSO_DB_LAYER]))
1023 $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
>";
1026 // total execution time
1027 if (defined('ISSO_MT_START'))
1029 $this->load('functions', 'functions');
1030 $debug .= "\n\t
<li
><strong
>Total Execution Time
:</strong
> " . round($this->modules['functions']->fetch_microtime_diff(ISSO_MT_START), 10) . "</li
>";
1034 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Debug
Notices (" . sizeof($this->debuginfo) . ")</option
>";
1035 foreach ((array)$this->debuginfo AS $msg)
1037 $debug .= "\n\t\t\t
<option
>--- $msg</option
>";
1039 $debug .= "\n\t\t
</select
>\n\t</li
>";
1042 $modules = $this->show_modules(true);
1043 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Loaded
Modules (" . sizeof($modules) . ")</option
>";
1044 foreach ($modules AS $mod)
1046 $debug .= "\n\t\t\t
<option
>--- $mod</option
>";
1048 $debug .= "\n\t\t
</select
>\n\t</li
>";
1053 $debug .= "\n\t
<li
>\n\t\t<select
>\n\t\t\t<option
>Template
Usage (" . array_sum($tpl_obj->usage) . ")</option
>";
1054 foreach ($usage AS $tpl)
1056 $debug .= "\n\t\t\t
<option
>--- $tpl</option
>";
1058 $debug .= "\n\t\t
</select
>\n\t</li
>";
1061 $debug .= "\n
</ul
>";
1063 $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";
1070 /*=====================================================================*\
1071 || ###################################################################
1074 || ###################################################################
1075 \*=====================================================================*/