allow methods to generate a "user does not have required permissions" error by throwi...
[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 wfMsgReal( $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 if ( $this->useMessageCache() ) {
137 return wfMsg( 'internalerror' );
138 } else {
139 global $wgSitename;
140
141 return "$wgSitename error";
142 }
143 }
144
145 /**
146 * Return the requested URL and point to file and line number from which the
147 * exception occured
148 *
149 * @return String
150 */
151 function getLogMessage() {
152 global $wgRequest;
153
154 $file = $this->getFile();
155 $line = $this->getLine();
156 $message = $this->getMessage();
157
158 if ( isset( $wgRequest ) ) {
159 $url = $wgRequest->getRequestURL();
160 if ( !$url ) {
161 $url = '[no URL]';
162 }
163 } else {
164 $url = '[no req]';
165 }
166
167 return "$url Exception from line $line of $file: $message";
168 }
169
170 /** Output the exception report using HTML */
171 function reportHTML() {
172 global $wgOut;
173
174 if ( $this->useOutputPage() ) {
175 $wgOut->setPageTitle( $this->getPageTitle() );
176 $wgOut->setRobotPolicy( "noindex,nofollow" );
177 $wgOut->setArticleRelated( false );
178 $wgOut->enableClientCache( false );
179 $wgOut->redirect( '' );
180 $wgOut->clearHTML();
181
182 $hookResult = $this->runHooks( get_class( $this ) );
183 if ( $hookResult ) {
184 $wgOut->addHTML( $hookResult );
185 } else {
186 $wgOut->addHTML( $this->getHTML() );
187 }
188
189 $wgOut->output();
190 } else {
191 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
192 if ( $hookResult ) {
193 die( $hookResult );
194 }
195
196 if ( defined( 'MEDIAWIKI_INSTALL' ) || $this->htmlBodyOnly() ) {
197 echo $this->getHTML();
198 } else {
199 echo $this->htmlHeader();
200 echo $this->getHTML();
201 echo $this->htmlFooter();
202 }
203 }
204 }
205
206 /**
207 * Output a report about the exception and takes care of formatting.
208 * It will be either HTML or plain text based on isCommandLine().
209 */
210 function report() {
211 $log = $this->getLogMessage();
212
213 if ( $log ) {
214 wfDebugLog( 'exception', $log );
215 }
216
217 if ( self::isCommandLine() ) {
218 wfPrintError( $this->getText() );
219 } else {
220 $this->reportHTML();
221 }
222 }
223
224 /**
225 * Send headers and output the beginning of the html page if not using
226 * $wgOut to output the exception.
227 */
228 function htmlHeader() {
229 global $wgLogo, $wgOutputEncoding, $wgLang;
230
231 if ( !headers_sent() ) {
232 header( 'HTTP/1.0 500 Internal Server Error' );
233 header( 'Content-type: text/html; charset=' . $wgOutputEncoding );
234 /* Don't cache error pages! They cause no end of trouble... */
235 header( 'Cache-control: none' );
236 header( 'Pragma: nocache' );
237 }
238
239 $head = Html::element( 'title', null, $this->getPageTitle() ) . "\n";
240 $head .= Html::inlineStyle( <<<ENDL
241 body {
242 color: #000;
243 background-color: #fff;
244 font-family: sans-serif;
245 padding: 2em;
246 text-align: center;
247 }
248 p, img, h1 {
249 text-align: left;
250 margin: 0.5em 0;
251 }
252 h1 {
253 font-size: 120%;
254 }
255 ENDL
256 );
257
258 $dir = 'ltr';
259 $code = 'en';
260
261 if ( $wgLang instanceof Language ) {
262 $dir = $wgLang->getDir();
263 $code = $wgLang->getCode();
264 }
265
266 $header = Html::element( 'img', array(
267 'src' => $wgLogo,
268 'alt' => '' ), $this->getPageTitle() );
269
270 $attribs = array( 'dir' => $dir, 'lang' => $code );
271
272 return
273 Html::htmlHeader( $attribs ) .
274 Html::rawElement( 'head', null, $head ) . "\n".
275 Html::openElement( 'body' ) . "\n" .
276 $header . "\n";
277 }
278
279 /**
280 * print the end of the html page if not using $wgOut.
281 */
282 function htmlFooter() {
283 return Html::closeElement( 'body' ) . Html::closeElement( 'html' );
284 }
285
286 /**
287 * headers handled by subclass?
288 */
289 function htmlBodyOnly() {
290 return false;
291 }
292
293 static function isCommandLine() {
294 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
295 }
296 }
297
298 /**
299 * Exception class which takes an HTML error message, and does not
300 * produce a backtrace. Replacement for OutputPage::fatalError().
301 * @ingroup Exception
302 */
303 class FatalError extends MWException {
304 function getHTML() {
305 return $this->getMessage();
306 }
307
308 function getText() {
309 return $this->getMessage();
310 }
311 }
312
313 /**
314 * An error page which can definitely be safely rendered using the OutputPage
315 * @ingroup Exception
316 */
317 class ErrorPageError extends MWException {
318 public $title, $msg, $params;
319
320 /**
321 * Note: these arguments are keys into wfMsg(), not text!
322 */
323 function __construct( $title, $msg, $params = null ) {
324 $this->title = $title;
325 $this->msg = $msg;
326 $this->params = $params;
327 parent::__construct( wfMsg( $msg ) );
328 }
329
330 function report() {
331 global $wgOut;
332
333 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
334 $wgOut->output();
335 }
336 }
337
338 /**
339 * Show an error when a user tries to do something they do not have the necessary
340 * permissions for.
341 */
342 class PermissionsError extends ErrorPageError {
343 public $permission;
344
345 function __construct( $permission ) {
346 global $wgLang;
347
348 $this->permission = $permission;
349
350 $groups = array_map(
351 array( 'User', 'makeGroupLinkWiki' ),
352 User::getGroupsWithPermission( $this->permission )
353 );
354
355 if( $groups ) {
356 parent::__construct(
357 'badaccess',
358 'badaccess-groups',
359 array(
360 $wgLang->commaList( $groups ),
361 count( $groups )
362 )
363 );
364 } else {
365 parent::__construct(
366 'badaccess',
367 'badaccess-group0'
368 );
369 }
370 }
371 }
372
373 /**
374 * Install an exception handler for MediaWiki exception types.
375 */
376 function wfInstallExceptionHandler() {
377 set_exception_handler( 'wfExceptionHandler' );
378 }
379
380 /**
381 * Report an exception to the user
382 */
383 function wfReportException( Exception $e ) {
384 global $wgShowExceptionDetails;
385
386 $cmdLine = MWException::isCommandLine();
387
388 if ( $e instanceof MWException ) {
389 try {
390 // Try and show the exception prettily, with the normal skin infrastructure
391 $e->report();
392 } catch ( Exception $e2 ) {
393 // Exception occurred from within exception handler
394 // Show a simpler error message for the original exception,
395 // don't try to invoke report()
396 $message = "MediaWiki internal error.\n\n";
397
398 if ( $wgShowExceptionDetails ) {
399 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
400 'Exception caught inside exception handler: ' . $e2->__toString();
401 } else {
402 $message .= "Exception caught inside exception handler.\n\n" .
403 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
404 "to show detailed debugging information.";
405 }
406
407 $message .= "\n";
408
409 if ( $cmdLine ) {
410 wfPrintError( $message );
411 } else {
412 wfDie( htmlspecialchars( $message ) ) . "\n";
413 }
414 }
415 } else {
416 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
417 $e->__toString() . "\n";
418
419 if ( $wgShowExceptionDetails ) {
420 $message .= "\n" . $e->getTraceAsString() . "\n";
421 }
422
423 if ( $cmdLine ) {
424 wfPrintError( $message );
425 } else {
426 wfDie( htmlspecialchars( $message ) ) . "\n";
427 }
428 }
429 }
430
431 /**
432 * Print a message, if possible to STDERR.
433 * Use this in command line mode only (see isCommandLine)
434 */
435 function wfPrintError( $message ) {
436 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
437 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
438 if ( defined( 'STDERR' ) ) {
439 fwrite( STDERR, $message );
440 } else {
441 echo( $message );
442 }
443 }
444
445 /**
446 * Exception handler which simulates the appropriate catch() handling:
447 *
448 * try {
449 * ...
450 * } catch ( MWException $e ) {
451 * $e->report();
452 * } catch ( Exception $e ) {
453 * echo $e->__toString();
454 * }
455 */
456 function wfExceptionHandler( $e ) {
457 global $wgFullyInitialised;
458
459 wfReportException( $e );
460
461 // Final cleanup
462 if ( $wgFullyInitialised ) {
463 try {
464 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
465 } catch ( Exception $e ) {}
466 }
467
468 // Exit value should be nonzero for the benefit of shell jobs
469 exit( 1 );
470 }