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