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