]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/ErrorManager.php
avoid Php Notice header
[SourceForge/phpwiki.git] / lib / ErrorManager.php
1 <?php rcs_id('$Id: ErrorManager.php,v 1.36 2004-10-12 15:35:43 rurban Exp $');
2
3 if (isset($GLOBALS['ErrorManager'])) return;
4
5 // php5: ignore E_STRICT (var warnings)
6 /*
7 if (defined('E_STRICT') 
8     and (E_ALL & E_STRICT)
9     and (error_reporting() & E_STRICT)) {
10     echo " errormgr: error_reporting=", error_reporting();
11     echo "\nplease fix that in your php.ini!";
12     error_reporting(E_ALL & ~E_STRICT);
13 }
14 */
15 define ('EM_FATAL_ERRORS', E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | ~2048);
16 define ('EM_WARNING_ERRORS',
17         E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING);
18 define ('EM_NOTICE_ERRORS', E_NOTICE | E_USER_NOTICE);
19
20 /* It is recommended to leave assertions on. 
21    You can simply comment the two lines below to leave them on.
22    Only where absolute speed is necessary you might want to turn 
23    them off.
24 */
25 if (1 or (defined('DEBUG') and DEBUG))
26     assert_options (ASSERT_ACTIVE, 1);
27 else
28     assert_options (ASSERT_ACTIVE, 0);
29 assert_options (ASSERT_CALLBACK, 'wiki_assert_handler');
30
31 function wiki_assert_handler ($file, $line, $code) {
32     ErrorManager_errorHandler( $code, sprintf("<br />%s:%s: %s: Assertion failed <br />", $file, $line, $code), $file, $line);
33 }
34
35 /**
36  * A class which allows custom handling of PHP errors.
37  *
38  * This is a singleton class. There should only be one instance
39  * of it --- you can access the one instance via $GLOBALS['ErrorManager'].
40  *
41  * FIXME: more docs.
42  */ 
43 class ErrorManager 
44 {
45     /**
46      * Constructor.
47      *
48      * As this is a singleton class, you should never call this.
49      * @access private
50      */
51     function ErrorManager() {
52         $this->_handlers = array();
53         $this->_fatal_handler = false;
54         $this->_postpone_mask = 0;
55         $this->_postponed_errors = array();
56
57         set_error_handler('ErrorManager_errorHandler');
58     }
59
60     /**
61      * Get mask indicating which errors are currently being postponed.
62      * @access public
63      * @return int The current postponed error mask.
64      */
65     function getPostponedErrorMask() {
66         return $this->_postpone_mask;
67     }
68
69     /**
70      * Set mask indicating which errors to postpone.
71      *
72      * The default value of the postpone mask is zero (no errors postponed.)
73      *
74      * When you set this mask, any queue errors which do not match the new
75      * mask are reported.
76      *
77      * @access public
78      * @param $newmask int The new value for the mask.
79      */
80     function setPostponedErrorMask($newmask) {
81         $this->_postpone_mask = $newmask;
82         if (function_exists('PrintXML'))
83             PrintXML($this->_flush_errors($newmask));
84         else
85             echo($this->_flush_errors($newmask));
86
87     }
88
89     /**
90      * Report any queued error messages.
91      * @access public
92      */
93     function flushPostponedErrors() {
94         if (function_exists('PrintXML'))
95             PrintXML($this->_flush_errors());
96         else
97             echo $this->_flush_errors();
98     }
99
100     /**
101      * Get postponed errors, formatted as HTML.
102      *
103      * This also flushes the postponed error queue.
104      *
105      * @return object HTML describing any queued errors (or false, if none). 
106      */
107     function getPostponedErrorsAsHTML() {
108         $flushed = $this->_flush_errors();
109         if (!$flushed)
110             return false;
111         if ($flushed->isEmpty())
112             return false;
113         // format it with the worst class (error, warning, notice)
114         //$class = 'notice';
115         $cur_err = new PhpError(0,"","","");
116         foreach ($flushed->_content as $err) {
117             if ($err and isa($err, 'PhpError') and $err->errno > $cur_err->errno) {
118                 $cur_err = $err;
119             }
120         }
121         if ($cur_err->isNotice())
122             return $flushed;
123         $class = $cur_err->getHtmlClass(); 
124         $html = HTML::div(array('class' => $class),
125                           HTML::h4(array('class' => 'errors'), 
126                                    "PHP " . $cur_err->getDescription()));
127         $html->pushContent($flushed);
128         return $html;
129     }
130     
131     /**
132      * Push a custom error handler on the handler stack.
133      *
134      * Sometimes one is performing an operation where one expects
135      * certain errors or warnings. In this case, one might not want
136      * these errors reported in the normal manner. Installing a custom
137      * error handler via this method allows one to intercept such
138      * errors.
139      *
140      * An error handler installed via this method should be either a
141      * function or an object method taking one argument: a PhpError
142      * object.
143      *
144      * The error handler should return either:
145      * <dl>
146      * <dt> False <dd> If it has not handled the error. In this case,
147      *                 error processing will proceed as if the handler
148      *                 had never been called: the error will be passed
149      *                 to the next handler in the stack, or the
150      *                 default handler, if there are no more handlers
151      *                 in the stack.
152      *
153      * <dt> True <dd> If the handler has handled the error. If the
154      *                error was a non-fatal one, no further processing
155      *                will be done. If it was a fatal error, the
156      *                ErrorManager will still terminate the PHP
157      *                process (see setFatalHandler.)
158      *
159      * <dt> A PhpError object <dd> The error is not considered
160      *                             handled, and will be passed on to
161      *                             the next handler(s) in the stack
162      *                             (or the default handler). The
163      *                             returned PhpError need not be the
164      *                             same as the one passed to the
165      *                             handler. This allows the handler to
166      *                             "adjust" the error message.
167      * </dl>
168      * @access public
169      * @param $handler WikiCallback  Handler to call.
170      */
171     function pushErrorHandler($handler) {
172         array_unshift($this->_handlers, $handler);
173     }
174
175     /**
176      * Pop an error handler off the handler stack.
177      * @access public
178      */
179     function popErrorHandler() {
180         return array_shift($this->_handlers);
181     }
182
183     /**
184      * Set a termination handler.
185      *
186      * This handler will be called upon fatal errors. The handler
187      * gets passed one argument: a PhpError object describing the
188      * fatal error.
189      *
190      * @access public
191      * @param $handler WikiCallback  Callback to call on fatal errors.
192      */
193     function setFatalHandler($handler) {
194         $this->_fatal_handler = $handler;
195     }
196
197     /**
198      * Handle an error.
199      *
200      * The error is passed through any registered error handlers, and
201      * then either reported or postponed.
202      *
203      * @access public
204      * @param $error object A PhpError object.
205      */
206     function handleError($error) {
207         static $in_handler;
208
209         if (!empty($in_handler)) {
210             $msg = $error->_getDetail();
211             $msg->unshiftContent(HTML::h2(fmt("%s: error while handling error:",
212                                               "ErrorManager")));
213             $msg->printXML();
214             return;
215         }
216         $in_handler = true;
217
218         foreach ($this->_handlers as $handler) {
219             if (!$handler) continue;
220             $result = $handler->call($error);
221             if (!$result) {
222                 continue;       // Handler did not handle error.
223             }
224             elseif (is_object($result)) {
225                 // handler filtered the result. Still should pass to
226                 // the rest of the chain.
227                 if ($error->isFatal()) {
228                     // Don't let handlers make fatal errors non-fatal.
229                     $result->errno = $error->errno;
230                 }
231                 $error = $result;
232             }
233             else {
234                 // Handler handled error.
235                 if (!$error->isFatal()) {
236                     $in_handler = false;
237                     return;
238                 }
239                 break;
240             }
241         }
242
243         $this->_noCacheHeaders();
244
245         // Error was either fatal, or was not handled by a handler.
246         // Handle it ourself.
247         if ($error->isFatal()) {
248             echo "<html><body><div style=\"font-width:bold; color:red\">Fatal</div>\n";
249             if (defined('DEBUG') and (DEBUG & _DEBUG_TRACE)) {
250                 echo "error_reporting=",error_reporting(),"\n<br>";
251                 $error->printSimpleTrace(debug_backtrace());
252             }
253             $this->_die($error);
254         }
255         else if (($error->errno & error_reporting()) != 0) {
256             if  (($error->errno & $this->_postpone_mask) != 0) {
257                 if ((function_exists('is_a') and is_a($error,'PhpErrorOnce'))
258                     or (!function_exists('is_a') and 
259                     (
260                      // stdlib independent isa()
261                      (strtolower(get_class($error)) == 'phperroronce')
262                      or (is_subclass_of($error, 'PhpErrorOnce'))))) {
263                     $error->removeDoublettes($this->_postponed_errors);
264                     if ( $error->_count < 2 )
265                         $this->_postponed_errors[] = $error;
266                 } else {
267                     $this->_postponed_errors[] = $error;
268                 }
269             }
270             else {
271                 //echo "postponed errors: ";
272                 if (defined('DEBUG') and (DEBUG & _DEBUG_TRACE)) {
273                     echo "error_reporting=",error_reporting(),"\n";
274                     $error->printSimpleTrace(debug_backtrace());
275                 }
276                 $error->printXML();
277             }
278         }
279         $in_handler = false;
280     }
281
282     function warning($msg, $errno=E_USER_NOTICE) {
283         $this->handleError(new PhpWikiError($errno, $msg));
284     }
285     
286     /**
287      * @access private
288      */
289     function _die($error) {
290         //echo "\n\n<html><body>";
291         $error->printXML();
292         PrintXML($this->_flush_errors());
293         if ($this->_fatal_handler)
294             $this->_fatal_handler->call($error);
295         exit -1;
296     }
297
298     /**
299      * @access private
300      */
301     function _flush_errors($keep_mask = 0) {
302         $errors = &$this->_postponed_errors;
303         if (empty($errors)) return '';
304         $flushed = HTML();
305         for ($i=0; $i<count($errors); $i++) {
306             $error =& $errors[$i];
307             if (($error->errno & $keep_mask) != 0)
308                 continue;
309             unset($errors[$i]);
310             $flushed->pushContent($error);
311         }
312         return $flushed;
313     }
314
315     function _noCacheHeaders() {
316         global $request;
317         static $already = false;
318
319         if (isset($request) and isset($request->_validators)) {
320             $request->_validators->_tag = false;
321             $request->_validators->_mtime = false;
322         }
323         if ($already) return;
324         
325         // FIXME: Howto announce that to Request->cacheControl()?
326         if (!headers_sent()) {
327             header( "Cache-control: no-cache" );
328             header( "Pragma: nocache" );
329         }
330         $already = true;
331     }
332 }
333
334 /**
335  * Global error handler for class ErrorManager.
336  *
337  * This is necessary since PHP's set_error_handler() does not allow
338  * one to set an object method as a handler.
339  * 
340  * @access private
341  */
342 function ErrorManager_errorHandler($errno, $errstr, $errfile, $errline) 
343 {
344     if (!isset($GLOBALS['ErrorManager'])) {
345       $GLOBALS['ErrorManager'] = new ErrorManager;
346     }
347         
348     $error = new PhpErrorOnce($errno, $errstr, $errfile, $errline);
349     $GLOBALS['ErrorManager']->handleError($error);
350 }
351
352
353 /**
354  * A class representing a PHP error report.
355  *
356  * @see The PHP documentation for set_error_handler at
357  *      http://php.net/manual/en/function.set-error-handler.php .
358  */
359 class PhpError {
360     /**
361      * The PHP errno
362      */
363     var $errno;
364
365     /**
366      * The PHP error message.
367      */
368     var $errstr;
369
370     /**
371      * The source file where the error occurred.
372      */
373     var $errfile;
374
375     /**
376      * The line number (in $this->errfile) where the error occured.
377      */
378     var $errline;
379
380     /**
381      * Construct a new PhpError.
382      * @param $errno   int
383      * @param $errstr  string
384      * @param $errfile string
385      * @param $errline int
386      */
387     function PhpError($errno, $errstr, $errfile, $errline) {
388         $this->errno   = $errno;
389         $this->errstr  = $errstr;
390         $this->errfile = $errfile;
391         $this->errline = $errline;
392     }
393
394     /**
395      * Determine whether this is a fatal error.
396      * @return boolean True if this is a fatal error.
397      */
398     function isFatal() {
399         return ($this->errno & (2048|EM_WARNING_ERRORS|EM_NOTICE_ERRORS)) == 0;
400     }
401
402     /**
403      * Determine whether this is a warning level error.
404      * @return boolean
405      */
406     function isWarning() {
407         return ($this->errno & EM_WARNING_ERRORS) != 0;
408     }
409
410     /**
411      * Determine whether this is a notice level error.
412      * @return boolean
413      */
414     function isNotice() {
415         return ($this->errno & EM_NOTICE_ERRORS) != 0;
416     }
417     function getHtmlClass() {
418         if ($this->isNotice()) {
419             return 'hint';
420         } elseif ($this->isWarning()) {
421             return 'errors';
422         } else {
423             return 'errors';
424         }
425     }
426     
427     function getDescription() {
428         if ($this->isNotice()) {
429             return 'Notice';
430         } elseif ($this->isWarning()) {
431             return 'Warning';
432         } else {
433             return 'Error';
434         }
435     }
436
437     /**
438      * Get a printable, HTML, message detailing this error.
439      * @return object The detailed error message.
440      */
441     function _getDetail() {
442         $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4);
443         if (substr(PHP_OS,0,3) == 'WIN') {
444            $dir = str_replace('/','\\',$dir);
445            $this->errfile = str_replace('/','\\',$this->errfile);
446            $dir .= "\\";
447         } else 
448            $dir .= '/';
449         $errfile = preg_replace('|^' . preg_quote($dir) . '|', '', $this->errfile);
450         $lines = explode("\n", $this->errstr);
451
452         $msg = sprintf("%s:%d: %s[%d]: %s",
453                        $errfile, $this->errline,
454                        $this->getDescription(), $this->errno,
455                        array_shift($lines));
456         
457         //$html = HTML::div(array('class' => $this->getHtmlClass()), HTML::p($msg));
458         // The class is now used for the div container.
459         $html = HTML::div(HTML::p($msg));
460         if ($lines) {
461             $list = HTML::ul();
462             foreach ($lines as $line)
463                 $list->pushContent(HTML::li($line));
464             $html->pushContent($list);
465         }
466         
467         return $html;
468     }
469
470     /**
471      * Print an HTMLified version of this error.
472      * @see asXML()
473      */
474     function printXML() {
475         PrintXML($this->_getDetail());
476     }
477
478     /**
479      * Return an HTMLified version of this error.
480      */
481     function asXML() {
482         return AsXML($this->_getDetail());
483     }
484
485     /**
486      * Return a plain-text version of this error.
487      */
488     function asString() {
489         return AsString($this->_getDetail());
490     }
491
492     function printSimpleTrace($bt) {
493         global $HTTP_SERVER_VARS;
494         $nl = isset($HTTP_SERVER_VARS['REQUEST_METHOD']) ? "<br />" : "\n";
495         echo $nl."Traceback:".$nl;
496         foreach ($bt as $i => $elem) {
497             if (!array_key_exists('file', $elem)) {
498                 continue;
499             }
500             print "  " . $elem['file'] . ':' . $elem['line'] . $nl;
501         }
502         flush();
503     }
504 }
505
506 /**
507  * A class representing a PhpWiki warning.
508  *
509  * This is essentially the same as a PhpError, except that the
510  * error message is quieter: no source line, etc...
511  */
512 class PhpWikiError extends PhpError {
513     /**
514      * Construct a new PhpError.
515      * @param $errno   int
516      * @param $errstr  string
517      */
518     function PhpWikiError($errno, $errstr) {
519         $this->PhpError($errno, $errstr, '?', '?');
520     }
521
522     function _getDetail() {
523         return HTML::div(//array('class' => $this->getHtmlClass()), 
524                          HTML::p($this->getDescription() . ": $this->errstr"));
525     }
526 }
527
528 /**
529  * A class representing a Php warning, printed only the first time.
530  *
531  * Similar to PhpError, except only the first same error message is printed, 
532  * with number of occurences.
533  */
534 class PhpErrorOnce extends PhpError {
535
536     function PhpErrorOnce($errno, $errstr, $errfile, $errline) {
537         $this->_count = 1;
538         $this->PhpError($errno, $errstr, $errfile, $errline);
539     }
540
541     function _sameError($error) {
542         if (!$error) return false;
543         return ($this->errno == $error->errno and
544                 $this->errfile == $error->errfile and
545                 $this->errline == $error->errline);
546     }
547
548     // count similar handlers, increase _count and remove the rest
549     function removeDoublettes(&$errors) {
550         for ($i=0; $i < count($errors); $i++) {
551             if (!isset($errors[$i])) continue;
552             if ($this->_sameError($errors[$i])) {
553                 $errors[$i]->_count++;
554                 $this->_count++;
555                 if ($i) unset($errors[$i]);
556             }
557         }
558         return $this->_count;
559     }
560     
561     function _getDetail($count=0) {
562         if (!$count) $count = $this->_count;
563         $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4);
564         if (substr(PHP_OS,0,3) == 'WIN') {
565            $dir = str_replace('/','\\',$dir);
566            $this->errfile = str_replace('/','\\',$this->errfile);
567            $dir .= "\\";
568         } else 
569            $dir .= '/';
570         $errfile = preg_replace('|^' . preg_quote($dir) . '|', '', $this->errfile);
571         $lines = explode("\n", $this->errstr);
572         $msg = sprintf("%s:%d: %s[%d]: %s %s",
573                        $errfile, $this->errline,
574                        $this->getDescription(), $this->errno,
575                        array_shift($lines),
576                        $count > 1 ? sprintf(" (...repeated %d times)",$count) : ""
577                        );
578         $html = HTML::div(//array('class' => $this->getHtmlClass()), 
579                           HTML::p($msg));
580         if ($lines) {
581             $list = HTML::ul();
582             foreach ($lines as $line)
583                 $list->pushContent(HTML::li($line));
584             $html->pushContent($list);
585         }
586         
587         return $html;
588     }
589 }
590
591 require_once(dirname(__FILE__).'/HtmlElement.php');
592
593 if (!isset($GLOBALS['ErrorManager'])) {
594     $GLOBALS['ErrorManager'] = new ErrorManager;
595 }
596
597 // $Log: not supported by cvs2svn $
598 // Revision 1.35  2004/10/12 13:13:19  rurban
599 // php5 compatibility (5.0.1 ok)
600 //
601 // Revision 1.34  2004/09/24 18:52:19  rurban
602 // in deferred html error messages use the worst header and class
603 // (notice => warning => errors)
604 //
605 // Revision 1.33  2004/09/14 10:28:21  rurban
606 // use assert, maybe we should only turn it off for releases
607 //
608 // Revision 1.32  2004/07/08 13:50:32  rurban
609 // various unit test fixes: print error backtrace on _DEBUG_TRACE; allusers fix; new PHPWIKI_NOMAIN constant for omitting the mainloop
610 //
611 // Revision 1.31  2004/07/02 09:55:58  rurban
612 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
613 //
614 // Revision 1.30  2004/06/25 14:29:12  rurban
615 // WikiGroup refactoring:
616 //   global group attached to user, code for not_current user.
617 //   improved helpers for special groups (avoid double invocations)
618 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
619 // fixed a XHTML validation error on userprefs.tmpl
620 //
621 // Revision 1.29  2004/06/20 15:30:04  rurban
622 // get_class case-sensitivity issues
623 //
624 // Revision 1.28  2004/06/16 11:51:04  rurban
625 // fixed typo: undefined object #235
626 //
627 // Revision 1.27  2004/06/13 09:38:20  rurban
628 // isa() workaround, if stdlib.php is not loaded
629 //
630 // Revision 1.26  2004/06/02 18:01:45  rurban
631 // init global FileFinder to add proper include paths at startup
632 //   adds PHPWIKI_DIR if started from another dir, lib/pear also
633 // fix slashify for Windows
634 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
635 //
636 // Revision 1.25  2004/06/02 10:18:36  rurban
637 // assert only if DEBUG is non-false
638 //
639 // Revision 1.24  2004/05/27 17:49:05  rurban
640 // renamed DB_Session to DbSession (in CVS also)
641 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
642 // remove leading slash in error message
643 // added force_unlock parameter to File_Passwd (no return on stale locks)
644 // fixed adodb session AffectedRows
645 // added FileFinder helpers to unify local filenames and DATA_PATH names
646 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
647 //
648 //
649
650 // (c-file-style: "gnu")
651 // Local Variables:
652 // mode: php
653 // tab-width: 8
654 // c-basic-offset: 4
655 // c-hanging-comment-ender-p: nil
656 // indent-tabs-mode: nil
657 // End:
658 ?>