Made loadFromFileCache() always disable $wgOut regardless of whether compression...
[lhc/web/wiklou.git] / includes / Exception.php
1 <?php
2 /**
3 * Exception class and handler
4 *
5 * @file
6 */
7
8 /**
9 * @defgroup Exception Exception
10 */
11
12 /**
13 * MediaWiki exception
14 *
15 * @ingroup Exception
16 */
17 class MWException extends Exception {
18 /**
19 * Should the exception use $wgOut to output the error ?
20 * @return bool
21 */
22 function useOutputPage() {
23 return $this->useMessageCache() &&
24 !empty( $GLOBALS['wgFullyInitialised'] ) &&
25 !empty( $GLOBALS['wgOut'] ) &&
26 !empty( $GLOBALS['wgTitle'] );
27 }
28
29 /**
30 * Can the extension use wfMsg() to get i18n messages ?
31 * @return bool
32 */
33 function useMessageCache() {
34 global $wgLang;
35
36 foreach ( $this->getTrace() as $frame ) {
37 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
38 return false;
39 }
40 }
41
42 return $wgLang instanceof Language;
43 }
44
45 /**
46 * Run hook to allow extensions to modify the text of the exception
47 *
48 * @param $name String: class name of the exception
49 * @param $args Array: arguments to pass to the callback functions
50 * @return Mixed: string to output or null if any hook has been called
51 */
52 function runHooks( $name, $args = array() ) {
53 global $wgExceptionHooks;
54
55 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
56 return; // Just silently ignore
57 }
58
59 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
60 return;
61 }
62
63 $hooks = $wgExceptionHooks[ $name ];
64 $callargs = array_merge( array( $this ), $args );
65
66 foreach ( $hooks as $hook ) {
67 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
68 $result = call_user_func_array( $hook, $callargs );
69 } else {
70 $result = null;
71 }
72
73 if ( is_string( $result ) ) {
74 return $result;
75 }
76 }
77 }
78
79 /**
80 * Get a message from i18n
81 *
82 * @param $key String: message name
83 * @param $fallback String: default message if the message cache can't be
84 * called by the exception
85 * The function also has other parameters that are arguments for the message
86 * @return String message with arguments replaced
87 */
88 function msg( $key, $fallback /*[, params...] */ ) {
89 $args = array_slice( func_get_args(), 2 );
90
91 if ( $this->useMessageCache() ) {
92 return wfMsgNoTrans( $key, $args );
93 } else {
94 return wfMsgReplaceArgs( $fallback, $args );
95 }
96 }
97
98 /**
99 * If $wgShowExceptionDetails is true, return a HTML message with a
100 * backtrace to the error, otherwise show a message to ask to set it to true
101 * to show that information.
102 *
103 * @return String html to output
104 */
105 function getHTML() {
106 global $wgShowExceptionDetails;
107
108 if ( $wgShowExceptionDetails ) {
109 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
110 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
111 "</p>\n";
112 } else {
113 return "<p>Set <b><tt>\$wgShowExceptionDetails = true;</tt></b> " .
114 "at the bottom of LocalSettings.php to show detailed " .
115 "debugging information.</p>";
116 }
117 }
118
119 /**
120 * If $wgShowExceptionDetails is true, return a text message with a
121 * backtrace to the error.
122 * @return string
123 */
124 function getText() {
125 global $wgShowExceptionDetails;
126
127 if ( $wgShowExceptionDetails ) {
128 return $this->getMessage() .
129 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
130 } else {
131 return "Set \$wgShowExceptionDetails = true; " .
132 "in LocalSettings.php to show detailed debugging information.\n";
133 }
134 }
135
136 /**
137 * Return titles of this error page
138 * @return String
139 */
140 function getPageTitle() {
141 return $this->msg( 'internalerror', "Internal error" );
142 }
143
144 /**
145 * Return the requested URL and point to file and line number from which the
146 * exception occured
147 *
148 * @return String
149 */
150 function getLogMessage() {
151 global $wgRequest;
152
153 $file = $this->getFile();
154 $line = $this->getLine();
155 $message = $this->getMessage();
156
157 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
158 $url = $wgRequest->getRequestURL();
159 if ( !$url ) {
160 $url = '[no URL]';
161 }
162 } else {
163 $url = '[no req]';
164 }
165
166 return "$url Exception from line $line of $file: $message";
167 }
168
169 /** Output the exception report using HTML */
170 function reportHTML() {
171 global $wgOut;
172 if ( $this->useOutputPage() ) {
173 $wgOut->prepareErrorPage( $this->getPageTitle() );
174
175 $hookResult = $this->runHooks( get_class( $this ) );
176 if ( $hookResult ) {
177 $wgOut->addHTML( $hookResult );
178 } else {
179 $wgOut->addHTML( $this->getHTML() );
180 }
181
182 $wgOut->output();
183 } else {
184 header( "Content-Type: text/html; charset=utf-8" );
185 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
186 if ( $hookResult ) {
187 die( $hookResult );
188 }
189
190 echo $this->getHTML();
191 die(1);
192 }
193 }
194
195 /**
196 * Output a report about the exception and takes care of formatting.
197 * It will be either HTML or plain text based on isCommandLine().
198 */
199 function report() {
200 $log = $this->getLogMessage();
201
202 if ( $log ) {
203 wfDebugLog( 'exception', $log );
204 }
205
206 if ( self::isCommandLine() ) {
207 MWExceptionHandler::printError( $this->getText() );
208 } else {
209 $this->reportHTML();
210 }
211 }
212
213 /**
214 * @static
215 * @return bool
216 */
217 static function isCommandLine() {
218 return !empty( $GLOBALS['wgCommandLineMode'] );
219 }
220 }
221
222 /**
223 * Exception class which takes an HTML error message, and does not
224 * produce a backtrace. Replacement for OutputPage::fatalError().
225 * @ingroup Exception
226 */
227 class FatalError extends MWException {
228
229 /**
230 * @return string
231 */
232 function getHTML() {
233 return $this->getMessage();
234 }
235
236 /**
237 * @return string
238 */
239 function getText() {
240 return $this->getMessage();
241 }
242 }
243
244 /**
245 * An error page which can definitely be safely rendered using the OutputPage
246 * @ingroup Exception
247 */
248 class ErrorPageError extends MWException {
249 public $title, $msg, $params;
250
251 /**
252 * Note: these arguments are keys into wfMsg(), not text!
253 */
254 function __construct( $title, $msg, $params = null ) {
255 $this->title = $title;
256 $this->msg = $msg;
257 $this->params = $params;
258
259 if( $msg instanceof Message ){
260 parent::__construct( $msg );
261 } else {
262 parent::__construct( wfMsg( $msg ) );
263 }
264 }
265
266 function report() {
267 global $wgOut;
268
269
270 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
271 $wgOut->output();
272 }
273 }
274
275 /**
276 * Show an error page on a badtitle.
277 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
278 * browser it is not really a valid content.
279 */
280 class BadTitleError extends ErrorPageError {
281
282 /**
283 * @param $msg string A message key (default: 'badtitletext')
284 * @param $params Array parameter to wfMsg()
285 */
286 function __construct( $msg = 'badtitletext', $params = null ) {
287 parent::__construct( 'badtitle', $msg, $params );
288 }
289
290 /**
291 * Just like ErrorPageError::report() but additionally set
292 * a 400 HTTP status code (bug 33646).
293 */
294 function report() {
295 global $wgOut;
296
297 // bug 33646: a badtitle error page need to return an error code
298 // to let mobile browser now that it is not a normal page.
299 $wgOut->setStatusCode( 400 );
300 parent::report();
301 }
302
303 }
304
305 /**
306 * Show an error when a user tries to do something they do not have the necessary
307 * permissions for.
308 * @ingroup Exception
309 */
310 class PermissionsError extends ErrorPageError {
311 public $permission, $errors;
312
313 function __construct( $permission, $errors = array() ) {
314 global $wgLang;
315
316 $this->permission = $permission;
317
318 if ( !count( $errors ) ) {
319 $groups = array_map(
320 array( 'User', 'makeGroupLinkWiki' ),
321 User::getGroupsWithPermission( $this->permission )
322 );
323
324 if ( $groups ) {
325 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
326 } else {
327 $errors[] = array( 'badaccess-group0' );
328 }
329 }
330
331 $this->errors = $errors;
332 }
333
334 function report() {
335 global $wgOut;
336
337 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
338 $wgOut->output();
339 }
340 }
341
342 /**
343 * Show an error when the wiki is locked/read-only and the user tries to do
344 * something that requires write access
345 * @ingroup Exception
346 */
347 class ReadOnlyError extends ErrorPageError {
348 public function __construct(){
349 parent::__construct(
350 'readonly',
351 'readonlytext',
352 wfReadOnlyReason()
353 );
354 }
355 }
356
357 /**
358 * Show an error when the user hits a rate limit
359 * @ingroup Exception
360 */
361 class ThrottledError extends ErrorPageError {
362 public function __construct(){
363 parent::__construct(
364 'actionthrottled',
365 'actionthrottledtext'
366 );
367 }
368
369 public function report(){
370 global $wgOut;
371 $wgOut->setStatusCode( 503 );
372 return parent::report();
373 }
374 }
375
376 /**
377 * Show an error when the user tries to do something whilst blocked
378 * @ingroup Exception
379 */
380 class UserBlockedError extends ErrorPageError {
381 public function __construct( Block $block ){
382 global $wgLang, $wgRequest;
383
384 $blocker = $block->getBlocker();
385 if ( $blocker instanceof User ) { // local user
386 $blockerUserpage = $block->getBlocker()->getUserPage();
387 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
388 } else { // foreign user
389 $link = $blocker;
390 }
391
392 $reason = $block->mReason;
393 if( $reason == '' ) {
394 $reason = wfMsg( 'blockednoreason' );
395 }
396
397 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
398 * This could be a username, an IP range, or a single IP. */
399 $intended = $block->getTarget();
400
401 parent::__construct(
402 'blockedtitle',
403 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
404 array(
405 $link,
406 $reason,
407 $wgRequest->getIP(),
408 $block->getByName(),
409 $block->getId(),
410 $wgLang->formatExpiry( $block->mExpiry ),
411 $intended,
412 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
413 )
414 );
415 }
416 }
417
418 /**
419 * Show an error that looks like an HTTP server error.
420 * Replacement for wfHttpError().
421 *
422 * @ingroup Exception
423 */
424 class HttpError extends MWException {
425 private $httpCode, $header, $content;
426
427 /**
428 * Constructor
429 *
430 * @param $httpCode Integer: HTTP status code to send to the client
431 * @param $content String|Message: content of the message
432 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
433 */
434 public function __construct( $httpCode, $content, $header = null ){
435 parent::__construct( $content );
436 $this->httpCode = (int)$httpCode;
437 $this->header = $header;
438 $this->content = $content;
439 }
440
441 public function reportHTML() {
442 $httpMessage = HttpStatus::getMessage( $this->httpCode );
443
444 header( "Status: {$this->httpCode} {$httpMessage}" );
445 header( 'Content-type: text/html; charset=utf-8' );
446
447 if ( $this->header === null ) {
448 $header = $httpMessage;
449 } elseif ( $this->header instanceof Message ) {
450 $header = $this->header->escaped();
451 } else {
452 $header = htmlspecialchars( $this->header );
453 }
454
455 if ( $this->content instanceof Message ) {
456 $content = $this->content->escaped();
457 } else {
458 $content = htmlspecialchars( $this->content );
459 }
460
461 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
462 "<html><head><title>$header</title></head>\n" .
463 "<body><h1>$header</h1><p>$content</p></body></html>\n";
464 }
465 }
466
467 /**
468 * Handler class for MWExceptions
469 * @ingroup Exception
470 */
471 class MWExceptionHandler {
472 /**
473 * Install an exception handler for MediaWiki exception types.
474 */
475 public static function installHandler() {
476 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
477 }
478
479 /**
480 * Report an exception to the user
481 */
482 protected static function report( Exception $e ) {
483 global $wgShowExceptionDetails;
484
485 $cmdLine = MWException::isCommandLine();
486
487 if ( $e instanceof MWException ) {
488 try {
489 // Try and show the exception prettily, with the normal skin infrastructure
490 $e->report();
491 } catch ( Exception $e2 ) {
492 // Exception occurred from within exception handler
493 // Show a simpler error message for the original exception,
494 // don't try to invoke report()
495 $message = "MediaWiki internal error.\n\n";
496
497 if ( $wgShowExceptionDetails ) {
498 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
499 'Exception caught inside exception handler: ' . $e2->__toString();
500 } else {
501 $message .= "Exception caught inside exception handler.\n\n" .
502 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
503 "to show detailed debugging information.";
504 }
505
506 $message .= "\n";
507
508 if ( $cmdLine ) {
509 self::printError( $message );
510 } else {
511 self::escapeEchoAndDie( $message );
512 }
513 }
514 } else {
515 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
516 $e->__toString() . "\n";
517
518 if ( $wgShowExceptionDetails ) {
519 $message .= "\n" . $e->getTraceAsString() . "\n";
520 }
521
522 if ( $cmdLine ) {
523 self::printError( $message );
524 } else {
525 self::escapeEchoAndDie( $message );
526 }
527 }
528 }
529
530 /**
531 * Print a message, if possible to STDERR.
532 * Use this in command line mode only (see isCommandLine)
533 * @param $message String Failure text
534 */
535 public static function printError( $message ) {
536 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
537 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
538 if ( defined( 'STDERR' ) ) {
539 fwrite( STDERR, $message );
540 } else {
541 echo( $message );
542 }
543 }
544
545 /**
546 * Print a message after escaping it and converting newlines to <br>
547 * Use this for non-command line failures
548 * @param $message String Failure text
549 */
550 private static function escapeEchoAndDie( $message ) {
551 echo nl2br( htmlspecialchars( $message ) ) . "\n";
552 die(1);
553 }
554
555 /**
556 * Exception handler which simulates the appropriate catch() handling:
557 *
558 * try {
559 * ...
560 * } catch ( MWException $e ) {
561 * $e->report();
562 * } catch ( Exception $e ) {
563 * echo $e->__toString();
564 * }
565 */
566 public static function handle( $e ) {
567 global $wgFullyInitialised;
568
569 self::report( $e );
570
571 // Final cleanup
572 if ( $wgFullyInitialised ) {
573 try {
574 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
575 } catch ( Exception $e ) {}
576 }
577
578 // Exit value should be nonzero for the benefit of shell jobs
579 exit( 1 );
580 }
581 }