(bug 33321. Sort of) Adding a line to MediaWiki:Sidebar that contains a pipe, but...
[mediawiki.git] / includes / Exception.php
blob08a63ee6bf863e5da8730a291fd9298850a1df1a
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;
79 /**
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 );
93 } else {
94 return wfMsgReplaceArgs( $fallback, $args );
98 /**
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
105 function getHTML() {
106 global $wgShowExceptionDetails;
108 if ( $wgShowExceptionDetails ) {
109 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
110 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
111 "</p>\n";
112 } else {
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.
122 * @return string
124 function getText() {
125 global $wgShowExceptionDetails;
127 if ( $wgShowExceptionDetails ) {
128 return $this->getMessage() .
129 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
130 } else {
131 return "Set \$wgShowExceptionDetails = true; " .
132 "in LocalSettings.php to show detailed debugging information.\n";
137 * Return titles of this error page
138 * @return String
140 function getPageTitle() {
141 return $this->msg( 'internalerror', "Internal error" );
145 * Return the requested URL and point to file and line number from which the
146 * exception occured
148 * @return String
150 function getLogMessage() {
151 global $wgRequest;
153 $file = $this->getFile();
154 $line = $this->getLine();
155 $message = $this->getMessage();
157 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
158 $url = $wgRequest->getRequestURL();
159 if ( !$url ) {
160 $url = '[no URL]';
162 } else {
163 $url = '[no req]';
166 return "$url Exception from line $line of $file: $message";
169 /** Output the exception report using HTML */
170 function reportHTML() {
171 global $wgOut;
172 if ( $this->useOutputPage() ) {
173 $wgOut->prepareErrorPage( $this->getPageTitle() );
175 $hookResult = $this->runHooks( get_class( $this ) );
176 if ( $hookResult ) {
177 $wgOut->addHTML( $hookResult );
178 } else {
179 $wgOut->addHTML( $this->getHTML() );
182 $wgOut->output();
183 } else {
184 header( "Content-Type: text/html; charset=utf-8" );
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();
214 * @static
215 * @return bool
217 static function isCommandLine() {
218 return !empty( $GLOBALS['wgCommandLineMode'] );
223 * Exception class which takes an HTML error message, and does not
224 * produce a backtrace. Replacement for OutputPage::fatalError().
225 * @ingroup Exception
227 class FatalError extends MWException {
230 * @return string
232 function getHTML() {
233 return $this->getMessage();
237 * @return string
239 function getText() {
240 return $this->getMessage();
245 * An error page which can definitely be safely rendered using the OutputPage
246 * @ingroup Exception
248 class ErrorPageError extends MWException {
249 public $title, $msg, $params;
252 * Note: these arguments are keys into wfMsg(), not text!
254 function __construct( $title, $msg, $params = null ) {
255 $this->title = $title;
256 $this->msg = $msg;
257 $this->params = $params;
259 if( $msg instanceof Message ){
260 parent::__construct( $msg );
261 } else {
262 parent::__construct( wfMsg( $msg ) );
266 function report() {
267 global $wgOut;
269 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
270 $wgOut->output();
275 * Show an error when a user tries to do something they do not have the necessary
276 * permissions for.
277 * @ingroup Exception
279 class PermissionsError extends ErrorPageError {
280 public $permission, $errors;
282 function __construct( $permission, $errors = array() ) {
283 global $wgLang;
285 $this->permission = $permission;
287 if ( !count( $errors ) ) {
288 $groups = array_map(
289 array( 'User', 'makeGroupLinkWiki' ),
290 User::getGroupsWithPermission( $this->permission )
293 if ( $groups ) {
294 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
295 } else {
296 $errors[] = array( 'badaccess-group0' );
300 $this->errors = $errors;
303 function report() {
304 global $wgOut;
306 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
307 $wgOut->output();
312 * Show an error when the wiki is locked/read-only and the user tries to do
313 * something that requires write access
314 * @ingroup Exception
316 class ReadOnlyError extends ErrorPageError {
317 public function __construct(){
318 parent::__construct(
319 'readonly',
320 'readonlytext',
321 wfReadOnlyReason()
327 * Show an error when the user hits a rate limit
328 * @ingroup Exception
330 class ThrottledError extends ErrorPageError {
331 public function __construct(){
332 parent::__construct(
333 'actionthrottled',
334 'actionthrottledtext'
338 public function report(){
339 global $wgOut;
340 $wgOut->setStatusCode( 503 );
341 return parent::report();
346 * Show an error when the user tries to do something whilst blocked
347 * @ingroup Exception
349 class UserBlockedError extends ErrorPageError {
350 public function __construct( Block $block ){
351 global $wgLang, $wgRequest;
353 $blocker = $block->getBlocker();
354 if ( $blocker instanceof User ) { // local user
355 $blockerUserpage = $block->getBlocker()->getUserPage();
356 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
357 } else { // foreign user
358 $link = $blocker;
361 $reason = $block->mReason;
362 if( $reason == '' ) {
363 $reason = wfMsg( 'blockednoreason' );
366 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
367 * This could be a username, an IP range, or a single IP. */
368 $intended = $block->getTarget();
370 parent::__construct(
371 'blockedtitle',
372 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
373 array(
374 $link,
375 $reason,
376 $wgRequest->getIP(),
377 $block->getByName(),
378 $block->getId(),
379 $wgLang->formatExpiry( $block->mExpiry ),
380 $intended,
381 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
388 * Show an error that looks like an HTTP server error.
389 * Replacement for wfHttpError().
391 * @ingroup Exception
393 class HttpError extends MWException {
394 private $httpCode, $header, $content;
397 * Constructor
399 * @param $httpCode Integer: HTTP status code to send to the client
400 * @param $content String|Message: content of the message
401 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
403 public function __construct( $httpCode, $content, $header = null ){
404 parent::__construct( $content );
405 $this->httpCode = (int)$httpCode;
406 $this->header = $header;
407 $this->content = $content;
410 public function reportHTML() {
411 $httpMessage = HttpStatus::getMessage( $this->httpCode );
413 header( "Status: {$this->httpCode} {$httpMessage}" );
414 header( 'Content-type: text/html; charset=utf-8' );
416 if ( $this->header === null ) {
417 $header = $httpMessage;
418 } elseif ( $this->header instanceof Message ) {
419 $header = $this->header->escaped();
420 } else {
421 $header = htmlspecialchars( $this->header );
424 if ( $this->content instanceof Message ) {
425 $content = $this->content->escaped();
426 } else {
427 $content = htmlspecialchars( $this->content );
430 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
431 "<html><head><title>$header</title></head>\n" .
432 "<body><h1>$header</h1><p>$content</p></body></html>\n";
437 * Handler class for MWExceptions
438 * @ingroup Exception
440 class MWExceptionHandler {
442 * Install an exception handler for MediaWiki exception types.
444 public static function installHandler() {
445 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
449 * Report an exception to the user
451 protected static function report( Exception $e ) {
452 global $wgShowExceptionDetails;
454 $cmdLine = MWException::isCommandLine();
456 if ( $e instanceof MWException ) {
457 try {
458 // Try and show the exception prettily, with the normal skin infrastructure
459 $e->report();
460 } catch ( Exception $e2 ) {
461 // Exception occurred from within exception handler
462 // Show a simpler error message for the original exception,
463 // don't try to invoke report()
464 $message = "MediaWiki internal error.\n\n";
466 if ( $wgShowExceptionDetails ) {
467 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
468 'Exception caught inside exception handler: ' . $e2->__toString();
469 } else {
470 $message .= "Exception caught inside exception handler.\n\n" .
471 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
472 "to show detailed debugging information.";
475 $message .= "\n";
477 if ( $cmdLine ) {
478 self::printError( $message );
479 } else {
480 self::escapeEchoAndDie( $message );
483 } else {
484 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
485 $e->__toString() . "\n";
487 if ( $wgShowExceptionDetails ) {
488 $message .= "\n" . $e->getTraceAsString() . "\n";
491 if ( $cmdLine ) {
492 self::printError( $message );
493 } else {
494 self::escapeEchoAndDie( $message );
500 * Print a message, if possible to STDERR.
501 * Use this in command line mode only (see isCommandLine)
502 * @param $message String Failure text
504 public static function printError( $message ) {
505 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
506 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
507 if ( defined( 'STDERR' ) ) {
508 fwrite( STDERR, $message );
509 } else {
510 echo( $message );
515 * Print a message after escaping it and converting newlines to <br>
516 * Use this for non-command line failures
517 * @param $message String Failure text
519 private static function escapeEchoAndDie( $message ) {
520 echo nl2br( htmlspecialchars( $message ) ) . "\n";
521 die(1);
525 * Exception handler which simulates the appropriate catch() handling:
527 * try {
528 * ...
529 * } catch ( MWException $e ) {
530 * $e->report();
531 * } catch ( Exception $e ) {
532 * echo $e->__toString();
535 public static function handle( $e ) {
536 global $wgFullyInitialised;
538 self::report( $e );
540 // Final cleanup
541 if ( $wgFullyInitialised ) {
542 try {
543 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
544 } catch ( Exception $e ) {}
547 // Exit value should be nonzero for the benefit of shell jobs
548 exit( 1 );