Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / Exception.php
blob21952bbf5b8728fc5e76e8d596e4f85691245b08
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 the Message class/wfMessage to get i18n-ed 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 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] ) ) {
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 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();
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 "<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.
148 * @return string
150 function getText() {
151 global $wgShowExceptionDetails;
153 if ( $wgShowExceptionDetails ) {
154 return $this->getMessage() .
155 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
156 } else {
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.
165 * @return string
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.
176 * @return string
178 function getLogId() {
179 if ( $this->logId === null ) {
180 $this->logId = wfRandomString( 8 );
182 return $this->logId;
186 * Return the requested URL and point to file and line number from which the
187 * exception occurred
189 * @return string
191 function getLogMessage() {
192 global $wgRequest;
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();
201 if ( !$url ) {
202 $url = '[no URL]';
204 } else {
205 $url = '[no req]';
208 return "[$id] $url Exception from line $line of $file: $message";
212 * Output the exception report using HTML.
214 function reportHTML() {
215 global $wgOut;
216 if ( $this->useOutputPage() ) {
217 $wgOut->prepareErrorPage( $this->getPageTitle() );
219 $hookResult = $this->runHooks( get_class( $this ) );
220 if ( $hookResult ) {
221 $wgOut->addHTML( $hookResult );
222 } else {
223 $wgOut->addHTML( $this->getHTML() );
226 $wgOut->output();
227 } else {
228 header( "Content-Type: text/html; charset=utf-8" );
229 echo "<!doctype html>\n" .
230 '<html><head>' .
231 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
232 "</head><body>\n";
234 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
235 if ( $hookResult ) {
236 echo $hookResult;
237 } else {
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().
249 function report() {
250 global $wgLogExceptionBacktrace, $wgMimeType;
251 $log = $this->getLogMessage();
253 if ( $log ) {
254 if ( $wgLogExceptionBacktrace ) {
255 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
256 } else {
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() );
267 } else {
268 header( "HTTP/1.1 500 MediaWiki exception" );
269 header( "Status: 500 MediaWiki exception", true );
270 header( "Content-Type: $wgMimeType; charset=utf-8", true );
272 $this->reportHTML();
277 * Check whether we are in command line mode or not to report the exception
278 * in the correct format.
280 * @return bool
282 static function isCommandLine() {
283 return !empty( $GLOBALS['wgCommandLineMode'] );
288 * Exception class which takes an HTML error message, and does not
289 * produce a backtrace. Replacement for OutputPage::fatalError().
291 * @since 1.7
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 * @since 1.7
315 * @ingroup Exception
317 class ErrorPageError extends MWException {
318 public $title, $msg, $params;
321 * Note: these arguments are keys into wfMessage(), not text!
323 * @param string|Message $title Message key (string) for page title, or a Message object
324 * @param string|Message $msg Message key (string) for error text, or a Message object
325 * @param array $params with parameters to wfMessage()
327 function __construct( $title, $msg, $params = null ) {
328 $this->title = $title;
329 $this->msg = $msg;
330 $this->params = $params;
332 // Bug 44111: Messages in the log files should be in English and not
333 // customized by the local wiki. So get the default English version for
334 // passing to the parent constructor. Our overridden report() below
335 // makes sure that the page shown to the user is not forced to English.
336 if( $msg instanceof Message ) {
337 $enMsg = clone( $msg );
338 } else {
339 $enMsg = wfMessage( $msg, $params );
341 $enMsg->inLanguage( 'en' )->useDatabase( false );
342 parent::__construct( $enMsg->text() );
345 function report() {
346 global $wgOut;
348 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
349 $wgOut->output();
354 * Show an error page on a badtitle.
355 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
356 * browser it is not really a valid content.
358 * @since 1.19
359 * @ingroup Exception
361 class BadTitleError extends ErrorPageError {
363 * @param string|Message $msg A message key (default: 'badtitletext')
364 * @param array $params parameter to wfMessage()
366 function __construct( $msg = 'badtitletext', $params = null ) {
367 parent::__construct( 'badtitle', $msg, $params );
371 * Just like ErrorPageError::report() but additionally set
372 * a 400 HTTP status code (bug 33646).
374 function report() {
375 global $wgOut;
377 // bug 33646: a badtitle error page need to return an error code
378 // to let mobile browser now that it is not a normal page.
379 $wgOut->setStatusCode( 400 );
380 parent::report();
386 * Show an error when a user tries to do something they do not have the necessary
387 * permissions for.
389 * @since 1.18
390 * @ingroup Exception
392 class PermissionsError extends ErrorPageError {
393 public $permission, $errors;
395 function __construct( $permission, $errors = array() ) {
396 global $wgLang;
398 $this->permission = $permission;
400 if ( !count( $errors ) ) {
401 $groups = array_map(
402 array( 'User', 'makeGroupLinkWiki' ),
403 User::getGroupsWithPermission( $this->permission )
406 if ( $groups ) {
407 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
408 } else {
409 $errors[] = array( 'badaccess-group0' );
413 $this->errors = $errors;
416 function report() {
417 global $wgOut;
419 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
420 $wgOut->output();
425 * Show an error when the wiki is locked/read-only and the user tries to do
426 * something that requires write access.
428 * @since 1.18
429 * @ingroup Exception
431 class ReadOnlyError extends ErrorPageError {
432 public function __construct() {
433 parent::__construct(
434 'readonly',
435 'readonlytext',
436 wfReadOnlyReason()
442 * Show an error when the user hits a rate limit.
444 * @since 1.18
445 * @ingroup Exception
447 class ThrottledError extends ErrorPageError {
448 public function __construct() {
449 parent::__construct(
450 'actionthrottled',
451 'actionthrottledtext'
455 public function report() {
456 global $wgOut;
457 $wgOut->setStatusCode( 503 );
458 parent::report();
463 * Show an error when the user tries to do something whilst blocked.
465 * @since 1.18
466 * @ingroup Exception
468 class UserBlockedError extends ErrorPageError {
469 public function __construct( Block $block ) {
470 global $wgLang, $wgRequest;
472 $blocker = $block->getBlocker();
473 if ( $blocker instanceof User ) { // local user
474 $blockerUserpage = $block->getBlocker()->getUserPage();
475 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
476 } else { // foreign user
477 $link = $blocker;
480 $reason = $block->mReason;
481 if( $reason == '' ) {
482 $reason = wfMessage( 'blockednoreason' )->text();
485 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
486 * This could be a username, an IP range, or a single IP. */
487 $intended = $block->getTarget();
489 parent::__construct(
490 'blockedtitle',
491 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
492 array(
493 $link,
494 $reason,
495 $wgRequest->getIP(),
496 $block->getByName(),
497 $block->getId(),
498 $wgLang->formatExpiry( $block->mExpiry ),
499 $intended,
500 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
507 * Shows a generic "user is not logged in" error page.
509 * This is essentially an ErrorPageError exception which by default uses the
510 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
511 * @see bug 37627
512 * @since 1.20
514 * @par Example:
515 * @code
516 * if( $user->isAnon() ) {
517 * throw new UserNotLoggedIn();
519 * @endcode
521 * Note the parameter order differs from ErrorPageError, this allows you to
522 * simply specify a reason without overriding the default title.
524 * @par Example:
525 * @code
526 * if( $user->isAnon() ) {
527 * throw new UserNotLoggedIn( 'action-require-loggedin' );
529 * @endcode
531 * @ingroup Exception
533 class UserNotLoggedIn extends ErrorPageError {
536 * @param $reasonMsg A message key containing the reason for the error.
537 * Optional, default: 'exception-nologin-text'
538 * @param $titleMsg A message key to set the page title.
539 * Optional, default: 'exception-nologin'
540 * @param $params Parameters to wfMessage().
541 * Optional, default: null
543 public function __construct(
544 $reasonMsg = 'exception-nologin-text',
545 $titleMsg = 'exception-nologin',
546 $params = null
548 parent::__construct( $titleMsg, $reasonMsg, $params );
553 * Show an error that looks like an HTTP server error.
554 * Replacement for wfHttpError().
556 * @since 1.19
557 * @ingroup Exception
559 class HttpError extends MWException {
560 private $httpCode, $header, $content;
563 * Constructor
565 * @param $httpCode Integer: HTTP status code to send to the client
566 * @param string|Message $content content of the message
567 * @param string|Message $header content of the header (\<title\> and \<h1\>)
569 public function __construct( $httpCode, $content, $header = null ) {
570 parent::__construct( $content );
571 $this->httpCode = (int)$httpCode;
572 $this->header = $header;
573 $this->content = $content;
577 * Returns the HTTP status code supplied to the constructor.
579 * @return int
581 public function getStatusCode() {
582 return $this->httpCode;
586 * Report the HTTP error.
587 * Sends the appropriate HTTP status code and outputs an
588 * HTML page with an error message.
590 public function report() {
591 $httpMessage = HttpStatus::getMessage( $this->httpCode );
593 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode );
594 header( 'Content-type: text/html; charset=utf-8' );
596 print $this->getHTML();
600 * Returns HTML for reporting the HTTP error.
601 * This will be a minimal but complete HTML document.
603 * @return string HTML
605 public function getHTML() {
606 if ( $this->header === null ) {
607 $header = HttpStatus::getMessage( $this->httpCode );
608 } elseif ( $this->header instanceof Message ) {
609 $header = $this->header->escaped();
610 } else {
611 $header = htmlspecialchars( $this->header );
614 if ( $this->content instanceof Message ) {
615 $content = $this->content->escaped();
616 } else {
617 $content = htmlspecialchars( $this->content );
620 return "<!DOCTYPE html>\n".
621 "<html><head><title>$header</title></head>\n" .
622 "<body><h1>$header</h1><p>$content</p></body></html>\n";
627 * Handler class for MWExceptions
628 * @ingroup Exception
630 class MWExceptionHandler {
632 * Install an exception handler for MediaWiki exception types.
634 public static function installHandler() {
635 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
639 * Report an exception to the user
641 protected static function report( Exception $e ) {
642 global $wgShowExceptionDetails;
644 $cmdLine = MWException::isCommandLine();
646 if ( $e instanceof MWException ) {
647 try {
648 // Try and show the exception prettily, with the normal skin infrastructure
649 $e->report();
650 } catch ( Exception $e2 ) {
651 // Exception occurred from within exception handler
652 // Show a simpler error message for the original exception,
653 // don't try to invoke report()
654 $message = "MediaWiki internal error.\n\n";
656 if ( $wgShowExceptionDetails ) {
657 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
658 'Exception caught inside exception handler: ' . $e2->__toString();
659 } else {
660 $message .= "Exception caught inside exception handler.\n\n" .
661 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
662 "to show detailed debugging information.";
665 $message .= "\n";
667 if ( $cmdLine ) {
668 self::printError( $message );
669 } else {
670 echo nl2br( htmlspecialchars( $message ) ) . "\n";
673 } else {
674 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
675 $e->__toString() . "\n";
677 if ( $wgShowExceptionDetails ) {
678 $message .= "\n" . $e->getTraceAsString() . "\n";
681 if ( $cmdLine ) {
682 self::printError( $message );
683 } else {
684 echo nl2br( htmlspecialchars( $message ) ) . "\n";
690 * Print a message, if possible to STDERR.
691 * Use this in command line mode only (see isCommandLine)
693 * @param string $message Failure text
695 public static function printError( $message ) {
696 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
697 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
698 if ( defined( 'STDERR' ) ) {
699 fwrite( STDERR, $message );
700 } else {
701 echo( $message );
706 * Exception handler which simulates the appropriate catch() handling:
708 * try {
709 * ...
710 * } catch ( MWException $e ) {
711 * $e->report();
712 * } catch ( Exception $e ) {
713 * echo $e->__toString();
716 public static function handle( $e ) {
717 global $wgFullyInitialised;
719 self::report( $e );
721 // Final cleanup
722 if ( $wgFullyInitialised ) {
723 try {
724 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
725 } catch ( Exception $e ) {}
728 // Exit value should be nonzero for the benefit of shell jobs
729 exit( 1 );