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