Added visibility information to all the functions
[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 * Constructor
217 */
218 function __construct()
219 {
220 // error reporting
221 set_error_handler(array(&$this, '_error_handler'));
222
223 // magic quotes
224 $this->magicquotes = get_magic_quotes_gpc();
225 set_magic_quotes_runtime(0);
226
227 if (defined('ISSO_ESCAPE_STRINGS'))
228 {
229 $this->escapestrings = (bool)constant('ISSO_ESCAPE_STRINGS');
230 }
231
232 // start input sanitize using variable_order GPC
233 if (!$this->escapestrings)
234 {
235 $this->exec_sanitize_data();
236 }
237
238 if (defined('ISSO_CHECK_POST_REFERER'))
239 {
240 $this->exec_referer_check();
241 }
242
243 $GLOBALS['isso:null-framework'] = null;
244 }
245
246 /**
247 * (PHP 4) Constructor
248 */
249 function Shared_Object_Framework()
250 {
251 $this->__construct();
252 }
253
254 /**
255 * Prepares a path for being set as the sourcepath
256 *
257 * @access public
258 *
259 * @param string Source path or URL
260 *
261 * @return string Prepared source path
262 */
263 function fetch_sourcepath($source)
264 {
265 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
266 {
267 $source .= DIRECTORY_SEPARATOR;
268 }
269 return $source;
270 }
271
272 /**
273 * Loads a framework module
274 *
275 * @access public
276 *
277 * @param string Name of the framework file to load
278 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
279 * @param bool Globalize the internal variable?
280 *
281 * @return object Instantiated instance
282 */
283 function &load($framework, $asobject, $globalize = false)
284 {
285 // set the object interlock
286 if (!method_exists($GLOBALS['isso:null-framework'], 'load'))
287 {
288 $GLOBALS['isso:null-framework'] =& $this;
289 }
290
291 if ($this->is_loaded($framework))
292 {
293 return $this->modules["$framework"];
294 }
295
296 if ($this->sourcepath == '')
297 {
298 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
299 }
300
301 if (file_exists($this->sourcepath . $framework . '.php'))
302 {
303 require_once($this->sourcepath . $framework . '.php');
304 }
305 else
306 {
307 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
308 }
309
310 if ($asobject === null)
311 {
312 return;
313 }
314
315 if (isset($this->$asobject))
316 {
317 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
318 }
319
320 $this->$asobject = new $framework($this);
321
322 $this->modules["$framework"] =& $this->$asobject;
323
324 if ($globalize)
325 {
326 $GLOBALS["$asobject"] =& $this->$asobject;
327 }
328
329 return $this->$asobject;
330 }
331
332 /**
333 * Prints a list of all currently loaded framework modules
334 *
335 * @access public
336 *
337 * @param bool Return the data as an array?
338 *
339 * @return mixed HTML output or an array of loaded modules
340 */
341 function show_modules($return = false)
342 {
343 foreach ($this->modules AS $object)
344 {
345 $modules[] = get_class($object);
346 }
347
348 if ($return)
349 {
350 return $modules;
351 }
352 else
353 {
354 $output = "\n\n<ul>\n\t<li>";
355 $output .= implode("</li>\n\t<li>", $modules);
356 $output .= "</li>\n</ul>\n\n";
357 $this->message('Loaded Modules', $output, 1);
358 }
359 }
360
361 /**
362 * Verifies to see if a framework has been loaded
363 *
364 * @access public
365 *
366 * @param string Framework name
367 *
368 * @return bool Whether or not the framework has been loaded
369 */
370 function is_loaded($framework)
371 {
372 if (isset($this->modules["$framework"]))
373 {
374 return true;
375 }
376 else
377 {
378 return false;
379 }
380 }
381
382 /**
383 * Prints an ISSO message
384 *
385 * @access public
386 *
387 * @param string The title of the message
388 * @param string The content of the message
389 * @param integer Type of message to be printed
390 * @param bool Return the output?
391 * @param bool Show the debug stack?
392 *
393 * @return mixed Output or null
394 */
395 function message($title, $message, $type, $return = false, $stack = true)
396 {
397 switch ($type)
398 {
399 // Message
400 case 1:
401 $prefix = 'Message';
402 $color = '#669900';
403 $font = '#000000';
404 break;
405
406 // Warning
407 case 2:
408 $prefix = 'Warning';
409 $color = '#003399';
410 $font = '#FFFFFF';
411 break;
412
413 case 3:
414 $prefix = 'Error';
415 $color = '#990000';
416 $font = '#EFEFEF';
417 break;
418 }
419
420 $backtrace = debug_backtrace();
421 unset($backtrace[0]);
422
423 $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;\">";
424 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
425 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
426 $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>" : '');
427 $output .= "\n</table>\n<br />\n";
428
429 if ($return)
430 {
431 return $output;
432 }
433 else
434 {
435 print($output);
436 }
437 }
438
439 /**
440 * Custom error handler for ISSO
441 * We only handle E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
442 *
443 * @access private
444 *
445 * @param integer Error number
446 * @param string Error message string
447 * @param string File that contains the error
448 * @param string The line number of the error
449 * @param string The active symbol table at which point the error occurred
450 */
451 function _error_handler($errno, $errstr, $errfile, $errline)
452 {
453 switch ($errno)
454 {
455 // Fatal
456 case E_USER_ERROR:
457 $title = 'Fatal';
458 $level = 3;
459 if (!(ini_get('error_reporting') & E_USER_ERROR))
460 {
461 return;
462 }
463 break;
464
465 // Error
466 case E_USER_WARNING:
467 $title = 'Warning';
468 $level = 2;
469 if (!(ini_get('error_reporting') & E_USER_WARNING) AND !(ini_get('error_reporting') & E_WARNING))
470 {
471 return;
472 }
473 break;
474
475 // Warning
476 case E_USER_NOTICE:
477 default:
478 $title = 'Notice';
479 $level = 1;
480 if (!(ini_get('error_reporting') & E_USER_NOTICE) AND !(ini_get('error_reporting') & E_NOTICE))
481 {
482 return;
483 }
484 break;
485 }
486
487 $errfile = str_replace(array(getcwd(), dirname(getcwd())), '', $errfile);
488
489 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
490
491 $this->message($title, $errstr, $level);
492
493 if ($errno == E_USER_ERROR)
494 {
495 exit;
496 }
497 }
498
499 /**
500 * Creates a table that explains the error reporting levels and their sate
501 *
502 * @access public
503 */
504 function explain_error_reporting()
505 {
506 $levels = array(
507 'E_ERROR' => E_ERROR,
508 'E_WARNING' => E_WARNING,
509 'E_PARSE' => E_PARSE,
510 'E_NOTICE' => E_NOTICE,
511 'E_CORE_ERROR' => E_CORE_ERROR,
512 'E_CORE_WARNING' => E_CORE_WARNING,
513 'E_COMPILE_ERROR' => 64,
514 'E_COMPILE_WARNING' => 128,
515 'E_USER_ERROR' => E_USER_ERROR,
516 'E_USER_WARNING' => E_USER_WARNING,
517 'E_USER_NOTICE' => E_USER_NOTICE,
518 'E_ALL' => E_ALL,
519 'E_STRICT' => 2048
520 );
521
522 $table = '<table cellspacing="0" cellpadding="2" border="0">';
523
524 foreach ($levels AS $name => $value)
525 {
526 $table .= '
527 <tr>
528 <td>' . $name . '</td>
529 <td>' . (ini_get('error_reporting') & $value) . '</td>
530 </tr>';
531 }
532
533 $table .= '
534 </table>';
535
536 $this->message('Error Reporting', $table, 1);
537 }
538
539 /**
540 * Logs a debug message for verbose output
541 *
542 * @access public
543 *
544 * @param string Message
545 */
546 function debug($message)
547 {
548 $this->debuginfo[] = $message;
549 }
550
551 /**
552 * Recursive XSS cleaner
553 *
554 * @access private
555 *
556 * @param mixed Unsanitized REQUEST data
557 *
558 * @return mixed Sanitized data
559 */
560 function _sanitize_input_recursive($data)
561 {
562 foreach ($data AS $key => $value)
563 {
564 if (is_array($value))
565 {
566 $data["$key"] = $this->_sanitize_input_recursive($value);
567 }
568 else
569 {
570 if ($this->escapestrings)
571 {
572 $data["$key"] = $this->escape($this->sanitize($value), false, false);
573 }
574 else
575 {
576 $data["$key"] = $this->sanitize($value);
577 }
578 }
579 }
580 return $data;
581 }
582
583 /**
584 * Simple way to protect against HTML attacks with Unicode support
585 *
586 * @access public
587 *
588 * @param string Unsanitzed text
589 *
590 * @return string Properly protected text that only encodes potential threats
591 */
592 function sanitize($text)
593 {
594 if ($this->magicquotes)
595 {
596 return str_replace(array('<', '>', '\"', '"'), array('&lt;', '&gt;', '&quot;', '&quot;'), $text);
597 }
598 else
599 {
600 return str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $text);
601 }
602 }
603
604 /**
605 * Unicode-safe entity encoding system; similar to sanitize()
606 *
607 * @access public
608 *
609 * @param string Unsanitized text
610 *
611 * @return string Unicode-safe sanitized text with entities preserved
612 */
613 function entity_encode($text)
614 {
615 $text = str_replace('&', '&amp;', $text);
616 $text = $this->sanitize($text);
617 return $text;
618 }
619
620 /**
621 * Takes text that has been processed for HTML and unsanitizes it
622 *
623 * @access public
624 *
625 * @param string Text that needs to be turned back into HTML
626 * @param bool Force magicquotes off
627 *
628 * @return string Unsanitized text
629 */
630 function unsanitize($text, $force = false)
631 {
632 if ($this->magicquotes AND !$force)
633 {
634 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '\"'), $text);
635 }
636 else
637 {
638 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '"'), $text);
639 }
640 }
641
642 /**
643 * Smart addslashes() that only applies itself it the Magic Quotes GPC is off
644 *
645 * @access public
646 *
647 * @param string Some string
648 * @param bool If the data is binary; if so it'll be run through DB::escape_stringing()
649 * @param bool Force magic quotes to be off
650 *
651 * @return string String that has slashes added
652 */
653 function escape($str, $binary = false, $force = true)
654 {
655 if ($this->magicquotes AND !$force)
656 {
657 if (isset($this->db) AND $binary)
658 {
659 if (is_resource($this->db->link_id))
660 {
661 return $this->db->escape_string(stripslashes($str));
662 }
663 }
664 return $str;
665 }
666 else
667 {
668 if (isset($this->db) AND $binary)
669 {
670 if (is_resource($this->db->link_id))
671 {
672 return $this->db->escape_string($str);
673 }
674 }
675 return addslashes($str);
676 }
677 }
678
679 /**
680 * Runs through all of the input data and sanitizes it.
681 *
682 * @access public
683 */
684 function exec_sanitize_data()
685 {
686 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
687 // we're now using magic quotes
688 if ($this->escapestrings)
689 {
690 $this->magicquotes = 1;
691 }
692 }
693
694 /**
695 * Sanitize function for something other than a string (which everything is sanitized for if you use exec_sanitize_data().
696 * Cleaned data is placed back into $isso->in; this makes it so you don't have to constantly intval() [etc.] data
697 *
698 * @access public
699 *
700 * @param array Array of elements to clean as varname => type
701 */
702 function input_clean_array($vars)
703 {
704 foreach ($vars AS $varname => $type)
705 {
706 $this->input_clean($varname, $type);
707 }
708 }
709
710 /**
711 * Sanitize function that does a single variable as oppoesd to an array (see input_clean_array() for more details)
712 *
713 * @access public
714 *
715 * @param string Variable name in $isso->in[]
716 * @param integer Sanitization type constant
717 */
718 function input_clean($varname, $type)
719 {
720 if (isset($this->in["$varname"]))
721 {
722 $this->in["$varname"] = $this->clean($this->in["$varname"], $type);
723 }
724 else
725 {
726 $this->in["$varname"] = null;
727 }
728 }
729
730 /**
731 * Cleaning function that does the work for input_clean(); this is moved here so it can be used to clean things that aren't in $isso->in[]
732 *
733 * @access public
734 *
735 * @param mixed Data
736 * @param integer Sanitization type constant
737 *
738 * @return mixed Cleaned data
739 */
740 function clean($value, $type)
741 {
742 if ($type == TYPE_INT)
743 {
744 $value = intval($value);
745 }
746 else if ($type == TYPE_UINT)
747 {
748 $value = abs(intval($value));
749 }
750 else if ($type == TYPE_FLOAT)
751 {
752 $value = floatval($value);
753 }
754 else if ($type == TYPE_BOOL)
755 {
756 $value = (bool)$value;
757 }
758 else if ($type == TYPE_STR)
759 {
760 if (!$this->escapestrings)
761 {
762 $value = $this->escape($value);
763 }
764 }
765 else if ($type == TYPE_STRUN)
766 {
767 $value = $this->unsanitize($value);
768 }
769 else if ($type == TYPE_NOCLEAN)
770 {
771 if ($this->escapestrings)
772 {
773 $value = $this->escape($value);
774 }
775 }
776 else
777 {
778 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR);
779 }
780
781 return $value;
782 }
783
784 /**
785 * Checks to see if a POST refer is actually from us
786 *
787 * @access public
788 */
789 function exec_referer_check()
790 {
791 if ($_SERVER['REQUEST_METHOD'] == 'POST')
792 {
793 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
794
795 if ($host AND $_SERVER['HTTP_REFERER'])
796 {
797 $parts = parse_url($_SERVER['HTTP_REFERER']);
798 $ourhost = $parts['host'] . (($parts['port']) ? ":$parts[port]" : '');
799
800 if ($ourhost != $host)
801 {
802 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
803 }
804 $this->debug('remote post check = ok');
805 }
806 else
807 {
808 $this->debug('remote post check = FAILED');
809 }
810 }
811 }
812 }
813
814 /*=====================================================================*\
815 || ###################################################################
816 || # $HeadURL$
817 || # $Id$
818 || ###################################################################
819 \*=====================================================================*/
820 ?>