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