Merging r182 to the 2.x branch
[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 * Iris Studios Shared Object Framework (ISSO)
91 *
92 * This framework allows a common backend to be used amongst all Iris
93 * Studios applications and is built to be abstract and flexible.
94 * The base framework handles all loading and module management.
95 *
96 * @author Iris Studios, Inc.
97 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
98 * @version $Revision$
99 * @package ISSO
100 *
101 */
102 class Shared_Object_Framework
103 {
104 /**
105 * ISSO version
106 * @var string
107 */
108 var $version = '[#]version[#]';
109
110 /**
111 * Location of ISSO, used for internal linking
112 * @var string
113 */
114 var $sourcepath = '';
115
116 /**
117 * Path of the current application
118 * @var string
119 */
120 var $apppath = '';
121
122 /**
123 * Name of the current application
124 * @var string
125 */
126 var $application = '';
127
128 /**
129 * Version of the current application
130 * @var string
131 */
132 var $appversion = '';
133
134 /**
135 * Whether debug mode is on or off
136 * @var bool
137 */
138 var $debug = false;
139
140 /**
141 * List of all active debug messages
142 * @var array
143 */
144 var $debuginfo = array();
145
146 /**
147 * List of loaded modules
148 * @var array
149 */
150 var $modules = array();
151
152 /**
153 * An array of sanitized variables that have been cleaned for HTML tag openers and double quotes
154 * @var array
155 */
156 var $in = array();
157
158 /**
159 * If we are running with magic_quotes_gpc on or off
160 * @var int
161 */
162 var $magicquotes = 0;
163
164 /**
165 * If we should automagically escape strings, mimicking magic_quotes_gpc
166 * @var bool
167 */
168 var $escapestrings = false;
169
170 /**
171 * Constructor
172 */
173 function Shared_Object_Framework()
174 {
175 // error reporting
176 set_error_handler(array(&$this, '_error_handler'));
177
178 // magic quotes
179 $this->magicquotes = get_magic_quotes_gpc();
180 set_magic_quotes_runtime(0);
181
182 if (defined('ISSO_ESCAPE_STRINGS'))
183 {
184 $this->escapestrings = (bool)constant('ISSO_ESCAPE_STRINGS');
185 }
186
187 // start input sanitize using variable_order GPC
188 if (!$this->escapestrings)
189 {
190 $this->exec_sanitize_data();
191 }
192
193 if (defined('ISSO_CHECK_POST_REFERER'))
194 {
195 $this->exec_referer_check();
196 }
197
198 $this->modules['kernel'] = 'Shared Object Framework Core';
199 }
200
201 /**
202 * Prepares a path for being set as the sourcepath
203 *
204 * @param string Source path or URL
205 *
206 * @return string Prepared source path
207 */
208 function fetch_sourcepath($source)
209 {
210 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
211 {
212 $source .= DIRECTORY_SEPARATOR;
213 }
214 return $source;
215 }
216
217 /**
218 * Loads a framework extension
219 *
220 * @param string Name of the framework
221 */
222 function load($framework)
223 {
224 if (!$this->is_loaded($framework))
225 {
226 $newobj = $this->locate($framework);
227 $this->$newobj['OBJ'] = new $newobj['CLASS']($this);
228 $GLOBALS["$newobj[OBJ]"] =& $this->$newobj['OBJ'];
229 $this->modules["$framework"] = $newobj['OBJECT'];
230 }
231 }
232
233 /**
234 * Includes a framework module. Module definitions need three variables:
235 * class, object, and obj. Class is the name of the class, object is
236 * the name human-readable name, and obj is the name that the module
237 * should be initialized as; this is used in class extensions.
238 *
239 * @param string Name of the framework
240 *
241 * @return array List of initialization variables
242 */
243 function locate($framework)
244 {
245 if ($this->sourcepath == '')
246 {
247 trigger_error('Invalid sourcepath specified', E_USER_ERROR);
248 }
249
250 if (file_exists($this->sourcepath . $framework . '.php'))
251 {
252 require_once($this->sourcepath . $framework . '.php');
253 return array('CLASS' => $CLASS, 'OBJECT' => $OBJECT, 'OBJ' => $OBJ);
254 }
255 else
256 {
257 trigger_error('Could not find the framework ' . $this->sourcepath . $framework . '.php', E_USER_ERROR);
258 exit;
259 }
260 }
261
262 /**
263 * Prints a list of all currently loaded framework modules
264 *
265 * @param bool Return the data as an array?
266 *
267 * @return mixed HTML output or an array of loaded modules
268 */
269 function show_modules($return = false)
270 {
271 if ($return)
272 {
273 return $this->modules;
274 }
275 else
276 {
277 $output = "\n\n<ul>\n\t<li>";
278 $output .= implode("</li>\n\t<li>", $this->modules);
279 $output .= "</li>\n</ul>\n\n";
280 $this->_message('Loaded Modules', $output, 1);
281 }
282 }
283
284 /**
285 * Verifies to see if a framework has been loaded
286 *
287 * @param string Framework name
288 *
289 * @return bool Whether or not the framework has been loaded
290 */
291 function is_loaded($framework)
292 {
293 if (isset($this->modules["$framework"]))
294 {
295 return true;
296 }
297 else
298 {
299 return false;
300 }
301 }
302
303 /**
304 * Prints an ISSO message
305 *
306 * @param string The title of the message
307 * @param string The content of the message
308 * @param integer Type of message to be printed
309 * @param bool Return the output?
310 *
311 * @return mixed Output or null
312 */
313 function _message($title, $message, $type, $return = false)
314 {
315 switch ($type)
316 {
317 // Message
318 case 1:
319 $prefix = 'Message';
320 $color = '#669900';
321 $font = '#000000';
322 break;
323
324 // Warning
325 case 2:
326 $prefix = 'Warning';
327 $color = '#003399';
328 $font = '#FFFFFF';
329 break;
330
331 case 3:
332 $prefix = 'Error';
333 $color = '#990000';
334 $font = '#EFEFEF';
335 break;
336 }
337
338 $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;\">";
339 $output .= "\n<tr style=\"color: $font; text-align: left\">\n\t<td><strong>$prefix: $title</strong></td>\n</tr>";
340 $output .= "\n<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>$message</td>\n</tr>\n</table>\n<br />\n";
341
342 if ($return)
343 {
344 return $output;
345 }
346 else
347 {
348 print($output);
349 }
350 }
351
352 /**
353 * Custom error handler for ISSO
354 * We only handle E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
355 *
356 * @param integer Error number
357 * @param string Error message string
358 * @param string File that contains the error
359 * @param string The line number of the error
360 * @param string The active symbol table at which point the error occurred
361 */
362 function _error_handler($errno, $errstr, $errfile, $errline)
363 {
364 switch ($errno)
365 {
366 // Fatal
367 case E_USER_ERROR:
368 $title = 'Fatal';
369 $level = 3;
370 if (!(ini_get('error_reporting') & E_USER_ERROR))
371 {
372 return;
373 }
374 break;
375
376 // Error
377 case E_USER_WARNING:
378 $title = 'Warning';
379 $level = 2;
380 if (!(ini_get('error_reporting') & E_USER_WARNING) AND !(ini_get('error_reporting') & E_WARNING))
381 {
382 return;
383 }
384 break;
385
386 // Warning
387 case E_USER_NOTICE:
388 default:
389 $title = 'Notice';
390 $level = 1;
391 if (!(ini_get('error_reporting') & E_USER_NOTICE) AND !(ini_get('error_reporting') & E_NOTICE))
392 {
393 return;
394 }
395 break;
396 }
397
398 $errfile = str_replace(array(getcwd(), dirname(getcwd())), '', $errfile);
399
400 $errstr .= " in <strong>$errfile</strong> on line <strong>$errline</strong>";
401
402 $this->_message($title, $errstr, $level);
403
404 if ($errno == E_USER_ERROR)
405 {
406 exit;
407 }
408 }
409
410 /**
411 * Logs a debug message for verbose output
412 *
413 * @param string Message
414 */
415 function debug($message)
416 {
417 $this->debuginfo[] = $message;
418 }
419
420 /**
421 * Recursive XSS cleaner
422 *
423 * @param mixed Unsanitized REQUEST data
424 *
425 * @return mixed Sanitized data
426 */
427 function _sanitize_input_recursive($data)
428 {
429 foreach ($data AS $key => $value)
430 {
431 if (is_array($value))
432 {
433 $data["$key"] = $this->_sanitize_input_recursive($value);
434 }
435 else
436 {
437 if ($this->escapestrings)
438 {
439 $data["$key"] = $this->escape($this->sanitize($value), false, false);
440 }
441 else
442 {
443 $data["$key"] = $this->sanitize($value);
444 }
445 }
446 }
447 return $data;
448 }
449
450 /**
451 * Simple way to protect against HTML attacks with Unicode support
452 *
453 * @param string Unsanitzed text
454 *
455 * @return string Properly protected text that only encodes potential threats
456 */
457 function sanitize($text)
458 {
459 if ($this->magicquotes)
460 {
461 return str_replace(array('<', '>', '\"', '"'), array('&lt;', '&gt;', '&quot;', '&quot;'), $text);
462 }
463 else
464 {
465 return str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $text);
466 }
467 }
468
469 /**
470 * Takes text that has been processed for HTML and unsanitizes it
471 *
472 * @param string Text that needs to be turned back into HTML
473 * @param bool Force magicquotes off
474 *
475 * @return string Unsanitized text
476 */
477 function unsanitize($text, $force = false)
478 {
479 if ($this->magicquotes AND !$force)
480 {
481 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '\"'), $text);
482 }
483 else
484 {
485 return str_replace(array('&lt;', '&gt;', '&quot;'), array('<', '>', '"'), $text);
486 }
487 }
488
489 /**
490 * Smart addslashes() that only applies itself it the Magic Quotes GPC is off
491 *
492 * @param string Some string
493 * @param bool If the data is binary; if so it'll be run through DB::escape_stringing()
494 * @param bool Force magic quotes to be off
495 *
496 * @return string String that has slashes added
497 */
498 function escape($str, $binary = false, $force = true)
499 {
500 if ($this->magicquotes AND !$force)
501 {
502 if (isset($this->db) AND $binary)
503 {
504 if (is_resource($this->db->link_id))
505 {
506 return $this->db->escape_string(stripslashes($str));
507 }
508 }
509 return $str;
510 }
511 else
512 {
513 if (isset($this->db) AND $binary)
514 {
515 if (is_resource($this->db->link_id))
516 {
517 return $this->db->escape_string($str);
518 }
519 }
520 return addslashes($str);
521 }
522 }
523
524 /**
525 * Runs through all of the input data and sanitizes it.
526 */
527 function exec_sanitize_data()
528 {
529 $this->in = $this->_sanitize_input_recursive(array_merge($_GET, $_POST, $_COOKIE));
530 // we're now using magic quotes
531 if ($this->escapestrings)
532 {
533 $this->magicquotes = 1;
534 }
535 }
536
537 /**
538 * Checks to see if a POST refer is actually from us
539 */
540 function exec_referer_check()
541 {
542 if ($_SERVER['REQUEST_METHOD'] == 'POST')
543 {
544 $host = ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST'];
545
546 if ($host AND $_SERVER['HTTP_REFERER'])
547 {
548 $parts = parse_url($_SERVER['HTTP_REFERER']);
549 $ourhost = $parts['host'] . (($parts['port']) ? ":$parts[port]" : '');
550
551 if ($ourhost != $host)
552 {
553 trigger_error('No external hosts are allowed to POST to this application', E_USER_ERROR);
554 }
555 $this->debug('remote post check = ok');
556 }
557 else
558 {
559 $this->debug('remote post check = FAILED');
560 }
561 }
562 }
563 }
564
565 /*=====================================================================*\
566 || ###################################################################
567 || # $HeadURL$
568 || # $Id$
569 || ###################################################################
570 \*=====================================================================*/
571 ?>