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