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