aeafda8805d89fa1b82d0ff29f9be052e4c7f096
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
{
34 * Should the exception use $wgOut to output the error?
38 function useOutputPage() {
39 return $this->useMessageCache() &&
40 !empty( $GLOBALS['wgFullyInitialised'] ) &&
41 !empty( $GLOBALS['wgOut'] ) &&
42 !empty( $GLOBALS['wgTitle'] );
46 * Whether to log this exception in the exception debug log.
51 function isLoggable() {
56 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
60 function useMessageCache() {
63 foreach ( $this->getTrace() as $frame ) {
64 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
69 return $wgLang instanceof Language
;
73 * Run hook to allow extensions to modify the text of the exception
75 * @param string $name class name of the exception
76 * @param array $args arguments to pass to the callback functions
77 * @return string|null string to output or null if any hook has been called
79 function runHooks( $name, $args = array() ) {
80 global $wgExceptionHooks;
82 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
83 return null; // Just silently ignore
86 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
87 !is_array( $wgExceptionHooks[$name] )
92 $hooks = $wgExceptionHooks[$name];
93 $callargs = array_merge( array( $this ), $args );
95 foreach ( $hooks as $hook ) {
98 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
100 // 'function' or array( 'class', hook' )
101 $result = call_user_func_array( $hook, $callargs );
106 if ( is_string( $result ) ) {
114 * Get a message from i18n
116 * @param string $key message name
117 * @param string $fallback default message if the message cache can't be
118 * called by the exception
119 * The function also has other parameters that are arguments for the message
120 * @return string message with arguments replaced
122 function msg( $key, $fallback /*[, params...] */ ) {
123 $args = array_slice( func_get_args(), 2 );
125 if ( $this->useMessageCache() ) {
126 return wfMessage( $key, $args )->plain();
128 return wfMsgReplaceArgs( $fallback, $args );
133 * If $wgShowExceptionDetails is true, return a HTML message with a
134 * backtrace to the error, otherwise show a message to ask to set it to true
135 * to show that information.
137 * @return string html to output
140 global $wgShowExceptionDetails;
142 if ( $wgShowExceptionDetails ) {
143 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
144 '</p><p>Backtrace:</p><p>' .
145 nl2br( htmlspecialchars( MWExceptionHandler
::formatRedactedTrace( $this ) ) ) .
148 return "<div class=\"errorbox\">" .
149 '[' . MWExceptionHandler
::getLogId( $this ) . '] ' .
150 gmdate( 'Y-m-d H:i:s' ) .
151 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
152 "<!-- Set \$wgShowExceptionDetails = true; " .
153 "at the bottom of LocalSettings.php to show detailed " .
154 "debugging information. -->";
159 * Get the text to display when reporting the error on the command line.
160 * If $wgShowExceptionDetails is true, return a text message with a
161 * backtrace to the error.
166 global $wgShowExceptionDetails;
168 if ( $wgShowExceptionDetails ) {
169 return $this->getMessage() .
170 "\nBacktrace:\n" . MWExceptionHandler
::formatRedactedTrace( $this ) . "\n";
172 return "Set \$wgShowExceptionDetails = true; " .
173 "in LocalSettings.php to show detailed debugging information.\n";
178 * Return the title of the page when reporting this error in a HTTP response.
182 function getPageTitle() {
184 return $this->msg( 'pagetitle', "$1 - $wgSitename", $this->msg( 'internalerror', 'Internal error' ) );
188 * Get a the ID for this error.
191 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
194 function getLogId() {
195 wfDeprecated( __METHOD__
, '1.22' );
196 return MWExceptionHandler
::getLogId( $this );
200 * Return the requested URL and point to file and line number from which the
204 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
207 function getLogMessage() {
208 wfDeprecated( __METHOD__
, '1.22' );
209 return MWExceptionHandler
::getLogMessage( $this );
213 * Output the exception report using HTML.
215 function reportHTML() {
217 if ( $this->useOutputPage() ) {
218 $wgOut->prepareErrorPage( $this->getPageTitle() );
220 $hookResult = $this->runHooks( get_class( $this ) );
222 $wgOut->addHTML( $hookResult );
224 $wgOut->addHTML( $this->getHTML() );
229 header( 'Content-Type: text/html; charset=utf-8' );
230 echo "<!DOCTYPE html>\n" .
232 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
233 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
236 $hookResult = $this->runHooks( get_class( $this ) . 'Raw' );
240 echo $this->getHTML();
243 echo "</body></html>\n";
248 * Output a report about the exception and takes care of formatting.
249 * It will be either HTML or plain text based on isCommandLine().
254 MWExceptionHandler
::logException( $this );
256 if ( defined( 'MW_API' ) ) {
257 // Unhandled API exception, we can't be sure that format printer is alive
258 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
259 wfHttpError( 500, 'Internal Server Error', $this->getText() );
260 } elseif ( self
::isCommandLine() ) {
261 MWExceptionHandler
::printError( $this->getText() );
263 header( 'HTTP/1.1 500 MediaWiki exception' );
264 header( 'Status: 500 MediaWiki exception', true );
265 header( "Content-Type: $wgMimeType; charset=utf-8", true );
272 * Check whether we are in command line mode or not to report the exception
273 * in the correct format.
277 static function isCommandLine() {
278 return !empty( $GLOBALS['wgCommandLineMode'] );
283 * Exception class which takes an HTML error message, and does not
284 * produce a backtrace. Replacement for OutputPage::fatalError().
289 class FatalError
extends MWException
{
295 return $this->getMessage();
302 return $this->getMessage();
307 * An error page which can definitely be safely rendered using the OutputPage.
312 class ErrorPageError
extends MWException
{
313 public $title, $msg, $params;
316 * Note: these arguments are keys into wfMessage(), not text!
318 * @param string|Message $title Message key (string) for page title, or a Message object
319 * @param string|Message $msg Message key (string) for error text, or a Message object
320 * @param array $params with parameters to wfMessage()
322 function __construct( $title, $msg, $params = null ) {
323 $this->title
= $title;
325 $this->params
= $params;
327 // Bug 44111: Messages in the log files should be in English and not
328 // customized by the local wiki. So get the default English version for
329 // passing to the parent constructor. Our overridden report() below
330 // makes sure that the page shown to the user is not forced to English.
331 if ( $msg instanceof Message
) {
332 $enMsg = clone( $msg );
334 $enMsg = wfMessage( $msg, $params );
336 $enMsg->inLanguage( 'en' )->useDatabase( false );
337 parent
::__construct( $enMsg->text() );
343 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
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.
356 class BadTitleError
extends ErrorPageError
{
358 * @param string|Message $msg A message key (default: 'badtitletext')
359 * @param array $params parameter to wfMessage()
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).
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 );
381 * Show an error when a user tries to do something they do not have the necessary
387 class PermissionsError
extends ErrorPageError
{
388 public $permission, $errors;
390 function __construct( $permission, $errors = array() ) {
393 $this->permission
= $permission;
395 if ( !count( $errors ) ) {
397 array( 'User', 'makeGroupLinkWiki' ),
398 User
::getGroupsWithPermission( $this->permission
)
402 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
404 $errors[] = array( 'badaccess-group0' );
408 $this->errors
= $errors;
414 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
420 * Show an error when the wiki is locked/read-only and the user tries to do
421 * something that requires write access.
426 class ReadOnlyError
extends ErrorPageError
{
427 public function __construct() {
437 * Show an error when the user hits a rate limit.
442 class ThrottledError
extends ErrorPageError
{
443 public function __construct() {
446 'actionthrottledtext'
450 public function report() {
452 $wgOut->setStatusCode( 503 );
458 * Show an error when the user tries to do something whilst blocked.
463 class UserBlockedError
extends ErrorPageError
{
464 public function __construct( Block
$block ) {
465 // @todo FIXME: Implement a more proper way to get context here.
466 $params = $block->getPermissionsError( RequestContext
::getMain() );
467 parent
::__construct( 'blockedtitle', array_shift( $params ), $params );
472 * Shows a generic "user is not logged in" error page.
474 * This is essentially an ErrorPageError exception which by default uses the
475 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
481 * if( $user->isAnon() ) {
482 * throw new UserNotLoggedIn();
486 * Note the parameter order differs from ErrorPageError, this allows you to
487 * simply specify a reason without overriding the default title.
491 * if( $user->isAnon() ) {
492 * throw new UserNotLoggedIn( 'action-require-loggedin' );
498 class UserNotLoggedIn
extends ErrorPageError
{
501 * @param string $reasonMsg A message key containing the reason for the error.
502 * Optional, default: 'exception-nologin-text'
503 * @param string $titleMsg A message key to set the page title.
504 * Optional, default: 'exception-nologin'
505 * @param array $params Parameters to wfMessage().
506 * Optional, default: null
508 public function __construct(
509 $reasonMsg = 'exception-nologin-text',
510 $titleMsg = 'exception-nologin',
513 parent
::__construct( $titleMsg, $reasonMsg, $params );
518 * Show an error that looks like an HTTP server error.
519 * Replacement for wfHttpError().
524 class HttpError
extends MWException
{
525 private $httpCode, $header, $content;
530 * @param $httpCode Integer: HTTP status code to send to the client
531 * @param string|Message $content content of the message
532 * @param string|Message $header content of the header (\<title\> and \<h1\>)
534 public function __construct( $httpCode, $content, $header = null ) {
535 parent
::__construct( $content );
536 $this->httpCode
= (int)$httpCode;
537 $this->header
= $header;
538 $this->content
= $content;
542 * Returns the HTTP status code supplied to the constructor.
546 public function getStatusCode() {
547 return $this->httpCode
;
551 * Report the HTTP error.
552 * Sends the appropriate HTTP status code and outputs an
553 * HTML page with an error message.
555 public function report() {
556 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
558 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode
);
559 header( 'Content-type: text/html; charset=utf-8' );
561 print $this->getHTML();
565 * Returns HTML for reporting the HTTP error.
566 * This will be a minimal but complete HTML document.
568 * @return string HTML
570 public function getHTML() {
571 if ( $this->header
=== null ) {
572 $header = HttpStatus
::getMessage( $this->httpCode
);
573 } elseif ( $this->header
instanceof Message
) {
574 $header = $this->header
->escaped();
576 $header = htmlspecialchars( $this->header
);
579 if ( $this->content
instanceof Message
) {
580 $content = $this->content
->escaped();
582 $content = htmlspecialchars( $this->content
);
585 return "<!DOCTYPE html>\n" .
586 "<html><head><title>$header</title></head>\n" .
587 "<body><h1>$header</h1><p>$content</p></body></html>\n";
592 * Handler class for MWExceptions
595 class MWExceptionHandler
{
597 * Install an exception handler for MediaWiki exception types.
599 public static function installHandler() {
600 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
604 * Report an exception to the user
606 protected static function report( Exception
$e ) {
607 global $wgShowExceptionDetails;
609 $cmdLine = MWException
::isCommandLine();
611 if ( $e instanceof MWException
) {
613 // Try and show the exception prettily, with the normal skin infrastructure
615 } catch ( Exception
$e2 ) {
616 // Exception occurred from within exception handler
617 // Show a simpler error message for the original exception,
618 // don't try to invoke report()
619 $message = "MediaWiki internal error.\n\n";
621 if ( $wgShowExceptionDetails ) {
622 $message .= 'Original exception: ' . self
::formatRedactedTrace( $e ) . "\n\n" .
623 'Exception caught inside exception handler: ' . $e2->__toString();
625 $message .= "Exception caught inside exception handler.\n\n" .
626 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
627 "to show detailed debugging information.";
633 self
::printError( $message );
635 echo nl2br( htmlspecialchars( $message ) ) . "\n";
639 $message = "Unexpected non-MediaWiki exception encountered, of type \"" .
640 get_class( $e ) . "\"";
642 if ( $wgShowExceptionDetails ) {
643 $message .= "\nexception '" . get_class( $e ) . "' in " .
644 $e->getFile() . ":" . $e->getLine() . "\nStack trace:\n" .
645 self
::formatRedactedTrace( $e ) . "\n";
649 self
::printError( $message );
651 echo nl2br( htmlspecialchars( $message ) ) . "\n";
657 * Print a message, if possible to STDERR.
658 * Use this in command line mode only (see isCommandLine)
660 * @param string $message Failure text
662 public static function printError( $message ) {
663 # NOTE: STDERR may not be available, especially if php-cgi is used from the
664 # command line (bug #15602). Try to produce meaningful output anyway. Using
665 # echo may corrupt output to STDOUT though.
666 if ( defined( 'STDERR' ) ) {
667 fwrite( STDERR
, $message );
674 * Exception handler which simulates the appropriate catch() handling:
678 * } catch ( MWException $e ) {
680 * } catch ( Exception $e ) {
681 * echo $e->__toString();
684 public static function handle( $e ) {
685 global $wgFullyInitialised;
690 if ( $wgFullyInitialised ) {
692 // uses $wgRequest, hence the $wgFullyInitialised condition
693 wfLogProfilingData();
694 } catch ( Exception
$e ) {
698 // Exit value should be nonzero for the benefit of shell jobs
703 * Get the stack trace from the exception as a string, redacting certain
704 * function arguments in the process.
705 * @param Exception $e The exception
706 * @return string The stack trace as a string
708 public static function formatRedactedTrace( Exception
$e ) {
709 global $wgRedactedFunctionArguments;
710 $finalExceptionText = '';
712 // Unique value to indicate redacted parameters
713 $redacted = new stdClass();
715 foreach ( $e->getTrace() as $i => $call ) {
717 if ( isset( $call['class'] ) ) {
718 $checkFor[] = $call['class'] . '::' . $call['function'];
719 foreach ( class_parents( $call['class'] ) as $parent ) {
720 $checkFor[] = $parent . '::' . $call['function'];
723 $checkFor[] = $call['function'];
726 foreach ( $checkFor as $check ) {
727 if ( isset( $wgRedactedFunctionArguments[$check] ) ) {
728 foreach ( (array)$wgRedactedFunctionArguments[$check] as $argNo ) {
729 $call['args'][$argNo] = $redacted;
734 if ( isset( $call['file'] ) && isset( $call['line'] ) ) {
735 $finalExceptionText .= "#{$i} {$call['file']}({$call['line']}): ";
737 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
738 // This matches behaviour of Exception::getTraceAsString to instead
739 // display "[internal function]".
740 $finalExceptionText .= "#{$i} [internal function]: ";
743 if ( isset( $call['class'] ) ) {
744 $finalExceptionText .= $call['class'] . $call['type'] . $call['function'];
746 $finalExceptionText .= $call['function'];
749 if ( isset( $call['args'] ) ) {
750 foreach ( $call['args'] as $arg ) {
751 if ( $arg === $redacted ) {
752 $args[] = 'REDACTED';
753 } elseif ( is_object( $arg ) ) {
754 $args[] = 'Object(' . get_class( $arg ) . ')';
755 } elseif( is_array( $arg ) ) {
758 $args[] = var_export( $arg, true );
762 $finalExceptionText .= '(' . implode( ', ', $args ) . ")\n";
764 return $finalExceptionText . '#' . ( $i +
1 ) . ' {main}';
768 * Get the ID for this error.
770 * The ID is saved so that one can match the one output to the user (when
771 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
774 * @param Exception $e
777 public static function getLogId( Exception
$e ) {
778 if ( !isset( $e->_mwLogId
) ) {
779 $e->_mwLogId
= wfRandomString( 8 );
785 * Return the requested URL and point to file and line number from which the
786 * exception occurred.
789 * @param Exception $e
792 public static function getLogMessage( Exception
$e ) {
795 $id = self
::getLogId( $e );
796 $file = $e->getFile();
797 $line = $e->getLine();
798 $message = $e->getMessage();
800 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
801 $url = $wgRequest->getRequestURL();
809 return "[$id] $url Exception from line $line of $file: $message";
813 * Log an exception to the exception log (if enabled).
815 * This method must not assume the exception is an MWException,
816 * it is also used to handle PHP errors or errors from other libraries.
819 * @param Exception $e
821 public static function logException( Exception
$e ) {
822 global $wgLogExceptionBacktrace;
824 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
825 $log = self
::getLogMessage( $e );
826 if ( $wgLogExceptionBacktrace ) {
827 wfDebugLog( 'exception', $log . "\n" . self
::formatRedactedTrace( $e ) . "\n" );
829 wfDebugLog( 'exception', $log );