Add some debug logs
[isso.git] / kernel.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]issoversion[#]
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 // when we are PHP5-nat instead of PHP5-compat, we can remove this
36 if (version_compare(PHP_VERSION, '5.0.0', '>='))
37 {
38 if (ini_get('error_reporting') & E_NOTICE)
39 {
40 error_reporting(ini_get('error_reporting') - E_NOTICE);
41 }
42 if (ini_get('error_reporting') & E_USER_NOTICE)
43 {
44 error_reporting(ini_get('error_reporting') - E_USER_NOTICE);
45 }
46 }
47
48 if ((bool)ini_get('register_globals') === true)
49 {
50 $superglobals = array('_GET', '_COOKIE', '_FILES', '_POST', '_SERVER', '_ENV');
51 foreach ($superglobals AS $global)
52 {
53 if (is_array(${$global}))
54 {
55 foreach (${$global} AS $_key => $_val)
56 {
57 if (isset(${$_key}))
58 {
59 unset(${$_key});
60 }
61 }
62 }
63 }
64 }
65
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)
70 {
71 if ($oldlevel & $php)
72 {
73 if (!($oldlevel & $isso))
74 {
75 $newlevel += $isso;
76 }
77 }
78 else
79 {
80 if ($oldlevel & $isso)
81 {
82 $newlevel -= $isso;
83 }
84 }
85 }
86 error_reporting($newlevel);
87
88 /**#@+
89 * Input cleaning type constant
90 */
91 /**
92 * Integer type
93 */
94 define('TYPE_INT', 1);
95
96 /**
97 * Unsigned integer
98 */
99 define('TYPE_UINT', 2);
100
101 /**
102 * Float type
103 */
104 define('TYPE_FLOAT', 4);
105
106 /**
107 * Boolean type
108 */
109 define('TYPE_BOOL', 8);
110
111 /**
112 * String - cleaned
113 */
114 define('TYPE_STR', 16);
115
116 /**
117 * String - deliberate unclean
118 */
119 define('TYPE_STRUN', 32);
120
121 /**
122 * No cleaning - here for use in API
123 */
124 define('TYPE_NOCLEAN', 64);
125 /**#@-*/
126
127 /**
128 * Yes, required
129 */
130 define('REQ_YES', 1);
131
132 /**
133 * No, not required
134 */
135 define('REQ_NO', 0);
136
137 /**
138 * Iris Studios Shared Object Framework (ISSO)
139 *
140 * This framework allows a common backend to be used amongst all Iris
141 * Studios applications and is built to be abstract and flexible.
142 * The base framework handles all loading and module management.
143 *
144 * Constants:
145 * ISSO_NO_INPUT_SANITIZE - Disables the automatic input sanitizer
146 * ISSO_CHECK_POST_REFERER - Will check to make sure that on POSTed
147 * data, the referer matches the host
148 * ISSO_MT_START - Define the microtime() value at the top of your
149 * script and this will calculate the total execution
150 * time
151 * SVN - Place SVN keywords (like $Id) to display the information on output
152 *
153 * @author Iris Studios, Inc.
154 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
155 * @version $Revision$
156 * @package ISSO
157 *
158 */
159 class ISSO
160 {
161 /**
162 * ISSO version
163 * @var string
164 * @access private
165 */
166 var $version = '[#]issoversion[#]';
167
168 /**
169 * Location of ISSO, used for internal linking
170 * @var string
171 * @access private
172 */
173 var $sourcepath = '';
174
175 /**
176 * Path of the current application
177 * @var string
178 * @access private
179 */
180 var $apppath = '';
181
182 /**
183 * Web path used to get the web location of the installation of ISSO; only used for Printer module
184 * @var string
185 * @access private
186 */
187 var $webpath = '';
188
189 /**
190 * Name of the current application
191 * @var string
192 * @access private
193 */
194 var $application = '';
195
196 /**
197 * Version of the current application
198 * @var string
199 * @access private
200 */
201 var $appversion = '';
202
203 /**
204 * Whether debug mode is on or off
205 * @var bool
206 * @access private
207 */
208 var $debug = false;
209
210 /**
211 * List of all active debug messages
212 * @var array
213 * @access private
214 */
215 var $debuginfo = array();
216
217 /**
218 * List of loaded modules
219 * @var array
220 * @access private
221 */
222 var $modules = array();
223
224 /**
225 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
226 * @var array
227 * @access public
228 */
229 var $in = array();
230
231 /**
232 * If we are running with magic_quotes_gpc on or off
233 * @var int
234 * @access private
235 */
236 var $magicquotes = 0;
237
238 /**
239 * Array of user-specified fields that are required for ISSO initialization
240 * fieldname => array(REQUIRED, CALLBACK PARSER, SET)
241 * @var array
242 * @access private
243 */
244 var $fields = array(
245 'sourcepath' => array(REQ_YES, 'fetch_sourcepath', false),
246 'apppath' => array(REQ_YES, 'fetch_sourcepath', false),
247 'webpath' => array(REQ_NO, 'fetch_sourcepath', false),
248 'application' => array(REQ_YES, null, false),
249 'appversion' => array(REQ_NO, null, false),
250 'debug' => array(REQ_NO, null, false)
251 );
252
253 // ###################################################################
254 /**
255 * Constructor
256 */
257 function __construct()
258 {
259 $GLOBALS['isso:callback'] = null;
260
261 // error reporting
262 set_error_handler(array(&$this, '_error_handler'));
263
264 // magic quotes
265 $this->magicquotes = get_magic_quotes_gpc();
266 set_magic_quotes_runtime(0);
267
268 // some debug info that's always useful
269 $this->debug('magic_quotes_gpc = ' . $this->magicquotes);
270 $this->debug('register_globals = ' . ini_get('register_globals'));
271
272 // attempt to set the sourcepath
273 $path = call_user_func('debug_backtrace');
274 $this->set('sourcepath', str_replace('kernel.php', '', $path[0]['file']));
275
276 // start input sanitize using variable_order GPC
277 if (!defined('ISSO_NO_INPUT_SANITIZE'))
278 {
279 $this->exec_sanitize_data();
280 }
281
282 if (defined('ISSO_CHECK_POST_REFERER'))
283 {
284 $this->exec_referer_check();
285 }
286 }
287
288 // ###################################################################
289 /**
290 * (PHP 4) Constructor
291 */
292 function ISSO()
293 {
294 $this->__construct();
295 }
296
297 // ###################################################################
298 /**
299 * Sets a specified field in the ISSO. This is used to set all the
300 * required fields that ISSO uses for linking. It replaces the old
301 * method of setting the instance variables directly.
302 *
303 * @access public
304 *
305 * @param string Field name
306 * @param mixed Value of the field
307 */
308 function set($fieldname, $value)
309 {
310 $this->do_set($fieldname, $value, null);
311 }
312
313 // ###################################################################
314 /**
315 * Does the actual setting of the field. set() is defined in each
316 * module, but this controls the actual data. This is done so that
317 * there isn't an extra parameter in set() that controls module spaces
318 *
319 * @access protected
320 *
321 * @param string Field name
322 * @param mixed Value
323 * @param string Module name (as referred to in ISSO->modules[]) to place in
324 */
325 function do_set($fieldname, $value, $module)
326 {
327 if ($module == null)
328 {
329 $field =& $this->fields["$fieldname"];
330 }
331 else
332 {
333 $field =& $this->modules["$module"]->fields["$fieldname"];
334 }
335
336 if (is_array($field))
337 {
338 if ($field[1] != null)
339 {
340 if (preg_match('#^\$(.*)#', $field[1]))
341 {
342 $caller = preg_replace('#^\$(.*)->([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$#', 'array(&$\1, "\2")', $field[1]);
343 eval('$caller = ' . $caller . ';');
344 }
345 else
346 {
347 $caller = array(&$this, $field[1]);
348 }
349
350 $value = call_user_func($caller, $value);
351 }
352
353 if ($module == null)
354 {
355 $this->$fieldname = $value;
356 }
357 else
358 {
359 $this->modules["$module"]->$fieldname = $value;
360 }
361
362 $field[2] = true;
363 }
364 else
365 {
366 trigger_error('Invalid field `' . $module . '.' . $fieldname . '` specified in ISSO->do_set()', E_USER_ERROR);
367 }
368 }
369
370 // ###################################################################
371 /**
372 * Fetches the value of a field. This is protected because get() should
373 * be defined in each module to make a call to this function.
374 *
375 * @access protected
376 *
377 * @param string Field name
378 * @param string Module name (as referred to in ISSO->modules[]) to fetch from
379 */
380 function do_get($fieldname, $module)
381 {
382 if ($module == null)
383 {
384 $field =& $this->fields["$fieldname"];
385 }
386 else
387 {
388 $field =& $this->modules["$module"]->fields["$fieldname"];
389 }
390
391 if (is_array($field))
392 {
393 if ($field[2] == false)
394 {
395 trigger_error('Field ' . $module . ':: ' . $filedname . ' is not set and therefore cannot be get()', E_USER_ERROR);
396 }
397
398 if ($module == null)
399 {
400 return $this->$fieldname;
401 }
402 else
403 {
404 return $this->modules["$module"]->$fieldname;
405 }
406
407 $field[2] = true;
408 }
409 else
410 {
411 trigger_error('Invalid field `' . $module . '.' . $fieldname . '` specified in ISSO->do_get()', E_USER_ERROR);
412 }
413 }
414
415 // ###################################################################
416 /**
417 * Returns the value of an ISSO field. You should not access any instance
418 * variables directly, use this instead.
419 *
420 * @access public
421 *
422 * @param string Field name
423 *
424 * @return mixed Value of the field
425 */
426 function get($fieldname)
427 {
428 return $this->do_get($fieldname, null);
429 }
430
431 // ###################################################################
432 /**
433 * Makes sure that all of the required fields in ISSO are set before
434 * any action is done. This will throw an error block describing
435 * the fields that need to be set if any are missing.
436 *
437 * @access public
438 *
439 * @param string Module to check for; null is kernel, string is a module name, false is all
440 * @param bool Is this a non-error environment that should display all fields?
441 */
442 function check_isso_fields($module = null, $called = false)
443 {
444 $missing = array();
445
446 if ($module === false)
447 {
448 $modules = $this->show_modules(true);
449 }
450 else if ($module === null)
451 {
452 $modules = array(get_class($this));
453 }
454 else
455 {
456 $modules = array($module);
457 }
458
459 foreach ($modules AS $module)
460 {
461 if (empty($this->modules["$module"]->fields))
462 {
463 continue;
464 }
465
466 foreach ($this->modules["$module"]->fields AS $name => $field)
467 {
468 if ($field[0] == REQ_YES AND $field[2] == false AND $called == false)
469 {
470 $missing[] = $module . ':: ' . $name;
471 }
472 else if ($called == true AND $field[2] == false)
473 {
474 $missing[] = $module . ':: ' . $name . ($field[0] == REQ_YES ? ' <strong>(REQUIRED)</strong>' : '');
475 }
476 }
477 }
478
479 if (sizeof($missing) > 0)
480 {
481 $error = ($called ? 'The following fields are not set:' : 'You are missing required ISSO fields. Please make sure you have set:');
482 $error .= "\n";
483 $error .= '<ul>';
484
485 foreach ($missing AS $field)
486 {
487 $error .= "\n\t" . '<li>' . $field . '</li>';
488 }
489
490 $error .= "\n" . '</ul>';
491
492 $this->message(($called ? '' : 'Missing ') . 'Fields', $error, ($called ? 1 : 3));
493
494 if ($called == false)
495 {
496 exit;
497 }
498 }
499 }
500
501 // ###################################################################
502 /**
503 * Prepares a path for being set as the sourcepath
504 *
505 * @access public
506 *
507 * @param string Source path or URL
508 *
509 * @return string Prepared source path
510 */
511 function fetch_sourcepath($source)
512 {
513 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
514 {
515 $source .= DIRECTORY_SEPARATOR;
516 }
517 return $source;
518 }
519
520 // ###################################################################
521 /**
522 * Loads a framework module
523 *
524 * @access public
525 *
526 * @param string Name of the framework file to load
527 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
528 * @param bool Globalize the internal variable?
529 *
530 * @return object Instantiated instance
531 */
532 function &load($framework, $asobject, $globalize = false)
533 {
534 $this->check_isso_fields(null);
535
536 // set the object interlock
537 if (!method_exists($GLOBALS['isso:callback'], 'load'))
538 {
539 $GLOBALS['isso:callback'] =& $this;
540 $this->modules['isso'] =& $this;
541 }
542
543 if ($this->is_loaded($framework))
544 {
545 return $this->modules["$framework"];
546 }
547
548 if ($this->sourcepath == '')
549 {
550 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
551 }
552
553 if (file_exists($this->sourcepath . $framework . '.php'))
554 {
555 require_once($this->sourcepath . $framework . '.php');
556 }
557 else
558 {
559 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
560 }
561
562 if ($asobject === null)
563 {
564 return;
565 }
566
567 if (isset($this->$asobject))
568 {
569 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
570 }
571
572 $this->$asobject = new $framework($this);
573
574 $this->modules["$framework"] =& $this->$asobject;
575
576 if ($globalize)
577 {
578 $GLOBALS["$asobject"] =& $this->$asobject;
579 }
580
581 // allow for init_as_package to link
582 if (method_exists($this->modules["$framework"], 'init_as_package'))
583 {
584 $this->modules[ $this->modules["$framework"]->init_as_package() ] =& $this->modules["$framework"];
585 }
586
587 return $this->$asobject;
588 }
589
590 // ###################################################################
591 /**
592 * Prints a list of all currently loaded framework modules
593 *
594 * @access public
595 *
596 * @param bool Return the data as an array?
597 *
598 * @return mixed HTML output or an array of loaded modules
599 */
600 function show_modules($return = false)
601 {
602 $modules = array();
603 foreach ($this->modules AS $object)
604 {
605 $module = get_class($object);
606 if (method_exists($object, 'init_as_package') AND in_array($module, $modules))
607 {
608 $module = $object->init_as_package() . " - ($module)";
609 }
610
611 $modules[] = $module;
612 }
613
614 if ($return)
615 {
616 return $modules;
617 }
618 else
619 {
620 $output = "\n\n<ul>\n\t<li>";
621 $output .= implode("</li>\n\t<li>", $modules);
622 $output .= "</li>\n</ul>\n\n";
623 $this->message('Loaded Modules', $output, 1);
624 }
625 }
626
627 // ###################################################################
628 /**
629 * Verifies to see if a framework has been loaded
630 *
631 * @access public
632 *
633 * @param string Framework name
634 *
635 * @return bool Whether or not the framework has been loaded
636 */
637 function is_loaded($framework)
638 {
639 if (isset($this->modules["$framework"]))
640 {
641 return true;
642 }
643 else
644 {
645 return false;
646 }
647 }
648
649 // ###################################################################
650 /**
651 * Prints an ISSO message
652 *
653 * @access public
654 *
655 * @param string The title of the message
656 * @param string The content of the message
657 * @param integer Type of message to be printed
658 * @param bool Return the output?
659 * @param bool Show the debug stack?
660 * @param integer Message width
661 *
662 * @return mixed Output or null
663 */
664 function message($title, $message, $type, $return = false, $stack = true, $width = 500)
665 {
666 switch ($type)
667 {
668 // Message
669 case 1:
670 $prefix = 'Message';
671 $color = '#669900';
672 $font = '#000000';
673 break;
674
675 // Warning
676 case 2:
677 $prefix = 'Warning';
678 $color = '#003399';
679 $font = '#FFFFFF';
680 break;
681
682 case 3:
683 $prefix = 'Error';
684 $color = '#990000';
685 $font = '#EFEFEF';
686 break;
687 }
688
689 $backtrace = debug_backtrace();
690 array_shift($backtrace);
691
692 if (isset($backtrace[0]) AND $backtrace[0]['function'] == '_error_handler')
693 {
694 array_shift($backtrace);
695 }
696
697 $trace = $this->format_debug_trace($backtrace);
698
699 $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;\">";
700 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
701 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>";
702 $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>" : '');
703 $output .= "\n</table>\n<br />\n";
704
705 if ($return)
706 {
707 return $output;
708 }
709 else
710 {
711 print($output);
712 }
713 }
714
715 // ###################################################################
716 /**
717 * Prepares a debug_backtrace() array for output to the browser by
718 * compressing the array into visible text
719 *
720 * @access public
721 *
722 * @param array debug_backtrace() array
723 *
724 * @return array Formatted trace output
725 */
726 function format_debug_trace($backtrace)
727 {
728 $trace = array();
729 foreach ($backtrace AS $i => $step)
730 {
731 $args = '';
732 $file = $step['file'] . ':' . $step['line'];
733 $funct = (isset($step['class']) ? $step['class'] . '::' . $step['function'] : $step['function']);
734
735 if (isset($step['args']) AND is_array($step['args']))
736 {
737 // we need to do this so we don't get "Array to string conversion" notices
738 foreach ($step['args'] AS $id => $arg)
739 {
740 if (is_array($arg))
741 {
742 $step['args']["$id"] = 'Array';
743 }
744 }
745 $args = implode(', ', $step['args']);
746 }
747
748 $trace[] = "#$i $funct($args) called at [$file]";
749 }
750
751 return $trace;
752 }
753
754 // ###################################################################
755 /**
756 * Custom error handler for ISSO; only handle E_WARNING, E_NOTICE,
757 * E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
758 *
759 * @access private
760 *
761 * @param integer Error number
762 * @param string Error message string
763 * @param string File that contains the error
764 * @param string The line number of the error
765 * @param string The active symbol table at which point the error occurred
766 */
767 function _error_handler($errno, $errstr, $errfile, $errline, $errcontext)
768 {
769 $level = ini_get('error_reporting');
770
771 switch ($errno)
772 {
773 // Fatal
774 case E_USER_ERROR:
775 $title = 'Fatal';
776 $mode = 3;
777 if (!($level & E_USER_ERROR))
778 {
779 return;
780 }
781 break;
782
783 // Error
784 case E_USER_WARNING:
785 case E_WARNING:
786 $title = 'Warning';
787 $mode = 2;
788 if (! (($level & E_USER_WARNING) AND ($level & E_WARNING)) )
789 {
790 return;
791 }
792 break;
793
794 // Warning
795 case E_USER_NOTICE:
796 case E_NOTICE:
797 default:
798 $title = 'Notice';
799 $mode = 1;
800 if (! (($level & E_USER_NOTICE) AND ($level & E_NOTICE)) )
801 {
802 return;
803 }
804 break;
805 }
806
807 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
808
809 $errstr = str_replace(array(getcwd(), dirname(getcwd())), '', $errstr);
810
811 $this->message($title, $errstr, $mode);
812
813 if ($errno == E_USER_ERROR)
814 {
815 exit;
816 }
817 }
818
819 // ###################################################################
820 /**
821 * Creates a table that explains the error reporting levels and their
822 * state
823 *
824 * @access public
825 */
826 function explain_error_reporting()
827 {
828 $levels = array(
829 'E_ERROR' => E_ERROR,
830 'E_WARNING' => E_WARNING,
831 'E_PARSE' => E_PARSE,
832 'E_NOTICE' => E_NOTICE,
833 'E_CORE_ERROR' => E_CORE_ERROR,
834 'E_CORE_WARNING' => E_CORE_WARNING,
835 'E_COMPILE_ERROR' => 64,
836 'E_COMPILE_WARNING' => 128,
837 'E_USER_ERROR' => E_USER_ERROR,
838 'E_USER_WARNING' => E_USER_WARNING,
839 'E_USER_NOTICE' => E_USER_NOTICE,
840 'E_ALL' => E_ALL,
841 'E_STRICT' => 2048
842 );
843
844 $table = '<table cellspacing="0" cellpadding="2" border="0">';
845
846 foreach ($levels AS $name => $value)
847 {
848 $table .= '
849 <tr>
850 <td>' . $name . '</td>
851 <td>' . (ini_get('error_reporting') & $value) . '</td>
852 </tr>';
853 }
854
855 $table .= '
856 </table>';
857
858 $this->message('Error Reporting', $table, 1);
859 }
860
861 // ###################################################################
862 /**
863 * Logs a debug message for verbose output
864 *
865 * @access public
866 *
867 * @param string Message
868 */
869 function debug($message)
870 {
871 $this->debuginfo[] = $message;
872 }
873
874 // ###################################################################
875 /**
876 * Recursive XSS cleaner
877 *
878 * @access private
879 *
880 * @param mixed Unsanitized REQUEST data
881 *
882 * @return mixed Sanitized data
883 */
884 function _sanitize_input_recursive($data)
885 {
886 foreach ($data AS $key => $value)
887 {
888 if (is_array($value))
889 {
890 $data["$key"] = $this->_sanitize_input_recursive($value);
891 }
892 else
893 {
894 if ($this->magicquotes)
895 {
896 $value = str_replace("\'", "'", $value);
897 }
898 $data["$key"] = $this->sanitize($value);
899 }
900 }
901 return $data;
902 }
903
904 // ###################################################################
905 /**
906 * Simple way to protect against HTML attacks with Unicode support
907 *
908 * @access public
909 *
910 * @param string Unsanitzed text
911 *
912 * @return string Properly protected text that only encodes potential threats
913 */
914 function sanitize($text)
915 {
916 if ($this->magicquotes)
917 {
918 return str_replace(array('<', '>', '\"', '"'), array('&lt;', '&gt;', '&quot;', '&quot;'), $text);
919 }
920 else
921 {
922 return str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $text);
923 }
924 }
925
926 // ###################################################################
927 /**
928 * Unicode-safe entity encoding system; similar to sanitize()
929 *
930 * @access public
931 *
932 * @param string Unsanitized text
933 *
934 * @return string Unicode-safe sanitized text with entities preserved
935 */
936 function entity_encode($text)
937 {
938 $text = str_replace('&', '&amp;', $text);
939 $text = $this->sanitize($text);
940 return $text;
941 }
942
943 // ###################################################################
944 /**
945 * Takes text that has been processed for HTML and unsanitizes it
946 *
947 * @access public
948 *
949 * @param string Text that needs to be turned back into HTML
950 *
951 * @return string Unsanitized text
952 */
953 function unsanitize($text)
954 {
955 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '"'), $text);
956 }
957
958 // ###################################################################
959 /**
960 * Smart addslashes() that only applies itself it the Magic Quotes GPC
961 * is off. This should only be run on database query values that come
962 * from ISSO->in[] input; data that needs sanitization should be run
963 * through ISSO->DB->escape_string()
964 *
965 * @access public
966 *
967 * @param string Some string
968 * @param bool Force magic quotes to be off
969 *
970 * @return string String that has slashes added
971 */
972 function escape($str, $force = true)
973 {
974 if ($this->magicquotes AND !$force)
975 {
976 if (isset($this->modules[ISSO_DB_LAYER]))
977 {
978 return $this->modules[ISSO_DB_LAYER]->escape_string(str_replace(array("\'", '\"'), array("'", '"'), $str));
979 }
980 return $str;
981 }
982 else
983 {
984 if (isset($this->modules[ISSO_DB_LAYER]))
985 {
986 return $this->modules[ISSO_DB_LAYER]->escape_string($str);
987 }
988 return addslashes($str);
989 }
990 }
991
992 // ###################################################################
993 /**
994 * Runs through all of the input data and sanitizes it.
995 *
996 * @access private
997 */
998 function exec_sanitize_data()
999 {
1000 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
1001 }
1002
1003 // ###################################################################
1004 /**
1005 * Sanitize function for something other than a string (which
1006 * everything is sanitized for if you use exec_sanitize_data(). Cleaned
1007 * data is placed back into $isso->in; this makes it so you don't have
1008 * to constantly intval() [etc.] data.
1009 *
1010 * @access public
1011 *
1012 * @param array Array of elements to clean as varname => type
1013 */
1014 function input_clean_array($vars)
1015 {
1016 foreach ($vars AS $varname => $type)
1017 {
1018 $this->input_clean($varname, $type);
1019 }
1020 }
1021
1022 // ###################################################################
1023 /**
1024 * Sanitize function that does a single variable as oppoesd to an array
1025 * (see input_clean_array() for more details)
1026 *
1027 * @access public
1028 *
1029 * @param string Variable name in $isso->in[]
1030 * @param integer Sanitization type constant
1031 */
1032 function input_clean($varname, $type)
1033 {
1034 if (isset($this->in["$varname"]))
1035 {
1036 $this->in["$varname"] = $this->clean($this->in["$varname"], $type);
1037 }
1038 else
1039 {
1040 $this->in["$varname"] = $this->clean(null, $type);
1041 }
1042
1043 return $this->in["$varname"];
1044 }
1045
1046 // ###################################################################
1047 /**
1048 * Runs ISSO->escape() on a variable on ISSO->in[]. This is just a
1049 * short-hand wrapper so that queries can be shortened. When this is used,
1050 * the actual value in ISSO->in[] is not changed, only the return value
1051 * is escaped.
1052 *
1053 * @access public
1054 *
1055 * @param string Input variable
1056 *
1057 * @return string Escaped input
1058 */
1059 function input_escape($varname)
1060 {
1061 if (isset($this->in["$varname"]))
1062 {
1063 return $this->escape($this->in["$varname"]);
1064 }
1065 else
1066 {
1067 return $this->escape(null);
1068 }
1069 }
1070
1071 // ###################################################################
1072 /**
1073 * Cleaning function that does the work for input_clean(); this is
1074 * moved here so it can be used to clean things that aren't in
1075 * $isso->in[]
1076 *
1077 * @access public
1078 *
1079 * @param mixed Data
1080 * @param integer Sanitization type constant
1081 *
1082 * @return mixed Cleaned data
1083 */
1084 function clean($value, $type)
1085 {
1086 if (is_array($value))
1087 {
1088 return $this->clean_array($value, $type);
1089 }
1090
1091 if ($type == TYPE_INT)
1092 {
1093 $value = intval($value);
1094 }
1095 else if ($type == TYPE_UINT)
1096 {
1097 $value = (($val = intval($value)) < 0 ? 0 : $val);
1098 }
1099 else if ($type == TYPE_FLOAT)
1100 {
1101 $value = floatval($value);
1102 }
1103 else if ($type == TYPE_BOOL)
1104 {
1105 $value = (bool)$value;
1106 }
1107 else if ($type == TYPE_STR)
1108 {
1109 $value = $value;
1110 }
1111 else if ($type == TYPE_STRUN)
1112 {
1113 $value = $this->unsanitize($value);
1114 }
1115 else if ($type == TYPE_NOCLEAN)
1116 {
1117 if ($this->magicquotes)
1118 {
1119 $value = str_replace(array('\"', "\'"), array('"', "'"), $value);
1120 }
1121 else
1122 {
1123 $value = $value;
1124 }
1125 }
1126 else
1127 {
1128 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR);
1129 }
1130
1131 return $value;
1132 }
1133
1134 // ###################################################################
1135 /**
1136 * Recursion function for ISSO->clean()
1137 *
1138 * @access private
1139 *
1140 * @param array Uncleaned array
1141 * @param integer Sanitization type constant
1142 *
1143 * @return array Cleaned array of data
1144 */
1145 function clean_array($array, $type)
1146 {
1147 foreach ($array AS $key => $value)
1148 {
1149 $array["$key"] = $this->clean($value, $type);
1150 }
1151
1152 return $array;
1153 }
1154
1155 // ###################################################################
1156 /**
1157 * Checks to see if a POST refer is actually from us
1158 *
1159 * @access public
1160 */
1161 function exec_referer_check()
1162 {
1163 if ($_SERVER['REQUEST_METHOD'] == 'POST')
1164 {
1165 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
1166
1167 if ($host AND $_SERVER['HTTP_REFERER'])
1168 {
1169 $parts = parse_url($_SERVER['HTTP_REFERER']);
1170 $ourhost = $parts['host'] . (isset($parts['port']) ? ":$parts[port]" : '');
1171
1172 if ($ourhost != $host)
1173 {
1174 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
1175 }
1176 $this->debug('remote post check = ok');
1177 }
1178 else
1179 {
1180 $this->debug('remote post check = FAILED');
1181 }
1182 }
1183 }
1184
1185 // ###################################################################
1186 /**
1187 * Constructs a debug information box that contains various debugging
1188 * information points
1189 *
1190 * @access public
1191 *
1192 * @param bool Show template information?
1193 *
1194 * @return string Debugging block
1195 */
1196 function construct_debug_block($dotemplates)
1197 {
1198 $debug = '';
1199
1200 if ($this->debug)
1201 {
1202 $debug = "\n<ul>";
1203
1204 // templates
1205 if ($dotemplates)
1206 {
1207 $optlist = array();
1208 $usage = array();
1209 foreach ($this->modules['template']->usage AS $name => $count)
1210 {
1211 if (in_array($name, $this->modules['template']->uncached))
1212 {
1213 $optlist[] = $name . '[' . $count . ']';
1214 }
1215 $usage[] = $name . " ($count)";
1216 }
1217
1218 $sizeof = sizeof($this->modules['template']->uncached);
1219 if ($sizeof > 0)
1220 {
1221 $debug .= "\n\t<li><strong style=\"color: red\">Uncached Template(s):</strong> $sizeof ( " . implode(' &nbsp; ', $optlist) . " )</li>";
1222 }
1223 }
1224
1225 // source control
1226 $scinfo = 'Not Under Source Control';
1227 if (defined('SVN'))
1228 {
1229 $scinfo = constant('SVN');
1230
1231 if (preg_match('#\$Id:?\s*\$#', $scinfo))
1232 {
1233 $scinfo = 'Not Under Source Control';
1234 }
1235 else
1236 {
1237 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
1238 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
1239 $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);
1240 }
1241 }
1242
1243 $scinfo = trim($scinfo);
1244 $debug .= "\n\t<li><strong>Source Control:</strong> $scinfo</li>";
1245
1246 // query information
1247 if (is_object($this->modules[ISSO_DB_LAYER]))
1248 {
1249 $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) ? '&amp;query=1' : '?query=1') . "\">?</a>)</li>";
1250 }
1251
1252 // total execution time
1253 if (defined('ISSO_MT_START'))
1254 {
1255 $this->load('functions', 'functions');
1256 $debug .= "\n\t<li><strong>Total Execution Time:</strong> " . round($this->modules['functions']->fetch_microtime_diff(ISSO_MT_START), 10) . "</li>";
1257 }
1258
1259 // debug notices
1260 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Debug Notices (" . sizeof($this->debuginfo) . ")</option>";
1261 foreach ((array)$this->debuginfo AS $msg)
1262 {
1263 $debug .= "\n\t\t\t<option>--- $msg</option>";
1264 }
1265 $debug .= "\n\t\t</select>\n\t</li>";
1266
1267 // loaded modules
1268 $modules = $this->show_modules(true);
1269 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Loaded Modules (" . sizeof($modules) . ")</option>";
1270 foreach ($modules AS $mod)
1271 {
1272 $debug .= "\n\t\t\t<option>--- $mod</option>";
1273 }
1274 $debug .= "\n\t\t</select>\n\t</li>";
1275
1276 // template usage
1277 if ($dotemplates)
1278 {
1279 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Template Usage (" . array_sum($this->modules['template']->usage) . ")</option>";
1280 foreach ($usage AS $tpl)
1281 {
1282 $debug .= "\n\t\t\t<option>--- $tpl</option>";
1283 }
1284 $debug .= "\n\t\t</select>\n\t</li>";
1285 }
1286
1287 $debug .= "\n</ul>";
1288
1289 $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";
1290 }
1291
1292 return $debug;
1293 }
1294 }
1295
1296 /*=====================================================================*\
1297 || ###################################################################
1298 || # $HeadURL$
1299 || # $Id$
1300 || ###################################################################
1301 \*=====================================================================*/
1302 ?>