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