* Added HttpError exception as replacement for wfHttpError(); changed alls core calls...
[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 * Get a message from i18n
80 *
81 * @param $key String: message name
82 * @param $fallback String: default message if the message cache can't be
83 * called by the exception
84 * The function also has other parameters that are arguments for the message
85 * @return String message with arguments replaced
86 */
87 function msg( $key, $fallback /*[, params...] */ ) {
88 $args = array_slice( func_get_args(), 2 );
89
90 if ( $this->useMessageCache() ) {
91 return wfMsgNoTrans( $key, $args );
92 } else {
93 return wfMsgReplaceArgs( $fallback, $args );
94 }
95 }
96
97 /**
98 * If $wgShowExceptionDetails is true, return a HTML message with a
99 * backtrace to the error, otherwise show a message to ask to set it to true
100 * to show that information.
101 *
102 * @return String html to output
103 */
104 function getHTML() {
105 global $wgShowExceptionDetails;
106
107 if ( $wgShowExceptionDetails ) {
108 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
109 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
110 "</p>\n";
111 } else {
112 return "<p>Set <b><tt>\$wgShowExceptionDetails = true;</tt></b> " .
113 "at the bottom of LocalSettings.php to show detailed " .
114 "debugging information.</p>";
115 }
116 }
117
118 /**
119 * If $wgShowExceptionDetails is true, return a text message with a
120 * backtrace to the error.
121 */
122 function getText() {
123 global $wgShowExceptionDetails;
124
125 if ( $wgShowExceptionDetails ) {
126 return $this->getMessage() .
127 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
128 } else {
129 return "Set \$wgShowExceptionDetails = true; " .
130 "in LocalSettings.php to show detailed debugging information.\n";
131 }
132 }
133
134 /* Return titles of this error page */
135 function getPageTitle() {
136 global $wgSitename;
137 return $this->msg( 'internalerror', "$wgSitename error" );
138 }
139
140 /**
141 * Return the requested URL and point to file and line number from which the
142 * exception occured
143 *
144 * @return String
145 */
146 function getLogMessage() {
147 global $wgRequest;
148
149 $file = $this->getFile();
150 $line = $this->getLine();
151 $message = $this->getMessage();
152
153 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
154 $url = $wgRequest->getRequestURL();
155 if ( !$url ) {
156 $url = '[no URL]';
157 }
158 } else {
159 $url = '[no req]';
160 }
161
162 return "$url Exception from line $line of $file: $message";
163 }
164
165 /** Output the exception report using HTML */
166 function reportHTML() {
167 global $wgOut;
168 if ( $this->useOutputPage() ) {
169 $wgOut->setPageTitle( $this->getPageTitle() );
170 $wgOut->setRobotPolicy( "noindex,nofollow" );
171 $wgOut->setArticleRelated( false );
172 $wgOut->enableClientCache( false );
173 $wgOut->redirect( '' );
174 $wgOut->clearHTML();
175
176 $hookResult = $this->runHooks( get_class( $this ) );
177 if ( $hookResult ) {
178 $wgOut->addHTML( $hookResult );
179 } else {
180 $wgOut->addHTML( $this->getHTML() );
181 }
182
183 $wgOut->output();
184 } else {
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 static function isCommandLine() {
214 return !empty( $GLOBALS['wgCommandLineMode'] );
215 }
216 }
217
218 /**
219 * Exception class which takes an HTML error message, and does not
220 * produce a backtrace. Replacement for OutputPage::fatalError().
221 * @ingroup Exception
222 */
223 class FatalError extends MWException {
224 function getHTML() {
225 return $this->getMessage();
226 }
227
228 function getText() {
229 return $this->getMessage();
230 }
231 }
232
233 /**
234 * An error page which can definitely be safely rendered using the OutputPage
235 * @ingroup Exception
236 */
237 class ErrorPageError extends MWException {
238 public $title, $msg, $params;
239
240 /**
241 * Note: these arguments are keys into wfMsg(), not text!
242 */
243 function __construct( $title, $msg, $params = null ) {
244 $this->title = $title;
245 $this->msg = $msg;
246 $this->params = $params;
247
248 if( $msg instanceof Message ){
249 parent::__construct( $msg );
250 } else {
251 parent::__construct( wfMsg( $msg ) );
252 }
253 }
254
255 function report() {
256 global $wgOut;
257
258 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
259 $wgOut->output();
260 }
261 }
262
263 /**
264 * Show an error when a user tries to do something they do not have the necessary
265 * permissions for.
266 * @ingroup Exception
267 */
268 class PermissionsError extends ErrorPageError {
269 public $permission;
270
271 function __construct( $permission ) {
272 global $wgLang;
273
274 $this->permission = $permission;
275
276 $groups = array_map(
277 array( 'User', 'makeGroupLinkWiki' ),
278 User::getGroupsWithPermission( $this->permission )
279 );
280
281 if( $groups ) {
282 parent::__construct(
283 'badaccess',
284 'badaccess-groups',
285 array(
286 $wgLang->commaList( $groups ),
287 count( $groups )
288 )
289 );
290 } else {
291 parent::__construct(
292 'badaccess',
293 'badaccess-group0'
294 );
295 }
296 }
297 }
298
299 /**
300 * Show an error when the wiki is locked/read-only and the user tries to do
301 * something that requires write access
302 * @ingroup Exception
303 */
304 class ReadOnlyError extends ErrorPageError {
305 public function __construct(){
306 parent::__construct(
307 'readonly',
308 'readonlytext',
309 wfReadOnlyReason()
310 );
311 }
312 }
313
314 /**
315 * Show an error when the user hits a rate limit
316 * @ingroup Exception
317 */
318 class ThrottledError extends ErrorPageError {
319 public function __construct(){
320 parent::__construct(
321 'actionthrottled',
322 'actionthrottledtext'
323 );
324 }
325 public function report(){
326 global $wgOut;
327 $wgOut->setStatusCode( 503 );
328 return parent::report();
329 }
330 }
331
332 /**
333 * Show an error when the user tries to do something whilst blocked
334 * @ingroup Exception
335 */
336 class UserBlockedError extends ErrorPageError {
337 public function __construct( Block $block ){
338 global $wgLang, $wgRequest;
339
340 $blockerUserpage = $block->getBlocker()->getUserPage();
341 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
342
343 $reason = $block->mReason;
344 if( $reason == '' ) {
345 $reason = wfMsg( 'blockednoreason' );
346 }
347
348 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
349 * This could be a username, an IP range, or a single IP. */
350 $intended = $block->getTarget();
351
352 parent::__construct(
353 'blockedtitle',
354 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
355 array(
356 $link,
357 $reason,
358 $wgRequest->getIP(),
359 $block->getBlocker()->getName(),
360 $block->getId(),
361 $wgLang->formatExpiry( $block->mExpiry ),
362 $intended,
363 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
364 )
365 );
366 }
367 }
368
369 /**
370 * Show an error that looks like an HTTP server error.
371 * Replacement for wfHttpError().
372 *
373 * @ingroup Exception
374 */
375 class HttpError extends MWException {
376 private $httpCode, $header, $content;
377
378 /**
379 * Constructor
380 *
381 * @param $httpCode Integer: HTTP status code to send to the client
382 * @param $content String|Message: content of the message
383 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
384 */
385 public function __construct( $httpCode, $content, $header = null ){
386 parent::__construct( $content );
387 $this->httpCode = (int)$httpCode;
388 $this->header = $header;
389 $this->content = $content;
390 }
391
392 public function reportHTML() {
393 $httpMessage = HttpStatus::getMessage( $this->httpCode );
394
395 header( "Status: {$this->httpCode} {$httpMessage}" );
396 header( 'Content-type: text/html; charset=utf-8' );
397
398 if ( $this->header === null ) {
399 $header = $httpMessage;
400 } elseif ( $this->header instanceof Message ) {
401 $header = $this->header->escaped();
402 } else {
403 $header = htmlspecialchars( $this->header );
404 }
405
406 if ( $this->content instanceof Message ) {
407 $content = $this->content->escaped();
408 } else {
409 $content = htmlspecialchars( $this->content );
410 }
411
412 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
413 "<html><head><title>$header</title></head>\n" .
414 "<body><h1>$header</h1><p>$content</p></body></html>\n";
415 }
416 }
417
418 /**
419 * Handler class for MWExceptions
420 * @ingroup Exception
421 */
422 class MWExceptionHandler {
423 /**
424 * Install an exception handler for MediaWiki exception types.
425 */
426 public static function installHandler() {
427 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
428 }
429
430 /**
431 * Report an exception to the user
432 */
433 protected static function report( Exception $e ) {
434 global $wgShowExceptionDetails;
435
436 $cmdLine = MWException::isCommandLine();
437
438 if ( $e instanceof MWException ) {
439 try {
440 // Try and show the exception prettily, with the normal skin infrastructure
441 $e->report();
442 } catch ( Exception $e2 ) {
443 // Exception occurred from within exception handler
444 // Show a simpler error message for the original exception,
445 // don't try to invoke report()
446 $message = "MediaWiki internal error.\n\n";
447
448 if ( $wgShowExceptionDetails ) {
449 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
450 'Exception caught inside exception handler: ' . $e2->__toString();
451 } else {
452 $message .= "Exception caught inside exception handler.\n\n" .
453 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
454 "to show detailed debugging information.";
455 }
456
457 $message .= "\n";
458
459 if ( $cmdLine ) {
460 self::printError( $message );
461 } else {
462 self::escapeEchoAndDie( $message );
463 }
464 }
465 } else {
466 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
467 $e->__toString() . "\n";
468
469 if ( $wgShowExceptionDetails ) {
470 $message .= "\n" . $e->getTraceAsString() . "\n";
471 }
472
473 if ( $cmdLine ) {
474 self::printError( $message );
475 } else {
476 self::escapeEchoAndDie( $message );
477 }
478 }
479 }
480
481 /**
482 * Print a message, if possible to STDERR.
483 * Use this in command line mode only (see isCommandLine)
484 * @param $message String Failure text
485 */
486 public static function printError( $message ) {
487 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
488 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
489 if ( defined( 'STDERR' ) ) {
490 fwrite( STDERR, $message );
491 } else {
492 echo( $message );
493 }
494 }
495
496 /**
497 * Print a message after escaping it and converting newlines to <br>
498 * Use this for non-command line failures
499 * @param $message String Failure text
500 */
501 private static function escapeEchoAndDie( $message ) {
502 echo nl2br( htmlspecialchars( $message ) ) . "\n";
503 die(1);
504 }
505
506 /**
507 * Exception handler which simulates the appropriate catch() handling:
508 *
509 * try {
510 * ...
511 * } catch ( MWException $e ) {
512 * $e->report();
513 * } catch ( Exception $e ) {
514 * echo $e->__toString();
515 * }
516 */
517 public static function handle( $e ) {
518 global $wgFullyInitialised;
519
520 self::report( $e );
521
522 // Final cleanup
523 if ( $wgFullyInitialised ) {
524 try {
525 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
526 } catch ( Exception $e ) {}
527 }
528
529 // Exit value should be nonzero for the benefit of shell jobs
530 exit( 1 );
531 }
532 }