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