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