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