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