Change default value for format property of mw.message object from 'parse' to 'plain...
[mediawiki.git] / includes / Exception.php
blobf380d5d0b4e6b25b9ac84e1efdf48adee227e1c1
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['wgOut'] ) &&
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;
168 if ( $this->useOutputPage() ) {
169 $wgOut->setPageTitle( $this->getPageTitle() );
170 $wgOut->setRobotPolicy( "noindex,nofollow" );
171 $wgOut->setArticleRelated( false );
172 $wgOut->enableClientCache( false );
173 $wgOut->redirect( '' );
174 $wgOut->clearHTML();
176 $hookResult = $this->runHooks( get_class( $this ) );
177 if ( $hookResult ) {
178 $wgOut->addHTML( $hookResult );
179 } else {
180 $wgOut->addHTML( $this->getHTML() );
183 $wgOut->output();
184 } else {
185 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
186 if ( $hookResult ) {
187 die( $hookResult );
190 echo $this->getHTML();
191 die(1);
196 * Output a report about the exception and takes care of formatting.
197 * It will be either HTML or plain text based on isCommandLine().
199 function report() {
200 $log = $this->getLogMessage();
202 if ( $log ) {
203 wfDebugLog( 'exception', $log );
206 if ( self::isCommandLine() ) {
207 MWExceptionHandler::printError( $this->getText() );
208 } else {
209 $this->reportHTML();
213 static function isCommandLine() {
214 return !empty( $GLOBALS['wgCommandLineMode'] );
219 * Exception class which takes an HTML error message, and does not
220 * produce a backtrace. Replacement for OutputPage::fatalError().
221 * @ingroup Exception
223 class FatalError extends MWException {
224 function getHTML() {
225 return $this->getMessage();
228 function getText() {
229 return $this->getMessage();
234 * An error page which can definitely be safely rendered using the OutputPage
235 * @ingroup Exception
237 class ErrorPageError extends MWException {
238 public $title, $msg, $params;
241 * Note: these arguments are keys into wfMsg(), not text!
243 function __construct( $title, $msg, $params = null ) {
244 $this->title = $title;
245 $this->msg = $msg;
246 $this->params = $params;
248 if( $msg instanceof Message ){
249 parent::__construct( $msg );
250 } else {
251 parent::__construct( wfMsg( $msg ) );
255 function report() {
256 global $wgOut;
258 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
259 $wgOut->output();
264 * Show an error when a user tries to do something they do not have the necessary
265 * permissions for.
266 * @ingroup Exception
268 class PermissionsError extends ErrorPageError {
269 public $permission;
271 function __construct( $permission ) {
272 global $wgLang;
274 $this->permission = $permission;
276 $groups = array_map(
277 array( 'User', 'makeGroupLinkWiki' ),
278 User::getGroupsWithPermission( $this->permission )
281 if( $groups ) {
282 parent::__construct(
283 'badaccess',
284 'badaccess-groups',
285 array(
286 $wgLang->commaList( $groups ),
287 count( $groups )
290 } else {
291 parent::__construct(
292 'badaccess',
293 'badaccess-group0'
300 * Show an error when the wiki is locked/read-only and the user tries to do
301 * something that requires write access
302 * @ingroup Exception
304 class ReadOnlyError extends ErrorPageError {
305 public function __construct(){
306 parent::__construct(
307 'readonly',
308 'readonlytext',
309 wfReadOnlyReason()
315 * Show an error when the user hits a rate limit
316 * @ingroup Exception
318 class ThrottledError extends ErrorPageError {
319 public function __construct(){
320 parent::__construct(
321 'actionthrottled',
322 'actionthrottledtext'
325 public function report(){
326 global $wgOut;
327 $wgOut->setStatusCode( 503 );
328 return parent::report();
333 * Show an error when the user tries to do something whilst blocked
334 * @ingroup Exception
336 class UserBlockedError extends ErrorPageError {
337 public function __construct( Block $block ){
338 global $wgLang, $wgRequest;
340 $blockerUserpage = $block->getBlocker()->getUserPage();
341 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
343 $reason = $block->mReason;
344 if( $reason == '' ) {
345 $reason = wfMsg( 'blockednoreason' );
348 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
349 * This could be a username, an IP range, or a single IP. */
350 $intended = $block->getTarget();
352 parent::__construct(
353 'blockedtitle',
354 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
355 array(
356 $link,
357 $reason,
358 $wgRequest->getIP(),
359 $block->getBlocker()->getName(),
360 $block->getId(),
361 $wgLang->formatExpiry( $block->mExpiry ),
362 $intended,
363 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
370 * Handler class for MWExceptions
371 * @ingroup Exception
373 class MWExceptionHandler {
375 * Install an exception handler for MediaWiki exception types.
377 public static function installHandler() {
378 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
382 * Report an exception to the user
384 protected static function report( Exception $e ) {
385 global $wgShowExceptionDetails;
387 $cmdLine = MWException::isCommandLine();
389 if ( $e instanceof MWException ) {
390 try {
391 // Try and show the exception prettily, with the normal skin infrastructure
392 $e->report();
393 } catch ( Exception $e2 ) {
394 // Exception occurred from within exception handler
395 // Show a simpler error message for the original exception,
396 // don't try to invoke report()
397 $message = "MediaWiki internal error.\n\n";
399 if ( $wgShowExceptionDetails ) {
400 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
401 'Exception caught inside exception handler: ' . $e2->__toString();
402 } else {
403 $message .= "Exception caught inside exception handler.\n\n" .
404 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
405 "to show detailed debugging information.";
408 $message .= "\n";
410 if ( $cmdLine ) {
411 self::printError( $message );
412 } else {
413 self::escapeEchoAndDie( $message );
416 } else {
417 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
418 $e->__toString() . "\n";
420 if ( $wgShowExceptionDetails ) {
421 $message .= "\n" . $e->getTraceAsString() . "\n";
424 if ( $cmdLine ) {
425 self::printError( $message );
426 } else {
427 self::escapeEchoAndDie( $message );
433 * Print a message, if possible to STDERR.
434 * Use this in command line mode only (see isCommandLine)
435 * @param $message String Failure text
437 public static function printError( $message ) {
438 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
439 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
440 if ( defined( 'STDERR' ) ) {
441 fwrite( STDERR, $message );
442 } else {
443 echo( $message );
448 * Print a message after escaping it and converting newlines to <br>
449 * Use this for non-command line failures
450 * @param $message String Failure text
452 private static function escapeEchoAndDie( $message ) {
453 echo nl2br( htmlspecialchars( $message ) ) . "\n";
454 die(1);
458 * Exception handler which simulates the appropriate catch() handling:
460 * try {
461 * ...
462 * } catch ( MWException $e ) {
463 * $e->report();
464 * } catch ( Exception $e ) {
465 * echo $e->__toString();
468 public static function handle( $e ) {
469 global $wgFullyInitialised;
471 self::report( $e );
473 // Final cleanup
474 if ( $wgFullyInitialised ) {
475 try {
476 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
477 } catch ( Exception $e ) {}
480 // Exit value should be nonzero for the benefit of shell jobs
481 exit( 1 );