Fixed spelling boo-boo
[isso.git] / kernel.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
6 || #
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.
10 || #
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
14 || # more details.
15 || #
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 \*=====================================================================*/
21
22 /**
23 * Iris Studios Shared Object Framework Kernel
24 * kernel.php
25 *
26 * @package ISSO
27 */
28
29 if (!function_exists('version_compare'))
30 {
31 trigger_error('You need PHP version 4.1.0 or newer to run ISSO', E_USER_ERROR);
32 exit;
33 }
34
35 if (version_compare(PHP_VERSION, '5.0.0', '>='))
36 {
37 if (ini_get('error_reporting') & E_NOTICE)
38 {
39 error_reporting(ini_get('error_reporting') - E_NOTICE);
40 }
41 if (ini_get('error_reporting') & E_USER_NOTICE)
42 {
43 error_reporting(ini_get('error_reporting') - E_USER_NOTICE);
44 }
45 }
46
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)
51 {
52 if ($oldlevel & $php)
53 {
54 if (!($oldlevel & $isso))
55 {
56 //echo "increasing newlevel by $isso; ";
57 $newlevel += $isso;
58 }
59 }
60 else
61 {
62 if ($oldlevel & $isso)
63 {
64 //echo "decreasing newlevel by $isso; ";
65 $newlevel -= $isso;
66 }
67 }
68 }
69 error_reporting($newlevel);
70
71 if ((bool)ini_get('register_globals') === true)
72 {
73 $superglobals = array('_GET', '_COOKIE', '_FILES', '_POST', '_SERVER', '_ENV');
74 foreach ($superglobals AS $global)
75 {
76 if (is_array(${$global}))
77 {
78 foreach (${$global} AS $_key => $_val)
79 {
80 if (isset(${$_key}))
81 {
82 unset(${$_key});
83 }
84 }
85 }
86 }
87 }
88
89 /**#@+
90 * Input cleaning type constant
91 */
92 /**
93 * Integer type
94 */
95 define('TYPE_INT', 1);
96
97 /**
98 * Unsigned integer
99 */
100 define('TYPE_UINT', 2);
101
102 /**
103 * Float type
104 */
105 define('TYPE_FLOAT', 4);
106
107 /**
108 * Boolean type
109 */
110 define('TYPE_BOOL', 8);
111
112 /**
113 * String - cleaned
114 */
115 define('TYPE_STR', 16);
116
117 /**
118 * String - deliberate unclean
119 */
120 define('TYPE_STRUN', 32);
121
122 /**
123 * No cleaning - here for use in API
124 */
125 define('TYPE_NOCLEAN', 64);
126 /**#@-*/
127
128 /**
129 * Iris Studios Shared Object Framework (ISSO)
130 *
131 * This framework allows a common backend to be used amongst all Iris
132 * Studios applications and is built to be abstract and flexible.
133 * The base framework handles all loading and module management.
134 *
135 * @author Iris Studios, Inc.
136 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
137 * @version $Revision$
138 * @package ISSO
139 *
140 */
141 class Shared_Object_Framework
142 {
143 /**
144 * ISSO version
145 * @var string
146 */
147 var $version = '[#]version[#]';
148
149 /**
150 * Location of ISSO, used for internal linking
151 * @var string
152 */
153 var $sourcepath = '';
154
155 /**
156 * Path of the current application
157 * @var string
158 */
159 var $apppath = '';
160
161 /**
162 * Web path used to get the web location of the installation of ISSO; only used for Printer module
163 * @var string
164 */
165 var $webpath = '';
166
167 /**
168 * Name of the current application
169 * @var string
170 */
171 var $application = '';
172
173 /**
174 * Version of the current application
175 * @var string
176 */
177 var $appversion = '';
178
179 /**
180 * Whether debug mode is on or off
181 * @var bool
182 */
183 var $debug = false;
184
185 /**
186 * List of all active debug messages
187 * @var array
188 */
189 var $debuginfo = array();
190
191 /**
192 * List of loaded modules
193 * @var array
194 */
195 var $modules = array();
196
197 /**
198 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
199 * @var array
200 */
201 var $in = array();
202
203 /**
204 * If we are running with magic_quotes_gpc on or off
205 * @var int
206 */
207 var $magicquotes = 0;
208
209 /**
210 * If we should automagically escape strings, mimicking magic_quotes_gpc
211 * @var bool
212 */
213 var $escapestrings = false;
214
215 // ###################################################################
216 /**
217 * Constructor
218 */
219 function __construct()
220 {
221 // error reporting
222 set_error_handler(array(&$this, '_error_handler'));
223
224 // magic quotes
225 $this->magicquotes = get_magic_quotes_gpc();
226 set_magic_quotes_runtime(0);
227
228 if (defined('ISSO_ESCAPE_STRINGS'))
229 {
230 $this->escapestrings = (bool)constant('ISSO_ESCAPE_STRINGS');
231 }
232
233 // start input sanitize using variable_order GPC
234 if (!$this->escapestrings)
235 {
236 $this->exec_sanitize_data();
237 }
238
239 if (defined('ISSO_CHECK_POST_REFERER'))
240 {
241 $this->exec_referer_check();
242 }
243
244 $GLOBALS['isso:null-framework'] = null;
245 }
246
247 // ###################################################################
248 /**
249 * (PHP 4) Constructor
250 */
251 function Shared_Object_Framework()
252 {
253 $this->__construct();
254 }
255
256 // ###################################################################
257 /**
258 * Prepares a path for being set as the sourcepath
259 *
260 * @access public
261 *
262 * @param string Source path or URL
263 *
264 * @return string Prepared source path
265 */
266 function fetch_sourcepath($source)
267 {
268 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
269 {
270 $source .= DIRECTORY_SEPARATOR;
271 }
272 return $source;
273 }
274
275 // ###################################################################
276 /**
277 * Loads a framework module
278 *
279 * @access public
280 *
281 * @param string Name of the framework file to load
282 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
283 * @param bool Globalize the internal variable?
284 *
285 * @return object Instantiated instance
286 */
287 function &load($framework, $asobject, $globalize = false)
288 {
289 // set the object interlock
290 if (!method_exists($GLOBALS['isso:null-framework'], 'load'))
291 {
292 $GLOBALS['isso:null-framework'] =& $this;
293 }
294
295 if ($this->is_loaded($framework))
296 {
297 return $this->modules["$framework"];
298 }
299
300 if ($this->sourcepath == '')
301 {
302 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
303 }
304
305 if (file_exists($this->sourcepath . $framework . '.php'))
306 {
307 require_once($this->sourcepath . $framework . '.php');
308 }
309 else
310 {
311 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
312 }
313
314 if ($asobject === null)
315 {
316 return;
317 }
318
319 if (isset($this->$asobject))
320 {
321 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
322 }
323
324 $this->$asobject = new $framework($this);
325
326 $this->modules["$framework"] =& $this->$asobject;
327
328 if ($globalize)
329 {
330 $GLOBALS["$asobject"] =& $this->$asobject;
331 }
332
333 return $this->$asobject;
334 }
335
336 // ###################################################################
337 /**
338 * Prints a list of all currently loaded framework modules
339 *
340 * @access public
341 *
342 * @param bool Return the data as an array?
343 *
344 * @return mixed HTML output or an array of loaded modules
345 */
346 function show_modules($return = false)
347 {
348 foreach ($this->modules AS $object)
349 {
350 $modules[] = get_class($object);
351 }
352
353 if ($return)
354 {
355 return $modules;
356 }
357 else
358 {
359 $output = "\n\n<ul>\n\t<li>";
360 $output .= implode("</li>\n\t<li>", $modules);
361 $output .= "</li>\n</ul>\n\n";
362 $this->message('Loaded Modules', $output, 1);
363 }
364 }
365
366 // ###################################################################
367 /**
368 * Verifies to see if a framework has been loaded
369 *
370 * @access public
371 *
372 * @param string Framework name
373 *
374 * @return bool Whether or not the framework has been loaded
375 */
376 function is_loaded($framework)
377 {
378 if (isset($this->modules["$framework"]))
379 {
380 return true;
381 }
382 else
383 {
384 return false;
385 }
386 }
387
388 // ###################################################################
389 /**
390 * Prints an ISSO message
391 *
392 * @access public
393 *
394 * @param string The title of the message
395 * @param string The content of the message
396 * @param integer Type of message to be printed
397 * @param bool Return the output?
398 * @param bool Show the debug stack?
399 *
400 * @return mixed Output or null
401 */
402 function message($title, $message, $type, $return = false, $stack = true)
403 {
404 switch ($type)
405 {
406 // Message
407 case 1:
408 $prefix = 'Message';
409 $color = '#669900';
410 $font = '#000000';
411 break;
412
413 // Warning
414 case 2:
415 $prefix = 'Warning';
416 $color = '#003399';
417 $font = '#FFFFFF';
418 break;
419
420 case 3:
421 $prefix = 'Error';
422 $color = '#990000';
423 $font = '#EFEFEF';
424 break;
425 }
426
427 $backtrace = debug_backtrace();
428 unset($backtrace[0]);
429
430 $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;\">";
431 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
432 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
433 $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>" : '');
434 $output .= "\n</table>\n<br />\n";
435
436 if ($return)
437 {
438 return $output;
439 }
440 else
441 {
442 print($output);
443 }
444 }
445
446 // ###################################################################
447 /**
448 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
449 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
450 *
451 * @access private
452 *
453 * @param integer Error number
454 * @param string Error message string
455 * @param string File that contains the error
456 * @param string The line number of the error
457 * @param string The active symbol table at which point the error occurred
458 */
459 function _error_handler($errno, $errstr, $errfile, $errline)
460 {
461 switch ($errno)
462 {
463 // Fatal
464 case E_USER_ERROR:
465 $title = 'Fatal';
466 $level = 3;
467 if (!(ini_get('error_reporting') & E_USER_ERROR))
468 {
469 return;
470 }
471 break;
472
473 // Error
474 case E_USER_WARNING:
475 $title = 'Warning';
476 $level = 2;
477 if (!(ini_get('error_reporting') & E_USER_WARNING) AND !(ini_get('error_reporting') & E_WARNING))
478 {
479 return;
480 }
481 break;
482
483 // Warning
484 case E_USER_NOTICE:
485 default:
486 $title = 'Notice';
487 $level = 1;
488 if (!(ini_get('error_reporting') & E_USER_NOTICE) AND !(ini_get('error_reporting') & E_NOTICE))
489 {
490 return;
491 }
492 break;
493 }
494
495 $errfile = str_replace(array(getcwd(), dirname(getcwd())), '', $errfile);
496
497 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
498
499 $this->message($title, $errstr, $level);
500
501 if ($errno == E_USER_ERROR)
502 {
503 exit;
504 }
505 }
506
507 // ###################################################################
508 /**
509 * Creates a table that explains the error reporting levels and their
510 * state
511 *
512 * @access public
513 */
514 function explain_error_reporting()
515 {
516 $levels = array(
517 'E_ERROR' => E_ERROR,
518 'E_WARNING' => E_WARNING,
519 'E_PARSE' => E_PARSE,
520 'E_NOTICE' => E_NOTICE,
521 'E_CORE_ERROR' => E_CORE_ERROR,
522 'E_CORE_WARNING' => E_CORE_WARNING,
523 'E_COMPILE_ERROR' => 64,
524 'E_COMPILE_WARNING' => 128,
525 'E_USER_ERROR' => E_USER_ERROR,
526 'E_USER_WARNING' => E_USER_WARNING,
527 'E_USER_NOTICE' => E_USER_NOTICE,
528 'E_ALL' => E_ALL,
529 'E_STRICT' => 2048
530 );
531
532 $table = '<table cellspacing="0" cellpadding="2" border="0">';
533
534 foreach ($levels AS $name => $value)
535 {
536 $table .= '
537 <tr>
538 <td>' . $name . '</td>
539 <td>' . (ini_get('error_reporting') & $value) . '</td>
540 </tr>';
541 }
542
543 $table .= '
544 </table>';
545
546 $this->message('Error Reporting', $table, 1);
547 }
548
549 // ###################################################################
550 /**
551 * Logs a debug message for verbose output
552 *
553 * @access public
554 *
555 * @param string Message
556 */
557 function debug($message)
558 {
559 $this->debuginfo[] = $message;
560 }
561
562 // ###################################################################
563 /**
564 * Recursive XSS cleaner
565 *
566 * @access private
567 *
568 * @param mixed Unsanitized REQUEST data
569 *
570 * @return mixed Sanitized data
571 */
572 function _sanitize_input_recursive($data)
573 {
574 foreach ($data AS $key => $value)
575 {
576 if (is_array($value))
577 {
578 $data["$key"] = $this->_sanitize_input_recursive($value);
579 }
580 else
581 {
582 if ($this->escapestrings)
583 {
584 $data["$key"] = $this->escape($this->sanitize($value), false, false);
585 }
586 else
587 {
588 $data["$key"] = $this->sanitize($value);
589 }
590 }
591 }
592 return $data;
593 }
594
595 // ###################################################################
596 /**
597 * Simple way to protect against HTML attacks with Unicode support
598 *
599 * @access public
600 *
601 * @param string Unsanitzed text
602 *
603 * @return string Properly protected text that only encodes potential threats
604 */
605 function sanitize($text)
606 {
607 if ($this->magicquotes)
608 {
609 return str_replace(array('<', '>', '\"', '"'), array('&lt;', '&gt;', '&quot;', '&quot;'), $text);
610 }
611 else
612 {
613 return str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $text);
614 }
615 }
616
617 // ###################################################################
618 /**
619 * Unicode-safe entity encoding system; similar to sanitize()
620 *
621 * @access public
622 *
623 * @param string Unsanitized text
624 *
625 * @return string Unicode-safe sanitized text with entities preserved
626 */
627 function entity_encode($text)
628 {
629 $text = str_replace('&', '&amp;', $text);
630 $text = $this->sanitize($text);
631 return $text;
632 }
633
634 // ###################################################################
635 /**
636 * Takes text that has been processed for HTML and unsanitizes it
637 *
638 * @access public
639 *
640 * @param string Text that needs to be turned back into HTML
641 * @param bool Force magicquotes off
642 *
643 * @return string Unsanitized text
644 */
645 function unsanitize($text, $force = false)
646 {
647 if ($this->magicquotes AND !$force)
648 {
649 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '\"'), $text);
650 }
651 else
652 {
653 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '"'), $text);
654 }
655 }
656
657 // ###################################################################
658 /**
659 * Smart addslashes() that only applies itself it the Magic Quotes GPC
660 * is off
661 *
662 * @access public
663 *
664 * @param string Some string
665 * @param bool If the data is binary; if so it'll be run through DB::escape_stringing()
666 * @param bool Force magic quotes to be off
667 *
668 * @return string String that has slashes added
669 */
670 function escape($str, $binary = false, $force = true)
671 {
672 if ($this->magicquotes AND !$force)
673 {
674 if (isset($this->db) AND $binary)
675 {
676 if (is_resource($this->db->link_id))
677 {
678 return $this->db->escape_string(stripslashes($str));
679 }
680 }
681 return $str;
682 }
683 else
684 {
685 if (isset($this->db) AND $binary)
686 {
687 if (is_resource($this->db->link_id))
688 {
689 return $this->db->escape_string($str);
690 }
691 }
692 return addslashes($str);
693 }
694 }
695
696 // ###################################################################
697 /**
698 * Runs through all of the input data and sanitizes it.
699 *
700 * @access public
701 */
702 function exec_sanitize_data()
703 {
704 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
705 // we're now using magic quotes
706 if ($this->escapestrings)
707 {
708 $this->magicquotes = 1;
709 }
710 }
711
712 // ###################################################################
713 /**
714 * Sanitize function for something other than a string (which
715 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
716 * data is placed back into $isso->in; this makes it so you don't have
717 * to constantly intval() [etc.] data.
718 *
719 * @access public
720 *
721 * @param array Array of elements to clean as varname => type
722 */
723 function input_clean_array($vars)
724 {
725 foreach ($vars AS $varname => $type)
726 {
727 $this->input_clean($varname, $type);
728 }
729 }
730
731 // ###################################################################
732 /**
733 * Sanitize function that does a single variable as oppoesd to an array
734 * (see input_clean_array() for more details)
735 *
736 * @access public
737 *
738 * @param string Variable name in $isso->in[]
739 * @param integer Sanitization type constant
740 */
741 function input_clean($varname, $type)
742 {
743 if (isset($this->in["$varname"]))
744 {
745 $this->in["$varname"] = $this->clean($this->in["$varname"], $type);
746 }
747 else
748 {
749 $this->in["$varname"] = null;
750 }
751 }
752
753 // ###################################################################
754 /**
755 * Cleaning function that does the work for input_clean(); this is
756 * moved here so it can be used to clean things that aren't in
757 * $isso->in[]
758 *
759 * @access public
760 *
761 * @param mixed Data
762 * @param integer Sanitization type constant
763 *
764 * @return mixed Cleaned data
765 */
766 function clean($value, $type)
767 {
768 if ($type == TYPE_INT)
769 {
770 $value = intval($value);
771 }
772 else if ($type == TYPE_UINT)
773 {
774 $value = abs(intval($value));
775 }
776 else if ($type == TYPE_FLOAT)
777 {
778 $value = floatval($value);
779 }
780 else if ($type == TYPE_BOOL)
781 {
782 $value = (bool)$value;
783 }
784 else if ($type == TYPE_STR)
785 {
786 if (!$this->escapestrings)
787 {
788 $value = $this->escape($value);
789 }
790 }
791 else if ($type == TYPE_STRUN)
792 {
793 $value = $this->unsanitize($value);
794 }
795 else if ($type == TYPE_NOCLEAN)
796 {
797 if ($this->escapestrings)
798 {
799 $value = $this->escape($value);
800 }
801 }
802 else
803 {
804 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR);
805 }
806
807 return $value;
808 }
809
810 // ###################################################################
811 /**
812 * Checks to see if a POST refer is actually from us
813 *
814 * @access public
815 */
816 function exec_referer_check()
817 {
818 if ($_SERVER['REQUEST_METHOD'] == 'POST')
819 {
820 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
821
822 if ($host AND $_SERVER['HTTP_REFERER'])
823 {
824 $parts = parse_url($_SERVER['HTTP_REFERER']);
825 $ourhost = $parts['host'] . (($parts['port']) ? ":$parts[port]" : '');
826
827 if ($ourhost != $host)
828 {
829 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
830 }
831 $this->debug('remote post check = ok');
832 }
833 else
834 {
835 $this->debug('remote post check = FAILED');
836 }
837 }
838 }
839 }
840
841 /*=====================================================================*\
842 || ###################################################################
843 || # $HeadURL$
844 || # $Id$
845 || ###################################################################
846 \*=====================================================================*/
847 ?>