Misc. exception handling cleanup--moved it out of global function namespace
[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 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
186 if ( $hookResult ) {
187 die( $hookResult );
188 }
189
190 $html = $this->getHTML();
191 if ( defined( 'MEDIAWIKI_INSTALL' ) ) {
192 echo $html;
193 } else {
194 wfDie( $html );
195 }
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'] ) && !defined( 'MEDIAWIKI_INSTALL' );
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 if ( $wgOut->getTitle() ) {
263 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
264 }
265 $wgOut->setPageTitle( wfMsg( $this->title ) );
266 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
267 $wgOut->setRobotPolicy( 'noindex,nofollow' );
268 $wgOut->setArticleRelated( false );
269 $wgOut->enableClientCache( false );
270 $wgOut->mRedirect = '';
271 $wgOut->clearHTML();
272
273 if( $this->msg instanceof Message ){
274 $wgOut->addHTML( $this->msg->parse() );
275 } else {
276 $wgOut->addWikiMsgArray( $this->msg, $this->params );
277 }
278
279 $wgOut->returnToMain();
280 $wgOut->output();
281 }
282 }
283
284 /**
285 * Show an error when a user tries to do something they do not have the necessary
286 * permissions for.
287 */
288 class PermissionsError extends ErrorPageError {
289 public $permission;
290
291 function __construct( $permission ) {
292 global $wgLang;
293
294 $this->permission = $permission;
295
296 $groups = array_map(
297 array( 'User', 'makeGroupLinkWiki' ),
298 User::getGroupsWithPermission( $this->permission )
299 );
300
301 if( $groups ) {
302 parent::__construct(
303 'badaccess',
304 'badaccess-groups',
305 array(
306 $wgLang->commaList( $groups ),
307 count( $groups )
308 )
309 );
310 } else {
311 parent::__construct(
312 'badaccess',
313 'badaccess-group0'
314 );
315 }
316 }
317 }
318
319 /**
320 * Show an error when the wiki is locked/read-only and the user tries to do
321 * something that requires write access
322 */
323 class ReadOnlyError extends ErrorPageError {
324 public function __construct(){
325 parent::__construct(
326 'readonly',
327 'readonlytext',
328 wfReadOnlyReason()
329 );
330 }
331 }
332
333 /**
334 * Show an error when the user hits a rate limit
335 */
336 class ThrottledError extends ErrorPageError {
337 public function __construct(){
338 parent::__construct(
339 'actionthrottled',
340 'actionthrottledtext'
341 );
342 }
343 public function report(){
344 global $wgOut;
345 $wgOut->setStatusCode( 503 );
346 return parent::report();
347 }
348 }
349
350 /**
351 * Show an error when the user tries to do something whilst blocked
352 */
353 class UserBlockedError extends ErrorPageError {
354 public function __construct( Block $block ){
355 global $wgLang;
356
357 $blockerUserpage = $block->getBlocker()->getUserPage();
358 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
359
360 $reason = $block->mReason;
361 if( $reason == '' ) {
362 $reason = wfMsg( 'blockednoreason' );
363 }
364
365 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
366 * This could be a username, an IP range, or a single IP. */
367 $intended = $block->getTarget();
368
369 parent::__construct(
370 'blockedtitle',
371 $block->mAuto ? 'autoblocketext' : 'blockedtext',
372 array(
373 $link,
374 $reason,
375 wfGetIP(),
376 $block->getBlocker()->getName(),
377 $block->getId(),
378 $wgLang->formatExpiry( $block->mExpiry ),
379 $intended,
380 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
381 )
382 );
383 }
384 }
385
386 /**
387 * Handler class for MWExceptions
388 */
389 class MWExceptionHandler {
390 /**
391 * Install an exception handler for MediaWiki exception types.
392 */
393 public static function installHandler() {
394 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
395 }
396
397 /**
398 * Report an exception to the user
399 */
400 protected static function report( Exception $e ) {
401 global $wgShowExceptionDetails;
402
403 $cmdLine = MWException::isCommandLine();
404
405 if ( $e instanceof MWException ) {
406 try {
407 // Try and show the exception prettily, with the normal skin infrastructure
408 $e->report();
409 } catch ( Exception $e2 ) {
410 // Exception occurred from within exception handler
411 // Show a simpler error message for the original exception,
412 // don't try to invoke report()
413 $message = "MediaWiki internal error.\n\n";
414
415 if ( $wgShowExceptionDetails ) {
416 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
417 'Exception caught inside exception handler: ' . $e2->__toString();
418 } else {
419 $message .= "Exception caught inside exception handler.\n\n" .
420 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
421 "to show detailed debugging information.";
422 }
423
424 $message .= "\n";
425
426 if ( $cmdLine ) {
427 self::printError( $message );
428 } else {
429 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
430 }
431 }
432 } else {
433 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
434 $e->__toString() . "\n";
435
436 if ( $wgShowExceptionDetails ) {
437 $message .= "\n" . $e->getTraceAsString() . "\n";
438 }
439
440 if ( $cmdLine ) {
441 self::printError( $message );
442 } else {
443 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
444 }
445 }
446 }
447
448 /**
449 * Print a message, if possible to STDERR.
450 * Use this in command line mode only (see isCommandLine)
451 */
452 public static function printError( $message ) {
453 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
454 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
455 if ( defined( 'STDERR' ) ) {
456 fwrite( STDERR, $message );
457 } else {
458 echo( $message );
459 }
460 }
461
462 /**
463 * Exception handler which simulates the appropriate catch() handling:
464 *
465 * try {
466 * ...
467 * } catch ( MWException $e ) {
468 * $e->report();
469 * } catch ( Exception $e ) {
470 * echo $e->__toString();
471 * }
472 */
473 public static function handle( $e ) {
474 global $wgFullyInitialised;
475
476 self::report( $e );
477
478 // Final cleanup
479 if ( $wgFullyInitialised ) {
480 try {
481 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
482 } catch ( Exception $e ) {}
483 }
484
485 // Exit value should be nonzero for the benefit of shell jobs
486 exit( 1 );
487 }
488 }