Don't log HttpError
[lhc/web/wiklou.git] / includes / Exception.php
1 <?php
2 /**
3 * Exception class and handler
4 *
5 * @file
6 */
7
8 /**
9 * @defgroup Exception Exception
10 */
11
12 /**
13 * MediaWiki exception
14 *
15 * @ingroup Exception
16 */
17 class MWException extends Exception {
18 var $logId;
19
20 /**
21 * Should the exception use $wgOut to output the error ?
22 * @return bool
23 */
24 function useOutputPage() {
25 return $this->useMessageCache() &&
26 !empty( $GLOBALS['wgFullyInitialised'] ) &&
27 !empty( $GLOBALS['wgOut'] ) &&
28 !empty( $GLOBALS['wgTitle'] );
29 }
30
31 /**
32 * Can the extension use wfMsg() to get i18n messages ?
33 * @return bool
34 */
35 function useMessageCache() {
36 global $wgLang;
37
38 foreach ( $this->getTrace() as $frame ) {
39 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
40 return false;
41 }
42 }
43
44 return $wgLang instanceof Language;
45 }
46
47 /**
48 * Run hook to allow extensions to modify the text of the exception
49 *
50 * @param $name String: class name of the exception
51 * @param $args Array: arguments to pass to the callback functions
52 * @return Mixed: string to output or null if any hook has been called
53 */
54 function runHooks( $name, $args = array() ) {
55 global $wgExceptionHooks;
56
57 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
58 return null; // Just silently ignore
59 }
60
61 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
62 return null;
63 }
64
65 $hooks = $wgExceptionHooks[ $name ];
66 $callargs = array_merge( array( $this ), $args );
67
68 foreach ( $hooks as $hook ) {
69 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
70 $result = call_user_func_array( $hook, $callargs );
71 } else {
72 $result = null;
73 }
74
75 if ( is_string( $result ) ) {
76 return $result;
77 }
78 }
79 return null;
80 }
81
82 /**
83 * Get a message from i18n
84 *
85 * @param $key String: message name
86 * @param $fallback String: default message if the message cache can't be
87 * called by the exception
88 * The function also has other parameters that are arguments for the message
89 * @return String message with arguments replaced
90 */
91 function msg( $key, $fallback /*[, params...] */ ) {
92 $args = array_slice( func_get_args(), 2 );
93
94 if ( $this->useMessageCache() ) {
95 return wfMsgNoTrans( $key, $args );
96 } else {
97 return wfMsgReplaceArgs( $fallback, $args );
98 }
99 }
100
101 /**
102 * If $wgShowExceptionDetails is true, return a HTML message with a
103 * backtrace to the error, otherwise show a message to ask to set it to true
104 * to show that information.
105 *
106 * @return String html to output
107 */
108 function getHTML() {
109 global $wgShowExceptionDetails;
110
111 if ( $wgShowExceptionDetails ) {
112 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
113 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
114 "</p>\n";
115 } else {
116 return
117 "<div class=\"errorbox\">" .
118 '[' . $this->getLogId() . '] ' .
119 gmdate( 'Y-m-d H:i:s' ) .
120 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
121 "<!-- Set \$wgShowExceptionDetails = true; " .
122 "at the bottom of LocalSettings.php to show detailed " .
123 "debugging information. -->";
124 }
125 }
126
127 /**
128 * If $wgShowExceptionDetails is true, return a text message with a
129 * backtrace to the error.
130 * @return string
131 */
132 function getText() {
133 global $wgShowExceptionDetails;
134
135 if ( $wgShowExceptionDetails ) {
136 return $this->getMessage() .
137 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
138 } else {
139 return "Set \$wgShowExceptionDetails = true; " .
140 "in LocalSettings.php to show detailed debugging information.\n";
141 }
142 }
143
144 /**
145 * Return titles of this error page
146 * @return String
147 */
148 function getPageTitle() {
149 return $this->msg( 'internalerror', "Internal error" );
150 }
151
152 function getLogId() {
153 if ( $this->logId === null ) {
154 $this->logId = wfRandomString( 8 );
155 }
156 return $this->logId;
157 }
158
159 /**
160 * Return the requested URL and point to file and line number from which the
161 * exception occured
162 *
163 * @return String
164 */
165 function getLogMessage() {
166 global $wgRequest;
167
168 $id = $this->getLogId();
169 $file = $this->getFile();
170 $line = $this->getLine();
171 $message = $this->getMessage();
172
173 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
174 $url = $wgRequest->getRequestURL();
175 if ( !$url ) {
176 $url = '[no URL]';
177 }
178 } else {
179 $url = '[no req]';
180 }
181
182 return "[$id] $url Exception from line $line of $file: $message";
183 }
184
185 /** Output the exception report using HTML */
186 function reportHTML() {
187 global $wgOut;
188 if ( $this->useOutputPage() ) {
189 $wgOut->prepareErrorPage( $this->getPageTitle() );
190
191 $hookResult = $this->runHooks( get_class( $this ) );
192 if ( $hookResult ) {
193 $wgOut->addHTML( $hookResult );
194 } else {
195 $wgOut->addHTML( $this->getHTML() );
196 }
197
198 $wgOut->output();
199 } else {
200 header( "Content-Type: text/html; charset=utf-8" );
201 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
202 if ( $hookResult ) {
203 die( $hookResult );
204 }
205
206 echo $this->getHTML();
207 die(1);
208 }
209 }
210
211 /**
212 * Output a report about the exception and takes care of formatting.
213 * It will be either HTML or plain text based on isCommandLine().
214 */
215 function report() {
216 global $wgLogExceptionBacktrace;
217 $log = $this->getLogMessage();
218
219 if ( $log ) {
220 if ( $wgLogExceptionBacktrace ) {
221 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
222 } else {
223 wfDebugLog( 'exception', $log );
224 }
225 }
226
227 if ( defined( 'MW_API' ) ) {
228 // Unhandled API exception, we can't be sure that format printer is alive
229 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
230 wfHttpError(500, 'Internal Server Error', $this->getText() );
231 } elseif ( self::isCommandLine() ) {
232 MWExceptionHandler::printError( $this->getText() );
233 } else {
234 $this->reportHTML();
235 }
236 }
237
238 /**
239 * @static
240 * @return bool
241 */
242 static function isCommandLine() {
243 return !empty( $GLOBALS['wgCommandLineMode'] );
244 }
245 }
246
247 /**
248 * Exception class which takes an HTML error message, and does not
249 * produce a backtrace. Replacement for OutputPage::fatalError().
250 * @ingroup Exception
251 */
252 class FatalError extends MWException {
253
254 /**
255 * @return string
256 */
257 function getHTML() {
258 return $this->getMessage();
259 }
260
261 /**
262 * @return string
263 */
264 function getText() {
265 return $this->getMessage();
266 }
267 }
268
269 /**
270 * An error page which can definitely be safely rendered using the OutputPage
271 * @ingroup Exception
272 */
273 class ErrorPageError extends MWException {
274 public $title, $msg, $params;
275
276 /**
277 * Note: these arguments are keys into wfMsg(), not text!
278 */
279 function __construct( $title, $msg, $params = null ) {
280 $this->title = $title;
281 $this->msg = $msg;
282 $this->params = $params;
283
284 if( $msg instanceof Message ){
285 parent::__construct( $msg );
286 } else {
287 parent::__construct( wfMsg( $msg ) );
288 }
289 }
290
291 function report() {
292 global $wgOut;
293
294 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
295 $wgOut->output();
296 }
297 }
298
299 /**
300 * Show an error page on a badtitle.
301 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
302 * browser it is not really a valid content.
303 */
304 class BadTitleError extends ErrorPageError {
305
306 /**
307 * @param $msg string A message key (default: 'badtitletext')
308 * @param $params Array parameter to wfMsg()
309 */
310 function __construct( $msg = 'badtitletext', $params = null ) {
311 parent::__construct( 'badtitle', $msg, $params );
312 }
313
314 /**
315 * Just like ErrorPageError::report() but additionally set
316 * a 400 HTTP status code (bug 33646).
317 */
318 function report() {
319 global $wgOut;
320
321 // bug 33646: a badtitle error page need to return an error code
322 // to let mobile browser now that it is not a normal page.
323 $wgOut->setStatusCode( 400 );
324 parent::report();
325 }
326
327 }
328
329 /**
330 * Show an error when a user tries to do something they do not have the necessary
331 * permissions for.
332 * @ingroup Exception
333 */
334 class PermissionsError extends ErrorPageError {
335 public $permission, $errors;
336
337 function __construct( $permission, $errors = array() ) {
338 global $wgLang;
339
340 $this->permission = $permission;
341
342 if ( !count( $errors ) ) {
343 $groups = array_map(
344 array( 'User', 'makeGroupLinkWiki' ),
345 User::getGroupsWithPermission( $this->permission )
346 );
347
348 if ( $groups ) {
349 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
350 } else {
351 $errors[] = array( 'badaccess-group0' );
352 }
353 }
354
355 $this->errors = $errors;
356 }
357
358 function report() {
359 global $wgOut;
360
361 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
362 $wgOut->output();
363 }
364 }
365
366 /**
367 * Show an error when the wiki is locked/read-only and the user tries to do
368 * something that requires write access
369 * @ingroup Exception
370 */
371 class ReadOnlyError extends ErrorPageError {
372 public function __construct(){
373 parent::__construct(
374 'readonly',
375 'readonlytext',
376 wfReadOnlyReason()
377 );
378 }
379 }
380
381 /**
382 * Show an error when the user hits a rate limit
383 * @ingroup Exception
384 */
385 class ThrottledError extends ErrorPageError {
386 public function __construct(){
387 parent::__construct(
388 'actionthrottled',
389 'actionthrottledtext'
390 );
391 }
392
393 public function report(){
394 global $wgOut;
395 $wgOut->setStatusCode( 503 );
396 parent::report();
397 }
398 }
399
400 /**
401 * Show an error when the user tries to do something whilst blocked
402 * @ingroup Exception
403 */
404 class UserBlockedError extends ErrorPageError {
405 public function __construct( Block $block ){
406 global $wgLang, $wgRequest;
407
408 $blocker = $block->getBlocker();
409 if ( $blocker instanceof User ) { // local user
410 $blockerUserpage = $block->getBlocker()->getUserPage();
411 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
412 } else { // foreign user
413 $link = $blocker;
414 }
415
416 $reason = $block->mReason;
417 if( $reason == '' ) {
418 $reason = wfMsg( 'blockednoreason' );
419 }
420
421 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
422 * This could be a username, an IP range, or a single IP. */
423 $intended = $block->getTarget();
424
425 parent::__construct(
426 'blockedtitle',
427 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
428 array(
429 $link,
430 $reason,
431 $wgRequest->getIP(),
432 $block->getByName(),
433 $block->getId(),
434 $wgLang->formatExpiry( $block->mExpiry ),
435 $intended,
436 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
437 )
438 );
439 }
440 }
441
442 /**
443 * Show an error that looks like an HTTP server error.
444 * Replacement for wfHttpError().
445 *
446 * @ingroup Exception
447 */
448 class HttpError extends MWException {
449 private $httpCode, $header, $content;
450
451 /**
452 * Constructor
453 *
454 * @param $httpCode Integer: HTTP status code to send to the client
455 * @param $content String|Message: content of the message
456 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
457 */
458 public function __construct( $httpCode, $content, $header = null ){
459 parent::__construct( $content );
460 $this->httpCode = (int)$httpCode;
461 $this->header = $header;
462 $this->content = $content;
463 }
464
465 public function report() {
466 $httpMessage = HttpStatus::getMessage( $this->httpCode );
467
468 header( "Status: {$this->httpCode} {$httpMessage}" );
469 header( 'Content-type: text/html; charset=utf-8' );
470
471 if ( $this->header === null ) {
472 $header = $httpMessage;
473 } elseif ( $this->header instanceof Message ) {
474 $header = $this->header->escaped();
475 } else {
476 $header = htmlspecialchars( $this->header );
477 }
478
479 if ( $this->content instanceof Message ) {
480 $content = $this->content->escaped();
481 } else {
482 $content = htmlspecialchars( $this->content );
483 }
484
485 print "<!DOCTYPE html>\n".
486 "<html><head><title>$header</title></head>\n" .
487 "<body><h1>$header</h1><p>$content</p></body></html>\n";
488 }
489 }
490
491 /**
492 * Handler class for MWExceptions
493 * @ingroup Exception
494 */
495 class MWExceptionHandler {
496 /**
497 * Install an exception handler for MediaWiki exception types.
498 */
499 public static function installHandler() {
500 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
501 }
502
503 /**
504 * Report an exception to the user
505 */
506 protected static function report( Exception $e ) {
507 global $wgShowExceptionDetails;
508
509 $cmdLine = MWException::isCommandLine();
510
511 if ( $e instanceof MWException ) {
512 try {
513 // Try and show the exception prettily, with the normal skin infrastructure
514 $e->report();
515 } catch ( Exception $e2 ) {
516 // Exception occurred from within exception handler
517 // Show a simpler error message for the original exception,
518 // don't try to invoke report()
519 $message = "MediaWiki internal error.\n\n";
520
521 if ( $wgShowExceptionDetails ) {
522 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
523 'Exception caught inside exception handler: ' . $e2->__toString();
524 } else {
525 $message .= "Exception caught inside exception handler.\n\n" .
526 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
527 "to show detailed debugging information.";
528 }
529
530 $message .= "\n";
531
532 if ( $cmdLine ) {
533 self::printError( $message );
534 } else {
535 self::escapeEchoAndDie( $message );
536 }
537 }
538 } else {
539 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
540 $e->__toString() . "\n";
541
542 if ( $wgShowExceptionDetails ) {
543 $message .= "\n" . $e->getTraceAsString() . "\n";
544 }
545
546 if ( $cmdLine ) {
547 self::printError( $message );
548 } else {
549 self::escapeEchoAndDie( $message );
550 }
551 }
552 }
553
554 /**
555 * Print a message, if possible to STDERR.
556 * Use this in command line mode only (see isCommandLine)
557 * @param $message String Failure text
558 */
559 public static function printError( $message ) {
560 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
561 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
562 if ( defined( 'STDERR' ) ) {
563 fwrite( STDERR, $message );
564 } else {
565 echo( $message );
566 }
567 }
568
569 /**
570 * Print a message after escaping it and converting newlines to <br>
571 * Use this for non-command line failures
572 * @param $message String Failure text
573 */
574 private static function escapeEchoAndDie( $message ) {
575 echo nl2br( htmlspecialchars( $message ) ) . "\n";
576 die(1);
577 }
578
579 /**
580 * Exception handler which simulates the appropriate catch() handling:
581 *
582 * try {
583 * ...
584 * } catch ( MWException $e ) {
585 * $e->report();
586 * } catch ( Exception $e ) {
587 * echo $e->__toString();
588 * }
589 */
590 public static function handle( $e ) {
591 global $wgFullyInitialised;
592
593 self::report( $e );
594
595 // Final cleanup
596 if ( $wgFullyInitialised ) {
597 try {
598 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
599 } catch ( Exception $e ) {}
600 }
601
602 // Exit value should be nonzero for the benefit of shell jobs
603 exit( 1 );
604 }
605 }