Committing my new logging classes for review. Will later commit changes that use...
[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 echo $this->getHTML();
191 die(1);
192 }
193 }
194
195 /**
196 * Output a report about the exception and takes care of formatting.
197 * It will be either HTML or plain text based on isCommandLine().
198 */
199 function report() {
200 $log = $this->getLogMessage();
201
202 if ( $log ) {
203 wfDebugLog( 'exception', $log );
204 }
205
206 if ( self::isCommandLine() ) {
207 MWExceptionHandler::printError( $this->getText() );
208 } else {
209 $this->reportHTML();
210 }
211 }
212
213 static function isCommandLine() {
214 return !empty( $GLOBALS['wgCommandLineMode'] );
215 }
216 }
217
218 /**
219 * Exception class which takes an HTML error message, and does not
220 * produce a backtrace. Replacement for OutputPage::fatalError().
221 * @ingroup Exception
222 */
223 class FatalError extends MWException {
224 function getHTML() {
225 return $this->getMessage();
226 }
227
228 function getText() {
229 return $this->getMessage();
230 }
231 }
232
233 /**
234 * An error page which can definitely be safely rendered using the OutputPage
235 * @ingroup Exception
236 */
237 class ErrorPageError extends MWException {
238 public $title, $msg, $params;
239
240 /**
241 * Note: these arguments are keys into wfMsg(), not text!
242 */
243 function __construct( $title, $msg, $params = null ) {
244 $this->title = $title;
245 $this->msg = $msg;
246 $this->params = $params;
247
248 if( $msg instanceof Message ){
249 parent::__construct( $msg );
250 } else {
251 parent::__construct( wfMsg( $msg ) );
252 }
253 }
254
255 function report() {
256 global $wgOut;
257
258 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
259 $wgOut->output();
260 }
261 }
262
263 /**
264 * Show an error when a user tries to do something they do not have the necessary
265 * permissions for.
266 * @ingroup Exception
267 */
268 class PermissionsError extends ErrorPageError {
269 public $permission;
270
271 function __construct( $permission ) {
272 global $wgLang;
273
274 $this->permission = $permission;
275
276 $groups = array_map(
277 array( 'User', 'makeGroupLinkWiki' ),
278 User::getGroupsWithPermission( $this->permission )
279 );
280
281 if( $groups ) {
282 parent::__construct(
283 'badaccess',
284 'badaccess-groups',
285 array(
286 $wgLang->commaList( $groups ),
287 count( $groups )
288 )
289 );
290 } else {
291 parent::__construct(
292 'badaccess',
293 'badaccess-group0'
294 );
295 }
296 }
297 }
298
299 /**
300 * Show an error when the wiki is locked/read-only and the user tries to do
301 * something that requires write access
302 * @ingroup Exception
303 */
304 class ReadOnlyError extends ErrorPageError {
305 public function __construct(){
306 parent::__construct(
307 'readonly',
308 'readonlytext',
309 wfReadOnlyReason()
310 );
311 }
312 }
313
314 /**
315 * Show an error when the user hits a rate limit
316 * @ingroup Exception
317 */
318 class ThrottledError extends ErrorPageError {
319 public function __construct(){
320 parent::__construct(
321 'actionthrottled',
322 'actionthrottledtext'
323 );
324 }
325 public function report(){
326 global $wgOut;
327 $wgOut->setStatusCode( 503 );
328 return parent::report();
329 }
330 }
331
332 /**
333 * Show an error when the user tries to do something whilst blocked
334 * @ingroup Exception
335 */
336 class UserBlockedError extends ErrorPageError {
337 public function __construct( Block $block ){
338 global $wgLang, $wgRequest;
339
340 $blockerUserpage = $block->getBlocker()->getUserPage();
341 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
342
343 $reason = $block->mReason;
344 if( $reason == '' ) {
345 $reason = wfMsg( 'blockednoreason' );
346 }
347
348 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
349 * This could be a username, an IP range, or a single IP. */
350 $intended = $block->getTarget();
351
352 parent::__construct(
353 'blockedtitle',
354 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
355 array(
356 $link,
357 $reason,
358 $wgRequest->getIP(),
359 $block->getBlocker()->getName(),
360 $block->getId(),
361 $wgLang->formatExpiry( $block->mExpiry ),
362 $intended,
363 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
364 )
365 );
366 }
367 }
368
369 /**
370 * Handler class for MWExceptions
371 * @ingroup Exception
372 */
373 class MWExceptionHandler {
374 /**
375 * Install an exception handler for MediaWiki exception types.
376 */
377 public static function installHandler() {
378 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
379 }
380
381 /**
382 * Report an exception to the user
383 */
384 protected static function report( Exception $e ) {
385 global $wgShowExceptionDetails;
386
387 $cmdLine = MWException::isCommandLine();
388
389 if ( $e instanceof MWException ) {
390 try {
391 // Try and show the exception prettily, with the normal skin infrastructure
392 $e->report();
393 } catch ( Exception $e2 ) {
394 // Exception occurred from within exception handler
395 // Show a simpler error message for the original exception,
396 // don't try to invoke report()
397 $message = "MediaWiki internal error.\n\n";
398
399 if ( $wgShowExceptionDetails ) {
400 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
401 'Exception caught inside exception handler: ' . $e2->__toString();
402 } else {
403 $message .= "Exception caught inside exception handler.\n\n" .
404 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
405 "to show detailed debugging information.";
406 }
407
408 $message .= "\n";
409
410 if ( $cmdLine ) {
411 self::printError( $message );
412 } else {
413 self::escapeEchoAndDie( $message );
414 }
415 }
416 } else {
417 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
418 $e->__toString() . "\n";
419
420 if ( $wgShowExceptionDetails ) {
421 $message .= "\n" . $e->getTraceAsString() . "\n";
422 }
423
424 if ( $cmdLine ) {
425 self::printError( $message );
426 } else {
427 self::escapeEchoAndDie( $message );
428 }
429 }
430 }
431
432 /**
433 * Print a message, if possible to STDERR.
434 * Use this in command line mode only (see isCommandLine)
435 * @param $message String Failure text
436 */
437 public static function printError( $message ) {
438 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
439 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
440 if ( defined( 'STDERR' ) ) {
441 fwrite( STDERR, $message );
442 } else {
443 echo( $message );
444 }
445 }
446
447 /**
448 * Print a message after escaping it and converting newlines to <br>
449 * Use this for non-command line failures
450 * @param $message String Failure text
451 */
452 private static function escapeEchoAndDie( $message ) {
453 echo nl2br( htmlspecialchars( $message ) ) . "\n";
454 die(1);
455 }
456
457 /**
458 * Exception handler which simulates the appropriate catch() handling:
459 *
460 * try {
461 * ...
462 * } catch ( MWException $e ) {
463 * $e->report();
464 * } catch ( Exception $e ) {
465 * echo $e->__toString();
466 * }
467 */
468 public static function handle( $e ) {
469 global $wgFullyInitialised;
470
471 self::report( $e );
472
473 // Final cleanup
474 if ( $wgFullyInitialised ) {
475 try {
476 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
477 } catch ( Exception $e ) {}
478 }
479
480 // Exit value should be nonzero for the benefit of shell jobs
481 exit( 1 );
482 }
483 }