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 wfMsgReal( $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() {
136 if ( $this->useMessageCache() ) {
137 return wfMsg( 'internalerror' );
141 return "$wgSitename error";
146 * Return the requested URL and point to file and line number from which the
151 function getLogMessage() {
154 $file = $this->getFile();
155 $line = $this->getLine();
156 $message = $this->getMessage();
158 if ( isset( $wgRequest ) ) {
159 $url = $wgRequest->getRequestURL();
167 return "$url Exception from line $line of $file: $message";
170 /** Output the exception report using HTML */
171 function reportHTML() {
174 if ( $this->useOutputPage() ) {
175 $wgOut->setPageTitle( $this->getPageTitle() );
176 $wgOut->setRobotPolicy( "noindex,nofollow" );
177 $wgOut->setArticleRelated( false );
178 $wgOut->enableClientCache( false );
179 $wgOut->redirect( '' );
182 $hookResult = $this->runHooks( get_class( $this ) );
184 $wgOut->addHTML( $hookResult );
186 $wgOut->addHTML( $this->getHTML() );
191 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
196 if ( defined( 'MEDIAWIKI_INSTALL' ) ||
$this->htmlBodyOnly() ) {
197 echo $this->getHTML();
199 echo $this->htmlHeader();
200 echo $this->getHTML();
201 echo $this->htmlFooter();
207 * Output a report about the exception and takes care of formatting.
208 * It will be either HTML or plain text based on isCommandLine().
211 $log = $this->getLogMessage();
214 wfDebugLog( 'exception', $log );
217 if ( self
::isCommandLine() ) {
218 wfPrintError( $this->getText() );
225 * Send headers and output the beginning of the html page if not using
226 * $wgOut to output the exception.
228 function htmlHeader() {
229 global $wgLogo, $wgOutputEncoding, $wgLang;
231 if ( !headers_sent() ) {
232 header( 'HTTP/1.0 500 Internal Server Error' );
233 header( 'Content-type: text/html; charset=' . $wgOutputEncoding );
234 /* Don't cache error pages! They cause no end of trouble... */
235 header( 'Cache-control: none' );
236 header( 'Pragma: nocache' );
239 $head = Html
::element( 'title', null, $this->getPageTitle() ) . "\n";
240 $head .= Html
::inlineStyle( <<<ENDL
243 background-color: #fff;
244 font-family: sans-serif;
261 if ( $wgLang instanceof Language
) {
262 $dir = $wgLang->getDir();
263 $code = $wgLang->getCode();
266 $header = Html
::element( 'img', array(
268 'alt' => '' ), $this->getPageTitle() );
270 $attribs = array( 'dir' => $dir, 'lang' => $code );
273 Html
::htmlHeader( $attribs ) .
274 Html
::rawElement( 'head', null, $head ) . "\n".
275 Html
::openElement( 'body' ) . "\n" .
280 * print the end of the html page if not using $wgOut.
282 function htmlFooter() {
283 return Html
::closeElement( 'body' ) . Html
::closeElement( 'html' );
287 * headers handled by subclass?
289 function htmlBodyOnly() {
293 static function isCommandLine() {
294 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
299 * Exception class which takes an HTML error message, and does not
300 * produce a backtrace. Replacement for OutputPage::fatalError().
303 class FatalError
extends MWException
{
305 return $this->getMessage();
309 return $this->getMessage();
314 * An error page which can definitely be safely rendered using the OutputPage
317 class ErrorPageError
extends MWException
{
318 public $title, $msg, $params;
321 * Note: these arguments are keys into wfMsg(), not text!
323 function __construct( $title, $msg, $params = null ) {
324 $this->title
= $title;
326 $this->params
= $params;
328 if( $msg instanceof Message
){
329 parent
::__construct( $msg );
331 parent
::__construct( wfMsg( $msg ) );
338 if ( $wgOut->getTitle() ) {
339 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
341 $wgOut->setPageTitle( wfMsg( $this->title
) );
342 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
343 $wgOut->setRobotPolicy( 'noindex,nofollow' );
344 $wgOut->setArticleRelated( false );
345 $wgOut->enableClientCache( false );
346 $wgOut->mRedirect
= '';
349 if( $this->msg
instanceof Message
){
350 $wgOut->addHTML( $this->msg
->parse() );
352 $wgOut->addWikiMsgArray( $this->msg
, $this->params
);
355 $wgOut->returnToMain();
361 * Show an error when a user tries to do something they do not have the necessary
364 class PermissionsError
extends ErrorPageError
{
367 function __construct( $permission ) {
370 $this->permission
= $permission;
373 array( 'User', 'makeGroupLinkWiki' ),
374 User
::getGroupsWithPermission( $this->permission
)
382 $wgLang->commaList( $groups ),
396 * Show an error when the wiki is locked/read-only and the user tries to do
397 * something that requires write access
399 class ReadOnlyError
extends ErrorPageError
{
400 public function __construct(){
410 * Show an error when the user hits a rate limit
412 class ThrottledError
extends ErrorPageError
{
413 public function __construct(){
416 'actionthrottledtext'
419 public function report(){
421 $wgOut->setStatusCode( 503 );
422 return parent
::report();
427 * Show an error when the user tries to do something whilst blocked
429 class UserBlockedError
extends ErrorPageError
{
430 public function __construct( Block
$block ){
433 $blockerUserpage = $block->getBlocker()->getUserPage();
434 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
436 $reason = $block->mReason
;
437 if( $reason == '' ) {
438 $reason = wfMsg( 'blockednoreason' );
441 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
442 * This could be a username, an IP range, or a single IP. */
443 $intended = $block->getTarget();
447 $block->mAuto ?
'autoblocketext' : 'blockedtext',
452 $block->getBlocker()->getName(),
454 $wgLang->formatExpiry( $block->mExpiry
),
456 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
463 * Install an exception handler for MediaWiki exception types.
465 function wfInstallExceptionHandler() {
466 set_exception_handler( 'wfExceptionHandler' );
470 * Report an exception to the user
472 function wfReportException( Exception
$e ) {
473 global $wgShowExceptionDetails;
475 $cmdLine = MWException
::isCommandLine();
477 if ( $e instanceof MWException
) {
479 // Try and show the exception prettily, with the normal skin infrastructure
481 } catch ( Exception
$e2 ) {
482 // Exception occurred from within exception handler
483 // Show a simpler error message for the original exception,
484 // don't try to invoke report()
485 $message = "MediaWiki internal error.\n\n";
487 if ( $wgShowExceptionDetails ) {
488 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
489 'Exception caught inside exception handler: ' . $e2->__toString();
491 $message .= "Exception caught inside exception handler.\n\n" .
492 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
493 "to show detailed debugging information.";
499 wfPrintError( $message );
501 wfDie( htmlspecialchars( $message ) ) . "\n";
505 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
506 $e->__toString() . "\n";
508 if ( $wgShowExceptionDetails ) {
509 $message .= "\n" . $e->getTraceAsString() . "\n";
513 wfPrintError( $message );
515 wfDie( htmlspecialchars( $message ) ) . "\n";
521 * Print a message, if possible to STDERR.
522 * Use this in command line mode only (see isCommandLine)
524 function wfPrintError( $message ) {
525 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
526 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
527 if ( defined( 'STDERR' ) ) {
528 fwrite( STDERR
, $message );
535 * Exception handler which simulates the appropriate catch() handling:
539 * } catch ( MWException $e ) {
541 * } catch ( Exception $e ) {
542 * echo $e->__toString();
545 function wfExceptionHandler( $e ) {
546 global $wgFullyInitialised;
548 wfReportException( $e );
551 if ( $wgFullyInitialised ) {
553 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
554 } catch ( Exception
$e ) {}
557 // Exit value should be nonzero for the benefit of shell jobs