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