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