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