* changed display function for length to Linker::formatRevisionSize
[mediawiki.git] / includes / Exception.php
blob4c7fb6e441e4f1972d19d6276783b2e2200ec85d
1 <?php
2 /**
3 * Exception class and handler
5 * @file
6 */
8 /**
9 * @defgroup Exception Exception
12 /**
13 * MediaWiki exception
15 * @ingroup Exception
17 class MWException extends Exception {
18 /**
19 * Should the exception use $wgOut to output the error ?
20 * @return bool
22 function useOutputPage() {
23 return $this->useMessageCache() &&
24 !empty( $GLOBALS['wgFullyInitialised'] ) &&
25 ( !empty( $GLOBALS['wgArticle'] ) || ( !empty( $GLOBALS['wgOut'] ) && !$GLOBALS['wgOut']->isArticleRelated() ) ) &&
26 !empty( $GLOBALS['wgTitle'] );
29 /**
30 * Can the extension use wfMsg() to get i18n messages ?
31 * @return bool
33 function useMessageCache() {
34 global $wgLang;
36 foreach ( $this->getTrace() as $frame ) {
37 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
38 return false;
42 return $wgLang instanceof Language;
45 /**
46 * Run hook to allow extensions to modify the text of the exception
48 * @param $name String: class name of the exception
49 * @param $args Array: arguments to pass to the callback functions
50 * @return Mixed: string to output or null if any hook has been called
52 function runHooks( $name, $args = array() ) {
53 global $wgExceptionHooks;
55 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
56 return; // Just silently ignore
59 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
60 return;
63 $hooks = $wgExceptionHooks[ $name ];
64 $callargs = array_merge( array( $this ), $args );
66 foreach ( $hooks as $hook ) {
67 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
68 $result = call_user_func_array( $hook, $callargs );
69 } else {
70 $result = null;
73 if ( is_string( $result ) )
74 return $result;
78 /**
79 * Get a message from i18n
81 * @param $key String: message name
82 * @param $fallback String: default message if the message cache can't be
83 * called by the exception
84 * The function also has other parameters that are arguments for the message
85 * @return String message with arguments replaced
87 function msg( $key, $fallback /*[, params...] */ ) {
88 $args = array_slice( func_get_args(), 2 );
90 if ( $this->useMessageCache() ) {
91 return wfMsgNoTrans( $key, $args );
92 } else {
93 return wfMsgReplaceArgs( $fallback, $args );
97 /**
98 * If $wgShowExceptionDetails is true, return a HTML message with a
99 * backtrace to the error, otherwise show a message to ask to set it to true
100 * to show that information.
102 * @return String html to output
104 function getHTML() {
105 global $wgShowExceptionDetails;
107 if ( $wgShowExceptionDetails ) {
108 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
109 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
110 "</p>\n";
111 } else {
112 return "<p>Set <b><tt>\$wgShowExceptionDetails = true;</tt></b> " .
113 "at the bottom of LocalSettings.php to show detailed " .
114 "debugging information.</p>";
119 * If $wgShowExceptionDetails is true, return a text message with a
120 * backtrace to the error.
122 function getText() {
123 global $wgShowExceptionDetails;
125 if ( $wgShowExceptionDetails ) {
126 return $this->getMessage() .
127 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
128 } else {
129 return "Set \$wgShowExceptionDetails = true; " .
130 "in LocalSettings.php to show detailed debugging information.\n";
134 /* Return titles of this error page */
135 function getPageTitle() {
136 global $wgSitename;
137 return $this->msg( 'internalerror', "$wgSitename error" );
141 * Return the requested URL and point to file and line number from which the
142 * exception occured
144 * @return String
146 function getLogMessage() {
147 global $wgRequest;
149 $file = $this->getFile();
150 $line = $this->getLine();
151 $message = $this->getMessage();
153 if ( isset( $wgRequest ) ) {
154 $url = $wgRequest->getRequestURL();
155 if ( !$url ) {
156 $url = '[no URL]';
158 } else {
159 $url = '[no req]';
162 return "$url Exception from line $line of $file: $message";
165 /** Output the exception report using HTML */
166 function reportHTML() {
167 global $wgOut;
169 if ( $this->useOutputPage() ) {
170 $wgOut->setPageTitle( $this->getPageTitle() );
171 $wgOut->setRobotPolicy( "noindex,nofollow" );
172 $wgOut->setArticleRelated( false );
173 $wgOut->enableClientCache( false );
174 $wgOut->redirect( '' );
175 $wgOut->clearHTML();
177 $hookResult = $this->runHooks( get_class( $this ) );
178 if ( $hookResult ) {
179 $wgOut->addHTML( $hookResult );
180 } else {
181 $wgOut->addHTML( $this->getHTML() );
184 $wgOut->output();
185 } else {
186 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
187 if ( $hookResult ) {
188 die( $hookResult );
191 $html = $this->getHTML();
192 if ( defined( 'MEDIAWIKI_INSTALL' ) ) {
193 echo $html;
194 } else {
195 wfDie( $html );
201 * Output a report about the exception and takes care of formatting.
202 * It will be either HTML or plain text based on isCommandLine().
204 function report() {
205 $log = $this->getLogMessage();
207 if ( $log ) {
208 wfDebugLog( 'exception', $log );
211 if ( self::isCommandLine() ) {
212 wfPrintError( $this->getText() );
213 } else {
214 $this->reportHTML();
219 * Send headers and output the beginning of the html page if not using
220 * $wgOut to output the exception.
221 * @deprecated since 1.18 call wfDie() if you need to die immediately
223 function htmlHeader() {
224 global $wgLogo, $wgLang;
226 if ( !headers_sent() ) {
227 header( 'HTTP/1.0 500 Internal Server Error' );
228 header( 'Content-type: text/html; charset=UTF-8' );
229 /* Don't cache error pages! They cause no end of trouble... */
230 header( 'Cache-control: none' );
231 header( 'Pragma: nocache' );
234 $head = Html::element( 'title', null, $this->getPageTitle() ) . "\n";
235 $head .= Html::inlineStyle( <<<ENDL
236 body {
237 color: #000;
238 background-color: #fff;
239 font-family: sans-serif;
240 padding: 2em;
241 text-align: center;
243 p, img, h1 {
244 text-align: left;
245 margin: 0.5em 0;
247 h1 {
248 font-size: 120%;
250 ENDL
253 $dir = 'ltr';
254 $code = 'en';
256 if ( $wgLang instanceof Language ) {
257 $dir = $wgLang->getDir();
258 $code = $wgLang->getCode();
261 $header = Html::element( 'img', array(
262 'src' => $wgLogo,
263 'alt' => '' ) );
265 $attribs = array( 'dir' => $dir, 'lang' => $code );
267 return
268 Html::htmlHeader( $attribs ) .
269 Html::rawElement( 'head', null, $head ) . "\n".
270 Html::openElement( 'body' ) . "\n" .
271 $header . "\n";
275 * print the end of the html page if not using $wgOut.
276 * @deprecated since 1.18
278 function htmlFooter() {
279 return Html::closeElement( 'body' ) . Html::closeElement( 'html' );
282 static function isCommandLine() {
283 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
288 * Exception class which takes an HTML error message, and does not
289 * produce a backtrace. Replacement for OutputPage::fatalError().
290 * @ingroup Exception
292 class FatalError extends MWException {
293 function getHTML() {
294 return $this->getMessage();
297 function getText() {
298 return $this->getMessage();
303 * An error page which can definitely be safely rendered using the OutputPage
304 * @ingroup Exception
306 class ErrorPageError extends MWException {
307 public $title, $msg, $params;
310 * Note: these arguments are keys into wfMsg(), not text!
312 function __construct( $title, $msg, $params = null ) {
313 $this->title = $title;
314 $this->msg = $msg;
315 $this->params = $params;
317 if( $msg instanceof Message ){
318 parent::__construct( $msg );
319 } else {
320 parent::__construct( wfMsg( $msg ) );
324 function report() {
325 global $wgOut;
327 if ( $wgOut->getTitle() ) {
328 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
330 $wgOut->setPageTitle( wfMsg( $this->title ) );
331 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
332 $wgOut->setRobotPolicy( 'noindex,nofollow' );
333 $wgOut->setArticleRelated( false );
334 $wgOut->enableClientCache( false );
335 $wgOut->mRedirect = '';
336 $wgOut->clearHTML();
338 if( $this->msg instanceof Message ){
339 $wgOut->addHTML( $this->msg->parse() );
340 } else {
341 $wgOut->addWikiMsgArray( $this->msg, $this->params );
344 $wgOut->returnToMain();
345 $wgOut->output();
350 * Show an error when a user tries to do something they do not have the necessary
351 * permissions for.
353 class PermissionsError extends ErrorPageError {
354 public $permission;
356 function __construct( $permission ) {
357 global $wgLang;
359 $this->permission = $permission;
361 $groups = array_map(
362 array( 'User', 'makeGroupLinkWiki' ),
363 User::getGroupsWithPermission( $this->permission )
366 if( $groups ) {
367 parent::__construct(
368 'badaccess',
369 'badaccess-groups',
370 array(
371 $wgLang->commaList( $groups ),
372 count( $groups )
375 } else {
376 parent::__construct(
377 'badaccess',
378 'badaccess-group0'
385 * Show an error when the wiki is locked/read-only and the user tries to do
386 * something that requires write access
388 class ReadOnlyError extends ErrorPageError {
389 public function __construct(){
390 parent::__construct(
391 'readonly',
392 'readonlytext',
393 wfReadOnlyReason()
399 * Show an error when the user hits a rate limit
401 class ThrottledError extends ErrorPageError {
402 public function __construct(){
403 parent::__construct(
404 'actionthrottled',
405 'actionthrottledtext'
408 public function report(){
409 global $wgOut;
410 $wgOut->setStatusCode( 503 );
411 return parent::report();
416 * Show an error when the user tries to do something whilst blocked
418 class UserBlockedError extends ErrorPageError {
419 public function __construct( Block $block ){
420 global $wgLang;
422 $blockerUserpage = $block->getBlocker()->getUserPage();
423 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
425 $reason = $block->mReason;
426 if( $reason == '' ) {
427 $reason = wfMsg( 'blockednoreason' );
430 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
431 * This could be a username, an IP range, or a single IP. */
432 $intended = $block->getTarget();
434 parent::__construct(
435 'blockedtitle',
436 $block->mAuto ? 'autoblocketext' : 'blockedtext',
437 array(
438 $link,
439 $reason,
440 wfGetIP(),
441 $block->getBlocker()->getName(),
442 $block->getId(),
443 $wgLang->formatExpiry( $block->mExpiry ),
444 $intended,
445 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
452 * Install an exception handler for MediaWiki exception types.
454 function wfInstallExceptionHandler() {
455 set_exception_handler( 'wfExceptionHandler' );
459 * Report an exception to the user
461 function wfReportException( Exception $e ) {
462 global $wgShowExceptionDetails;
464 $cmdLine = MWException::isCommandLine();
466 if ( $e instanceof MWException ) {
467 try {
468 // Try and show the exception prettily, with the normal skin infrastructure
469 $e->report();
470 } catch ( Exception $e2 ) {
471 // Exception occurred from within exception handler
472 // Show a simpler error message for the original exception,
473 // don't try to invoke report()
474 $message = "MediaWiki internal error.\n\n";
476 if ( $wgShowExceptionDetails ) {
477 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
478 'Exception caught inside exception handler: ' . $e2->__toString();
479 } else {
480 $message .= "Exception caught inside exception handler.\n\n" .
481 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
482 "to show detailed debugging information.";
485 $message .= "\n";
487 if ( $cmdLine ) {
488 wfPrintError( $message );
489 } else {
490 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
493 } else {
494 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
495 $e->__toString() . "\n";
497 if ( $wgShowExceptionDetails ) {
498 $message .= "\n" . $e->getTraceAsString() . "\n";
501 if ( $cmdLine ) {
502 wfPrintError( $message );
503 } else {
504 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
510 * Print a message, if possible to STDERR.
511 * Use this in command line mode only (see isCommandLine)
513 function wfPrintError( $message ) {
514 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
515 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
516 if ( defined( 'STDERR' ) ) {
517 fwrite( STDERR, $message );
518 } else {
519 echo( $message );
524 * Exception handler which simulates the appropriate catch() handling:
526 * try {
527 * ...
528 * } catch ( MWException $e ) {
529 * $e->report();
530 * } catch ( Exception $e ) {
531 * echo $e->__toString();
534 function wfExceptionHandler( $e ) {
535 global $wgFullyInitialised;
537 wfReportException( $e );
539 // Final cleanup
540 if ( $wgFullyInitialised ) {
541 try {
542 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
543 } catch ( Exception $e ) {}
546 // Exit value should be nonzero for the benefit of shell jobs
547 exit( 1 );