Added a function that returns the list of supported formats to ApiMain
[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 if ( defined( 'MEDIAWIKI_INSTALL' ) || $this->htmlBodyOnly() ) {
192 echo $this->getHTML();
193 } else {
194 echo $this->htmlHeader();
195 echo $this->getHTML();
196 echo $this->htmlFooter();
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 */
223 function htmlHeader() {
224 global $wgLogo, $wgOutputEncoding, $wgLang;
225
226 if ( !headers_sent() ) {
227 header( 'HTTP/1.0 500 Internal Server Error' );
228 header( 'Content-type: text/html; charset=' . $wgOutputEncoding );
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 */
277 function htmlFooter() {
278 return Html::closeElement( 'body' ) . Html::closeElement( 'html' );
279 }
280
281 /**
282 * headers handled by subclass?
283 */
284 function htmlBodyOnly() {
285 return false;
286 }
287
288 static function isCommandLine() {
289 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
290 }
291 }
292
293 /**
294 * Exception class which takes an HTML error message, and does not
295 * produce a backtrace. Replacement for OutputPage::fatalError().
296 * @ingroup Exception
297 */
298 class FatalError extends MWException {
299 function getHTML() {
300 return $this->getMessage();
301 }
302
303 function getText() {
304 return $this->getMessage();
305 }
306 }
307
308 /**
309 * An error page which can definitely be safely rendered using the OutputPage
310 * @ingroup Exception
311 */
312 class ErrorPageError extends MWException {
313 public $title, $msg, $params;
314
315 /**
316 * Note: these arguments are keys into wfMsg(), not text!
317 */
318 function __construct( $title, $msg, $params = null ) {
319 $this->title = $title;
320 $this->msg = $msg;
321 $this->params = $params;
322
323 if( $msg instanceof Message ){
324 parent::__construct( $msg );
325 } else {
326 parent::__construct( wfMsg( $msg ) );
327 }
328 }
329
330 function report() {
331 global $wgOut;
332
333 if ( $wgOut->getTitle() ) {
334 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
335 }
336 $wgOut->setPageTitle( wfMsg( $this->title ) );
337 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
338 $wgOut->setRobotPolicy( 'noindex,nofollow' );
339 $wgOut->setArticleRelated( false );
340 $wgOut->enableClientCache( false );
341 $wgOut->mRedirect = '';
342 $wgOut->clearHTML();
343
344 if( $this->msg instanceof Message ){
345 $wgOut->addHTML( $this->msg->parse() );
346 } else {
347 $wgOut->addWikiMsgArray( $this->msg, $this->params );
348 }
349
350 $wgOut->returnToMain();
351 $wgOut->output();
352 }
353 }
354
355 /**
356 * Show an error when a user tries to do something they do not have the necessary
357 * permissions for.
358 */
359 class PermissionsError extends ErrorPageError {
360 public $permission;
361
362 function __construct( $permission ) {
363 global $wgLang;
364
365 $this->permission = $permission;
366
367 $groups = array_map(
368 array( 'User', 'makeGroupLinkWiki' ),
369 User::getGroupsWithPermission( $this->permission )
370 );
371
372 if( $groups ) {
373 parent::__construct(
374 'badaccess',
375 'badaccess-groups',
376 array(
377 $wgLang->commaList( $groups ),
378 count( $groups )
379 )
380 );
381 } else {
382 parent::__construct(
383 'badaccess',
384 'badaccess-group0'
385 );
386 }
387 }
388 }
389
390 /**
391 * Show an error when the wiki is locked/read-only and the user tries to do
392 * something that requires write access
393 */
394 class ReadOnlyError extends ErrorPageError {
395 public function __construct(){
396 parent::__construct(
397 'readonly',
398 'readonlytext',
399 wfReadOnlyReason()
400 );
401 }
402 }
403
404 /**
405 * Show an error when the user hits a rate limit
406 */
407 class ThrottledError extends ErrorPageError {
408 public function __construct(){
409 parent::__construct(
410 'actionthrottled',
411 'actionthrottledtext'
412 );
413 }
414 public function report(){
415 global $wgOut;
416 $wgOut->setStatusCode( 503 );
417 return parent::report();
418 }
419 }
420
421 /**
422 * Show an error when the user tries to do something whilst blocked
423 */
424 class UserBlockedError extends ErrorPageError {
425 public function __construct( Block $block ){
426 global $wgLang;
427
428 $blockerUserpage = $block->getBlocker()->getUserPage();
429 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
430
431 $reason = $block->mReason;
432 if( $reason == '' ) {
433 $reason = wfMsg( 'blockednoreason' );
434 }
435
436 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
437 * This could be a username, an IP range, or a single IP. */
438 $intended = $block->getTarget();
439
440 parent::__construct(
441 'blockedtitle',
442 $block->mAuto ? 'autoblocketext' : 'blockedtext',
443 array(
444 $link,
445 $reason,
446 wfGetIP(),
447 $block->getBlocker()->getName(),
448 $block->getId(),
449 $wgLang->formatExpiry( $block->mExpiry ),
450 $intended,
451 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
452 )
453 );
454 }
455 }
456
457 /**
458 * Install an exception handler for MediaWiki exception types.
459 */
460 function wfInstallExceptionHandler() {
461 set_exception_handler( 'wfExceptionHandler' );
462 }
463
464 /**
465 * Report an exception to the user
466 */
467 function wfReportException( Exception $e ) {
468 global $wgShowExceptionDetails;
469
470 $cmdLine = MWException::isCommandLine();
471
472 if ( $e instanceof MWException ) {
473 try {
474 // Try and show the exception prettily, with the normal skin infrastructure
475 $e->report();
476 } catch ( Exception $e2 ) {
477 // Exception occurred from within exception handler
478 // Show a simpler error message for the original exception,
479 // don't try to invoke report()
480 $message = "MediaWiki internal error.\n\n";
481
482 if ( $wgShowExceptionDetails ) {
483 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
484 'Exception caught inside exception handler: ' . $e2->__toString();
485 } else {
486 $message .= "Exception caught inside exception handler.\n\n" .
487 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
488 "to show detailed debugging information.";
489 }
490
491 $message .= "\n";
492
493 if ( $cmdLine ) {
494 wfPrintError( $message );
495 } else {
496 wfDie( htmlspecialchars( $message ) ) . "\n";
497 }
498 }
499 } else {
500 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
501 $e->__toString() . "\n";
502
503 if ( $wgShowExceptionDetails ) {
504 $message .= "\n" . $e->getTraceAsString() . "\n";
505 }
506
507 if ( $cmdLine ) {
508 wfPrintError( $message );
509 } else {
510 wfDie( htmlspecialchars( $message ) ) . "\n";
511 }
512 }
513 }
514
515 /**
516 * Print a message, if possible to STDERR.
517 * Use this in command line mode only (see isCommandLine)
518 */
519 function wfPrintError( $message ) {
520 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
521 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
522 if ( defined( 'STDERR' ) ) {
523 fwrite( STDERR, $message );
524 } else {
525 echo( $message );
526 }
527 }
528
529 /**
530 * Exception handler which simulates the appropriate catch() handling:
531 *
532 * try {
533 * ...
534 * } catch ( MWException $e ) {
535 * $e->report();
536 * } catch ( Exception $e ) {
537 * echo $e->__toString();
538 * }
539 */
540 function wfExceptionHandler( $e ) {
541 global $wgFullyInitialised;
542
543 wfReportException( $e );
544
545 // Final cleanup
546 if ( $wgFullyInitialised ) {
547 try {
548 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
549 } catch ( Exception $e ) {}
550 }
551
552 // Exit value should be nonzero for the benefit of shell jobs
553 exit( 1 );
554 }