- Moved rendition of API::do_clean() to ISSO::clean()
[isso.git] / kernel.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
6 || #
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version [#]gpl[#] of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Iris Studios Shared Object Framework Kernel
24 * kernel.php
25 *
26 * @package ISSO
27 */
28
29 if (!function_exists('version_compare'))
30 {
31 trigger_error('You need PHP version 4.1.0 or newer to run ISSO', E_USER_ERROR);
32 exit;
33 }
34
35 if (version_compare(PHP_VERSION, '5.0.0', '>='))
36 {
37 if (ini_get('error_reporting') & E_NOTICE)
38 {
39 error_reporting(ini_get('error_reporting') - E_NOTICE);
40 }
41 if (ini_get('error_reporting') & E_USER_NOTICE)
42 {
43 error_reporting(ini_get('error_reporting') - E_USER_NOTICE);
44 }
45 }
46
47 $oldlevel = ini_get('error_reporting');
48 $newlevel = $oldlevel;
49 $levels = array(E_ERROR => E_USER_ERROR, E_WARNING => E_USER_WARNING, E_NOTICE => E_USER_NOTICE);
50 foreach ($levels AS $php => $isso)
51 {
52 if ($oldlevel & $php)
53 {
54 if (!($oldlevel & $isso))
55 {
56 //echo "increasing newlevel by $isso; ";
57 $newlevel += $isso;
58 }
59 }
60 else
61 {
62 if ($oldlevel & $isso)
63 {
64 //echo "decreasing newlevel by $isso; ";
65 $newlevel -= $isso;
66 }
67 }
68 }
69 error_reporting($newlevel);
70
71 if ((bool)ini_get('register_globals') === true)
72 {
73 $superglobals = array('_GET', '_COOKIE', '_FILES', '_POST', '_SERVER', '_ENV');
74 foreach ($superglobals AS $global)
75 {
76 if (is_array(${$global}))
77 {
78 foreach (${$global} AS $_key => $_val)
79 {
80 if (isset(${$_key}))
81 {
82 unset(${$_key});
83 }
84 }
85 }
86 }
87 }
88
89 /**
90 * Integer type
91 */
92 define('TYPE_INT', 1);
93
94 /**
95 * Unsigned integer
96 */
97 define('TYPE_UINT', 2);
98
99 /**
100 * Float type
101 */
102 define('TYPE_FLOAT', 4);
103
104 /**
105 * Boolean type
106 */
107 define('TYPE_BOOL', 8);
108
109 /**
110 * String - cleaned
111 */
112 define('TYPE_STR', 16);
113
114 /**
115 * String - deliberate unclean
116 */
117 define('TYPE_STRUN', 32);
118
119 /**
120 * No cleaning - here for use in API
121 */
122 define('TYPE_NOCLEAN', 64);
123
124 /**
125 * Iris Studios Shared Object Framework (ISSO)
126 *
127 * This framework allows a common backend to be used amongst all Iris
128 * Studios applications and is built to be abstract and flexible.
129 * The base framework handles all loading and module management.
130 *
131 * @author Iris Studios, Inc.
132 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
133 * @version $Revision$
134 * @package ISSO
135 *
136 */
137 class Shared_Object_Framework
138 {
139 /**
140 * ISSO version
141 * @var string
142 */
143 var $version = '[#]version[#]';
144
145 /**
146 * Location of ISSO, used for internal linking
147 * @var string
148 */
149 var $sourcepath = '';
150
151 /**
152 * Path of the current application
153 * @var string
154 */
155 var $apppath = '';
156
157 /**
158 * Name of the current application
159 * @var string
160 */
161 var $application = '';
162
163 /**
164 * Version of the current application
165 * @var string
166 */
167 var $appversion = '';
168
169 /**
170 * Whether debug mode is on or off
171 * @var bool
172 */
173 var $debug = false;
174
175 /**
176 * List of all active debug messages
177 * @var array
178 */
179 var $debuginfo = array();
180
181 /**
182 * List of loaded modules
183 * @var array
184 */
185 var $modules = array();
186
187 /**
188 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
189 * @var array
190 */
191 var $in = array();
192
193 /**
194 * If we are running with magic_quotes_gpc on or off
195 * @var int
196 */
197 var $magicquotes = 0;
198
199 /**
200 * If we should automagically escape strings, mimicking magic_quotes_gpc
201 * @var bool
202 */
203 var $escapestrings = false;
204
205 /**
206 * Constructor
207 */
208 function Shared_Object_Framework()
209 {
210 // error reporting
211 set_error_handler(array(&$this, '_error_handler'));
212
213 // magic quotes
214 $this->magicquotes = get_magic_quotes_gpc();
215 set_magic_quotes_runtime(0);
216
217 if (defined('ISSO_ESCAPE_STRINGS'))
218 {
219 $this->escapestrings = (bool)constant('ISSO_ESCAPE_STRINGS');
220 }
221
222 // start input sanitize using variable_order GPC
223 if (!$this->escapestrings)
224 {
225 $this->exec_sanitize_data();
226 }
227
228 if (defined('ISSO_CHECK_POST_REFERER'))
229 {
230 $this->exec_referer_check();
231 }
232 }
233
234 /**
235 * Prepares a path for being set as the sourcepath
236 *
237 * @param string Source path or URL
238 *
239 * @return string Prepared source path
240 */
241 function fetch_sourcepath($source)
242 {
243 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
244 {
245 $source .= DIRECTORY_SEPARATOR;
246 }
247 return $source;
248 }
249
250 /**
251 * Loads a framework module
252 *
253 * @param string Name of the framework file to load
254 * @param string Internal variable to initialize as; to not instantiate (just require) leave it as NULL
255 * @param bool Globalize the internal variable?
256 *
257 * @return object Instantiated instance
258 */
259 function &load($framework, $asobject, $globalize = false)
260 {
261 if ($this->is_loaded($framework))
262 {
263 return $this->getobj($framework);
264 }
265
266 if ($this->sourcepath == '')
267 {
268 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
269 }
270
271 if (file_exists($this->sourcepath . $framework . '.php'))
272 {
273 require_once($this->sourcepath . $framework . '.php');
274 }
275 else
276 {
277 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
278 }
279
280 if ($asobject === null)
281 {
282 return;
283 }
284
285 if (isset($this->$asobject))
286 {
287 trigger_error('Cannot instantiate framework `' . $framework . '` into `' . $asobject . '`', E_USER_ERROR);
288 }
289
290 $this->$asobject = new $framework($this);
291
292 $this->modules["$framework"] =& $this->$asobject;
293
294 if ($globalize)
295 {
296 $GLOBALS["$asobject"] =& $this->$asobject;
297 }
298
299 return $this->$asobject;
300 }
301
302 /**
303 * Prints a list of all currently loaded framework modules
304 *
305 * @param bool Return the data as an array?
306 *
307 * @return mixed HTML output or an array of loaded modules
308 */
309 function show_modules($return = false)
310 {
311 foreach ($this->modules AS $object)
312 {
313 $modules[] = get_class($object);
314 }
315
316 if ($return)
317 {
318 return $modules;
319 }
320 else
321 {
322 $output = "\n\n<ul>\n\t<li>";
323 $output .= implode("</li>\n\t<li>", $modules);
324 $output .= "</li>\n</ul>\n\n";
325 $this->_message('Loaded Modules', $output, 1);
326 }
327 }
328
329 /**
330 * Verifies to see if a framework has been loaded
331 *
332 * @param string Framework name
333 *
334 * @return bool Whether or not the framework has been loaded
335 */
336 function is_loaded($framework)
337 {
338 if (isset($this->modules["$framework"]))
339 {
340 return true;
341 }
342 else
343 {
344 return false;
345 }
346 }
347
348 /**
349 * Prints an ISSO message
350 *
351 * @param string The title of the message
352 * @param string The content of the message
353 * @param integer Type of message to be printed
354 * @param bool Return the output?
355 *
356 * @return mixed Output or null
357 */
358 function _message($title, $message, $type, $return = false)
359 {
360 switch ($type)
361 {
362 // Message
363 case 1:
364 $prefix = 'Message';
365 $color = '#669900';
366 $font = '#000000';
367 break;
368
369 // Warning
370 case 2:
371 $prefix = 'Warning';
372 $color = '#003399';
373 $font = '#FFFFFF';
374 break;
375
376 case 3:
377 $prefix = 'Error';
378 $color = '#990000';
379 $font = '#EFEFEF';
380 break;
381 }
382
383 $output = "\n<br />\n<table cellpadding=\"4\" cellspacing=\"1\" border=\"0\" width=\"500\" style=\"background-color: $color; color: black; font-family: Verdana, sans-serif; font-size: 12px;\">";
384 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
385 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>\n</table>\n<br />\n";
386
387 if ($return)
388 {
389 return $output;
390 }
391 else
392 {
393 print($output);
394 }
395 }
396
397 /**
398 * Custom error handler for ISSO
399 * We only handle E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
400 *
401 * @param integer Error number
402 * @param string Error message string
403 * @param string File that contains the error
404 * @param string The line number of the error
405 * @param string The active symbol table at which point the error occurred
406 */
407 function _error_handler($errno, $errstr, $errfile, $errline)
408 {
409 switch ($errno)
410 {
411 // Fatal
412 case E_USER_ERROR:
413 $title = 'Fatal';
414 $level = 3;
415 if (!(ini_get('error_reporting') & E_USER_ERROR))
416 {
417 return;
418 }
419 break;
420
421 // Error
422 case E_USER_WARNING:
423 $title = 'Warning';
424 $level = 2;
425 if (!(ini_get('error_reporting') & E_USER_WARNING) AND !(ini_get('error_reporting') & E_WARNING))
426 {
427 return;
428 }
429 break;
430
431 // Warning
432 case E_USER_NOTICE:
433 default:
434 $title = 'Notice';
435 $level = 1;
436 if (!(ini_get('error_reporting') & E_USER_NOTICE) AND !(ini_get('error_reporting') & E_NOTICE))
437 {
438 return;
439 }
440 break;
441 }
442
443 $errfile = str_replace(array(getcwd(), dirname(getcwd())), '', $errfile);
444
445 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
446
447 $this->_message($title, $errstr, $level);
448
449 if ($errno == E_USER_ERROR)
450 {
451 exit;
452 }
453 }
454
455 /**
456 * Logs a debug message for verbose output
457 *
458 * @param string Message
459 */
460 function debug($message)
461 {
462 $this->debuginfo[] = $message;
463 }
464
465 /**
466 * Recursive XSS cleaner
467 *
468 * @param mixed Unsanitized REQUEST data
469 *
470 * @return mixed Sanitized data
471 */
472 function _sanitize_input_recursive($data)
473 {
474 foreach ($data AS $key => $value)
475 {
476 if (is_array($value))
477 {
478 $data["$key"] = $this->_sanitize_input_recursive($value);
479 }
480 else
481 {
482 if ($this->escapestrings)
483 {
484 $data["$key"] = $this->escape($this->sanitize($value), false, false);
485 }
486 else
487 {
488 $data["$key"] = $this->sanitize($value);
489 }
490 }
491 }
492 return $data;
493 }
494
495 /**
496 * Simple way to protect against HTML attacks with Unicode support
497 *
498 * @param string Unsanitzed text
499 *
500 * @return string Properly protected text that only encodes potential threats
501 */
502 function sanitize($text)
503 {
504 if ($this->magicquotes)
505 {
506 return str_replace(array('<', '>', '\"', '"'), array('&lt;', '&gt;', '&quot;', '&quot;'), $text);
507 }
508 else
509 {
510 return str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $text);
511 }
512 }
513
514 /**
515 * Takes text that has been processed for HTML and unsanitizes it
516 *
517 * @param string Text that needs to be turned back into HTML
518 * @param bool Force magicquotes off
519 *
520 * @return string Unsanitized text
521 */
522 function unsanitize($text, $force = false)
523 {
524 if ($this->magicquotes AND !$force)
525 {
526 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '\"'), $text);
527 }
528 else
529 {
530 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '"'), $text);
531 }
532 }
533
534 /**
535 * Smart addslashes() that only applies itself it the Magic Quotes GPC is off
536 *
537 * @param string Some string
538 * @param bool If the data is binary; if so it'll be run through DB::escape_stringing()
539 * @param bool Force magic quotes to be off
540 *
541 * @return string String that has slashes added
542 */
543 function escape($str, $binary = false, $force = true)
544 {
545 if ($this->magicquotes AND !$force)
546 {
547 if (isset($this->db) AND $binary)
548 {
549 if (is_resource($this->db->link_id))
550 {
551 return $this->db->escape_string(stripslashes($str));
552 }
553 }
554 return $str;
555 }
556 else
557 {
558 if (isset($this->db) AND $binary)
559 {
560 if (is_resource($this->db->link_id))
561 {
562 return $this->db->escape_string($str);
563 }
564 }
565 return addslashes($str);
566 }
567 }
568
569 /**
570 * Runs through all of the input data and sanitizes it.
571 */
572 function exec_sanitize_data()
573 {
574 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
575 // we're now using magic quotes
576 if ($this->escapestrings)
577 {
578 $this->magicquotes = 1;
579 }
580 }
581
582 /**
583 * Sanitize function for something other than a string (which everything is sanitized for if you use exec_sanitize_data().
584 * Cleaned data is placed back into $isso->in; this makes it so you don't have to constantly intval() [etc.] data
585 *
586 * @param array Array of elements to clean as varname => type
587 */
588 function input_clean_array($vars)
589 {
590 foreach ($vars AS $varname => $type)
591 {
592 $this->input_clean($varname, $type);
593 }
594 }
595
596 /**
597 * Sanitize function that does a single variable as oppoesd to an array (see input_clean_array() for more details)
598 *
599 * @param string Variable name in $isso->in[]
600 * @param integer Sanitization type constant
601 */
602 function input_clean($varname, $type)
603 {
604 $this->in["$varname"] = $this->clean($this->in["$varname"], $type);
605 }
606
607 /**
608 * Cleaning function that does the work for input_clean(); this is moved here so it can be used to clean things that aren't in $isso->in[]
609 *
610 * @param mixed Data
611 * @param integer Sanitization type constant
612 *
613 * @return mixed Cleaned data
614 */
615 function clean($value, $type)
616 {
617 if ($type == TYPE_INT)
618 {
619 $value = intval($value);
620 }
621 else if ($type == TYPE_UINT)
622 {
623 $value = abs(intval($value));
624 }
625 else if ($type == TYPE_FLOAT)
626 {
627 $value = floatval($value);
628 }
629 else if ($type == TYPE_BOOL)
630 {
631 $value = (bool)$value;
632 }
633 else if ($type == TYPE_STR)
634 {
635 if (!$this->escapestrings)
636 {
637 $value = $this->escape($value);
638 }
639 }
640 else if ($type == TYPE_STRUN)
641 {
642 $value = $this->unsanitize($value);
643 }
644 else if ($type == TYPE_NOCLEAN)
645 {
646 }
647 else
648 {
649 trigger_error('Invalid clean type `' . $type . '` specified', E_USER_ERROR);
650 }
651
652 return $value;
653 }
654
655 /**
656 * Checks to see if a POST refer is actually from us
657 */
658 function exec_referer_check()
659 {
660 if ($_SERVER['REQUEST_METHOD'] == 'POST')
661 {
662 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
663
664 if ($host AND $_SERVER['HTTP_REFERER'])
665 {
666 $parts = parse_url($_SERVER['HTTP_REFERER']);
667 $ourhost = $parts['host'] . (($parts['port']) ? ":$parts[port]" : '');
668
669 if ($ourhost != $host)
670 {
671 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
672 }
673 $this->debug('remote post check = ok');
674 }
675 else
676 {
677 $this->debug('remote post check = FAILED');
678 }
679 }
680 }
681 }
682
683 /*=====================================================================*\
684 || ###################################################################
685 || # $HeadURL$
686 || # $Id$
687 || ###################################################################
688 \*=====================================================================*/
689 ?>