2d1772b7b2cef15ad9cd6a2a82e373ee412eae5c
[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 ( defined( 'MW_API' ) ) {
207 // Unhandled API exception, we can't be sure that format printer is alive
208 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
209 wfHttpError(500, 'Internal Server Error', $this->getText() );
210 } elseif ( self::isCommandLine() ) {
211 MWExceptionHandler::printError( $this->getText() );
212 } else {
213 $this->reportHTML();
214 }
215 }
216
217 /**
218 * @static
219 * @return bool
220 */
221 static function isCommandLine() {
222 return !empty( $GLOBALS['wgCommandLineMode'] );
223 }
224 }
225
226 /**
227 * Exception class which takes an HTML error message, and does not
228 * produce a backtrace. Replacement for OutputPage::fatalError().
229 * @ingroup Exception
230 */
231 class FatalError extends MWException {
232
233 /**
234 * @return string
235 */
236 function getHTML() {
237 return $this->getMessage();
238 }
239
240 /**
241 * @return string
242 */
243 function getText() {
244 return $this->getMessage();
245 }
246 }
247
248 /**
249 * An error page which can definitely be safely rendered using the OutputPage
250 * @ingroup Exception
251 */
252 class ErrorPageError extends MWException {
253 public $title, $msg, $params;
254
255 /**
256 * Note: these arguments are keys into wfMsg(), not text!
257 */
258 function __construct( $title, $msg, $params = null ) {
259 $this->title = $title;
260 $this->msg = $msg;
261 $this->params = $params;
262
263 if( $msg instanceof Message ){
264 parent::__construct( $msg );
265 } else {
266 parent::__construct( wfMsg( $msg ) );
267 }
268 }
269
270 function report() {
271 global $wgOut;
272
273 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
274 $wgOut->output();
275 }
276 }
277
278 /**
279 * Show an error page on a badtitle.
280 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
281 * browser it is not really a valid content.
282 */
283 class BadTitleError extends ErrorPageError {
284
285 /**
286 * @param $msg string A message key (default: 'badtitletext')
287 * @param $params Array parameter to wfMsg()
288 */
289 function __construct( $msg = 'badtitletext', $params = null ) {
290 parent::__construct( 'badtitle', $msg, $params );
291 }
292
293 /**
294 * Just like ErrorPageError::report() but additionally set
295 * a 400 HTTP status code (bug 33646).
296 */
297 function report() {
298 global $wgOut;
299
300 // bug 33646: a badtitle error page need to return an error code
301 // to let mobile browser now that it is not a normal page.
302 $wgOut->setStatusCode( 400 );
303 parent::report();
304 }
305
306 }
307
308 /**
309 * Show an error when a user tries to do something they do not have the necessary
310 * permissions for.
311 * @ingroup Exception
312 */
313 class PermissionsError extends ErrorPageError {
314 public $permission, $errors;
315
316 function __construct( $permission, $errors = array() ) {
317 global $wgLang;
318
319 $this->permission = $permission;
320
321 if ( !count( $errors ) ) {
322 $groups = array_map(
323 array( 'User', 'makeGroupLinkWiki' ),
324 User::getGroupsWithPermission( $this->permission )
325 );
326
327 if ( $groups ) {
328 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
329 } else {
330 $errors[] = array( 'badaccess-group0' );
331 }
332 }
333
334 $this->errors = $errors;
335 }
336
337 function report() {
338 global $wgOut;
339
340 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
341 $wgOut->output();
342 }
343 }
344
345 /**
346 * Show an error when the wiki is locked/read-only and the user tries to do
347 * something that requires write access
348 * @ingroup Exception
349 */
350 class ReadOnlyError extends ErrorPageError {
351 public function __construct(){
352 parent::__construct(
353 'readonly',
354 'readonlytext',
355 wfReadOnlyReason()
356 );
357 }
358 }
359
360 /**
361 * Show an error when the user hits a rate limit
362 * @ingroup Exception
363 */
364 class ThrottledError extends ErrorPageError {
365 public function __construct(){
366 parent::__construct(
367 'actionthrottled',
368 'actionthrottledtext'
369 );
370 }
371
372 public function report(){
373 global $wgOut;
374 $wgOut->setStatusCode( 503 );
375 parent::report();
376 }
377 }
378
379 /**
380 * Show an error when the user tries to do something whilst blocked
381 * @ingroup Exception
382 */
383 class UserBlockedError extends ErrorPageError {
384 public function __construct( Block $block ){
385 global $wgLang, $wgRequest;
386
387 $blocker = $block->getBlocker();
388 if ( $blocker instanceof User ) { // local user
389 $blockerUserpage = $block->getBlocker()->getUserPage();
390 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
391 } else { // foreign user
392 $link = $blocker;
393 }
394
395 $reason = $block->mReason;
396 if( $reason == '' ) {
397 $reason = wfMsg( 'blockednoreason' );
398 }
399
400 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
401 * This could be a username, an IP range, or a single IP. */
402 $intended = $block->getTarget();
403
404 parent::__construct(
405 'blockedtitle',
406 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
407 array(
408 $link,
409 $reason,
410 $wgRequest->getIP(),
411 $block->getByName(),
412 $block->getId(),
413 $wgLang->formatExpiry( $block->mExpiry ),
414 $intended,
415 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
416 )
417 );
418 }
419 }
420
421 /**
422 * Show an error that looks like an HTTP server error.
423 * Replacement for wfHttpError().
424 *
425 * @ingroup Exception
426 */
427 class HttpError extends MWException {
428 private $httpCode, $header, $content;
429
430 /**
431 * Constructor
432 *
433 * @param $httpCode Integer: HTTP status code to send to the client
434 * @param $content String|Message: content of the message
435 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
436 */
437 public function __construct( $httpCode, $content, $header = null ){
438 parent::__construct( $content );
439 $this->httpCode = (int)$httpCode;
440 $this->header = $header;
441 $this->content = $content;
442 }
443
444 public function reportHTML() {
445 $httpMessage = HttpStatus::getMessage( $this->httpCode );
446
447 header( "Status: {$this->httpCode} {$httpMessage}" );
448 header( 'Content-type: text/html; charset=utf-8' );
449
450 if ( $this->header === null ) {
451 $header = $httpMessage;
452 } elseif ( $this->header instanceof Message ) {
453 $header = $this->header->escaped();
454 } else {
455 $header = htmlspecialchars( $this->header );
456 }
457
458 if ( $this->content instanceof Message ) {
459 $content = $this->content->escaped();
460 } else {
461 $content = htmlspecialchars( $this->content );
462 }
463
464 print "<!DOCTYPE html>\n".
465 "<html><head><title>$header</title></head>\n" .
466 "<body><h1>$header</h1><p>$content</p></body></html>\n";
467 }
468 }
469
470 /**
471 * Handler class for MWExceptions
472 * @ingroup Exception
473 */
474 class MWExceptionHandler {
475 /**
476 * Install an exception handler for MediaWiki exception types.
477 */
478 public static function installHandler() {
479 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
480 }
481
482 /**
483 * Report an exception to the user
484 */
485 protected static function report( Exception $e ) {
486 global $wgShowExceptionDetails;
487
488 $cmdLine = MWException::isCommandLine();
489
490 if ( $e instanceof MWException ) {
491 try {
492 // Try and show the exception prettily, with the normal skin infrastructure
493 $e->report();
494 } catch ( Exception $e2 ) {
495 // Exception occurred from within exception handler
496 // Show a simpler error message for the original exception,
497 // don't try to invoke report()
498 $message = "MediaWiki internal error.\n\n";
499
500 if ( $wgShowExceptionDetails ) {
501 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
502 'Exception caught inside exception handler: ' . $e2->__toString();
503 } else {
504 $message .= "Exception caught inside exception handler.\n\n" .
505 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
506 "to show detailed debugging information.";
507 }
508
509 $message .= "\n";
510
511 if ( $cmdLine ) {
512 self::printError( $message );
513 } else {
514 self::escapeEchoAndDie( $message );
515 }
516 }
517 } else {
518 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
519 $e->__toString() . "\n";
520
521 if ( $wgShowExceptionDetails ) {
522 $message .= "\n" . $e->getTraceAsString() . "\n";
523 }
524
525 if ( $cmdLine ) {
526 self::printError( $message );
527 } else {
528 self::escapeEchoAndDie( $message );
529 }
530 }
531 }
532
533 /**
534 * Print a message, if possible to STDERR.
535 * Use this in command line mode only (see isCommandLine)
536 * @param $message String Failure text
537 */
538 public static function printError( $message ) {
539 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
540 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
541 if ( defined( 'STDERR' ) ) {
542 fwrite( STDERR, $message );
543 } else {
544 echo( $message );
545 }
546 }
547
548 /**
549 * Print a message after escaping it and converting newlines to <br>
550 * Use this for non-command line failures
551 * @param $message String Failure text
552 */
553 private static function escapeEchoAndDie( $message ) {
554 echo nl2br( htmlspecialchars( $message ) ) . "\n";
555 die(1);
556 }
557
558 /**
559 * Exception handler which simulates the appropriate catch() handling:
560 *
561 * try {
562 * ...
563 * } catch ( MWException $e ) {
564 * $e->report();
565 * } catch ( Exception $e ) {
566 * echo $e->__toString();
567 * }
568 */
569 public static function handle( $e ) {
570 global $wgFullyInitialised;
571
572 self::report( $e );
573
574 // Final cleanup
575 if ( $wgFullyInitialised ) {
576 try {
577 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
578 } catch ( Exception $e ) {}
579 }
580
581 // Exit value should be nonzero for the benefit of shell jobs
582 exit( 1 );
583 }
584 }