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