Refactor diffs
[mediawiki.git] / includes / Exception.php
bloba91f8657a0127635e7e5a1992a368078a9ebbc26
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 {
34 /**
35 * Should the exception use $wgOut to output the error?
37 * @return bool
39 function useOutputPage() {
40 return $this->useMessageCache() &&
41 !empty( $GLOBALS['wgFullyInitialised'] ) &&
42 !empty( $GLOBALS['wgOut'] ) &&
43 !empty( $GLOBALS['wgTitle'] );
46 /**
47 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
49 * @return bool
51 function useMessageCache() {
52 global $wgLang;
54 foreach ( $this->getTrace() as $frame ) {
55 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
56 return false;
60 return $wgLang instanceof Language;
63 /**
64 * Run hook to allow extensions to modify the text of the exception
66 * @param string $name class name of the exception
67 * @param array $args arguments to pass to the callback functions
68 * @return string|null string to output or null if any hook has been called
70 function runHooks( $name, $args = array() ) {
71 global $wgExceptionHooks;
73 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
74 return null; // Just silently ignore
77 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[$name] ) ) {
78 return null;
81 $hooks = $wgExceptionHooks[$name];
82 $callargs = array_merge( array( $this ), $args );
84 foreach ( $hooks as $hook ) {
85 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
86 $result = call_user_func_array( $hook, $callargs );
87 } else {
88 $result = null;
91 if ( is_string( $result ) ) {
92 return $result;
95 return null;
98 /**
99 * Get a message from i18n
101 * @param string $key message name
102 * @param string $fallback default message if the message cache can't be
103 * called by the exception
104 * The function also has other parameters that are arguments for the message
105 * @return string message with arguments replaced
107 function msg( $key, $fallback /*[, params...] */ ) {
108 $args = array_slice( func_get_args(), 2 );
110 if ( $this->useMessageCache() ) {
111 return wfMessage( $key, $args )->plain();
112 } else {
113 return wfMsgReplaceArgs( $fallback, $args );
118 * If $wgShowExceptionDetails is true, return a HTML message with a
119 * backtrace to the error, otherwise show a message to ask to set it to true
120 * to show that information.
122 * @return string html to output
124 function getHTML() {
125 global $wgShowExceptionDetails;
127 if ( $wgShowExceptionDetails ) {
128 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
129 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( MWExceptionHandler::formatRedactedTrace( $this ) ) ) .
130 "</p>\n";
131 } else {
132 return "<div class=\"errorbox\">" .
133 '[' . MWExceptionHandler::getLogId( $this ) . '] ' .
134 gmdate( 'Y-m-d H:i:s' ) .
135 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
136 "<!-- Set \$wgShowExceptionDetails = true; " .
137 "at the bottom of LocalSettings.php to show detailed " .
138 "debugging information. -->";
143 * Get the text to display when reporting the error on the command line.
144 * If $wgShowExceptionDetails is true, return a text message with a
145 * backtrace to the error.
147 * @return string
149 function getText() {
150 global $wgShowExceptionDetails;
152 if ( $wgShowExceptionDetails ) {
153 return $this->getMessage() .
154 "\nBacktrace:\n" . MWExceptionHandler::formatRedactedTrace( $this ) . "\n";
155 } else {
156 return "Set \$wgShowExceptionDetails = true; " .
157 "in LocalSettings.php to show detailed debugging information.\n";
162 * Return the title of the page when reporting this error in a HTTP response.
164 * @return string
166 function getPageTitle() {
167 return $this->msg( 'internalerror', "Internal error" );
171 * Get a the ID for this error.
173 * @since 1.20
174 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
175 * @return string
177 function getLogId() {
178 wfDeprecated( __METHOD__, '1.22' );
179 return MWExceptionHandler::getLogId( $this );
183 * Return the requested URL and point to file and line number from which the
184 * exception occurred
186 * @since 1.8
187 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
188 * @return string
190 function getLogMessage() {
191 wfDeprecated( __METHOD__, '1.22' );
192 return MWExceptionHandler::getLogMessage( $this );
196 * Output the exception report using HTML.
198 function reportHTML() {
199 global $wgOut;
200 if ( $this->useOutputPage() ) {
201 $wgOut->prepareErrorPage( $this->getPageTitle() );
203 $hookResult = $this->runHooks( get_class( $this ) );
204 if ( $hookResult ) {
205 $wgOut->addHTML( $hookResult );
206 } else {
207 $wgOut->addHTML( $this->getHTML() );
210 $wgOut->output();
211 } else {
212 header( "Content-Type: text/html; charset=utf-8" );
213 echo "<!doctype html>\n" .
214 '<html><head>' .
215 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
216 "</head><body>\n";
218 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
219 if ( $hookResult ) {
220 echo $hookResult;
221 } else {
222 echo $this->getHTML();
225 echo "</body></html>\n";
230 * Output a report about the exception and takes care of formatting.
231 * It will be either HTML or plain text based on isCommandLine().
233 function report() {
234 global $wgMimeType;
236 MWExceptionHandler::logException( $this );
238 if ( defined( 'MW_API' ) ) {
239 // Unhandled API exception, we can't be sure that format printer is alive
240 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
241 wfHttpError( 500, 'Internal Server Error', $this->getText() );
242 } elseif ( self::isCommandLine() ) {
243 MWExceptionHandler::printError( $this->getText() );
244 } else {
245 header( "HTTP/1.1 500 MediaWiki exception" );
246 header( "Status: 500 MediaWiki exception", true );
247 header( "Content-Type: $wgMimeType; charset=utf-8", true );
249 $this->reportHTML();
254 * Check whether we are in command line mode or not to report the exception
255 * in the correct format.
257 * @return bool
259 static function isCommandLine() {
260 return !empty( $GLOBALS['wgCommandLineMode'] );
265 * Exception class which takes an HTML error message, and does not
266 * produce a backtrace. Replacement for OutputPage::fatalError().
268 * @since 1.7
269 * @ingroup Exception
271 class FatalError extends MWException {
274 * @return string
276 function getHTML() {
277 return $this->getMessage();
281 * @return string
283 function getText() {
284 return $this->getMessage();
289 * An error page which can definitely be safely rendered using the OutputPage.
291 * @since 1.7
292 * @ingroup Exception
294 class ErrorPageError extends MWException {
295 public $title, $msg, $params;
298 * Note: these arguments are keys into wfMessage(), not text!
300 * @param string|Message $title Message key (string) for page title, or a Message object
301 * @param string|Message $msg Message key (string) for error text, or a Message object
302 * @param array $params with parameters to wfMessage()
304 function __construct( $title, $msg, $params = null ) {
305 $this->title = $title;
306 $this->msg = $msg;
307 $this->params = $params;
309 // Bug 44111: Messages in the log files should be in English and not
310 // customized by the local wiki. So get the default English version for
311 // passing to the parent constructor. Our overridden report() below
312 // makes sure that the page shown to the user is not forced to English.
313 if ( $msg instanceof Message ) {
314 $enMsg = clone( $msg );
315 } else {
316 $enMsg = wfMessage( $msg, $params );
318 $enMsg->inLanguage( 'en' )->useDatabase( false );
319 parent::__construct( $enMsg->text() );
322 function report() {
323 global $wgOut;
325 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
326 $wgOut->output();
331 * Show an error page on a badtitle.
332 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
333 * browser it is not really a valid content.
335 * @since 1.19
336 * @ingroup Exception
338 class BadTitleError extends ErrorPageError {
340 * @param string|Message $msg A message key (default: 'badtitletext')
341 * @param array $params parameter to wfMessage()
343 function __construct( $msg = 'badtitletext', $params = null ) {
344 parent::__construct( 'badtitle', $msg, $params );
348 * Just like ErrorPageError::report() but additionally set
349 * a 400 HTTP status code (bug 33646).
351 function report() {
352 global $wgOut;
354 // bug 33646: a badtitle error page need to return an error code
355 // to let mobile browser now that it is not a normal page.
356 $wgOut->setStatusCode( 400 );
357 parent::report();
363 * Show an error when a user tries to do something they do not have the necessary
364 * permissions for.
366 * @since 1.18
367 * @ingroup Exception
369 class PermissionsError extends ErrorPageError {
370 public $permission, $errors;
372 function __construct( $permission, $errors = array() ) {
373 global $wgLang;
375 $this->permission = $permission;
377 if ( !count( $errors ) ) {
378 $groups = array_map(
379 array( 'User', 'makeGroupLinkWiki' ),
380 User::getGroupsWithPermission( $this->permission )
383 if ( $groups ) {
384 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
385 } else {
386 $errors[] = array( 'badaccess-group0' );
390 $this->errors = $errors;
393 function report() {
394 global $wgOut;
396 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
397 $wgOut->output();
402 * Show an error when the wiki is locked/read-only and the user tries to do
403 * something that requires write access.
405 * @since 1.18
406 * @ingroup Exception
408 class ReadOnlyError extends ErrorPageError {
409 public function __construct() {
410 parent::__construct(
411 'readonly',
412 'readonlytext',
413 wfReadOnlyReason()
419 * Show an error when the user hits a rate limit.
421 * @since 1.18
422 * @ingroup Exception
424 class ThrottledError extends ErrorPageError {
425 public function __construct() {
426 parent::__construct(
427 'actionthrottled',
428 'actionthrottledtext'
432 public function report() {
433 global $wgOut;
434 $wgOut->setStatusCode( 503 );
435 parent::report();
440 * Show an error when the user tries to do something whilst blocked.
442 * @since 1.18
443 * @ingroup Exception
445 class UserBlockedError extends ErrorPageError {
446 public function __construct( Block $block ) {
447 // @todo FIXME: Implement a more proper way to get context here.
448 $params = $block->getPermissionsError( RequestContext::getMain() );
449 parent::__construct( 'blockedtitle', array_shift( $params ), $params );
454 * Shows a generic "user is not logged in" error page.
456 * This is essentially an ErrorPageError exception which by default uses the
457 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
458 * @see bug 37627
459 * @since 1.20
461 * @par Example:
462 * @code
463 * if( $user->isAnon() ) {
464 * throw new UserNotLoggedIn();
466 * @endcode
468 * Note the parameter order differs from ErrorPageError, this allows you to
469 * simply specify a reason without overriding the default title.
471 * @par Example:
472 * @code
473 * if( $user->isAnon() ) {
474 * throw new UserNotLoggedIn( 'action-require-loggedin' );
476 * @endcode
478 * @ingroup Exception
480 class UserNotLoggedIn extends ErrorPageError {
483 * @param $reasonMsg A message key containing the reason for the error.
484 * Optional, default: 'exception-nologin-text'
485 * @param $titleMsg A message key to set the page title.
486 * Optional, default: 'exception-nologin'
487 * @param $params Parameters to wfMessage().
488 * Optional, default: null
490 public function __construct(
491 $reasonMsg = 'exception-nologin-text',
492 $titleMsg = 'exception-nologin',
493 $params = null
495 parent::__construct( $titleMsg, $reasonMsg, $params );
500 * Show an error that looks like an HTTP server error.
501 * Replacement for wfHttpError().
503 * @since 1.19
504 * @ingroup Exception
506 class HttpError extends MWException {
507 private $httpCode, $header, $content;
510 * Constructor
512 * @param $httpCode Integer: HTTP status code to send to the client
513 * @param string|Message $content content of the message
514 * @param string|Message $header content of the header (\<title\> and \<h1\>)
516 public function __construct( $httpCode, $content, $header = null ) {
517 parent::__construct( $content );
518 $this->httpCode = (int)$httpCode;
519 $this->header = $header;
520 $this->content = $content;
524 * Returns the HTTP status code supplied to the constructor.
526 * @return int
528 public function getStatusCode() {
529 return $this->httpCode;
533 * Report the HTTP error.
534 * Sends the appropriate HTTP status code and outputs an
535 * HTML page with an error message.
537 public function report() {
538 $httpMessage = HttpStatus::getMessage( $this->httpCode );
540 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode );
541 header( 'Content-type: text/html; charset=utf-8' );
543 print $this->getHTML();
547 * Returns HTML for reporting the HTTP error.
548 * This will be a minimal but complete HTML document.
550 * @return string HTML
552 public function getHTML() {
553 if ( $this->header === null ) {
554 $header = HttpStatus::getMessage( $this->httpCode );
555 } elseif ( $this->header instanceof Message ) {
556 $header = $this->header->escaped();
557 } else {
558 $header = htmlspecialchars( $this->header );
561 if ( $this->content instanceof Message ) {
562 $content = $this->content->escaped();
563 } else {
564 $content = htmlspecialchars( $this->content );
567 return "<!DOCTYPE html>\n" .
568 "<html><head><title>$header</title></head>\n" .
569 "<body><h1>$header</h1><p>$content</p></body></html>\n";
574 * Handler class for MWExceptions
575 * @ingroup Exception
577 class MWExceptionHandler {
579 * Install an exception handler for MediaWiki exception types.
581 public static function installHandler() {
582 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
586 * Report an exception to the user
588 protected static function report( Exception $e ) {
589 global $wgShowExceptionDetails;
591 $cmdLine = MWException::isCommandLine();
593 if ( $e instanceof MWException ) {
594 try {
595 // Try and show the exception prettily, with the normal skin infrastructure
596 $e->report();
597 } catch ( Exception $e2 ) {
598 // Exception occurred from within exception handler
599 // Show a simpler error message for the original exception,
600 // don't try to invoke report()
601 $message = "MediaWiki internal error.\n\n";
603 if ( $wgShowExceptionDetails ) {
604 $message .= 'Original exception: ' . self::formatRedactedTrace( $e ) . "\n\n" .
605 'Exception caught inside exception handler: ' . $e2->__toString();
606 } else {
607 $message .= "Exception caught inside exception handler.\n\n" .
608 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
609 "to show detailed debugging information.";
612 $message .= "\n";
614 if ( $cmdLine ) {
615 self::printError( $message );
616 } else {
617 echo nl2br( htmlspecialchars( $message ) ) . "\n";
620 } else {
621 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"";
623 if ( $wgShowExceptionDetails ) {
624 $message .= "\nexception '" . get_class( $e ) . "' in " . $e->getFile() . ":" . $e->getLine() . "\nStack trace:\n" . self::formatRedactedTrace( $e ) . "\n";
627 if ( $cmdLine ) {
628 self::printError( $message );
629 } else {
630 echo nl2br( htmlspecialchars( $message ) ) . "\n";
636 * Print a message, if possible to STDERR.
637 * Use this in command line mode only (see isCommandLine)
639 * @param string $message Failure text
641 public static function printError( $message ) {
642 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
643 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
644 if ( defined( 'STDERR' ) ) {
645 fwrite( STDERR, $message );
646 } else {
647 echo $message;
652 * Exception handler which simulates the appropriate catch() handling:
654 * try {
655 * ...
656 * } catch ( MWException $e ) {
657 * $e->report();
658 * } catch ( Exception $e ) {
659 * echo $e->__toString();
662 public static function handle( $e ) {
663 global $wgFullyInitialised;
665 self::report( $e );
667 // Final cleanup
668 if ( $wgFullyInitialised ) {
669 try {
670 // uses $wgRequest, hence the $wgFullyInitialised condition
671 wfLogProfilingData();
672 } catch ( Exception $e ) {
676 // Exit value should be nonzero for the benefit of shell jobs
677 exit( 1 );
681 * Get the stack trace from the exception as a string, redacting certain function arguments in the process
682 * @param Exception $e The exception
683 * @return string The stack trace as a string
685 public static function formatRedactedTrace( Exception $e ) {
686 global $wgRedactedFunctionArguments;
687 $finalExceptionText = '';
689 // Unique value to indicate redacted parameters
690 $redacted = new stdClass();
692 foreach ( $e->getTrace() as $i => $call ) {
693 $checkFor = array();
694 if ( isset( $call['class'] ) ) {
695 $checkFor[] = $call['class'] . '::' . $call['function'];
696 foreach ( class_parents( $call['class'] ) as $parent ) {
697 $checkFor[] = $parent . '::' . $call['function'];
699 } else {
700 $checkFor[] = $call['function'];
703 foreach ( $checkFor as $check ) {
704 if ( isset( $wgRedactedFunctionArguments[$check] ) ) {
705 foreach ( (array)$wgRedactedFunctionArguments[$check] as $argNo ) {
706 $call['args'][$argNo] = $redacted;
711 if ( isset( $call['file'] ) && isset( $call['line'] ) ) {
712 $finalExceptionText .= "#{$i} {$call['file']}({$call['line']}): ";
713 } else {
714 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
715 // This matches behaviour of Exception::getTraceAsString to instead
716 // display "[internal function]".
717 $finalExceptionText .= "#{$i} [internal function]: ";
720 if ( isset( $call['class'] ) ) {
721 $finalExceptionText .= $call['class'] . $call['type'] . $call['function'];
722 } else {
723 $finalExceptionText .= $call['function'];
725 $args = array();
726 if ( isset( $call['args'] ) ) {
727 foreach ( $call['args'] as $arg ) {
728 if ( $arg === $redacted ) {
729 $args[] = 'REDACTED';
730 } elseif ( is_object( $arg ) ) {
731 $args[] = 'Object(' . get_class( $arg ) . ')';
732 } elseif( is_array( $arg ) ) {
733 $args[] = 'Array';
734 } else {
735 $args[] = var_export( $arg, true );
739 $finalExceptionText .= '(' . implode( ', ', $args ) . ")\n";
741 return $finalExceptionText . '#' . ( $i + 1 ) . ' {main}';
746 * Get the ID for this error.
748 * The ID is saved so that one can match the one output to the user (when
749 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
751 * @since 1.22
752 * @param Exception $e
753 * @return string
755 public static function getLogId( Exception $e ) {
756 if ( !isset( $e->_mwLogId ) ) {
757 $e->_mwLogId = wfRandomString( 8 );
759 return $e->_mwLogId;
763 * Return the requested URL and point to file and line number from which the
764 * exception occurred.
766 * @since 1.22
767 * @param Exception $e
768 * @return string
770 public static function getLogMessage( Exception $e ) {
771 global $wgRequest;
773 $id = self::getLogId( $e );
774 $file = $e->getFile();
775 $line = $e->getLine();
776 $message = $e->getMessage();
778 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
779 $url = $wgRequest->getRequestURL();
780 if ( !$url ) {
781 $url = '[no URL]';
783 } else {
784 $url = '[no req]';
787 return "[$id] $url Exception from line $line of $file: $message";
791 * Log an exception to the exception log (if enabled).
793 * This method must not assume the exception is an MWException,
794 * it is also used to handle PHP errors or errors from other libraries.
796 * @since 1.22
797 * @param Exception $e
799 public static function logException( Exception $e ) {
800 global $wgLogExceptionBacktrace;
802 $log = self::getLogMessage( $e );
803 if ( $log ) {
804 if ( $wgLogExceptionBacktrace ) {
805 wfDebugLog( 'exception', $log . "\n" . self::formatRedactedTrace( $e ) . "\n" );
806 } else {
807 wfDebugLog( 'exception', $log );