Merge "Use new xsd schema 0.7 in Export.php"
[mediawiki.git] / includes / Exception.php
blob9f6d5bdc6b7e0c309bd5b25f21404e8c96c9169d
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 ?
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 wfMsg() to get i18n messages ?
48 * @return bool
50 function useMessageCache() {
51 global $wgLang;
53 foreach ( $this->getTrace() as $frame ) {
54 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
55 return false;
59 return $wgLang instanceof Language;
62 /**
63 * Run hook to allow extensions to modify the text of the exception
65 * @param $name String: class name of the exception
66 * @param $args Array: arguments to pass to the callback functions
67 * @return Mixed: string to output or null if any hook has been called
69 function runHooks( $name, $args = array() ) {
70 global $wgExceptionHooks;
72 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
73 return null; // Just silently ignore
76 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
77 return null;
80 $hooks = $wgExceptionHooks[ $name ];
81 $callargs = array_merge( array( $this ), $args );
83 foreach ( $hooks as $hook ) {
84 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
85 $result = call_user_func_array( $hook, $callargs );
86 } else {
87 $result = null;
90 if ( is_string( $result ) ) {
91 return $result;
94 return null;
97 /**
98 * Get a message from i18n
100 * @param $key String: message name
101 * @param $fallback String: default message if the message cache can't be
102 * called by the exception
103 * The function also has other parameters that are arguments for the message
104 * @return String message with arguments replaced
106 function msg( $key, $fallback /*[, params...] */ ) {
107 $args = array_slice( func_get_args(), 2 );
109 if ( $this->useMessageCache() ) {
110 return wfMsgNoTrans( $key, $args );
111 } else {
112 return wfMsgReplaceArgs( $fallback, $args );
117 * If $wgShowExceptionDetails is true, return a HTML message with a
118 * backtrace to the error, otherwise show a message to ask to set it to true
119 * to show that information.
121 * @return String html to output
123 function getHTML() {
124 global $wgShowExceptionDetails;
126 if ( $wgShowExceptionDetails ) {
127 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
128 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
129 "</p>\n";
130 } else {
131 return
132 "<div class=\"errorbox\">" .
133 '[' . $this->getLogId() . '] ' .
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 * If $wgShowExceptionDetails is true, return a text message with a
144 * backtrace to the error.
145 * @return string
147 function getText() {
148 global $wgShowExceptionDetails;
150 if ( $wgShowExceptionDetails ) {
151 return $this->getMessage() .
152 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
153 } else {
154 return "Set \$wgShowExceptionDetails = true; " .
155 "in LocalSettings.php to show detailed debugging information.\n";
160 * Return titles of this error page
161 * @return String
163 function getPageTitle() {
164 return $this->msg( 'internalerror', "Internal error" );
167 function getLogId() {
168 if ( $this->logId === null ) {
169 $this->logId = wfRandomString( 8 );
171 return $this->logId;
175 * Return the requested URL and point to file and line number from which the
176 * exception occured
178 * @return String
180 function getLogMessage() {
181 global $wgRequest;
183 $id = $this->getLogId();
184 $file = $this->getFile();
185 $line = $this->getLine();
186 $message = $this->getMessage();
188 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
189 $url = $wgRequest->getRequestURL();
190 if ( !$url ) {
191 $url = '[no URL]';
193 } else {
194 $url = '[no req]';
197 return "[$id] $url Exception from line $line of $file: $message";
200 /** Output the exception report using HTML */
201 function reportHTML() {
202 global $wgOut;
203 if ( $this->useOutputPage() ) {
204 $wgOut->prepareErrorPage( $this->getPageTitle() );
206 $hookResult = $this->runHooks( get_class( $this ) );
207 if ( $hookResult ) {
208 $wgOut->addHTML( $hookResult );
209 } else {
210 $wgOut->addHTML( $this->getHTML() );
213 $wgOut->output();
214 } else {
215 header( "Content-Type: text/html; charset=utf-8" );
216 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
217 if ( $hookResult ) {
218 die( $hookResult );
221 echo $this->getHTML();
222 die(1);
227 * Output a report about the exception and takes care of formatting.
228 * It will be either HTML or plain text based on isCommandLine().
230 function report() {
231 global $wgLogExceptionBacktrace;
232 $log = $this->getLogMessage();
234 if ( $log ) {
235 if ( $wgLogExceptionBacktrace ) {
236 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
237 } else {
238 wfDebugLog( 'exception', $log );
242 if ( defined( 'MW_API' ) ) {
243 // Unhandled API exception, we can't be sure that format printer is alive
244 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
245 wfHttpError(500, 'Internal Server Error', $this->getText() );
246 } elseif ( self::isCommandLine() ) {
247 MWExceptionHandler::printError( $this->getText() );
248 } else {
249 header( "HTTP/1.1 500 MediaWiki exception" );
250 header( "Status: 500 MediaWiki exception", true );
252 $this->reportHTML();
257 * @static
258 * @return bool
260 static function isCommandLine() {
261 return !empty( $GLOBALS['wgCommandLineMode'] );
266 * Exception class which takes an HTML error message, and does not
267 * produce a backtrace. Replacement for OutputPage::fatalError().
268 * @ingroup Exception
270 class FatalError extends MWException {
273 * @return string
275 function getHTML() {
276 return $this->getMessage();
280 * @return string
282 function getText() {
283 return $this->getMessage();
288 * An error page which can definitely be safely rendered using the OutputPage
289 * @ingroup Exception
291 class ErrorPageError extends MWException {
292 public $title, $msg, $params;
295 * Note: these arguments are keys into wfMsg(), not text!
297 function __construct( $title, $msg, $params = null ) {
298 $this->title = $title;
299 $this->msg = $msg;
300 $this->params = $params;
302 if( $msg instanceof Message ){
303 parent::__construct( $msg );
304 } else {
305 parent::__construct( wfMsg( $msg ) );
309 function report() {
310 global $wgOut;
312 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
313 $wgOut->output();
318 * Show an error page on a badtitle.
319 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
320 * browser it is not really a valid content.
322 class BadTitleError extends ErrorPageError {
325 * @param $msg string A message key (default: 'badtitletext')
326 * @param $params Array parameter to wfMsg()
328 function __construct( $msg = 'badtitletext', $params = null ) {
329 parent::__construct( 'badtitle', $msg, $params );
333 * Just like ErrorPageError::report() but additionally set
334 * a 400 HTTP status code (bug 33646).
336 function report() {
337 global $wgOut;
339 // bug 33646: a badtitle error page need to return an error code
340 // to let mobile browser now that it is not a normal page.
341 $wgOut->setStatusCode( 400 );
342 parent::report();
348 * Show an error when a user tries to do something they do not have the necessary
349 * permissions for.
350 * @ingroup Exception
352 class PermissionsError extends ErrorPageError {
353 public $permission, $errors;
355 function __construct( $permission, $errors = array() ) {
356 global $wgLang;
358 $this->permission = $permission;
360 if ( !count( $errors ) ) {
361 $groups = array_map(
362 array( 'User', 'makeGroupLinkWiki' ),
363 User::getGroupsWithPermission( $this->permission )
366 if ( $groups ) {
367 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
368 } else {
369 $errors[] = array( 'badaccess-group0' );
373 $this->errors = $errors;
376 function report() {
377 global $wgOut;
379 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
380 $wgOut->output();
385 * Show an error when the wiki is locked/read-only and the user tries to do
386 * something that requires write access
387 * @ingroup Exception
389 class ReadOnlyError extends ErrorPageError {
390 public function __construct(){
391 parent::__construct(
392 'readonly',
393 'readonlytext',
394 wfReadOnlyReason()
400 * Show an error when the user hits a rate limit
401 * @ingroup Exception
403 class ThrottledError extends ErrorPageError {
404 public function __construct(){
405 parent::__construct(
406 'actionthrottled',
407 'actionthrottledtext'
411 public function report(){
412 global $wgOut;
413 $wgOut->setStatusCode( 503 );
414 parent::report();
419 * Show an error when the user tries to do something whilst blocked
420 * @ingroup Exception
422 class UserBlockedError extends ErrorPageError {
423 public function __construct( Block $block ){
424 global $wgLang, $wgRequest;
426 $blocker = $block->getBlocker();
427 if ( $blocker instanceof User ) { // local user
428 $blockerUserpage = $block->getBlocker()->getUserPage();
429 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
430 } else { // foreign user
431 $link = $blocker;
434 $reason = $block->mReason;
435 if( $reason == '' ) {
436 $reason = wfMsg( 'blockednoreason' );
439 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
440 * This could be a username, an IP range, or a single IP. */
441 $intended = $block->getTarget();
443 parent::__construct(
444 'blockedtitle',
445 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
446 array(
447 $link,
448 $reason,
449 $wgRequest->getIP(),
450 $block->getByName(),
451 $block->getId(),
452 $wgLang->formatExpiry( $block->mExpiry ),
453 $intended,
454 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
461 * Show an error that looks like an HTTP server error.
462 * Replacement for wfHttpError().
464 * @ingroup Exception
466 class HttpError extends MWException {
467 private $httpCode, $header, $content;
470 * Constructor
472 * @param $httpCode Integer: HTTP status code to send to the client
473 * @param $content String|Message: content of the message
474 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
476 public function __construct( $httpCode, $content, $header = null ){
477 parent::__construct( $content );
478 $this->httpCode = (int)$httpCode;
479 $this->header = $header;
480 $this->content = $content;
483 public function report() {
484 $httpMessage = HttpStatus::getMessage( $this->httpCode );
486 header( "Status: {$this->httpCode} {$httpMessage}" );
487 header( 'Content-type: text/html; charset=utf-8' );
489 if ( $this->header === null ) {
490 $header = $httpMessage;
491 } elseif ( $this->header instanceof Message ) {
492 $header = $this->header->escaped();
493 } else {
494 $header = htmlspecialchars( $this->header );
497 if ( $this->content instanceof Message ) {
498 $content = $this->content->escaped();
499 } else {
500 $content = htmlspecialchars( $this->content );
503 print "<!DOCTYPE html>\n".
504 "<html><head><title>$header</title></head>\n" .
505 "<body><h1>$header</h1><p>$content</p></body></html>\n";
510 * Handler class for MWExceptions
511 * @ingroup Exception
513 class MWExceptionHandler {
515 * Install an exception handler for MediaWiki exception types.
517 public static function installHandler() {
518 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
522 * Report an exception to the user
524 protected static function report( Exception $e ) {
525 global $wgShowExceptionDetails;
527 $cmdLine = MWException::isCommandLine();
529 if ( $e instanceof MWException ) {
530 try {
531 // Try and show the exception prettily, with the normal skin infrastructure
532 $e->report();
533 } catch ( Exception $e2 ) {
534 // Exception occurred from within exception handler
535 // Show a simpler error message for the original exception,
536 // don't try to invoke report()
537 $message = "MediaWiki internal error.\n\n";
539 if ( $wgShowExceptionDetails ) {
540 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
541 'Exception caught inside exception handler: ' . $e2->__toString();
542 } else {
543 $message .= "Exception caught inside exception handler.\n\n" .
544 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
545 "to show detailed debugging information.";
548 $message .= "\n";
550 if ( $cmdLine ) {
551 self::printError( $message );
552 } else {
553 self::escapeEchoAndDie( $message );
556 } else {
557 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
558 $e->__toString() . "\n";
560 if ( $wgShowExceptionDetails ) {
561 $message .= "\n" . $e->getTraceAsString() . "\n";
564 if ( $cmdLine ) {
565 self::printError( $message );
566 } else {
567 self::escapeEchoAndDie( $message );
573 * Print a message, if possible to STDERR.
574 * Use this in command line mode only (see isCommandLine)
575 * @param $message String Failure text
577 public static function printError( $message ) {
578 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
579 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
580 if ( defined( 'STDERR' ) ) {
581 fwrite( STDERR, $message );
582 } else {
583 echo( $message );
588 * Print a message after escaping it and converting newlines to <br>
589 * Use this for non-command line failures
590 * @param $message String Failure text
592 private static function escapeEchoAndDie( $message ) {
593 echo nl2br( htmlspecialchars( $message ) ) . "\n";
594 die(1);
598 * Exception handler which simulates the appropriate catch() handling:
600 * try {
601 * ...
602 * } catch ( MWException $e ) {
603 * $e->report();
604 * } catch ( Exception $e ) {
605 * echo $e->__toString();
608 public static function handle( $e ) {
609 global $wgFullyInitialised;
611 self::report( $e );
613 // Final cleanup
614 if ( $wgFullyInitialised ) {
615 try {
616 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
617 } catch ( Exception $e ) {}
620 // Exit value should be nonzero for the benefit of shell jobs
621 exit( 1 );