test SQL for our QueryPages objects
[mediawiki.git] / includes / Exception.php
blob8c4e0a754fa15be1e26e064304cae17798edd3e7
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 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
185 if ( $hookResult ) {
186 die( $hookResult );
189 echo $this->getHTML();
190 die(1);
195 * Output a report about the exception and takes care of formatting.
196 * It will be either HTML or plain text based on isCommandLine().
198 function report() {
199 $log = $this->getLogMessage();
201 if ( $log ) {
202 wfDebugLog( 'exception', $log );
205 if ( self::isCommandLine() ) {
206 MWExceptionHandler::printError( $this->getText() );
207 } else {
208 $this->reportHTML();
213 * @static
214 * @return bool
216 static function isCommandLine() {
217 return !empty( $GLOBALS['wgCommandLineMode'] );
222 * Exception class which takes an HTML error message, and does not
223 * produce a backtrace. Replacement for OutputPage::fatalError().
224 * @ingroup Exception
226 class FatalError extends MWException {
229 * @return string
231 function getHTML() {
232 return $this->getMessage();
236 * @return string
238 function getText() {
239 return $this->getMessage();
244 * An error page which can definitely be safely rendered using the OutputPage
245 * @ingroup Exception
247 class ErrorPageError extends MWException {
248 public $title, $msg, $params;
251 * Note: these arguments are keys into wfMsg(), not text!
253 function __construct( $title, $msg, $params = null ) {
254 $this->title = $title;
255 $this->msg = $msg;
256 $this->params = $params;
258 if( $msg instanceof Message ){
259 parent::__construct( $msg );
260 } else {
261 parent::__construct( wfMsg( $msg ) );
265 function report() {
266 global $wgOut;
268 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
269 $wgOut->output();
274 * Show an error when a user tries to do something they do not have the necessary
275 * permissions for.
276 * @ingroup Exception
278 class PermissionsError extends ErrorPageError {
279 public $permission, $errors;
281 function __construct( $permission, $errors = array() ) {
282 global $wgLang;
284 $this->permission = $permission;
286 if ( !count( $errors ) ) {
287 $groups = array_map(
288 array( 'User', 'makeGroupLinkWiki' ),
289 User::getGroupsWithPermission( $this->permission )
292 if ( $groups ) {
293 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
294 } else {
295 $errors[] = array( 'badaccess-group0' );
299 $this->errors = $errors;
302 function report() {
303 global $wgOut;
305 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
306 $wgOut->output();
311 * Show an error when the wiki is locked/read-only and the user tries to do
312 * something that requires write access
313 * @ingroup Exception
315 class ReadOnlyError extends ErrorPageError {
316 public function __construct(){
317 parent::__construct(
318 'readonly',
319 'readonlytext',
320 wfReadOnlyReason()
326 * Show an error when the user hits a rate limit
327 * @ingroup Exception
329 class ThrottledError extends ErrorPageError {
330 public function __construct(){
331 parent::__construct(
332 'actionthrottled',
333 'actionthrottledtext'
337 public function report(){
338 global $wgOut;
339 $wgOut->setStatusCode( 503 );
340 return parent::report();
345 * Show an error when the user tries to do something whilst blocked
346 * @ingroup Exception
348 class UserBlockedError extends ErrorPageError {
349 public function __construct( Block $block ){
350 global $wgLang, $wgRequest;
352 $blocker = $block->getBlocker();
353 if ( $blocker instanceof User ) { // local user
354 $blockerUserpage = $block->getBlocker()->getUserPage();
355 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
356 } else { // foreign user
357 $link = $blocker;
360 $reason = $block->mReason;
361 if( $reason == '' ) {
362 $reason = wfMsg( 'blockednoreason' );
365 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
366 * This could be a username, an IP range, or a single IP. */
367 $intended = $block->getTarget();
369 parent::__construct(
370 'blockedtitle',
371 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
372 array(
373 $link,
374 $reason,
375 $wgRequest->getIP(),
376 $block->getByName(),
377 $block->getId(),
378 $wgLang->formatExpiry( $block->mExpiry ),
379 $intended,
380 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
387 * Show an error that looks like an HTTP server error.
388 * Replacement for wfHttpError().
390 * @ingroup Exception
392 class HttpError extends MWException {
393 private $httpCode, $header, $content;
396 * Constructor
398 * @param $httpCode Integer: HTTP status code to send to the client
399 * @param $content String|Message: content of the message
400 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
402 public function __construct( $httpCode, $content, $header = null ){
403 parent::__construct( $content );
404 $this->httpCode = (int)$httpCode;
405 $this->header = $header;
406 $this->content = $content;
409 public function reportHTML() {
410 $httpMessage = HttpStatus::getMessage( $this->httpCode );
412 header( "Status: {$this->httpCode} {$httpMessage}" );
413 header( 'Content-type: text/html; charset=utf-8' );
415 if ( $this->header === null ) {
416 $header = $httpMessage;
417 } elseif ( $this->header instanceof Message ) {
418 $header = $this->header->escaped();
419 } else {
420 $header = htmlspecialchars( $this->header );
423 if ( $this->content instanceof Message ) {
424 $content = $this->content->escaped();
425 } else {
426 $content = htmlspecialchars( $this->content );
429 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
430 "<html><head><title>$header</title></head>\n" .
431 "<body><h1>$header</h1><p>$content</p></body></html>\n";
436 * Handler class for MWExceptions
437 * @ingroup Exception
439 class MWExceptionHandler {
441 * Install an exception handler for MediaWiki exception types.
443 public static function installHandler() {
444 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
448 * Report an exception to the user
450 protected static function report( Exception $e ) {
451 global $wgShowExceptionDetails;
453 $cmdLine = MWException::isCommandLine();
455 if ( $e instanceof MWException ) {
456 try {
457 // Try and show the exception prettily, with the normal skin infrastructure
458 $e->report();
459 } catch ( Exception $e2 ) {
460 // Exception occurred from within exception handler
461 // Show a simpler error message for the original exception,
462 // don't try to invoke report()
463 $message = "MediaWiki internal error.\n\n";
465 if ( $wgShowExceptionDetails ) {
466 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
467 'Exception caught inside exception handler: ' . $e2->__toString();
468 } else {
469 $message .= "Exception caught inside exception handler.\n\n" .
470 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
471 "to show detailed debugging information.";
474 $message .= "\n";
476 if ( $cmdLine ) {
477 self::printError( $message );
478 } else {
479 self::escapeEchoAndDie( $message );
482 } else {
483 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
484 $e->__toString() . "\n";
486 if ( $wgShowExceptionDetails ) {
487 $message .= "\n" . $e->getTraceAsString() . "\n";
490 if ( $cmdLine ) {
491 self::printError( $message );
492 } else {
493 self::escapeEchoAndDie( $message );
499 * Print a message, if possible to STDERR.
500 * Use this in command line mode only (see isCommandLine)
501 * @param $message String Failure text
503 public static function printError( $message ) {
504 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
505 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
506 if ( defined( 'STDERR' ) ) {
507 fwrite( STDERR, $message );
508 } else {
509 echo( $message );
514 * Print a message after escaping it and converting newlines to <br>
515 * Use this for non-command line failures
516 * @param $message String Failure text
518 private static function escapeEchoAndDie( $message ) {
519 echo nl2br( htmlspecialchars( $message ) ) . "\n";
520 die(1);
524 * Exception handler which simulates the appropriate catch() handling:
526 * try {
527 * ...
528 * } catch ( MWException $e ) {
529 * $e->report();
530 * } catch ( Exception $e ) {
531 * echo $e->__toString();
534 public static function handle( $e ) {
535 global $wgFullyInitialised;
537 self::report( $e );
539 // Final cleanup
540 if ( $wgFullyInitialised ) {
541 try {
542 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
543 } catch ( Exception $e ) {}
546 // Exit value should be nonzero for the benefit of shell jobs
547 exit( 1 );