Merge "Remove weird, confusing, unreachable code"
[mediawiki.git] / includes / Exception.php
blob0fc5cd78716351d634f43ad6d20d1b53be387b82
1 <?php
2 /**
3 * Exception class and handler.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * @defgroup Exception Exception
27 /**
28 * MediaWiki exception
30 * @ingroup Exception
32 class MWException extends Exception {
33 var $logId;
35 /**
36 * Should the exception use $wgOut to output the error?
38 * @return bool
40 function useOutputPage() {
41 return $this->useMessageCache() &&
42 !empty( $GLOBALS['wgFullyInitialised'] ) &&
43 !empty( $GLOBALS['wgOut'] ) &&
44 !empty( $GLOBALS['wgTitle'] );
47 /**
48 * Can the extension use wfMsg() to get i18n messages?
50 * @return bool
52 function useMessageCache() {
53 global $wgLang;
55 foreach ( $this->getTrace() as $frame ) {
56 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
57 return false;
61 return $wgLang instanceof Language;
64 /**
65 * Run hook to allow extensions to modify the text of the exception
67 * @param $name string: class name of the exception
68 * @param $args array: arguments to pass to the callback functions
69 * @return string|null string to output or null if any hook has been called
71 function runHooks( $name, $args = array() ) {
72 global $wgExceptionHooks;
74 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
75 return null; // Just silently ignore
78 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
79 return null;
82 $hooks = $wgExceptionHooks[ $name ];
83 $callargs = array_merge( array( $this ), $args );
85 foreach ( $hooks as $hook ) {
86 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
87 $result = call_user_func_array( $hook, $callargs );
88 } else {
89 $result = null;
92 if ( is_string( $result ) ) {
93 return $result;
96 return null;
99 /**
100 * Get a message from i18n
102 * @param $key string: message name
103 * @param $fallback string: default message if the message cache can't be
104 * called by the exception
105 * The function also has other parameters that are arguments for the message
106 * @return string message with arguments replaced
108 function msg( $key, $fallback /*[, params...] */ ) {
109 $args = array_slice( func_get_args(), 2 );
111 if ( $this->useMessageCache() ) {
112 return wfMsgNoTrans( $key, $args );
113 } else {
114 return wfMsgReplaceArgs( $fallback, $args );
119 * If $wgShowExceptionDetails is true, return a HTML message with a
120 * backtrace to the error, otherwise show a message to ask to set it to true
121 * to show that information.
123 * @return string html to output
125 function getHTML() {
126 global $wgShowExceptionDetails;
128 if ( $wgShowExceptionDetails ) {
129 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
130 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
131 "</p>\n";
132 } else {
133 return
134 "<div class=\"errorbox\">" .
135 '[' . $this->getLogId() . '] ' .
136 gmdate( 'Y-m-d H:i:s' ) .
137 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
138 "<!-- Set \$wgShowExceptionDetails = true; " .
139 "at the bottom of LocalSettings.php to show detailed " .
140 "debugging information. -->";
145 * Get the text to display when reporting the error on the command line.
146 * If $wgShowExceptionDetails is true, return a text message with a
147 * backtrace to the error.
149 * @return string
151 function getText() {
152 global $wgShowExceptionDetails;
154 if ( $wgShowExceptionDetails ) {
155 return $this->getMessage() .
156 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
157 } else {
158 return "Set \$wgShowExceptionDetails = true; " .
159 "in LocalSettings.php to show detailed debugging information.\n";
164 * Return the title of the page when reporting this error in a HTTP response.
166 * @return string
168 function getPageTitle() {
169 return $this->msg( 'internalerror', "Internal error" );
173 * Get a random ID for this error.
174 * This allows to link the exception to its correspoding log entry when
175 * $wgShowExceptionDetails is set to false.
177 * @return string
179 function getLogId() {
180 if ( $this->logId === null ) {
181 $this->logId = wfRandomString( 8 );
183 return $this->logId;
187 * Return the requested URL and point to file and line number from which the
188 * exception occured
190 * @return string
192 function getLogMessage() {
193 global $wgRequest;
195 $id = $this->getLogId();
196 $file = $this->getFile();
197 $line = $this->getLine();
198 $message = $this->getMessage();
200 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
201 $url = $wgRequest->getRequestURL();
202 if ( !$url ) {
203 $url = '[no URL]';
205 } else {
206 $url = '[no req]';
209 return "[$id] $url Exception from line $line of $file: $message";
213 * Output the exception report using HTML.
215 function reportHTML() {
216 global $wgOut;
217 if ( $this->useOutputPage() ) {
218 $wgOut->prepareErrorPage( $this->getPageTitle() );
220 $hookResult = $this->runHooks( get_class( $this ) );
221 if ( $hookResult ) {
222 $wgOut->addHTML( $hookResult );
223 } else {
224 $wgOut->addHTML( $this->getHTML() );
227 $wgOut->output();
228 } else {
229 header( "Content-Type: text/html; charset=utf-8" );
230 echo "<!doctype html>\n" .
231 '<html><head>' .
232 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
233 "</head><body>\n";
235 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
236 if ( $hookResult ) {
237 echo $hookResult;
238 } else {
239 echo $this->getHTML();
242 echo "</body></html>\n";
243 die( 1 );
248 * Output a report about the exception and takes care of formatting.
249 * It will be either HTML or plain text based on isCommandLine().
251 function report() {
252 global $wgLogExceptionBacktrace;
253 $log = $this->getLogMessage();
255 if ( $log ) {
256 if ( $wgLogExceptionBacktrace ) {
257 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
258 } else {
259 wfDebugLog( 'exception', $log );
263 if ( defined( 'MW_API' ) ) {
264 // Unhandled API exception, we can't be sure that format printer is alive
265 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
266 wfHttpError(500, 'Internal Server Error', $this->getText() );
267 } elseif ( self::isCommandLine() ) {
268 MWExceptionHandler::printError( $this->getText() );
269 } else {
270 header( "HTTP/1.1 500 MediaWiki exception" );
271 header( "Status: 500 MediaWiki exception", true );
273 $this->reportHTML();
278 * Check whether we are in command line mode or not to report the exception
279 * in the correct format.
281 * @return bool
283 static function isCommandLine() {
284 return !empty( $GLOBALS['wgCommandLineMode'] );
289 * Exception class which takes an HTML error message, and does not
290 * produce a backtrace. Replacement for OutputPage::fatalError().
292 * @ingroup Exception
294 class FatalError extends MWException {
297 * @return string
299 function getHTML() {
300 return $this->getMessage();
304 * @return string
306 function getText() {
307 return $this->getMessage();
312 * An error page which can definitely be safely rendered using the OutputPage.
314 * @ingroup Exception
316 class ErrorPageError extends MWException {
317 public $title, $msg, $params;
320 * @todo document
322 * Note: these arguments are keys into wfMsg(), not text!
324 * @param $title A title
325 * @param $msg String|Message . In string form, should be a message key
326 * @param $params Array Array to wfMsg()
328 function __construct( $title, $msg, $params = null ) {
329 $this->title = $title;
330 $this->msg = $msg;
331 $this->params = $params;
333 if( $msg instanceof Message ){
334 parent::__construct( $msg );
335 } else {
336 parent::__construct( wfMsg( $msg ) );
340 function report() {
341 global $wgOut;
343 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
344 $wgOut->output();
349 * Show an error page on a badtitle.
350 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
351 * browser it is not really a valid content.
353 * @ingroup Exception
355 class BadTitleError extends ErrorPageError {
358 * @param $msg string A message key (default: 'badtitletext')
359 * @param $params Array parameter to wfMsg()
361 function __construct( $msg = 'badtitletext', $params = null ) {
362 parent::__construct( 'badtitle', $msg, $params );
366 * Just like ErrorPageError::report() but additionally set
367 * a 400 HTTP status code (bug 33646).
369 function report() {
370 global $wgOut;
372 // bug 33646: a badtitle error page need to return an error code
373 // to let mobile browser now that it is not a normal page.
374 $wgOut->setStatusCode( 400 );
375 parent::report();
381 * Show an error when a user tries to do something they do not have the necessary
382 * permissions for.
384 * @ingroup Exception
386 class PermissionsError extends ErrorPageError {
387 public $permission, $errors;
389 function __construct( $permission, $errors = array() ) {
390 global $wgLang;
392 $this->permission = $permission;
394 if ( !count( $errors ) ) {
395 $groups = array_map(
396 array( 'User', 'makeGroupLinkWiki' ),
397 User::getGroupsWithPermission( $this->permission )
400 if ( $groups ) {
401 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
402 } else {
403 $errors[] = array( 'badaccess-group0' );
407 $this->errors = $errors;
410 function report() {
411 global $wgOut;
413 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
414 $wgOut->output();
419 * Show an error when the wiki is locked/read-only and the user tries to do
420 * something that requires write access.
422 * @ingroup Exception
424 class ReadOnlyError extends ErrorPageError {
425 public function __construct(){
426 parent::__construct(
427 'readonly',
428 'readonlytext',
429 wfReadOnlyReason()
435 * Show an error when the user hits a rate limit.
437 * @ingroup Exception
439 class ThrottledError extends ErrorPageError {
440 public function __construct(){
441 parent::__construct(
442 'actionthrottled',
443 'actionthrottledtext'
447 public function report(){
448 global $wgOut;
449 $wgOut->setStatusCode( 503 );
450 parent::report();
455 * Show an error when the user tries to do something whilst blocked.
457 * @ingroup Exception
459 class UserBlockedError extends ErrorPageError {
460 public function __construct( Block $block ){
461 global $wgLang, $wgRequest;
463 $blocker = $block->getBlocker();
464 if ( $blocker instanceof User ) { // local user
465 $blockerUserpage = $block->getBlocker()->getUserPage();
466 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
467 } else { // foreign user
468 $link = $blocker;
471 $reason = $block->mReason;
472 if( $reason == '' ) {
473 $reason = wfMsg( 'blockednoreason' );
476 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
477 * This could be a username, an IP range, or a single IP. */
478 $intended = $block->getTarget();
480 parent::__construct(
481 'blockedtitle',
482 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
483 array(
484 $link,
485 $reason,
486 $wgRequest->getIP(),
487 $block->getByName(),
488 $block->getId(),
489 $wgLang->formatExpiry( $block->mExpiry ),
490 $intended,
491 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
498 * Shows a generic "user is not logged in" error page.
500 * This is essentially an ErrorPageError exception which by default use the
501 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
502 * @see bug 37627
504 * @par Example:
505 * @code
506 * if( $user->isAnon ) {
507 * throw new UserNotLoggedIn();
509 * @endcode
511 * Please note the parameters are mixed up compared to ErrorPageError, this
512 * is done to be able to simply specify a reason whitout overriding the default
513 * title.
515 * @par Example:
516 * @code
517 * if( $user->isAnon ) {
518 * throw new UserNotLoggedIn( 'action-require-loggedin' );
520 * @endcode
522 * @ingroup Exception
524 class UserNotLoggedIn extends ErrorPageError {
527 * @param $reasonMsg A message key containing the reason for the error.
528 * Optional, default: 'exception-nologin-text'
529 * @param $titleMsg A message key to set the page title.
530 * Optional, default: 'exception-nologin'
531 * @param $params Parameters to wfMsg().
532 * Optiona, default: null
534 public function __construct(
535 $reasonMsg = 'exception-nologin-text',
536 $titleMsg = 'exception-nologin',
537 $params = null
539 parent::__construct( $titleMsg, $reasonMsg, $params );
544 * Show an error that looks like an HTTP server error.
545 * Replacement for wfHttpError().
547 * @ingroup Exception
549 class HttpError extends MWException {
550 private $httpCode, $header, $content;
553 * Constructor
555 * @param $httpCode Integer: HTTP status code to send to the client
556 * @param $content String|Message: content of the message
557 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
559 public function __construct( $httpCode, $content, $header = null ){
560 parent::__construct( $content );
561 $this->httpCode = (int)$httpCode;
562 $this->header = $header;
563 $this->content = $content;
566 public function report() {
567 $httpMessage = HttpStatus::getMessage( $this->httpCode );
569 header( "Status: {$this->httpCode} {$httpMessage}" );
570 header( 'Content-type: text/html; charset=utf-8' );
572 if ( $this->header === null ) {
573 $header = $httpMessage;
574 } elseif ( $this->header instanceof Message ) {
575 $header = $this->header->escaped();
576 } else {
577 $header = htmlspecialchars( $this->header );
580 if ( $this->content instanceof Message ) {
581 $content = $this->content->escaped();
582 } else {
583 $content = htmlspecialchars( $this->content );
586 print "<!DOCTYPE html>\n".
587 "<html><head><title>$header</title></head>\n" .
588 "<body><h1>$header</h1><p>$content</p></body></html>\n";
593 * Handler class for MWExceptions
594 * @ingroup Exception
596 class MWExceptionHandler {
598 * Install an exception handler for MediaWiki exception types.
600 public static function installHandler() {
601 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
605 * Report an exception to the user
607 protected static function report( Exception $e ) {
608 global $wgShowExceptionDetails;
610 $cmdLine = MWException::isCommandLine();
612 if ( $e instanceof MWException ) {
613 try {
614 // Try and show the exception prettily, with the normal skin infrastructure
615 $e->report();
616 } catch ( Exception $e2 ) {
617 // Exception occurred from within exception handler
618 // Show a simpler error message for the original exception,
619 // don't try to invoke report()
620 $message = "MediaWiki internal error.\n\n";
622 if ( $wgShowExceptionDetails ) {
623 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
624 'Exception caught inside exception handler: ' . $e2->__toString();
625 } else {
626 $message .= "Exception caught inside exception handler.\n\n" .
627 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
628 "to show detailed debugging information.";
631 $message .= "\n";
633 if ( $cmdLine ) {
634 self::printError( $message );
635 } else {
636 self::escapeEchoAndDie( $message );
639 } else {
640 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
641 $e->__toString() . "\n";
643 if ( $wgShowExceptionDetails ) {
644 $message .= "\n" . $e->getTraceAsString() . "\n";
647 if ( $cmdLine ) {
648 self::printError( $message );
649 } else {
650 self::escapeEchoAndDie( $message );
656 * Print a message, if possible to STDERR.
657 * Use this in command line mode only (see isCommandLine)
659 * @param $message string Failure text
661 public static function printError( $message ) {
662 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
663 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
664 if ( defined( 'STDERR' ) ) {
665 fwrite( STDERR, $message );
666 } else {
667 echo( $message );
672 * Print a message after escaping it and converting newlines to <br>
673 * Use this for non-command line failures.
675 * @param $message string Failure text
677 private static function escapeEchoAndDie( $message ) {
678 echo nl2br( htmlspecialchars( $message ) ) . "\n";
679 die(1);
683 * Exception handler which simulates the appropriate catch() handling:
685 * try {
686 * ...
687 * } catch ( MWException $e ) {
688 * $e->report();
689 * } catch ( Exception $e ) {
690 * echo $e->__toString();
693 public static function handle( $e ) {
694 global $wgFullyInitialised;
696 self::report( $e );
698 // Final cleanup
699 if ( $wgFullyInitialised ) {
700 try {
701 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
702 } catch ( Exception $e ) {}
705 // Exit value should be nonzero for the benefit of shell jobs
706 exit( 1 );