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