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
24 * @defgroup Exception Exception
32 class MWException
extends Exception
{
36 * Should the exception use $wgOut to output the error?
40 function useOutputPage() {
41 return $this->useMessageCache() &&
42 !empty( $GLOBALS['wgFullyInitialised'] ) &&
43 !empty( $GLOBALS['wgOut'] ) &&
44 !empty( $GLOBALS['wgTitle'] );
48 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
52 function useMessageCache() {
55 foreach ( $this->getTrace() as $frame ) {
56 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
61 return $wgLang instanceof Language
;
65 * Run hook to allow extensions to modify the text of the exception
67 * @param string $name class name of the exception
68 * @param array $args 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] ) ) {
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 );
92 if ( is_string( $result ) ) {
100 * Get a message from i18n
102 * @param string $key message name
103 * @param string $fallback 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 wfMessage( $key, $args )->plain();
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
126 global $wgShowExceptionDetails;
128 if ( $wgShowExceptionDetails ) {
129 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
130 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
133 return "<div class=\"errorbox\">" .
134 '[' . $this->getLogId() . '] ' .
135 gmdate( 'Y-m-d H:i:s' ) .
136 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
137 "<!-- Set \$wgShowExceptionDetails = true; " .
138 "at the bottom of LocalSettings.php to show detailed " .
139 "debugging information. -->";
144 * Get the text to display when reporting the error on the command line.
145 * If $wgShowExceptionDetails is true, return a text message with a
146 * backtrace to the error.
151 global $wgShowExceptionDetails;
153 if ( $wgShowExceptionDetails ) {
154 return $this->getMessage() .
155 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
157 return "Set \$wgShowExceptionDetails = true; " .
158 "in LocalSettings.php to show detailed debugging information.\n";
163 * Return the title of the page when reporting this error in a HTTP response.
167 function getPageTitle() {
168 return $this->msg( 'internalerror', "Internal error" );
172 * Get a random ID for this error.
173 * This allows to link the exception to its corresponding log entry when
174 * $wgShowExceptionDetails is set to false.
178 function getLogId() {
179 if ( $this->logId
=== null ) {
180 $this->logId
= wfRandomString( 8 );
186 * Return the requested URL and point to file and line number from which the
191 function getLogMessage() {
194 $id = $this->getLogId();
195 $file = $this->getFile();
196 $line = $this->getLine();
197 $message = $this->getMessage();
199 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
200 $url = $wgRequest->getRequestURL();
208 return "[$id] $url Exception from line $line of $file: $message";
212 * Output the exception report using HTML.
214 function reportHTML() {
216 if ( $this->useOutputPage() ) {
217 $wgOut->prepareErrorPage( $this->getPageTitle() );
219 $hookResult = $this->runHooks( get_class( $this ) );
221 $wgOut->addHTML( $hookResult );
223 $wgOut->addHTML( $this->getHTML() );
228 header( "Content-Type: text/html; charset=utf-8" );
229 echo "<!doctype html>\n" .
231 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
234 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
238 echo $this->getHTML();
241 echo "</body></html>\n";
246 * Output a report about the exception and takes care of formatting.
247 * It will be either HTML or plain text based on isCommandLine().
250 global $wgLogExceptionBacktrace;
251 $log = $this->getLogMessage();
254 if ( $wgLogExceptionBacktrace ) {
255 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
257 wfDebugLog( 'exception', $log );
261 if ( defined( 'MW_API' ) ) {
262 // Unhandled API exception, we can't be sure that format printer is alive
263 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
264 wfHttpError( 500, 'Internal Server Error', $this->getText() );
265 } elseif ( self
::isCommandLine() ) {
266 MWExceptionHandler
::printError( $this->getText() );
268 header( "HTTP/1.1 500 MediaWiki exception" );
269 header( "Status: 500 MediaWiki exception", true );
276 * Check whether we are in command line mode or not to report the exception
277 * in the correct format.
281 static function isCommandLine() {
282 return !empty( $GLOBALS['wgCommandLineMode'] );
287 * Exception class which takes an HTML error message, and does not
288 * produce a backtrace. Replacement for OutputPage::fatalError().
293 class FatalError
extends MWException
{
299 return $this->getMessage();
306 return $this->getMessage();
311 * An error page which can definitely be safely rendered using the OutputPage.
316 class ErrorPageError
extends MWException
{
317 public $title, $msg, $params;
320 * Note: these arguments are keys into wfMessage(), not text!
322 * @param string|Message $title Message key (string) for page title, or a Message object
323 * @param string|Message $msg Message key (string) for error text, or a Message object
324 * @param array $params with parameters to wfMessage()
326 function __construct( $title, $msg, $params = null ) {
327 $this->title
= $title;
329 $this->params
= $params;
331 // Bug 44111: Messages in the log files should be in English and not
332 // customized by the local wiki. So get the default English version for
333 // passing to the parent constructor. Our overridden report() below
334 // makes sure that the page shown to the user is not forced to English.
335 if( $msg instanceof Message
) {
336 $enMsg = clone( $msg );
338 $enMsg = wfMessage( $msg, $params );
340 $enMsg->inLanguage( 'en' )->useDatabase( false );
341 parent
::__construct( $enMsg->text() );
347 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
353 * Show an error page on a badtitle.
354 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
355 * browser it is not really a valid content.
360 class BadTitleError
extends ErrorPageError
{
362 * @param string|Message $msg A message key (default: 'badtitletext')
363 * @param array $params parameter to wfMessage()
365 function __construct( $msg = 'badtitletext', $params = null ) {
366 parent
::__construct( 'badtitle', $msg, $params );
370 * Just like ErrorPageError::report() but additionally set
371 * a 400 HTTP status code (bug 33646).
376 // bug 33646: a badtitle error page need to return an error code
377 // to let mobile browser now that it is not a normal page.
378 $wgOut->setStatusCode( 400 );
385 * Show an error when a user tries to do something they do not have the necessary
391 class PermissionsError
extends ErrorPageError
{
392 public $permission, $errors;
394 function __construct( $permission, $errors = array() ) {
397 $this->permission
= $permission;
399 if ( !count( $errors ) ) {
401 array( 'User', 'makeGroupLinkWiki' ),
402 User
::getGroupsWithPermission( $this->permission
)
406 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
408 $errors[] = array( 'badaccess-group0' );
412 $this->errors
= $errors;
418 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
424 * Show an error when the wiki is locked/read-only and the user tries to do
425 * something that requires write access.
430 class ReadOnlyError
extends ErrorPageError
{
431 public function __construct() {
441 * Show an error when the user hits a rate limit.
446 class ThrottledError
extends ErrorPageError
{
447 public function __construct() {
450 'actionthrottledtext'
454 public function report() {
456 $wgOut->setStatusCode( 503 );
462 * Show an error when the user tries to do something whilst blocked.
467 class UserBlockedError
extends ErrorPageError
{
468 public function __construct( Block
$block ) {
469 global $wgLang, $wgRequest;
471 $blocker = $block->getBlocker();
472 if ( $blocker instanceof User
) { // local user
473 $blockerUserpage = $block->getBlocker()->getUserPage();
474 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
475 } else { // foreign user
479 $reason = $block->mReason
;
480 if( $reason == '' ) {
481 $reason = wfMessage( 'blockednoreason' )->text();
484 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
485 * This could be a username, an IP range, or a single IP. */
486 $intended = $block->getTarget();
490 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
497 $wgLang->formatExpiry( $block->mExpiry
),
499 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
506 * Shows a generic "user is not logged in" error page.
508 * This is essentially an ErrorPageError exception which by default uses the
509 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
515 * if( $user->isAnon() ) {
516 * throw new UserNotLoggedIn();
520 * Note the parameter order differs from ErrorPageError, this allows you to
521 * simply specify a reason without overriding the default title.
525 * if( $user->isAnon() ) {
526 * throw new UserNotLoggedIn( 'action-require-loggedin' );
532 class UserNotLoggedIn
extends ErrorPageError
{
535 * @param $reasonMsg A message key containing the reason for the error.
536 * Optional, default: 'exception-nologin-text'
537 * @param $titleMsg A message key to set the page title.
538 * Optional, default: 'exception-nologin'
539 * @param $params Parameters to wfMessage().
540 * Optional, default: null
542 public function __construct(
543 $reasonMsg = 'exception-nologin-text',
544 $titleMsg = 'exception-nologin',
547 parent
::__construct( $titleMsg, $reasonMsg, $params );
552 * Show an error that looks like an HTTP server error.
553 * Replacement for wfHttpError().
558 class HttpError
extends MWException
{
559 private $httpCode, $header, $content;
564 * @param $httpCode Integer: HTTP status code to send to the client
565 * @param string|Message $content content of the message
566 * @param string|Message $header content of the header (\<title\> and \<h1\>)
568 public function __construct( $httpCode, $content, $header = null ) {
569 parent
::__construct( $content );
570 $this->httpCode
= (int)$httpCode;
571 $this->header
= $header;
572 $this->content
= $content;
576 * Returns the HTTP status code supplied to the constructor.
580 public function getStatusCode() {
581 return $this->httpCode
;
585 * Report the HTTP error.
586 * Sends the appropriate HTTP status code and outputs an
587 * HTML page with an error message.
589 public function report() {
590 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
592 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode
);
593 header( 'Content-type: text/html; charset=utf-8' );
595 print $this->getHTML();
599 * Returns HTML for reporting the HTTP error.
600 * This will be a minimal but complete HTML document.
602 * @return string HTML
604 public function getHTML() {
605 if ( $this->header
=== null ) {
606 $header = HttpStatus
::getMessage( $this->httpCode
);
607 } elseif ( $this->header
instanceof Message
) {
608 $header = $this->header
->escaped();
610 $header = htmlspecialchars( $this->header
);
613 if ( $this->content
instanceof Message
) {
614 $content = $this->content
->escaped();
616 $content = htmlspecialchars( $this->content
);
619 return "<!DOCTYPE html>\n".
620 "<html><head><title>$header</title></head>\n" .
621 "<body><h1>$header</h1><p>$content</p></body></html>\n";
626 * Handler class for MWExceptions
629 class MWExceptionHandler
{
631 * Install an exception handler for MediaWiki exception types.
633 public static function installHandler() {
634 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
638 * Report an exception to the user
640 protected static function report( Exception
$e ) {
641 global $wgShowExceptionDetails;
643 $cmdLine = MWException
::isCommandLine();
645 if ( $e instanceof MWException
) {
647 // Try and show the exception prettily, with the normal skin infrastructure
649 } catch ( Exception
$e2 ) {
650 // Exception occurred from within exception handler
651 // Show a simpler error message for the original exception,
652 // don't try to invoke report()
653 $message = "MediaWiki internal error.\n\n";
655 if ( $wgShowExceptionDetails ) {
656 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
657 'Exception caught inside exception handler: ' . $e2->__toString();
659 $message .= "Exception caught inside exception handler.\n\n" .
660 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
661 "to show detailed debugging information.";
667 self
::printError( $message );
669 echo nl2br( htmlspecialchars( $message ) ) . "\n";
673 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
674 $e->__toString() . "\n";
676 if ( $wgShowExceptionDetails ) {
677 $message .= "\n" . $e->getTraceAsString() . "\n";
681 self
::printError( $message );
683 echo nl2br( htmlspecialchars( $message ) ) . "\n";
689 * Print a message, if possible to STDERR.
690 * Use this in command line mode only (see isCommandLine)
692 * @param string $message Failure text
694 public static function printError( $message ) {
695 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
696 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
697 if ( defined( 'STDERR' ) ) {
698 fwrite( STDERR
, $message );
705 * Exception handler which simulates the appropriate catch() handling:
709 * } catch ( MWException $e ) {
711 * } catch ( Exception $e ) {
712 * echo $e->__toString();
715 public static function handle( $e ) {
716 global $wgFullyInitialised;
721 if ( $wgFullyInitialised ) {
723 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
724 } catch ( Exception
$e ) {}
727 // Exit value should be nonzero for the benefit of shell jobs