Follow-up r88054: register the file if a hook changed the target file.
[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 ) ) {
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 if ( $wgOut->getTitle() ) {
259 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
260 }
261 $wgOut->setPageTitle( wfMsg( $this->title ) );
262 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
263 $wgOut->setRobotPolicy( 'noindex,nofollow' );
264 $wgOut->setArticleRelated( false );
265 $wgOut->enableClientCache( false );
266 $wgOut->mRedirect = '';
267 $wgOut->clearHTML();
268
269 if( $this->msg instanceof Message ){
270 $wgOut->addHTML( $this->msg->parse() );
271 } else {
272 $wgOut->addWikiMsgArray( $this->msg, $this->params );
273 }
274
275 $wgOut->returnToMain();
276 $wgOut->output();
277 }
278 }
279
280 /**
281 * Show an error when a user tries to do something they do not have the necessary
282 * permissions for.
283 * @ingroup Exception
284 */
285 class PermissionsError extends ErrorPageError {
286 public $permission;
287
288 function __construct( $permission ) {
289 global $wgLang;
290
291 $this->permission = $permission;
292
293 $groups = array_map(
294 array( 'User', 'makeGroupLinkWiki' ),
295 User::getGroupsWithPermission( $this->permission )
296 );
297
298 if( $groups ) {
299 parent::__construct(
300 'badaccess',
301 'badaccess-groups',
302 array(
303 $wgLang->commaList( $groups ),
304 count( $groups )
305 )
306 );
307 } else {
308 parent::__construct(
309 'badaccess',
310 'badaccess-group0'
311 );
312 }
313 }
314 }
315
316 /**
317 * Show an error when the wiki is locked/read-only and the user tries to do
318 * something that requires write access
319 * @ingroup Exception
320 */
321 class ReadOnlyError extends ErrorPageError {
322 public function __construct(){
323 parent::__construct(
324 'readonly',
325 'readonlytext',
326 wfReadOnlyReason()
327 );
328 }
329 }
330
331 /**
332 * Show an error when the user hits a rate limit
333 * @ingroup Exception
334 */
335 class ThrottledError extends ErrorPageError {
336 public function __construct(){
337 parent::__construct(
338 'actionthrottled',
339 'actionthrottledtext'
340 );
341 }
342 public function report(){
343 global $wgOut;
344 $wgOut->setStatusCode( 503 );
345 return parent::report();
346 }
347 }
348
349 /**
350 * Show an error when the user tries to do something whilst blocked
351 * @ingroup Exception
352 */
353 class UserBlockedError extends ErrorPageError {
354 public function __construct( Block $block ){
355 global $wgLang;
356
357 $blockerUserpage = $block->getBlocker()->getUserPage();
358 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
359
360 $reason = $block->mReason;
361 if( $reason == '' ) {
362 $reason = wfMsg( 'blockednoreason' );
363 }
364
365 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
366 * This could be a username, an IP range, or a single IP. */
367 $intended = $block->getTarget();
368
369 parent::__construct(
370 'blockedtitle',
371 $block->mAuto ? 'autoblocketext' : 'blockedtext',
372 array(
373 $link,
374 $reason,
375 wfGetIP(),
376 $block->getBlocker()->getName(),
377 $block->getId(),
378 $wgLang->formatExpiry( $block->mExpiry ),
379 $intended,
380 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
381 )
382 );
383 }
384 }
385
386 /**
387 * Handler class for MWExceptions
388 * @ingroup Exception
389 */
390 class MWExceptionHandler {
391 /**
392 * Install an exception handler for MediaWiki exception types.
393 */
394 public static function installHandler() {
395 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
396 }
397
398 /**
399 * Report an exception to the user
400 */
401 protected static function report( Exception $e ) {
402 global $wgShowExceptionDetails;
403
404 $cmdLine = MWException::isCommandLine();
405
406 if ( $e instanceof MWException ) {
407 try {
408 // Try and show the exception prettily, with the normal skin infrastructure
409 $e->report();
410 } catch ( Exception $e2 ) {
411 // Exception occurred from within exception handler
412 // Show a simpler error message for the original exception,
413 // don't try to invoke report()
414 $message = "MediaWiki internal error.\n\n";
415
416 if ( $wgShowExceptionDetails ) {
417 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
418 'Exception caught inside exception handler: ' . $e2->__toString();
419 } else {
420 $message .= "Exception caught inside exception handler.\n\n" .
421 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
422 "to show detailed debugging information.";
423 }
424
425 $message .= "\n";
426
427 if ( $cmdLine ) {
428 self::printError( $message );
429 } else {
430 self::escapeEchoAndDie( $message );
431 }
432 }
433 } else {
434 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
435 $e->__toString() . "\n";
436
437 if ( $wgShowExceptionDetails ) {
438 $message .= "\n" . $e->getTraceAsString() . "\n";
439 }
440
441 if ( $cmdLine ) {
442 self::printError( $message );
443 } else {
444 self::escapeEchoAndDie( $message );
445 }
446 }
447 }
448
449 /**
450 * Print a message, if possible to STDERR.
451 * Use this in command line mode only (see isCommandLine)
452 * @param $message String Failure text
453 */
454 public static function printError( $message ) {
455 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
456 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
457 if ( defined( 'STDERR' ) ) {
458 fwrite( STDERR, $message );
459 } else {
460 echo( $message );
461 }
462 }
463
464 /**
465 * Print a message after escaping it and converting newlines to <br>
466 * Use this for non-command line failures
467 * @param $message String Failure text
468 */
469 private static function escapeEchoAndDie( $message ) {
470 echo nl2br( htmlspecialchars( $message ) ) . "\n";
471 die(1);
472 }
473
474 /**
475 * Exception handler which simulates the appropriate catch() handling:
476 *
477 * try {
478 * ...
479 * } catch ( MWException $e ) {
480 * $e->report();
481 * } catch ( Exception $e ) {
482 * echo $e->__toString();
483 * }
484 */
485 public static function handle( $e ) {
486 global $wgFullyInitialised;
487
488 self::report( $e );
489
490 // Final cleanup
491 if ( $wgFullyInitialised ) {
492 try {
493 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
494 } catch ( Exception $e ) {}
495 }
496
497 // Exit value should be nonzero for the benefit of shell jobs
498 exit( 1 );
499 }
500 }