Merge "Add new recentchanges field rc_source to replace rc_type"
[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
34 /**
35 * Should the exception use $wgOut to output the error?
36 *
37 * @return bool
38 */
39 function useOutputPage() {
40 return $this->useMessageCache() &&
41 !empty( $GLOBALS['wgFullyInitialised'] ) &&
42 !empty( $GLOBALS['wgOut'] ) &&
43 !empty( $GLOBALS['wgTitle'] );
44 }
45
46 /**
47 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
48 *
49 * @return bool
50 */
51 function useMessageCache() {
52 global $wgLang;
53
54 foreach ( $this->getTrace() as $frame ) {
55 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
56 return false;
57 }
58 }
59
60 return $wgLang instanceof Language;
61 }
62
63 /**
64 * Run hook to allow extensions to modify the text of the exception
65 *
66 * @param string $name class name of the exception
67 * @param array $args arguments to pass to the callback functions
68 * @return string|null string to output or null if any hook has been called
69 */
70 function runHooks( $name, $args = array() ) {
71 global $wgExceptionHooks;
72
73 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
74 return null; // Just silently ignore
75 }
76
77 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[$name] ) ) {
78 return null;
79 }
80
81 $hooks = $wgExceptionHooks[$name];
82 $callargs = array_merge( array( $this ), $args );
83
84 foreach ( $hooks as $hook ) {
85 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
86 $result = call_user_func_array( $hook, $callargs );
87 } else {
88 $result = null;
89 }
90
91 if ( is_string( $result ) ) {
92 return $result;
93 }
94 }
95 return null;
96 }
97
98 /**
99 * Get a message from i18n
100 *
101 * @param string $key message name
102 * @param string $fallback default message if the message cache can't be
103 * called by the exception
104 * The function also has other parameters that are arguments for the message
105 * @return string message with arguments replaced
106 */
107 function msg( $key, $fallback /*[, params...] */ ) {
108 $args = array_slice( func_get_args(), 2 );
109
110 if ( $this->useMessageCache() ) {
111 return wfMessage( $key, $args )->plain();
112 } else {
113 return wfMsgReplaceArgs( $fallback, $args );
114 }
115 }
116
117 /**
118 * If $wgShowExceptionDetails is true, return a HTML message with a
119 * backtrace to the error, otherwise show a message to ask to set it to true
120 * to show that information.
121 *
122 * @return string html to output
123 */
124 function getHTML() {
125 global $wgShowExceptionDetails;
126
127 if ( $wgShowExceptionDetails ) {
128 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
129 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( MWExceptionHandler::formatRedactedTrace( $this ) ) ) .
130 "</p>\n";
131 } else {
132 return "<div class=\"errorbox\">" .
133 '[' . MWExceptionHandler::getLogId( $this ) . '] ' .
134 gmdate( 'Y-m-d H:i:s' ) .
135 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
136 "<!-- Set \$wgShowExceptionDetails = true; " .
137 "at the bottom of LocalSettings.php to show detailed " .
138 "debugging information. -->";
139 }
140 }
141
142 /**
143 * Get the text to display when reporting the error on the command line.
144 * If $wgShowExceptionDetails is true, return a text message with a
145 * backtrace to the error.
146 *
147 * @return string
148 */
149 function getText() {
150 global $wgShowExceptionDetails;
151
152 if ( $wgShowExceptionDetails ) {
153 return $this->getMessage() .
154 "\nBacktrace:\n" . MWExceptionHandler::formatRedactedTrace( $this ) . "\n";
155 } else {
156 return "Set \$wgShowExceptionDetails = true; " .
157 "in LocalSettings.php to show detailed debugging information.\n";
158 }
159 }
160
161 /**
162 * Return the title of the page when reporting this error in a HTTP response.
163 *
164 * @return string
165 */
166 function getPageTitle() {
167 return $this->msg( 'internalerror', "Internal error" );
168 }
169
170 /**
171 * Get a the ID for this error.
172 *
173 * @since 1.20
174 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
175 * @return string
176 */
177 function getLogId() {
178 wfDeprecated( __METHOD__, '1.22' );
179 return MWExceptionHandler::getLogId( $this );
180 }
181
182 /**
183 * Return the requested URL and point to file and line number from which the
184 * exception occurred
185 *
186 * @since 1.8
187 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
188 * @return string
189 */
190 function getLogMessage() {
191 wfDeprecated( __METHOD__, '1.22' );
192 return MWExceptionHandler::getLogMessage( $this );
193 }
194
195 /**
196 * Output the exception report using HTML.
197 */
198 function reportHTML() {
199 global $wgOut;
200 if ( $this->useOutputPage() ) {
201 $wgOut->prepareErrorPage( $this->getPageTitle() );
202
203 $hookResult = $this->runHooks( get_class( $this ) );
204 if ( $hookResult ) {
205 $wgOut->addHTML( $hookResult );
206 } else {
207 $wgOut->addHTML( $this->getHTML() );
208 }
209
210 $wgOut->output();
211 } else {
212 header( "Content-Type: text/html; charset=utf-8" );
213 echo "<!doctype html>\n" .
214 '<html><head>' .
215 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
216 "</head><body>\n";
217
218 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
219 if ( $hookResult ) {
220 echo $hookResult;
221 } else {
222 echo $this->getHTML();
223 }
224
225 echo "</body></html>\n";
226 }
227 }
228
229 /**
230 * Output a report about the exception and takes care of formatting.
231 * It will be either HTML or plain text based on isCommandLine().
232 */
233 function report() {
234 global $wgMimeType;
235
236 MWExceptionHandler::logException( $this );
237
238 if ( defined( 'MW_API' ) ) {
239 // Unhandled API exception, we can't be sure that format printer is alive
240 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
241 wfHttpError( 500, 'Internal Server Error', $this->getText() );
242 } elseif ( self::isCommandLine() ) {
243 MWExceptionHandler::printError( $this->getText() );
244 } else {
245 header( "HTTP/1.1 500 MediaWiki exception" );
246 header( "Status: 500 MediaWiki exception", true );
247 header( "Content-Type: $wgMimeType; charset=utf-8", true );
248
249 $this->reportHTML();
250 }
251 }
252
253 /**
254 * Check whether we are in command line mode or not to report the exception
255 * in the correct format.
256 *
257 * @return bool
258 */
259 static function isCommandLine() {
260 return !empty( $GLOBALS['wgCommandLineMode'] );
261 }
262 }
263
264 /**
265 * Exception class which takes an HTML error message, and does not
266 * produce a backtrace. Replacement for OutputPage::fatalError().
267 *
268 * @since 1.7
269 * @ingroup Exception
270 */
271 class FatalError extends MWException {
272
273 /**
274 * @return string
275 */
276 function getHTML() {
277 return $this->getMessage();
278 }
279
280 /**
281 * @return string
282 */
283 function getText() {
284 return $this->getMessage();
285 }
286 }
287
288 /**
289 * An error page which can definitely be safely rendered using the OutputPage.
290 *
291 * @since 1.7
292 * @ingroup Exception
293 */
294 class ErrorPageError extends MWException {
295 public $title, $msg, $params;
296
297 /**
298 * Note: these arguments are keys into wfMessage(), not text!
299 *
300 * @param string|Message $title Message key (string) for page title, or a Message object
301 * @param string|Message $msg Message key (string) for error text, or a Message object
302 * @param array $params with parameters to wfMessage()
303 */
304 function __construct( $title, $msg, $params = null ) {
305 $this->title = $title;
306 $this->msg = $msg;
307 $this->params = $params;
308
309 // Bug 44111: Messages in the log files should be in English and not
310 // customized by the local wiki. So get the default English version for
311 // passing to the parent constructor. Our overridden report() below
312 // makes sure that the page shown to the user is not forced to English.
313 if ( $msg instanceof Message ) {
314 $enMsg = clone( $msg );
315 } else {
316 $enMsg = wfMessage( $msg, $params );
317 }
318 $enMsg->inLanguage( 'en' )->useDatabase( false );
319 parent::__construct( $enMsg->text() );
320 }
321
322 function report() {
323 global $wgOut;
324
325 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
326 $wgOut->output();
327 }
328 }
329
330 /**
331 * Show an error page on a badtitle.
332 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
333 * browser it is not really a valid content.
334 *
335 * @since 1.19
336 * @ingroup Exception
337 */
338 class BadTitleError extends ErrorPageError {
339 /**
340 * @param string|Message $msg A message key (default: 'badtitletext')
341 * @param array $params parameter to wfMessage()
342 */
343 function __construct( $msg = 'badtitletext', $params = null ) {
344 parent::__construct( 'badtitle', $msg, $params );
345 }
346
347 /**
348 * Just like ErrorPageError::report() but additionally set
349 * a 400 HTTP status code (bug 33646).
350 */
351 function report() {
352 global $wgOut;
353
354 // bug 33646: a badtitle error page need to return an error code
355 // to let mobile browser now that it is not a normal page.
356 $wgOut->setStatusCode( 400 );
357 parent::report();
358 }
359
360 }
361
362 /**
363 * Show an error when a user tries to do something they do not have the necessary
364 * permissions for.
365 *
366 * @since 1.18
367 * @ingroup Exception
368 */
369 class PermissionsError extends ErrorPageError {
370 public $permission, $errors;
371
372 function __construct( $permission, $errors = array() ) {
373 global $wgLang;
374
375 $this->permission = $permission;
376
377 if ( !count( $errors ) ) {
378 $groups = array_map(
379 array( 'User', 'makeGroupLinkWiki' ),
380 User::getGroupsWithPermission( $this->permission )
381 );
382
383 if ( $groups ) {
384 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
385 } else {
386 $errors[] = array( 'badaccess-group0' );
387 }
388 }
389
390 $this->errors = $errors;
391 }
392
393 function report() {
394 global $wgOut;
395
396 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
397 $wgOut->output();
398 }
399 }
400
401 /**
402 * Show an error when the wiki is locked/read-only and the user tries to do
403 * something that requires write access.
404 *
405 * @since 1.18
406 * @ingroup Exception
407 */
408 class ReadOnlyError extends ErrorPageError {
409 public function __construct() {
410 parent::__construct(
411 'readonly',
412 'readonlytext',
413 wfReadOnlyReason()
414 );
415 }
416 }
417
418 /**
419 * Show an error when the user hits a rate limit.
420 *
421 * @since 1.18
422 * @ingroup Exception
423 */
424 class ThrottledError extends ErrorPageError {
425 public function __construct() {
426 parent::__construct(
427 'actionthrottled',
428 'actionthrottledtext'
429 );
430 }
431
432 public function report() {
433 global $wgOut;
434 $wgOut->setStatusCode( 503 );
435 parent::report();
436 }
437 }
438
439 /**
440 * Show an error when the user tries to do something whilst blocked.
441 *
442 * @since 1.18
443 * @ingroup Exception
444 */
445 class UserBlockedError extends ErrorPageError {
446 public function __construct( Block $block ) {
447 // @todo FIXME: Implement a more proper way to get context here.
448 $params = $block->getPermissionsError( RequestContext::getMain() );
449 parent::__construct( 'blockedtitle', array_shift( $params ), $params );
450 }
451 }
452
453 /**
454 * Shows a generic "user is not logged in" error page.
455 *
456 * This is essentially an ErrorPageError exception which by default uses the
457 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
458 * @see bug 37627
459 * @since 1.20
460 *
461 * @par Example:
462 * @code
463 * if( $user->isAnon() ) {
464 * throw new UserNotLoggedIn();
465 * }
466 * @endcode
467 *
468 * Note the parameter order differs from ErrorPageError, this allows you to
469 * simply specify a reason without overriding the default title.
470 *
471 * @par Example:
472 * @code
473 * if( $user->isAnon() ) {
474 * throw new UserNotLoggedIn( 'action-require-loggedin' );
475 * }
476 * @endcode
477 *
478 * @ingroup Exception
479 */
480 class UserNotLoggedIn extends ErrorPageError {
481
482 /**
483 * @param $reasonMsg A message key containing the reason for the error.
484 * Optional, default: 'exception-nologin-text'
485 * @param $titleMsg A message key to set the page title.
486 * Optional, default: 'exception-nologin'
487 * @param $params Parameters to wfMessage().
488 * Optional, default: null
489 */
490 public function __construct(
491 $reasonMsg = 'exception-nologin-text',
492 $titleMsg = 'exception-nologin',
493 $params = null
494 ) {
495 parent::__construct( $titleMsg, $reasonMsg, $params );
496 }
497 }
498
499 /**
500 * Show an error that looks like an HTTP server error.
501 * Replacement for wfHttpError().
502 *
503 * @since 1.19
504 * @ingroup Exception
505 */
506 class HttpError extends MWException {
507 private $httpCode, $header, $content;
508
509 /**
510 * Constructor
511 *
512 * @param $httpCode Integer: HTTP status code to send to the client
513 * @param string|Message $content content of the message
514 * @param string|Message $header content of the header (\<title\> and \<h1\>)
515 */
516 public function __construct( $httpCode, $content, $header = null ) {
517 parent::__construct( $content );
518 $this->httpCode = (int)$httpCode;
519 $this->header = $header;
520 $this->content = $content;
521 }
522
523 /**
524 * Returns the HTTP status code supplied to the constructor.
525 *
526 * @return int
527 */
528 public function getStatusCode() {
529 return $this->httpCode;
530 }
531
532 /**
533 * Report the HTTP error.
534 * Sends the appropriate HTTP status code and outputs an
535 * HTML page with an error message.
536 */
537 public function report() {
538 $httpMessage = HttpStatus::getMessage( $this->httpCode );
539
540 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode );
541 header( 'Content-type: text/html; charset=utf-8' );
542
543 print $this->getHTML();
544 }
545
546 /**
547 * Returns HTML for reporting the HTTP error.
548 * This will be a minimal but complete HTML document.
549 *
550 * @return string HTML
551 */
552 public function getHTML() {
553 if ( $this->header === null ) {
554 $header = HttpStatus::getMessage( $this->httpCode );
555 } elseif ( $this->header instanceof Message ) {
556 $header = $this->header->escaped();
557 } else {
558 $header = htmlspecialchars( $this->header );
559 }
560
561 if ( $this->content instanceof Message ) {
562 $content = $this->content->escaped();
563 } else {
564 $content = htmlspecialchars( $this->content );
565 }
566
567 return "<!DOCTYPE html>\n" .
568 "<html><head><title>$header</title></head>\n" .
569 "<body><h1>$header</h1><p>$content</p></body></html>\n";
570 }
571 }
572
573 /**
574 * Handler class for MWExceptions
575 * @ingroup Exception
576 */
577 class MWExceptionHandler {
578 /**
579 * Install an exception handler for MediaWiki exception types.
580 */
581 public static function installHandler() {
582 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
583 }
584
585 /**
586 * Report an exception to the user
587 */
588 protected static function report( Exception $e ) {
589 global $wgShowExceptionDetails;
590
591 $cmdLine = MWException::isCommandLine();
592
593 if ( $e instanceof MWException ) {
594 try {
595 // Try and show the exception prettily, with the normal skin infrastructure
596 $e->report();
597 } catch ( Exception $e2 ) {
598 // Exception occurred from within exception handler
599 // Show a simpler error message for the original exception,
600 // don't try to invoke report()
601 $message = "MediaWiki internal error.\n\n";
602
603 if ( $wgShowExceptionDetails ) {
604 $message .= 'Original exception: ' . self::formatRedactedTrace( $e ) . "\n\n" .
605 'Exception caught inside exception handler: ' . $e2->__toString();
606 } else {
607 $message .= "Exception caught inside exception handler.\n\n" .
608 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
609 "to show detailed debugging information.";
610 }
611
612 $message .= "\n";
613
614 if ( $cmdLine ) {
615 self::printError( $message );
616 } else {
617 echo nl2br( htmlspecialchars( $message ) ) . "\n";
618 }
619 }
620 } else {
621 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"";
622
623 if ( $wgShowExceptionDetails ) {
624 $message .= "\nexception '" . get_class( $e ) . "' in " . $e->getFile() . ":" . $e->getLine() . "\nStack trace:\n" . self::formatRedactedTrace( $e ) . "\n";
625 }
626
627 if ( $cmdLine ) {
628 self::printError( $message );
629 } else {
630 echo nl2br( htmlspecialchars( $message ) ) . "\n";
631 }
632 }
633 }
634
635 /**
636 * Print a message, if possible to STDERR.
637 * Use this in command line mode only (see isCommandLine)
638 *
639 * @param string $message Failure text
640 */
641 public static function printError( $message ) {
642 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
643 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
644 if ( defined( 'STDERR' ) ) {
645 fwrite( STDERR, $message );
646 } else {
647 echo $message;
648 }
649 }
650
651 /**
652 * Exception handler which simulates the appropriate catch() handling:
653 *
654 * try {
655 * ...
656 * } catch ( MWException $e ) {
657 * $e->report();
658 * } catch ( Exception $e ) {
659 * echo $e->__toString();
660 * }
661 */
662 public static function handle( $e ) {
663 global $wgFullyInitialised;
664
665 self::report( $e );
666
667 // Final cleanup
668 if ( $wgFullyInitialised ) {
669 try {
670 // uses $wgRequest, hence the $wgFullyInitialised condition
671 wfLogProfilingData();
672 } catch ( Exception $e ) {
673 }
674 }
675
676 // Exit value should be nonzero for the benefit of shell jobs
677 exit( 1 );
678 }
679
680 /**
681 * Get the stack trace from the exception as a string, redacting certain function arguments in the process
682 * @param Exception $e The exception
683 * @return string The stack trace as a string
684 */
685 public static function formatRedactedTrace( Exception $e ) {
686 global $wgRedactedFunctionArguments;
687 $finalExceptionText = '';
688
689 foreach ( $e->getTrace() as $i => $call ) {
690 $checkFor = array();
691 if ( isset( $call['class'] ) ) {
692 $checkFor[] = $call['class'] . '::' . $call['function'];
693 foreach ( class_parents( $call['class'] ) as $parent ) {
694 $checkFor[] = $parent . '::' . $call['function'];
695 }
696 } else {
697 $checkFor[] = $call['function'];
698 }
699
700 foreach ( $checkFor as $check ) {
701 if ( isset( $wgRedactedFunctionArguments[$check] ) ) {
702 foreach ( (array)$wgRedactedFunctionArguments[$check] as $argNo ) {
703 $call['args'][$argNo] = 'REDACTED';
704 }
705 }
706 }
707
708 if ( isset( $call['file'] ) && isset( $call['line'] ) ) {
709 $finalExceptionText .= "#{$i} {$call['file']}({$call['line']}): ";
710 } else {
711 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
712 // This matches behaviour of Exception::getTraceAsString to instead
713 // display "[internal function]".
714 $finalExceptionText .= "#{$i} [internal function]: ";
715 }
716
717 if ( isset( $call['class'] ) ) {
718 $finalExceptionText .= $call['class'] . $call['type'] . $call['function'];
719 } else {
720 $finalExceptionText .= $call['function'];
721 }
722 $args = array();
723 if ( isset( $call['args'] ) ) {
724 foreach ( $call['args'] as $arg ) {
725 if ( is_object( $arg ) ) {
726 $args[] = 'Object(' . get_class( $arg ) . ')';
727 } elseif( is_array( $arg ) ) {
728 $args[] = 'Array';
729 } else {
730 $args[] = var_export( $arg, true );
731 }
732 }
733 }
734 $finalExceptionText .= '(' . implode( ', ', $args ) . ")\n";
735 }
736 return $finalExceptionText . '#' . ( $i + 1 ) . ' {main}';
737 }
738
739
740 /**
741 * Get the ID for this error.
742 *
743 * The ID is saved so that one can match the one output to the user (when
744 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
745 *
746 * @since 1.22
747 * @param Exception $e
748 * @return string
749 */
750 public static function getLogId( Exception $e ) {
751 if ( !isset( $e->_mwLogId ) ) {
752 $e->_mwLogId = wfRandomString( 8 );
753 }
754 return $e->_mwLogId;
755 }
756
757 /**
758 * Return the requested URL and point to file and line number from which the
759 * exception occurred.
760 *
761 * @since 1.22
762 * @param Exception $e
763 * @return string
764 */
765 public static function getLogMessage( Exception $e ) {
766 global $wgRequest;
767
768 $id = self::getLogId( $e );
769 $file = $e->getFile();
770 $line = $e->getLine();
771 $message = $e->getMessage();
772
773 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
774 $url = $wgRequest->getRequestURL();
775 if ( !$url ) {
776 $url = '[no URL]';
777 }
778 } else {
779 $url = '[no req]';
780 }
781
782 return "[$id] $url Exception from line $line of $file: $message";
783 }
784
785 /**
786 * Log an exception to the exception log (if enabled).
787 *
788 * This method must not assume the exception is an MWException,
789 * it is also used to handle PHP errors or errors from other libraries.
790 *
791 * @since 1.22
792 * @param Exception $e
793 */
794 public static function logException( Exception $e ) {
795 global $wgLogExceptionBacktrace;
796
797 $log = self::getLogMessage( $e );
798 if ( $log ) {
799 if ( $wgLogExceptionBacktrace ) {
800 wfDebugLog( 'exception', $log . "\n" . self::formatRedactedTrace( $e ) . "\n" );
801 } else {
802 wfDebugLog( 'exception', $log );
803 }
804 }
805 }
806
807 }