Fix separated login link so that create account and login are always next to each...
[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 wfMsg() to get i18n 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 wfMsgNoTrans( $key, $args );
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 die( 1 );
244 }
245 }
246
247 /**
248 * Output a report about the exception and takes care of formatting.
249 * It will be either HTML or plain text based on isCommandLine().
250 */
251 function report() {
252 global $wgLogExceptionBacktrace;
253 $log = $this->getLogMessage();
254
255 if ( $log ) {
256 if ( $wgLogExceptionBacktrace ) {
257 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
258 } else {
259 wfDebugLog( 'exception', $log );
260 }
261 }
262
263 if ( defined( 'MW_API' ) ) {
264 // Unhandled API exception, we can't be sure that format printer is alive
265 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
266 wfHttpError(500, 'Internal Server Error', $this->getText() );
267 } elseif ( self::isCommandLine() ) {
268 MWExceptionHandler::printError( $this->getText() );
269 } else {
270 header( "HTTP/1.1 500 MediaWiki exception" );
271 header( "Status: 500 MediaWiki exception", true );
272
273 $this->reportHTML();
274 }
275 }
276
277 /**
278 * Check whether we are in command line mode or not to report the exception
279 * in the correct format.
280 *
281 * @return bool
282 */
283 static function isCommandLine() {
284 return !empty( $GLOBALS['wgCommandLineMode'] );
285 }
286 }
287
288 /**
289 * Exception class which takes an HTML error message, and does not
290 * produce a backtrace. Replacement for OutputPage::fatalError().
291 *
292 * @since 1.7
293 * @ingroup Exception
294 */
295 class FatalError extends MWException {
296
297 /**
298 * @return string
299 */
300 function getHTML() {
301 return $this->getMessage();
302 }
303
304 /**
305 * @return string
306 */
307 function getText() {
308 return $this->getMessage();
309 }
310 }
311
312 /**
313 * An error page which can definitely be safely rendered using the OutputPage.
314 *
315 * @since 1.7
316 * @ingroup Exception
317 */
318 class ErrorPageError extends MWException {
319 public $title, $msg, $params;
320
321 /**
322 * @todo document
323 *
324 * Note: these arguments are keys into wfMsg(), not text!
325 *
326 * @param $title A title
327 * @param $msg String|Message . In string form, should be a message key
328 * @param $params Array Array to wfMsg()
329 */
330 function __construct( $title, $msg, $params = null ) {
331 $this->title = $title;
332 $this->msg = $msg;
333 $this->params = $params;
334
335 if( $msg instanceof Message ){
336 parent::__construct( $msg );
337 } else {
338 parent::__construct( wfMsg( $msg ) );
339 }
340 }
341
342 function report() {
343 global $wgOut;
344
345 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
346 $wgOut->output();
347 }
348 }
349
350 /**
351 * Show an error page on a badtitle.
352 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
353 * browser it is not really a valid content.
354 *
355 * @since 1.19
356 * @ingroup Exception
357 */
358 class BadTitleError extends ErrorPageError {
359
360 /**
361 * @param $msg string A message key (default: 'badtitletext')
362 * @param $params Array parameter to wfMsg()
363 */
364 function __construct( $msg = 'badtitletext', $params = null ) {
365 parent::__construct( 'badtitle', $msg, $params );
366 }
367
368 /**
369 * Just like ErrorPageError::report() but additionally set
370 * a 400 HTTP status code (bug 33646).
371 */
372 function report() {
373 global $wgOut;
374
375 // bug 33646: a badtitle error page need to return an error code
376 // to let mobile browser now that it is not a normal page.
377 $wgOut->setStatusCode( 400 );
378 parent::report();
379 }
380
381 }
382
383 /**
384 * Show an error when a user tries to do something they do not have the necessary
385 * permissions for.
386 *
387 * @since 1.18
388 * @ingroup Exception
389 */
390 class PermissionsError extends ErrorPageError {
391 public $permission, $errors;
392
393 function __construct( $permission, $errors = array() ) {
394 global $wgLang;
395
396 $this->permission = $permission;
397
398 if ( !count( $errors ) ) {
399 $groups = array_map(
400 array( 'User', 'makeGroupLinkWiki' ),
401 User::getGroupsWithPermission( $this->permission )
402 );
403
404 if ( $groups ) {
405 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
406 } else {
407 $errors[] = array( 'badaccess-group0' );
408 }
409 }
410
411 $this->errors = $errors;
412 }
413
414 function report() {
415 global $wgOut;
416
417 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
418 $wgOut->output();
419 }
420 }
421
422 /**
423 * Show an error when the wiki is locked/read-only and the user tries to do
424 * something that requires write access.
425 *
426 * @since 1.18
427 * @ingroup Exception
428 */
429 class ReadOnlyError extends ErrorPageError {
430 public function __construct(){
431 parent::__construct(
432 'readonly',
433 'readonlytext',
434 wfReadOnlyReason()
435 );
436 }
437 }
438
439 /**
440 * Show an error when the user hits a rate limit.
441 *
442 * @since 1.18
443 * @ingroup Exception
444 */
445 class ThrottledError extends ErrorPageError {
446 public function __construct(){
447 parent::__construct(
448 'actionthrottled',
449 'actionthrottledtext'
450 );
451 }
452
453 public function report(){
454 global $wgOut;
455 $wgOut->setStatusCode( 503 );
456 parent::report();
457 }
458 }
459
460 /**
461 * Show an error when the user tries to do something whilst blocked.
462 *
463 * @since 1.18
464 * @ingroup Exception
465 */
466 class UserBlockedError extends ErrorPageError {
467 public function __construct( Block $block ){
468 global $wgLang, $wgRequest;
469
470 $blocker = $block->getBlocker();
471 if ( $blocker instanceof User ) { // local user
472 $blockerUserpage = $block->getBlocker()->getUserPage();
473 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
474 } else { // foreign user
475 $link = $blocker;
476 }
477
478 $reason = $block->mReason;
479 if( $reason == '' ) {
480 $reason = wfMsg( 'blockednoreason' );
481 }
482
483 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
484 * This could be a username, an IP range, or a single IP. */
485 $intended = $block->getTarget();
486
487 parent::__construct(
488 'blockedtitle',
489 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
490 array(
491 $link,
492 $reason,
493 $wgRequest->getIP(),
494 $block->getByName(),
495 $block->getId(),
496 $wgLang->formatExpiry( $block->mExpiry ),
497 $intended,
498 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
499 )
500 );
501 }
502 }
503
504 /**
505 * Shows a generic "user is not logged in" error page.
506 *
507 * This is essentially an ErrorPageError exception which by default use the
508 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
509 * @see bug 37627
510 * @since 1.20
511 *
512 * @par Example:
513 * @code
514 * if( $user->isAnon ) {
515 * throw new UserNotLoggedIn();
516 * }
517 * @endcode
518 *
519 * Please note the parameters are mixed up compared to ErrorPageError, this
520 * is done to be able to simply specify a reason whitout overriding the default
521 * title.
522 *
523 * @par Example:
524 * @code
525 * if( $user->isAnon ) {
526 * throw new UserNotLoggedIn( 'action-require-loggedin' );
527 * }
528 * @endcode
529 *
530 * @ingroup Exception
531 */
532 class UserNotLoggedIn extends ErrorPageError {
533
534 /**
535 * @param $reasonMsg A message key containing the reason for the error.
536 * Optional, default: 'exception-nologin-text'
537 * @param $titleMsg A message key to set the page title.
538 * Optional, default: 'exception-nologin'
539 * @param $params Parameters to wfMsg().
540 * Optiona, default: null
541 */
542 public function __construct(
543 $reasonMsg = 'exception-nologin-text',
544 $titleMsg = 'exception-nologin',
545 $params = null
546 ) {
547 parent::__construct( $titleMsg, $reasonMsg, $params );
548 }
549 }
550
551 /**
552 * Show an error that looks like an HTTP server error.
553 * Replacement for wfHttpError().
554 *
555 * @since 1.19
556 * @ingroup Exception
557 */
558 class HttpError extends MWException {
559 private $httpCode, $header, $content;
560
561 /**
562 * Constructor
563 *
564 * @param $httpCode Integer: HTTP status code to send to the client
565 * @param $content String|Message: content of the message
566 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
567 */
568 public function __construct( $httpCode, $content, $header = null ){
569 parent::__construct( $content );
570 $this->httpCode = (int)$httpCode;
571 $this->header = $header;
572 $this->content = $content;
573 }
574
575 public function report() {
576 $httpMessage = HttpStatus::getMessage( $this->httpCode );
577
578 header( "Status: {$this->httpCode} {$httpMessage}" );
579 header( 'Content-type: text/html; charset=utf-8' );
580
581 if ( $this->header === null ) {
582 $header = $httpMessage;
583 } elseif ( $this->header instanceof Message ) {
584 $header = $this->header->escaped();
585 } else {
586 $header = htmlspecialchars( $this->header );
587 }
588
589 if ( $this->content instanceof Message ) {
590 $content = $this->content->escaped();
591 } else {
592 $content = htmlspecialchars( $this->content );
593 }
594
595 print "<!DOCTYPE html>\n".
596 "<html><head><title>$header</title></head>\n" .
597 "<body><h1>$header</h1><p>$content</p></body></html>\n";
598 }
599 }
600
601 /**
602 * Handler class for MWExceptions
603 * @ingroup Exception
604 */
605 class MWExceptionHandler {
606 /**
607 * Install an exception handler for MediaWiki exception types.
608 */
609 public static function installHandler() {
610 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
611 }
612
613 /**
614 * Report an exception to the user
615 */
616 protected static function report( Exception $e ) {
617 global $wgShowExceptionDetails;
618
619 $cmdLine = MWException::isCommandLine();
620
621 if ( $e instanceof MWException ) {
622 try {
623 // Try and show the exception prettily, with the normal skin infrastructure
624 $e->report();
625 } catch ( Exception $e2 ) {
626 // Exception occurred from within exception handler
627 // Show a simpler error message for the original exception,
628 // don't try to invoke report()
629 $message = "MediaWiki internal error.\n\n";
630
631 if ( $wgShowExceptionDetails ) {
632 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
633 'Exception caught inside exception handler: ' . $e2->__toString();
634 } else {
635 $message .= "Exception caught inside exception handler.\n\n" .
636 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
637 "to show detailed debugging information.";
638 }
639
640 $message .= "\n";
641
642 if ( $cmdLine ) {
643 self::printError( $message );
644 } else {
645 self::escapeEchoAndDie( $message );
646 }
647 }
648 } else {
649 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
650 $e->__toString() . "\n";
651
652 if ( $wgShowExceptionDetails ) {
653 $message .= "\n" . $e->getTraceAsString() . "\n";
654 }
655
656 if ( $cmdLine ) {
657 self::printError( $message );
658 } else {
659 self::escapeEchoAndDie( $message );
660 }
661 }
662 }
663
664 /**
665 * Print a message, if possible to STDERR.
666 * Use this in command line mode only (see isCommandLine)
667 *
668 * @param $message string Failure text
669 */
670 public static function printError( $message ) {
671 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
672 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
673 if ( defined( 'STDERR' ) ) {
674 fwrite( STDERR, $message );
675 } else {
676 echo( $message );
677 }
678 }
679
680 /**
681 * Print a message after escaping it and converting newlines to <br>
682 * Use this for non-command line failures.
683 *
684 * @param $message string Failure text
685 */
686 private static function escapeEchoAndDie( $message ) {
687 echo nl2br( htmlspecialchars( $message ) ) . "\n";
688 die(1);
689 }
690
691 /**
692 * Exception handler which simulates the appropriate catch() handling:
693 *
694 * try {
695 * ...
696 * } catch ( MWException $e ) {
697 * $e->report();
698 * } catch ( Exception $e ) {
699 * echo $e->__toString();
700 * }
701 */
702 public static function handle( $e ) {
703 global $wgFullyInitialised;
704
705 self::report( $e );
706
707 // Final cleanup
708 if ( $wgFullyInitialised ) {
709 try {
710 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
711 } catch ( Exception $e ) {}
712 }
713
714 // Exit value should be nonzero for the benefit of shell jobs
715 exit( 1 );
716 }
717 }