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['wgArticle'] ) ||
( !empty( $GLOBALS['wgOut'] ) && !$GLOBALS['wgOut']->isArticleRelated() ) ) &&
26 !empty( $GLOBALS['wgTitle'] );
30 * Can the extension use wfMsg() to get i18n messages ?
33 function useMessageCache() {
36 foreach ( $this->getTrace() as $frame ) {
37 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
42 return $wgLang instanceof Language
;
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 ] ) ) {
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 );
73 if ( is_string( $result ) )
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 );
93 return wfMsgReplaceArgs( $fallback, $args );
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
105 global $wgShowExceptionDetails;
107 if ( $wgShowExceptionDetails ) {
108 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
109 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
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.
123 global $wgShowExceptionDetails;
125 if ( $wgShowExceptionDetails ) {
126 return $this->getMessage() .
127 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
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() {
137 return $this->msg( 'internalerror', "$wgSitename error" );
141 * Return the requested URL and point to file and line number from which the
146 function getLogMessage() {
149 $file = $this->getFile();
150 $line = $this->getLine();
151 $message = $this->getMessage();
153 if ( isset( $wgRequest ) ) {
154 $url = $wgRequest->getRequestURL();
162 return "$url Exception from line $line of $file: $message";
165 /** Output the exception report using HTML */
166 function reportHTML() {
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( '' );
177 $hookResult = $this->runHooks( get_class( $this ) );
179 $wgOut->addHTML( $hookResult );
181 $wgOut->addHTML( $this->getHTML() );
186 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
191 if ( defined( 'MEDIAWIKI_INSTALL' ) ||
$this->htmlBodyOnly() ) {
192 echo $this->getHTML();
194 echo $this->htmlHeader();
195 echo $this->getHTML();
196 echo $this->htmlFooter();
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.
223 function htmlHeader() {
224 global $wgLogo, $wgOutputEncoding, $wgLang;
226 if ( !headers_sent() ) {
227 header( 'HTTP/1.0 500 Internal Server Error' );
228 header( 'Content-type: text/html; charset=' . $wgOutputEncoding );
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
238 background-color: #fff;
239 font-family: sans-serif;
256 if ( $wgLang instanceof Language
) {
257 $dir = $wgLang->getDir();
258 $code = $wgLang->getCode();
261 $header = Html
::element( 'img', array(
265 $attribs = array( 'dir' => $dir, 'lang' => $code );
268 Html
::htmlHeader( $attribs ) .
269 Html
::rawElement( 'head', null, $head ) . "\n".
270 Html
::openElement( 'body' ) . "\n" .
275 * print the end of the html page if not using $wgOut.
277 function htmlFooter() {
278 return Html
::closeElement( 'body' ) . Html
::closeElement( 'html' );
282 * headers handled by subclass?
284 function htmlBodyOnly() {
288 static function isCommandLine() {
289 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
294 * Exception class which takes an HTML error message, and does not
295 * produce a backtrace. Replacement for OutputPage::fatalError().
298 class FatalError
extends MWException
{
300 return $this->getMessage();
304 return $this->getMessage();
309 * An error page which can definitely be safely rendered using the OutputPage
312 class ErrorPageError
extends MWException
{
313 public $title, $msg, $params;
316 * Note: these arguments are keys into wfMsg(), not text!
318 function __construct( $title, $msg, $params = null ) {
319 $this->title
= $title;
321 $this->params
= $params;
323 if( $msg instanceof Message
){
324 parent
::__construct( $msg );
326 parent
::__construct( wfMsg( $msg ) );
333 if ( $wgOut->getTitle() ) {
334 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
336 $wgOut->setPageTitle( wfMsg( $this->title
) );
337 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
338 $wgOut->setRobotPolicy( 'noindex,nofollow' );
339 $wgOut->setArticleRelated( false );
340 $wgOut->enableClientCache( false );
341 $wgOut->mRedirect
= '';
344 if( $this->msg
instanceof Message
){
345 $wgOut->addHTML( $this->msg
->parse() );
347 $wgOut->addWikiMsgArray( $this->msg
, $this->params
);
350 $wgOut->returnToMain();
356 * Show an error when a user tries to do something they do not have the necessary
359 class PermissionsError
extends ErrorPageError
{
362 function __construct( $permission ) {
365 $this->permission
= $permission;
368 array( 'User', 'makeGroupLinkWiki' ),
369 User
::getGroupsWithPermission( $this->permission
)
377 $wgLang->commaList( $groups ),
391 * Show an error when the wiki is locked/read-only and the user tries to do
392 * something that requires write access
394 class ReadOnlyError
extends ErrorPageError
{
395 public function __construct(){
405 * Show an error when the user hits a rate limit
407 class ThrottledError
extends ErrorPageError
{
408 public function __construct(){
411 'actionthrottledtext'
414 public function report(){
416 $wgOut->setStatusCode( 503 );
417 return parent
::report();
422 * Show an error when the user tries to do something whilst blocked
424 class UserBlockedError
extends ErrorPageError
{
425 public function __construct( Block
$block ){
428 $blockerUserpage = $block->getBlocker()->getUserPage();
429 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
431 $reason = $block->mReason
;
432 if( $reason == '' ) {
433 $reason = wfMsg( 'blockednoreason' );
436 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
437 * This could be a username, an IP range, or a single IP. */
438 $intended = $block->getTarget();
442 $block->mAuto ?
'autoblocketext' : 'blockedtext',
447 $block->getBlocker()->getName(),
449 $wgLang->formatExpiry( $block->mExpiry
),
451 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
458 * Install an exception handler for MediaWiki exception types.
460 function wfInstallExceptionHandler() {
461 set_exception_handler( 'wfExceptionHandler' );
465 * Report an exception to the user
467 function wfReportException( Exception
$e ) {
468 global $wgShowExceptionDetails;
470 $cmdLine = MWException
::isCommandLine();
472 if ( $e instanceof MWException
) {
474 // Try and show the exception prettily, with the normal skin infrastructure
476 } catch ( Exception
$e2 ) {
477 // Exception occurred from within exception handler
478 // Show a simpler error message for the original exception,
479 // don't try to invoke report()
480 $message = "MediaWiki internal error.\n\n";
482 if ( $wgShowExceptionDetails ) {
483 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
484 'Exception caught inside exception handler: ' . $e2->__toString();
486 $message .= "Exception caught inside exception handler.\n\n" .
487 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
488 "to show detailed debugging information.";
494 wfPrintError( $message );
496 wfDie( htmlspecialchars( $message ) ) . "\n";
500 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
501 $e->__toString() . "\n";
503 if ( $wgShowExceptionDetails ) {
504 $message .= "\n" . $e->getTraceAsString() . "\n";
508 wfPrintError( $message );
510 wfDie( htmlspecialchars( $message ) ) . "\n";
516 * Print a message, if possible to STDERR.
517 * Use this in command line mode only (see isCommandLine)
519 function wfPrintError( $message ) {
520 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
521 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
522 if ( defined( 'STDERR' ) ) {
523 fwrite( STDERR
, $message );
530 * Exception handler which simulates the appropriate catch() handling:
534 * } catch ( MWException $e ) {
536 * } catch ( Exception $e ) {
537 * echo $e->__toString();
540 function wfExceptionHandler( $e ) {
541 global $wgFullyInitialised;
543 wfReportException( $e );
546 if ( $wgFullyInitialised ) {
548 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
549 } catch ( Exception
$e ) {}
552 // Exit value should be nonzero for the benefit of shell jobs