3 * Exception class and handler
9 * @defgroup Exception Exception
17 class MWException
extends Exception
{
19 * Should the exception use $wgOut to output the error ?
22 function useOutputPage() {
23 return $this->useMessageCache() &&
24 !empty( $GLOBALS['wgFullyInitialised'] ) &&
25 !empty( $GLOBALS['wgOut'] ) &&
26 !$GLOBALS['wgOut']->isArticleRelated() &&
27 !empty( $GLOBALS['wgTitle'] );
31 * Can the extension use wfMsg() to get i18n messages ?
34 function useMessageCache() {
37 foreach ( $this->getTrace() as $frame ) {
38 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
43 return $wgLang instanceof Language
;
47 * Run hook to allow extensions to modify the text of the exception
49 * @param $name String: class name of the exception
50 * @param $args Array: arguments to pass to the callback functions
51 * @return Mixed: string to output or null if any hook has been called
53 function runHooks( $name, $args = array() ) {
54 global $wgExceptionHooks;
56 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
57 return; // Just silently ignore
60 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks[ $name ] ) ) {
64 $hooks = $wgExceptionHooks[ $name ];
65 $callargs = array_merge( array( $this ), $args );
67 foreach ( $hooks as $hook ) {
68 if ( is_string( $hook ) ||
( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
69 $result = call_user_func_array( $hook, $callargs );
74 if ( is_string( $result ) )
80 * Get a message from i18n
82 * @param $key String: message name
83 * @param $fallback String: default message if the message cache can't be
84 * called by the exception
85 * The function also has other parameters that are arguments for the message
86 * @return String message with arguments replaced
88 function msg( $key, $fallback /*[, params...] */ ) {
89 $args = array_slice( func_get_args(), 2 );
91 if ( $this->useMessageCache() ) {
92 return wfMsgNoTrans( $key, $args );
94 return wfMsgReplaceArgs( $fallback, $args );
99 * If $wgShowExceptionDetails is true, return a HTML message with a
100 * backtrace to the error, otherwise show a message to ask to set it to true
101 * to show that information.
103 * @return String html to output
106 global $wgShowExceptionDetails;
108 if ( $wgShowExceptionDetails ) {
109 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
110 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
113 return "<p>Set <b><tt>\$wgShowExceptionDetails = true;</tt></b> " .
114 "at the bottom of LocalSettings.php to show detailed " .
115 "debugging information.</p>";
120 * If $wgShowExceptionDetails is true, return a text message with a
121 * backtrace to the error.
124 global $wgShowExceptionDetails;
126 if ( $wgShowExceptionDetails ) {
127 return $this->getMessage() .
128 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
130 return "Set \$wgShowExceptionDetails = true; " .
131 "in LocalSettings.php to show detailed debugging information.\n";
135 /* Return titles of this error page */
136 function getPageTitle() {
138 return $this->msg( 'internalerror', "$wgSitename error" );
142 * Return the requested URL and point to file and line number from which the
147 function getLogMessage() {
150 $file = $this->getFile();
151 $line = $this->getLine();
152 $message = $this->getMessage();
154 if ( isset( $wgRequest ) ) {
155 $url = $wgRequest->getRequestURL();
163 return "$url Exception from line $line of $file: $message";
166 /** Output the exception report using HTML */
167 function reportHTML() {
170 if ( $this->useOutputPage() ) {
171 $wgOut->setPageTitle( $this->getPageTitle() );
172 $wgOut->setRobotPolicy( "noindex,nofollow" );
173 $wgOut->setArticleRelated( false );
174 $wgOut->enableClientCache( false );
175 $wgOut->redirect( '' );
178 $hookResult = $this->runHooks( get_class( $this ) );
180 $wgOut->addHTML( $hookResult );
182 $wgOut->addHTML( $this->getHTML() );
187 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
192 $html = $this->getHTML();
193 if ( defined( 'MEDIAWIKI_INSTALL' ) ) {
202 * Output a report about the exception and takes care of formatting.
203 * It will be either HTML or plain text based on isCommandLine().
206 $log = $this->getLogMessage();
209 wfDebugLog( 'exception', $log );
212 if ( self
::isCommandLine() ) {
213 wfPrintError( $this->getText() );
220 * Send headers and output the beginning of the html page if not using
221 * $wgOut to output the exception.
222 * @deprecated since 1.18 call wfDie() if you need to die immediately
224 function htmlHeader() {
225 global $wgLogo, $wgLang;
227 if ( !headers_sent() ) {
228 header( 'HTTP/1.0 500 Internal Server Error' );
229 header( 'Content-type: text/html; charset=UTF-8' );
230 /* Don't cache error pages! They cause no end of trouble... */
231 header( 'Cache-control: none' );
232 header( 'Pragma: nocache' );
235 $head = Html
::element( 'title', null, $this->getPageTitle() ) . "\n";
236 $head .= Html
::inlineStyle( <<<ENDL
239 background-color: #fff;
240 font-family: sans-serif;
257 if ( $wgLang instanceof Language
) {
258 $dir = $wgLang->getDir();
259 $code = $wgLang->getCode();
262 $header = Html
::element( 'img', array(
266 $attribs = array( 'dir' => $dir, 'lang' => $code );
269 Html
::htmlHeader( $attribs ) .
270 Html
::rawElement( 'head', null, $head ) . "\n".
271 Html
::openElement( 'body' ) . "\n" .
276 * print the end of the html page if not using $wgOut.
277 * @deprecated since 1.18
279 function htmlFooter() {
280 return Html
::closeElement( 'body' ) . Html
::closeElement( 'html' );
283 static function isCommandLine() {
284 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
289 * Exception class which takes an HTML error message, and does not
290 * produce a backtrace. Replacement for OutputPage::fatalError().
293 class FatalError
extends MWException
{
295 return $this->getMessage();
299 return $this->getMessage();
304 * An error page which can definitely be safely rendered using the OutputPage
307 class ErrorPageError
extends MWException
{
308 public $title, $msg, $params;
311 * Note: these arguments are keys into wfMsg(), not text!
313 function __construct( $title, $msg, $params = null ) {
314 $this->title
= $title;
316 $this->params
= $params;
318 if( $msg instanceof Message
){
319 parent
::__construct( $msg );
321 parent
::__construct( wfMsg( $msg ) );
328 if ( $wgOut->getTitle() ) {
329 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
331 $wgOut->setPageTitle( wfMsg( $this->title
) );
332 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
333 $wgOut->setRobotPolicy( 'noindex,nofollow' );
334 $wgOut->setArticleRelated( false );
335 $wgOut->enableClientCache( false );
336 $wgOut->mRedirect
= '';
339 if( $this->msg
instanceof Message
){
340 $wgOut->addHTML( $this->msg
->parse() );
342 $wgOut->addWikiMsgArray( $this->msg
, $this->params
);
345 $wgOut->returnToMain();
351 * Show an error when a user tries to do something they do not have the necessary
354 class PermissionsError
extends ErrorPageError
{
357 function __construct( $permission ) {
360 $this->permission
= $permission;
363 array( 'User', 'makeGroupLinkWiki' ),
364 User
::getGroupsWithPermission( $this->permission
)
372 $wgLang->commaList( $groups ),
386 * Show an error when the wiki is locked/read-only and the user tries to do
387 * something that requires write access
389 class ReadOnlyError
extends ErrorPageError
{
390 public function __construct(){
400 * Show an error when the user hits a rate limit
402 class ThrottledError
extends ErrorPageError
{
403 public function __construct(){
406 'actionthrottledtext'
409 public function report(){
411 $wgOut->setStatusCode( 503 );
412 return parent
::report();
417 * Show an error when the user tries to do something whilst blocked
419 class UserBlockedError
extends ErrorPageError
{
420 public function __construct( Block
$block ){
423 $blockerUserpage = $block->getBlocker()->getUserPage();
424 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
426 $reason = $block->mReason
;
427 if( $reason == '' ) {
428 $reason = wfMsg( 'blockednoreason' );
431 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
432 * This could be a username, an IP range, or a single IP. */
433 $intended = $block->getTarget();
437 $block->mAuto ?
'autoblocketext' : 'blockedtext',
442 $block->getBlocker()->getName(),
444 $wgLang->formatExpiry( $block->mExpiry
),
446 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
453 * Install an exception handler for MediaWiki exception types.
455 function wfInstallExceptionHandler() {
456 set_exception_handler( 'wfExceptionHandler' );
460 * Report an exception to the user
462 function wfReportException( Exception
$e ) {
463 global $wgShowExceptionDetails;
465 $cmdLine = MWException
::isCommandLine();
467 if ( $e instanceof MWException
) {
469 // Try and show the exception prettily, with the normal skin infrastructure
471 } catch ( Exception
$e2 ) {
472 // Exception occurred from within exception handler
473 // Show a simpler error message for the original exception,
474 // don't try to invoke report()
475 $message = "MediaWiki internal error.\n\n";
477 if ( $wgShowExceptionDetails ) {
478 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
479 'Exception caught inside exception handler: ' . $e2->__toString();
481 $message .= "Exception caught inside exception handler.\n\n" .
482 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
483 "to show detailed debugging information.";
489 wfPrintError( $message );
491 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
495 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
496 $e->__toString() . "\n";
498 if ( $wgShowExceptionDetails ) {
499 $message .= "\n" . $e->getTraceAsString() . "\n";
503 wfPrintError( $message );
505 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
511 * Print a message, if possible to STDERR.
512 * Use this in command line mode only (see isCommandLine)
514 function wfPrintError( $message ) {
515 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
516 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
517 if ( defined( 'STDERR' ) ) {
518 fwrite( STDERR
, $message );
525 * Exception handler which simulates the appropriate catch() handling:
529 * } catch ( MWException $e ) {
531 * } catch ( Exception $e ) {
532 * echo $e->__toString();
535 function wfExceptionHandler( $e ) {
536 global $wgFullyInitialised;
538 wfReportException( $e );
541 if ( $wgFullyInitialised ) {
543 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
544 } catch ( Exception
$e ) {}
547 // Exit value should be nonzero for the benefit of shell jobs