]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/ErrorManager.php
reenable admin check on !ENABLE_PAGEPERM, honor s=Wildcard arg, fix warning after...
[SourceForge/phpwiki.git] / lib / ErrorManager.php
1 <?php rcs_id('$Id: ErrorManager.php,v 1.26 2004-06-02 18:01:45 rurban Exp $');
2
3 require_once(dirname(__FILE__).'/HtmlElement.php');
4 if (isset($GLOBALS['ErrorManager'])) return;
5
6 define ('EM_FATAL_ERRORS',
7         E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
8 define ('EM_WARNING_ERRORS',
9         E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING);
10 define ('EM_NOTICE_ERRORS', E_NOTICE | E_USER_NOTICE);
11
12 /* It is recommended to leave assertions on. 
13    You can simply comment the two lines below to leave them on.
14    Only where absolute speed is necessary you might want to turn 
15    them off.
16 */
17 if (defined('DEBUG') and DEBUG)
18     assert_options (ASSERT_ACTIVE, 1);
19 else
20     assert_options (ASSERT_ACTIVE, 0);
21 assert_options (ASSERT_CALLBACK, 'wiki_assert_handler');
22
23 function wiki_assert_handler ($file, $line, $code) {
24     ErrorManager_errorHandler( $code, sprintf("<br />%s:%s: %s: Assertion failed <br />", $file, $line, $code), $file, $line);
25 }
26
27 /**
28  * A class which allows custom handling of PHP errors.
29  *
30  * This is a singleton class. There should only be one instance
31  * of it --- you can access the one instance via $GLOBALS['ErrorManager'].
32  *
33  * FIXME: more docs.
34  */ 
35 class ErrorManager 
36 {
37     /**
38      * Constructor.
39      *
40      * As this is a singleton class, you should never call this.
41      * @access private
42      */
43     function ErrorManager() {
44         $this->_handlers = array();
45         $this->_fatal_handler = false;
46         $this->_postpone_mask = 0;
47         $this->_postponed_errors = array();
48
49         set_error_handler('ErrorManager_errorHandler');
50     }
51
52     /**
53      * Get mask indicating which errors are currently being postponed.
54      * @access public
55      * @return int The current postponed error mask.
56      */
57     function getPostponedErrorMask() {
58         return $this->_postpone_mask;
59     }
60
61     /**
62      * Set mask indicating which errors to postpone.
63      *
64      * The default value of the postpone mask is zero (no errors postponed.)
65      *
66      * When you set this mask, any queue errors which do not match the new
67      * mask are reported.
68      *
69      * @access public
70      * @param $newmask int The new value for the mask.
71      */
72     function setPostponedErrorMask($newmask) {
73         $this->_postpone_mask = $newmask;
74         if (function_exists('PrintXML'))
75             PrintXML($this->_flush_errors($newmask));
76         else
77             echo($this->_flush_errors($newmask));
78
79     }
80
81     /**
82      * Report any queued error messages.
83      * @access public
84      */
85     function flushPostponedErrors() {
86         if (function_exists('PrintXML'))
87             PrintXML($this->_flush_errors());
88         else
89             echo $this->_flush_errors();
90     }
91
92     /**
93      * Get postponed errors, formatted as HTML.
94      *
95      * This also flushes the postponed error queue.
96      *
97      * @return object HTML describing any queued errors (or false, if none). 
98      */
99     function getPostponedErrorsAsHTML() {
100         $flushed = $this->_flush_errors();
101         if (!$flushed)
102             return false;
103         if ($flushed->isEmpty())
104             return false;
105         $html = HTML::div(array('class' => 'errors'),
106                           HTML::h4("PHP Warnings"));
107         $html->pushContent($flushed);
108         return $html;
109     }
110     
111     /**
112      * Push a custom error handler on the handler stack.
113      *
114      * Sometimes one is performing an operation where one expects
115      * certain errors or warnings. In this case, one might not want
116      * these errors reported in the normal manner. Installing a custom
117      * error handler via this method allows one to intercept such
118      * errors.
119      *
120      * An error handler installed via this method should be either a
121      * function or an object method taking one argument: a PhpError
122      * object.
123      *
124      * The error handler should return either:
125      * <dl>
126      * <dt> False <dd> If it has not handled the error. In this case,
127      *                 error processing will proceed as if the handler
128      *                 had never been called: the error will be passed
129      *                 to the next handler in the stack, or the
130      *                 default handler, if there are no more handlers
131      *                 in the stack.
132      *
133      * <dt> True <dd> If the handler has handled the error. If the
134      *                error was a non-fatal one, no further processing
135      *                will be done. If it was a fatal error, the
136      *                ErrorManager will still terminate the PHP
137      *                process (see setFatalHandler.)
138      *
139      * <dt> A PhpError object <dd> The error is not considered
140      *                             handled, and will be passed on to
141      *                             the next handler(s) in the stack
142      *                             (or the default handler). The
143      *                             returned PhpError need not be the
144      *                             same as the one passed to the
145      *                             handler. This allows the handler to
146      *                             "adjust" the error message.
147      * </dl>
148      * @access public
149      * @param $handler WikiCallback  Handler to call.
150      */
151     function pushErrorHandler($handler) {
152         array_unshift($this->_handlers, $handler);
153     }
154
155     /**
156      * Pop an error handler off the handler stack.
157      * @access public
158      */
159     function popErrorHandler() {
160         return array_shift($this->_handlers);
161     }
162
163     /**
164      * Set a termination handler.
165      *
166      * This handler will be called upon fatal errors. The handler
167      * gets passed one argument: a PhpError object describing the
168      * fatal error.
169      *
170      * @access public
171      * @param $handler WikiCallback  Callback to call on fatal errors.
172      */
173     function setFatalHandler($handler) {
174         $this->_fatal_handler = $handler;
175     }
176
177     /**
178      * Handle an error.
179      *
180      * The error is passed through any registered error handlers, and
181      * then either reported or postponed.
182      *
183      * @access public
184      * @param $error object A PhpError object.
185      */
186     function handleError($error) {
187         static $in_handler;
188
189         if (!empty($in_handler)) {
190             $msg = $error->_getDetail();
191             $msg->unshiftContent(HTML::h2(fmt("%s: error while handling error:",
192                                               "ErrorManager")));
193             $msg->printXML();
194             return;
195         }
196         $in_handler = true;
197
198         foreach ($this->_handlers as $handler) {
199             if (!$handler) continue;
200             $result = $handler->call($error);
201             if (!$result) {
202                 continue;       // Handler did not handle error.
203             }
204             elseif (is_object($result)) {
205                 // handler filtered the result. Still should pass to
206                 // the rest of the chain.
207                 if ($error->isFatal()) {
208                     // Don't let handlers make fatal errors non-fatal.
209                     $result->errno = $error->errno;
210                 }
211                 $error = $result;
212             }
213             else {
214                 // Handler handled error.
215                 if (!$error->isFatal()) {
216                     $in_handler = false;
217                     return;
218                 }
219                 break;
220             }
221         }
222
223         // Error was either fatal, or was not handled by a handler.
224         // Handle it ourself.
225         if ($error->isFatal()) {
226             $this->_die($error);
227         }
228         else if (($error->errno & error_reporting()) != 0) {
229             if  (($error->errno & $this->_postpone_mask) != 0) {
230                 if (isa($error,'PhpErrorOnce')) {
231                     $error->removeDoublettes($this->_postponed_errors);
232                     if ( $error->_count < 2 )
233                         $this->_postponed_errors[] = $error;
234                 } else {
235                     $this->_postponed_errors[] = $error;
236                 }
237             }
238             else {
239                 $error->printXML();
240             }
241         }
242         $in_handler = false;
243     }
244
245     function warning($msg, $errno=E_USER_NOTICE) {
246         $this->handleError(new PhpWikiError($errno, $msg));
247     }
248     
249     /**
250      * @access private
251      */
252     function _die($error) {
253         $error->printXML();
254         PrintXML($this->_flush_errors());
255         if ($this->_fatal_handler)
256             $this->_fatal_handler->call($error);
257         exit -1;
258     }
259
260     /**
261      * @access private
262      */
263     function _flush_errors($keep_mask = 0) {
264         $errors = &$this->_postponed_errors;
265         if (empty($errors)) return '';
266         $flushed = HTML();
267         for ($i=0; $i<count($errors); $i++) {
268             $error =& $errors[$i];
269             if (($error->errno & $keep_mask) != 0)
270                 continue;
271             unset($errors[$i]);
272             $flushed->pushContent($error);
273         }
274         return $flushed;
275     }
276 }
277
278 /**
279  * Global error handler for class ErrorManager.
280  *
281  * This is necessary since PHP's set_error_handler() does not allow
282  * one to set an object method as a handler.
283  * 
284  * @access private
285  */
286 function ErrorManager_errorHandler($errno, $errstr, $errfile, $errline) 
287 {
288     if (!isset($GLOBALS['ErrorManager'])) {
289       $GLOBALS['ErrorManager'] = new ErrorManager;
290     }
291         
292     $error = new PhpErrorOnce($errno, $errstr, $errfile, $errline);
293     $GLOBALS['ErrorManager']->handleError($error);
294 }
295
296
297 /**
298  * A class representing a PHP error report.
299  *
300  * @see The PHP documentation for set_error_handler at
301  *      http://php.net/manual/en/function.set-error-handler.php .
302  */
303 class PhpError {
304     /**
305      * The PHP errno
306      */
307     var $errno;
308
309     /**
310      * The PHP error message.
311      */
312     var $errstr;
313
314     /**
315      * The source file where the error occurred.
316      */
317     var $errfile;
318
319     /**
320      * The line number (in $this->errfile) where the error occured.
321      */
322     var $errline;
323
324     /**
325      * Construct a new PhpError.
326      * @param $errno   int
327      * @param $errstr  string
328      * @param $errfile string
329      * @param $errline int
330      */
331     function PhpError($errno, $errstr, $errfile, $errline) {
332         $this->errno   = $errno;
333         $this->errstr  = $errstr;
334         $this->errfile = $errfile;
335         $this->errline = $errline;
336     }
337
338     /**
339      * Determine whether this is a fatal error.
340      * @return boolean True if this is a fatal error.
341      */
342     function isFatal() {
343         return ($this->errno & (EM_WARNING_ERRORS|EM_NOTICE_ERRORS)) == 0;
344     }
345
346     /**
347      * Determine whether this is a warning level error.
348      * @return boolean
349      */
350     function isWarning() {
351         return ($this->errno & EM_WARNING_ERRORS) != 0;
352     }
353
354     /**
355      * Determine whether this is a notice level error.
356      * @return boolean
357      */
358     function isNotice() {
359         return ($this->errno & EM_NOTICE_ERRORS) != 0;
360     }
361
362     /**
363      * Get a printable, HTML, message detailing this error.
364      * @return object The detailed error message.
365      */
366     function _getDetail() {
367         if ($this->isNotice())
368             $what = 'Notice';
369         else if ($this->isWarning())
370             $what = 'Warning';
371         else
372             $what = 'Fatal';
373
374         $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4);
375         if (substr(PHP_OS,0,3) == 'WIN') {
376            $dir = str_replace('/','\\',$dir);
377            $this->errfile = str_replace('/','\\',$this->errfile);
378            $dir .= "\\";
379         } else 
380            $dir .= '/';
381         $errfile = preg_replace('|^' . preg_quote($dir) . '|', '', $this->errfile);
382         $lines = explode("\n", $this->errstr);
383
384         $msg = sprintf("%s:%d: %s[%d]: %s",
385                        $errfile, $this->errline,
386                        $what, $this->errno,
387                        array_shift($lines));
388         
389         $html = HTML::div(array('class' => 'error'), HTML::p($msg));
390         
391         if ($lines) {
392             $list = HTML::ul();
393             foreach ($lines as $line)
394                 $list->pushContent(HTML::li($line));
395             $html->pushContent($list);
396         }
397         
398         return $html;
399     }
400
401     /**
402      * Print an HTMLified version of this error.
403      * @see asXML()
404      */
405     function printXML() {
406         PrintXML($this->_getDetail());
407     }
408
409     /**
410      * Return an HTMLified version of this error.
411      */
412     function asXML() {
413         return AsXML($this->_getDetail());
414     }
415
416     /**
417      * Return a plain-text version of this error.
418      */
419     function asString() {
420         return AsString($this->_getDetail());
421     }
422 }
423
424 /**
425  * A class representing a PhpWiki warning.
426  *
427  * This is essentially the same as a PhpError, except that the
428  * error message is quieter: no source line, etc...
429  */
430 class PhpWikiError extends PhpError {
431     /**
432      * Construct a new PhpError.
433      * @param $errno   int
434      * @param $errstr  string
435      */
436     function PhpWikiError($errno, $errstr) {
437         $this->PhpError($errno, $errstr, '?', '?');
438     }
439
440     function _getDetail() {
441         if ($this->isNotice())
442             $what = 'Notice';
443         else if ($this->isWarning())
444             $what = 'Warning';
445         else
446             $what = 'Fatal';
447
448         return HTML::div(array('class' => 'error'), HTML::p("$what: $this->errstr"));
449     }
450 }
451
452 /**
453  * A class representing a Php warning, printed only the first time.
454  *
455  * Similar to PhpError, except only the first same error message is printed, 
456  * with number of occurences.
457  */
458 class PhpErrorOnce extends PhpError {
459
460     function PhpErrorOnce($errno, $errstr, $errfile, $errline) {
461         $this->_count = 1;
462         $this->PhpError($errno, $errstr, $errfile, $errline);
463     }
464
465     function _sameError($error) {
466         if (!$error) return false;
467         return ($this->errno == $error->errno and
468                 $this->errfile == $error->errfile and
469                 $this->errline == $error->errline);
470     }
471
472     // count similar handlers, increase _count and remove the rest
473     function removeDoublettes(&$errors) {
474         for ($i=0; $i < count($errors); $i++) {
475             if (!isset($errors[$i])) continue;
476             if ($this->_sameError($errors[$i])) {
477                 $errors[$i]->_count++;
478                 $this->_count++;
479                 if ($i) unset($errors[$i]);
480             }
481         }
482         return $this->_count;
483     }
484     
485     function _getDetail($count=0) {
486         if (!$count) $count = $this->_count;
487         if ($this->isNotice())
488             $what = 'Notice';
489         else if ($this->isWarning())
490             $what = 'Warning';
491         else
492             $what = 'Fatal';
493         $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4);
494         if (substr(PHP_OS,0,3) == 'WIN') {
495            $dir = str_replace('/','\\',$dir);
496            $this->errfile = str_replace('/','\\',$this->errfile);
497            $dir .= "\\";
498         } else 
499            $dir .= '/';
500         $errfile = preg_replace('|^' . preg_quote($dir) . '|', '', $this->errfile);
501         $lines = explode("\n", $this->errstr);
502         $msg = sprintf("%s:%d: %s[%d]: %s %s",
503                        $errfile, $this->errline,
504                        $what, $this->errno,
505                        array_shift($lines),
506                        $count > 1 ? sprintf(" (...repeated %d times)",$count) : ""
507                        );
508                        
509         $html = HTML::div(array('class' => 'error'), HTML::p($msg));
510         if ($lines) {
511             $list = HTML::ul();
512             foreach ($lines as $line)
513                 $list->pushContent(HTML::li($line));
514             $html->pushContent($list);
515         }
516         
517         return $html;
518     }
519 }
520
521 if (!isset($GLOBALS['ErrorManager'])) {
522     $GLOBALS['ErrorManager'] = new ErrorManager;
523 }
524
525 // $Log: not supported by cvs2svn $
526 // Revision 1.25  2004/06/02 10:18:36  rurban
527 // assert only if DEBUG is non-false
528 //
529 // Revision 1.24  2004/05/27 17:49:05  rurban
530 // renamed DB_Session to DbSession (in CVS also)
531 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
532 // remove leading slash in error message
533 // added force_unlock parameter to File_Passwd (no return on stale locks)
534 // fixed adodb session AffectedRows
535 // added FileFinder helpers to unify local filenames and DATA_PATH names
536 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
537 //
538 //
539
540 // (c-file-style: "gnu")
541 // Local Variables:
542 // mode: php
543 // tab-width: 8
544 // c-basic-offset: 4
545 // c-hanging-comment-ender-p: nil
546 // indent-tabs-mode: nil
547 // End:
548 ?>