Add getters to HttpError, to use it in tests.
[lhc/web/wiklou.git] / includes / Exception.php
1 <?php
2 /**
3 * Exception class and handler.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * @defgroup Exception Exception
25 */
26
27 /**
28 * MediaWiki exception
29 *
30 * @ingroup Exception
31 */
32 class MWException extends Exception {
33 var $logId;
34
35 /**
36 * Should the exception use $wgOut to output the error?
37 *
38 * @return bool
39 */
40 function useOutputPage() {
41 return $this->useMessageCache() &&
42 !empty( $GLOBALS['wgFullyInitialised'] ) &&
43 !empty( $GLOBALS['wgOut'] ) &&
44 !empty( $GLOBALS['wgTitle'] );
45 }
46
47 /**
48 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
49 *
50 * @return bool
51 */
52 function useMessageCache() {
53 global $wgLang;
54
55 foreach ( $this->getTrace() as $frame ) {
56 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
57 return false;
58 }
59 }
60
61 return $wgLang instanceof Language;
62 }
63
64 /**
65 * Run hook to allow extensions to modify the text of the exception
66 *
67 * @param $name string: class name of the exception
68 * @param $args array: arguments to pass to the callback functions
69 * @return string|null string to output or null if any hook has been called
70 */
71 function runHooks( $name, $args = array() ) {
72 global $wgExceptionHooks;
73
74 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
75 return null; // Just silently ignore
76 }
77
78 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
79 return null;
80 }
81
82 $hooks = $wgExceptionHooks[ $name ];
83 $callargs = array_merge( array( $this ), $args );
84
85 foreach ( $hooks as $hook ) {
86 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
87 $result = call_user_func_array( $hook, $callargs );
88 } else {
89 $result = null;
90 }
91
92 if ( is_string( $result ) ) {
93 return $result;
94 }
95 }
96 return null;
97 }
98
99 /**
100 * Get a message from i18n
101 *
102 * @param $key string: message name
103 * @param $fallback string: default message if the message cache can't be
104 * called by the exception
105 * The function also has other parameters that are arguments for the message
106 * @return string message with arguments replaced
107 */
108 function msg( $key, $fallback /*[, params...] */ ) {
109 $args = array_slice( func_get_args(), 2 );
110
111 if ( $this->useMessageCache() ) {
112 return wfMessage( $key, $args )->plain();
113 } else {
114 return wfMsgReplaceArgs( $fallback, $args );
115 }
116 }
117
118 /**
119 * If $wgShowExceptionDetails is true, return a HTML message with a
120 * backtrace to the error, otherwise show a message to ask to set it to true
121 * to show that information.
122 *
123 * @return string html to output
124 */
125 function getHTML() {
126 global $wgShowExceptionDetails;
127
128 if ( $wgShowExceptionDetails ) {
129 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
130 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
131 "</p>\n";
132 } else {
133 return
134 "<div class=\"errorbox\">" .
135 '[' . $this->getLogId() . '] ' .
136 gmdate( 'Y-m-d H:i:s' ) .
137 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
138 "<!-- Set \$wgShowExceptionDetails = true; " .
139 "at the bottom of LocalSettings.php to show detailed " .
140 "debugging information. -->";
141 }
142 }
143
144 /**
145 * Get the text to display when reporting the error on the command line.
146 * If $wgShowExceptionDetails is true, return a text message with a
147 * backtrace to the error.
148 *
149 * @return string
150 */
151 function getText() {
152 global $wgShowExceptionDetails;
153
154 if ( $wgShowExceptionDetails ) {
155 return $this->getMessage() .
156 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
157 } else {
158 return "Set \$wgShowExceptionDetails = true; " .
159 "in LocalSettings.php to show detailed debugging information.\n";
160 }
161 }
162
163 /**
164 * Return the title of the page when reporting this error in a HTTP response.
165 *
166 * @return string
167 */
168 function getPageTitle() {
169 return $this->msg( 'internalerror', "Internal error" );
170 }
171
172 /**
173 * Get a random ID for this error.
174 * This allows to link the exception to its correspoding log entry when
175 * $wgShowExceptionDetails is set to false.
176 *
177 * @return string
178 */
179 function getLogId() {
180 if ( $this->logId === null ) {
181 $this->logId = wfRandomString( 8 );
182 }
183 return $this->logId;
184 }
185
186 /**
187 * Return the requested URL and point to file and line number from which the
188 * exception occurred
189 *
190 * @return string
191 */
192 function getLogMessage() {
193 global $wgRequest;
194
195 $id = $this->getLogId();
196 $file = $this->getFile();
197 $line = $this->getLine();
198 $message = $this->getMessage();
199
200 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
201 $url = $wgRequest->getRequestURL();
202 if ( !$url ) {
203 $url = '[no URL]';
204 }
205 } else {
206 $url = '[no req]';
207 }
208
209 return "[$id] $url Exception from line $line of $file: $message";
210 }
211
212 /**
213 * Output the exception report using HTML.
214 */
215 function reportHTML() {
216 global $wgOut;
217 if ( $this->useOutputPage() ) {
218 $wgOut->prepareErrorPage( $this->getPageTitle() );
219
220 $hookResult = $this->runHooks( get_class( $this ) );
221 if ( $hookResult ) {
222 $wgOut->addHTML( $hookResult );
223 } else {
224 $wgOut->addHTML( $this->getHTML() );
225 }
226
227 $wgOut->output();
228 } else {
229 header( "Content-Type: text/html; charset=utf-8" );
230 echo "<!doctype html>\n" .
231 '<html><head>' .
232 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
233 "</head><body>\n";
234
235 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
236 if ( $hookResult ) {
237 echo $hookResult;
238 } else {
239 echo $this->getHTML();
240 }
241
242 echo "</body></html>\n";
243 }
244 }
245
246 /**
247 * Output a report about the exception and takes care of formatting.
248 * It will be either HTML or plain text based on isCommandLine().
249 */
250 function report() {
251 global $wgLogExceptionBacktrace;
252 $log = $this->getLogMessage();
253
254 if ( $log ) {
255 if ( $wgLogExceptionBacktrace ) {
256 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
257 } else {
258 wfDebugLog( 'exception', $log );
259 }
260 }
261
262 if ( defined( 'MW_API' ) ) {
263 // Unhandled API exception, we can't be sure that format printer is alive
264 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
265 wfHttpError(500, 'Internal Server Error', $this->getText() );
266 } elseif ( self::isCommandLine() ) {
267 MWExceptionHandler::printError( $this->getText() );
268 } else {
269 header( "HTTP/1.1 500 MediaWiki exception" );
270 header( "Status: 500 MediaWiki exception", true );
271
272 $this->reportHTML();
273 }
274 }
275
276 /**
277 * Check whether we are in command line mode or not to report the exception
278 * in the correct format.
279 *
280 * @return bool
281 */
282 static function isCommandLine() {
283 return !empty( $GLOBALS['wgCommandLineMode'] );
284 }
285 }
286
287 /**
288 * Exception class which takes an HTML error message, and does not
289 * produce a backtrace. Replacement for OutputPage::fatalError().
290 *
291 * @since 1.7
292 * @ingroup Exception
293 */
294 class FatalError extends MWException {
295
296 /**
297 * @return string
298 */
299 function getHTML() {
300 return $this->getMessage();
301 }
302
303 /**
304 * @return string
305 */
306 function getText() {
307 return $this->getMessage();
308 }
309 }
310
311 /**
312 * An error page which can definitely be safely rendered using the OutputPage.
313 *
314 * @since 1.7
315 * @ingroup Exception
316 */
317 class ErrorPageError extends MWException {
318 public $title, $msg, $params;
319
320 /**
321 * Note: these arguments are keys into wfMessage(), not text!
322 *
323 * @param $title string|Message Message key (string) for page title, or a Message object
324 * @param $msg string|Message Message key (string) for error text, or a Message object
325 * @param $params array with parameters to wfMessage()
326 */
327 function __construct( $title, $msg, $params = null ) {
328 $this->title = $title;
329 $this->msg = $msg;
330 $this->params = $params;
331
332 if( $msg instanceof Message ) {
333 parent::__construct( $msg );
334 } else {
335 parent::__construct( wfMessage( $msg )->text() );
336 }
337 }
338
339 function report() {
340 global $wgOut;
341
342 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
343 $wgOut->output();
344 }
345 }
346
347 /**
348 * Show an error page on a badtitle.
349 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
350 * browser it is not really a valid content.
351 *
352 * @since 1.19
353 * @ingroup Exception
354 */
355 class BadTitleError extends ErrorPageError {
356 /**
357 * @param $msg string|Message A message key (default: 'badtitletext')
358 * @param $params Array parameter to wfMessage()
359 */
360 function __construct( $msg = 'badtitletext', $params = null ) {
361 parent::__construct( 'badtitle', $msg, $params );
362 }
363
364 /**
365 * Just like ErrorPageError::report() but additionally set
366 * a 400 HTTP status code (bug 33646).
367 */
368 function report() {
369 global $wgOut;
370
371 // bug 33646: a badtitle error page need to return an error code
372 // to let mobile browser now that it is not a normal page.
373 $wgOut->setStatusCode( 400 );
374 parent::report();
375 }
376
377 }
378
379 /**
380 * Show an error when a user tries to do something they do not have the necessary
381 * permissions for.
382 *
383 * @since 1.18
384 * @ingroup Exception
385 */
386 class PermissionsError extends ErrorPageError {
387 public $permission, $errors;
388
389 function __construct( $permission, $errors = array() ) {
390 global $wgLang;
391
392 $this->permission = $permission;
393
394 if ( !count( $errors ) ) {
395 $groups = array_map(
396 array( 'User', 'makeGroupLinkWiki' ),
397 User::getGroupsWithPermission( $this->permission )
398 );
399
400 if ( $groups ) {
401 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
402 } else {
403 $errors[] = array( 'badaccess-group0' );
404 }
405 }
406
407 $this->errors = $errors;
408 }
409
410 function report() {
411 global $wgOut;
412
413 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
414 $wgOut->output();
415 }
416 }
417
418 /**
419 * Show an error when the wiki is locked/read-only and the user tries to do
420 * something that requires write access.
421 *
422 * @since 1.18
423 * @ingroup Exception
424 */
425 class ReadOnlyError extends ErrorPageError {
426 public function __construct() {
427 parent::__construct(
428 'readonly',
429 'readonlytext',
430 wfReadOnlyReason()
431 );
432 }
433 }
434
435 /**
436 * Show an error when the user hits a rate limit.
437 *
438 * @since 1.18
439 * @ingroup Exception
440 */
441 class ThrottledError extends ErrorPageError {
442 public function __construct() {
443 parent::__construct(
444 'actionthrottled',
445 'actionthrottledtext'
446 );
447 }
448
449 public function report() {
450 global $wgOut;
451 $wgOut->setStatusCode( 503 );
452 parent::report();
453 }
454 }
455
456 /**
457 * Show an error when the user tries to do something whilst blocked.
458 *
459 * @since 1.18
460 * @ingroup Exception
461 */
462 class UserBlockedError extends ErrorPageError {
463 public function __construct( Block $block ) {
464 global $wgLang, $wgRequest;
465
466 $blocker = $block->getBlocker();
467 if ( $blocker instanceof User ) { // local user
468 $blockerUserpage = $block->getBlocker()->getUserPage();
469 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
470 } else { // foreign user
471 $link = $blocker;
472 }
473
474 $reason = $block->mReason;
475 if( $reason == '' ) {
476 $reason = wfMessage( 'blockednoreason' )->text();
477 }
478
479 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
480 * This could be a username, an IP range, or a single IP. */
481 $intended = $block->getTarget();
482
483 parent::__construct(
484 'blockedtitle',
485 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
486 array(
487 $link,
488 $reason,
489 $wgRequest->getIP(),
490 $block->getByName(),
491 $block->getId(),
492 $wgLang->formatExpiry( $block->mExpiry ),
493 $intended,
494 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
495 )
496 );
497 }
498 }
499
500 /**
501 * Shows a generic "user is not logged in" error page.
502 *
503 * This is essentially an ErrorPageError exception which by default uses the
504 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
505 * @see bug 37627
506 * @since 1.20
507 *
508 * @par Example:
509 * @code
510 * if( $user->isAnon() ) {
511 * throw new UserNotLoggedIn();
512 * }
513 * @endcode
514 *
515 * Note the parameter order differs from ErrorPageError, this allows you to
516 * simply specify a reason without overriding the default title.
517 *
518 * @par Example:
519 * @code
520 * if( $user->isAnon() ) {
521 * throw new UserNotLoggedIn( 'action-require-loggedin' );
522 * }
523 * @endcode
524 *
525 * @ingroup Exception
526 */
527 class UserNotLoggedIn extends ErrorPageError {
528
529 /**
530 * @param $reasonMsg A message key containing the reason for the error.
531 * Optional, default: 'exception-nologin-text'
532 * @param $titleMsg A message key to set the page title.
533 * Optional, default: 'exception-nologin'
534 * @param $params Parameters to wfMessage().
535 * Optional, default: null
536 */
537 public function __construct(
538 $reasonMsg = 'exception-nologin-text',
539 $titleMsg = 'exception-nologin',
540 $params = null
541 ) {
542 parent::__construct( $titleMsg, $reasonMsg, $params );
543 }
544 }
545
546 /**
547 * Show an error that looks like an HTTP server error.
548 * Replacement for wfHttpError().
549 *
550 * @since 1.19
551 * @ingroup Exception
552 */
553 class HttpError extends MWException {
554 private $httpCode, $header, $content;
555
556 /**
557 * Constructor
558 *
559 * @param $httpCode Integer: HTTP status code to send to the client
560 * @param $content String|Message: content of the message
561 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
562 */
563 public function __construct( $httpCode, $content, $header = null ) {
564 parent::__construct( $content );
565 $this->httpCode = (int)$httpCode;
566 $this->header = $header;
567 $this->content = $content;
568 }
569
570 /**
571 * Returns the HTTP status code supplied to the constructor.
572 *
573 * @return int
574 */
575 public function getStatusCode() {
576 $this->httpCode;
577 }
578
579 /**
580 * Report the HTTP error.
581 * Sends the appropriate HTTP status code and outputs an
582 * HTML page with an error message.
583 */
584 public function report() {
585 $httpMessage = HttpStatus::getMessage( $this->httpCode );
586
587 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode );
588 header( 'Content-type: text/html; charset=utf-8' );
589
590 print $this->getHTML();
591 }
592
593 /**
594 * Returns HTML for reporting the HTTP error.
595 * This will be a minimal but complete HTML document.
596 *
597 * @return string HTML
598 */
599 public function getHTML() {
600 if ( $this->header === null ) {
601 $header = HttpStatus::getMessage( $this->httpCode );
602 } elseif ( $this->header instanceof Message ) {
603 $header = $this->header->escaped();
604 } else {
605 $header = htmlspecialchars( $this->header );
606 }
607
608 if ( $this->content instanceof Message ) {
609 $content = $this->content->escaped();
610 } else {
611 $content = htmlspecialchars( $this->content );
612 }
613
614 return "<!DOCTYPE html>\n".
615 "<html><head><title>$header</title></head>\n" .
616 "<body><h1>$header</h1><p>$content</p></body></html>\n";
617 }
618 }
619
620 /**
621 * Handler class for MWExceptions
622 * @ingroup Exception
623 */
624 class MWExceptionHandler {
625 /**
626 * Install an exception handler for MediaWiki exception types.
627 */
628 public static function installHandler() {
629 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
630 }
631
632 /**
633 * Report an exception to the user
634 */
635 protected static function report( Exception $e ) {
636 global $wgShowExceptionDetails;
637
638 $cmdLine = MWException::isCommandLine();
639
640 if ( $e instanceof MWException ) {
641 try {
642 // Try and show the exception prettily, with the normal skin infrastructure
643 $e->report();
644 } catch ( Exception $e2 ) {
645 // Exception occurred from within exception handler
646 // Show a simpler error message for the original exception,
647 // don't try to invoke report()
648 $message = "MediaWiki internal error.\n\n";
649
650 if ( $wgShowExceptionDetails ) {
651 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
652 'Exception caught inside exception handler: ' . $e2->__toString();
653 } else {
654 $message .= "Exception caught inside exception handler.\n\n" .
655 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
656 "to show detailed debugging information.";
657 }
658
659 $message .= "\n";
660
661 if ( $cmdLine ) {
662 self::printError( $message );
663 } else {
664 echo nl2br( htmlspecialchars( $message ) ) . "\n";
665 }
666 }
667 } else {
668 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
669 $e->__toString() . "\n";
670
671 if ( $wgShowExceptionDetails ) {
672 $message .= "\n" . $e->getTraceAsString() . "\n";
673 }
674
675 if ( $cmdLine ) {
676 self::printError( $message );
677 } else {
678 echo nl2br( htmlspecialchars( $message ) ) . "\n";
679 }
680 }
681 }
682
683 /**
684 * Print a message, if possible to STDERR.
685 * Use this in command line mode only (see isCommandLine)
686 *
687 * @param $message string Failure text
688 */
689 public static function printError( $message ) {
690 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
691 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
692 if ( defined( 'STDERR' ) ) {
693 fwrite( STDERR, $message );
694 } else {
695 echo( $message );
696 }
697 }
698
699 /**
700 * Exception handler which simulates the appropriate catch() handling:
701 *
702 * try {
703 * ...
704 * } catch ( MWException $e ) {
705 * $e->report();
706 * } catch ( Exception $e ) {
707 * echo $e->__toString();
708 * }
709 */
710 public static function handle( $e ) {
711 global $wgFullyInitialised;
712
713 self::report( $e );
714
715 // Final cleanup
716 if ( $wgFullyInitialised ) {
717 try {
718 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
719 } catch ( Exception $e ) {}
720 }
721
722 // Exit value should be nonzero for the benefit of shell jobs
723 exit( 1 );
724 }
725 }