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