$wgArticle is deprecated! Possible removal in 1.20 or 1.21!
[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 !$GLOBALS['wgOut']->isArticleRelated() &&
27 !empty( $GLOBALS['wgTitle'] );
28 }
29
30 /**
31 * Can the extension use wfMsg() to get i18n messages ?
32 * @return bool
33 */
34 function useMessageCache() {
35 global $wgLang;
36
37 foreach ( $this->getTrace() as $frame ) {
38 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
39 return false;
40 }
41 }
42
43 return $wgLang instanceof Language;
44 }
45
46 /**
47 * Run hook to allow extensions to modify the text of the exception
48 *
49 * @param $name String: class name of the exception
50 * @param $args Array: arguments to pass to the callback functions
51 * @return Mixed: string to output or null if any hook has been called
52 */
53 function runHooks( $name, $args = array() ) {
54 global $wgExceptionHooks;
55
56 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
57 return; // Just silently ignore
58 }
59
60 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
61 return;
62 }
63
64 $hooks = $wgExceptionHooks[ $name ];
65 $callargs = array_merge( array( $this ), $args );
66
67 foreach ( $hooks as $hook ) {
68 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
69 $result = call_user_func_array( $hook, $callargs );
70 } else {
71 $result = null;
72 }
73
74 if ( is_string( $result ) )
75 return $result;
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 /* Return titles of this error page */
136 function getPageTitle() {
137 global $wgSitename;
138 return $this->msg( 'internalerror', "$wgSitename error" );
139 }
140
141 /**
142 * Return the requested URL and point to file and line number from which the
143 * exception occured
144 *
145 * @return String
146 */
147 function getLogMessage() {
148 global $wgRequest;
149
150 $file = $this->getFile();
151 $line = $this->getLine();
152 $message = $this->getMessage();
153
154 if ( isset( $wgRequest ) ) {
155 $url = $wgRequest->getRequestURL();
156 if ( !$url ) {
157 $url = '[no URL]';
158 }
159 } else {
160 $url = '[no req]';
161 }
162
163 return "$url Exception from line $line of $file: $message";
164 }
165
166 /** Output the exception report using HTML */
167 function reportHTML() {
168 global $wgOut;
169
170 if ( $this->useOutputPage() ) {
171 $wgOut->setPageTitle( $this->getPageTitle() );
172 $wgOut->setRobotPolicy( "noindex,nofollow" );
173 $wgOut->setArticleRelated( false );
174 $wgOut->enableClientCache( false );
175 $wgOut->redirect( '' );
176 $wgOut->clearHTML();
177
178 $hookResult = $this->runHooks( get_class( $this ) );
179 if ( $hookResult ) {
180 $wgOut->addHTML( $hookResult );
181 } else {
182 $wgOut->addHTML( $this->getHTML() );
183 }
184
185 $wgOut->output();
186 } else {
187 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
188 if ( $hookResult ) {
189 die( $hookResult );
190 }
191
192 $html = $this->getHTML();
193 if ( defined( 'MEDIAWIKI_INSTALL' ) ) {
194 echo $html;
195 } else {
196 wfDie( $html );
197 }
198 }
199 }
200
201 /**
202 * Output a report about the exception and takes care of formatting.
203 * It will be either HTML or plain text based on isCommandLine().
204 */
205 function report() {
206 $log = $this->getLogMessage();
207
208 if ( $log ) {
209 wfDebugLog( 'exception', $log );
210 }
211
212 if ( self::isCommandLine() ) {
213 wfPrintError( $this->getText() );
214 } else {
215 $this->reportHTML();
216 }
217 }
218
219 /**
220 * Send headers and output the beginning of the html page if not using
221 * $wgOut to output the exception.
222 * @deprecated since 1.18 call wfDie() if you need to die immediately
223 */
224 function htmlHeader() {
225 global $wgLogo, $wgLang;
226
227 if ( !headers_sent() ) {
228 header( 'HTTP/1.0 500 Internal Server Error' );
229 header( 'Content-type: text/html; charset=UTF-8' );
230 /* Don't cache error pages! They cause no end of trouble... */
231 header( 'Cache-control: none' );
232 header( 'Pragma: nocache' );
233 }
234
235 $head = Html::element( 'title', null, $this->getPageTitle() ) . "\n";
236 $head .= Html::inlineStyle( <<<ENDL
237 body {
238 color: #000;
239 background-color: #fff;
240 font-family: sans-serif;
241 padding: 2em;
242 text-align: center;
243 }
244 p, img, h1 {
245 text-align: left;
246 margin: 0.5em 0;
247 }
248 h1 {
249 font-size: 120%;
250 }
251 ENDL
252 );
253
254 $dir = 'ltr';
255 $code = 'en';
256
257 if ( $wgLang instanceof Language ) {
258 $dir = $wgLang->getDir();
259 $code = $wgLang->getCode();
260 }
261
262 $header = Html::element( 'img', array(
263 'src' => $wgLogo,
264 'alt' => '' ) );
265
266 $attribs = array( 'dir' => $dir, 'lang' => $code );
267
268 return
269 Html::htmlHeader( $attribs ) .
270 Html::rawElement( 'head', null, $head ) . "\n".
271 Html::openElement( 'body' ) . "\n" .
272 $header . "\n";
273 }
274
275 /**
276 * print the end of the html page if not using $wgOut.
277 * @deprecated since 1.18
278 */
279 function htmlFooter() {
280 return Html::closeElement( 'body' ) . Html::closeElement( 'html' );
281 }
282
283 static function isCommandLine() {
284 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
285 }
286 }
287
288 /**
289 * Exception class which takes an HTML error message, and does not
290 * produce a backtrace. Replacement for OutputPage::fatalError().
291 * @ingroup Exception
292 */
293 class FatalError extends MWException {
294 function getHTML() {
295 return $this->getMessage();
296 }
297
298 function getText() {
299 return $this->getMessage();
300 }
301 }
302
303 /**
304 * An error page which can definitely be safely rendered using the OutputPage
305 * @ingroup Exception
306 */
307 class ErrorPageError extends MWException {
308 public $title, $msg, $params;
309
310 /**
311 * Note: these arguments are keys into wfMsg(), not text!
312 */
313 function __construct( $title, $msg, $params = null ) {
314 $this->title = $title;
315 $this->msg = $msg;
316 $this->params = $params;
317
318 if( $msg instanceof Message ){
319 parent::__construct( $msg );
320 } else {
321 parent::__construct( wfMsg( $msg ) );
322 }
323 }
324
325 function report() {
326 global $wgOut;
327
328 if ( $wgOut->getTitle() ) {
329 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
330 }
331 $wgOut->setPageTitle( wfMsg( $this->title ) );
332 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
333 $wgOut->setRobotPolicy( 'noindex,nofollow' );
334 $wgOut->setArticleRelated( false );
335 $wgOut->enableClientCache( false );
336 $wgOut->mRedirect = '';
337 $wgOut->clearHTML();
338
339 if( $this->msg instanceof Message ){
340 $wgOut->addHTML( $this->msg->parse() );
341 } else {
342 $wgOut->addWikiMsgArray( $this->msg, $this->params );
343 }
344
345 $wgOut->returnToMain();
346 $wgOut->output();
347 }
348 }
349
350 /**
351 * Show an error when a user tries to do something they do not have the necessary
352 * permissions for.
353 */
354 class PermissionsError extends ErrorPageError {
355 public $permission;
356
357 function __construct( $permission ) {
358 global $wgLang;
359
360 $this->permission = $permission;
361
362 $groups = array_map(
363 array( 'User', 'makeGroupLinkWiki' ),
364 User::getGroupsWithPermission( $this->permission )
365 );
366
367 if( $groups ) {
368 parent::__construct(
369 'badaccess',
370 'badaccess-groups',
371 array(
372 $wgLang->commaList( $groups ),
373 count( $groups )
374 )
375 );
376 } else {
377 parent::__construct(
378 'badaccess',
379 'badaccess-group0'
380 );
381 }
382 }
383 }
384
385 /**
386 * Show an error when the wiki is locked/read-only and the user tries to do
387 * something that requires write access
388 */
389 class ReadOnlyError extends ErrorPageError {
390 public function __construct(){
391 parent::__construct(
392 'readonly',
393 'readonlytext',
394 wfReadOnlyReason()
395 );
396 }
397 }
398
399 /**
400 * Show an error when the user hits a rate limit
401 */
402 class ThrottledError extends ErrorPageError {
403 public function __construct(){
404 parent::__construct(
405 'actionthrottled',
406 'actionthrottledtext'
407 );
408 }
409 public function report(){
410 global $wgOut;
411 $wgOut->setStatusCode( 503 );
412 return parent::report();
413 }
414 }
415
416 /**
417 * Show an error when the user tries to do something whilst blocked
418 */
419 class UserBlockedError extends ErrorPageError {
420 public function __construct( Block $block ){
421 global $wgLang;
422
423 $blockerUserpage = $block->getBlocker()->getUserPage();
424 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
425
426 $reason = $block->mReason;
427 if( $reason == '' ) {
428 $reason = wfMsg( 'blockednoreason' );
429 }
430
431 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
432 * This could be a username, an IP range, or a single IP. */
433 $intended = $block->getTarget();
434
435 parent::__construct(
436 'blockedtitle',
437 $block->mAuto ? 'autoblocketext' : 'blockedtext',
438 array(
439 $link,
440 $reason,
441 wfGetIP(),
442 $block->getBlocker()->getName(),
443 $block->getId(),
444 $wgLang->formatExpiry( $block->mExpiry ),
445 $intended,
446 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
447 )
448 );
449 }
450 }
451
452 /**
453 * Install an exception handler for MediaWiki exception types.
454 */
455 function wfInstallExceptionHandler() {
456 set_exception_handler( 'wfExceptionHandler' );
457 }
458
459 /**
460 * Report an exception to the user
461 */
462 function wfReportException( Exception $e ) {
463 global $wgShowExceptionDetails;
464
465 $cmdLine = MWException::isCommandLine();
466
467 if ( $e instanceof MWException ) {
468 try {
469 // Try and show the exception prettily, with the normal skin infrastructure
470 $e->report();
471 } catch ( Exception $e2 ) {
472 // Exception occurred from within exception handler
473 // Show a simpler error message for the original exception,
474 // don't try to invoke report()
475 $message = "MediaWiki internal error.\n\n";
476
477 if ( $wgShowExceptionDetails ) {
478 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
479 'Exception caught inside exception handler: ' . $e2->__toString();
480 } else {
481 $message .= "Exception caught inside exception handler.\n\n" .
482 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
483 "to show detailed debugging information.";
484 }
485
486 $message .= "\n";
487
488 if ( $cmdLine ) {
489 wfPrintError( $message );
490 } else {
491 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
492 }
493 }
494 } else {
495 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
496 $e->__toString() . "\n";
497
498 if ( $wgShowExceptionDetails ) {
499 $message .= "\n" . $e->getTraceAsString() . "\n";
500 }
501
502 if ( $cmdLine ) {
503 wfPrintError( $message );
504 } else {
505 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
506 }
507 }
508 }
509
510 /**
511 * Print a message, if possible to STDERR.
512 * Use this in command line mode only (see isCommandLine)
513 */
514 function wfPrintError( $message ) {
515 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
516 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
517 if ( defined( 'STDERR' ) ) {
518 fwrite( STDERR, $message );
519 } else {
520 echo( $message );
521 }
522 }
523
524 /**
525 * Exception handler which simulates the appropriate catch() handling:
526 *
527 * try {
528 * ...
529 * } catch ( MWException $e ) {
530 * $e->report();
531 * } catch ( Exception $e ) {
532 * echo $e->__toString();
533 * }
534 */
535 function wfExceptionHandler( $e ) {
536 global $wgFullyInitialised;
537
538 wfReportException( $e );
539
540 // Final cleanup
541 if ( $wgFullyInitialised ) {
542 try {
543 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
544 } catch ( Exception $e ) {}
545 }
546
547 // Exit value should be nonzero for the benefit of shell jobs
548 exit( 1 );
549 }