Added DatabaseUpdater::addExtensionUpdate() to let extensions add their own updates...
[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']->isArticle() ) ) &&
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 is_object( $wgLang );
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 if ( $hookResult = $this->runHooks( get_class( $this ) ) ) {
183 $wgOut->addHTML( $hookResult );
184 } else {
185 $wgOut->addHTML( $this->getHTML() );
186 }
187
188 $wgOut->output();
189 } else {
190 if ( $hookResult = $this->runHooks( get_class( $this ) . "Raw" ) ) {
191 die( $hookResult );
192 }
193
194 if ( defined( 'MEDIAWIKI_INSTALL' ) || $this->htmlBodyOnly() ) {
195 echo $this->getHTML();
196 } else {
197 echo $this->htmlHeader();
198 echo $this->getHTML();
199 echo $this->htmlFooter();
200 }
201 }
202 }
203
204 /**
205 * Output a report about the exception and takes care of formatting.
206 * It will be either HTML or plain text based on isCommandLine().
207 */
208 function report() {
209 $log = $this->getLogMessage();
210
211 if ( $log ) {
212 wfDebugLog( 'exception', $log );
213 }
214
215 if ( self::isCommandLine() ) {
216 wfPrintError( $this->getText() );
217 } else {
218 $this->reportHTML();
219 }
220 }
221
222 /**
223 * Send headers and output the beginning of the html page if not using
224 * $wgOut to output the exception.
225 */
226 function htmlHeader() {
227 global $wgLogo, $wgOutputEncoding;
228
229 if ( !headers_sent() ) {
230 header( 'HTTP/1.0 500 Internal Server Error' );
231 header( 'Content-type: text/html; charset=' . $wgOutputEncoding );
232 /* Don't cache error pages! They cause no end of trouble... */
233 header( 'Cache-control: none' );
234 header( 'Pragma: nocache' );
235 }
236
237 $title = $this->getPageTitle();
238 return "<html>
239 <head>
240 <title>$title</title>
241 </head>
242 <body>
243 <h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''/>$title</h1>
244 ";
245 }
246
247 /**
248 * print the end of the html page if not using $wgOut.
249 */
250 function htmlFooter() {
251 return "</body></html>";
252 }
253
254 /**
255 * headers handled by subclass?
256 */
257 function htmlBodyOnly() {
258 return false;
259 }
260
261 static function isCommandLine() {
262 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
263 }
264 }
265
266 /**
267 * Exception class which takes an HTML error message, and does not
268 * produce a backtrace. Replacement for OutputPage::fatalError().
269 * @ingroup Exception
270 */
271 class FatalError extends MWException {
272 function getHTML() {
273 return $this->getMessage();
274 }
275
276 function getText() {
277 return $this->getMessage();
278 }
279 }
280
281 /**
282 * @ingroup Exception
283 */
284 class ErrorPageError extends MWException {
285 public $title, $msg;
286
287 /**
288 * Note: these arguments are keys into wfMsg(), not text!
289 */
290 function __construct( $title, $msg ) {
291 $this->title = $title;
292 $this->msg = $msg;
293 parent::__construct( wfMsg( $msg ) );
294 }
295
296 function report() {
297 global $wgOut;
298
299 $wgOut->showErrorPage( $this->title, $this->msg );
300 $wgOut->output();
301 }
302 }
303
304 /**
305 * Install an exception handler for MediaWiki exception types.
306 */
307 function wfInstallExceptionHandler() {
308 set_exception_handler( 'wfExceptionHandler' );
309 }
310
311 /**
312 * Report an exception to the user
313 */
314 function wfReportException( Exception $e ) {
315 global $wgShowExceptionDetails;
316
317 $cmdLine = MWException::isCommandLine();
318
319 if ( $e instanceof MWException ) {
320 try {
321 $e->report();
322 } catch ( Exception $e2 ) {
323 // Exception occurred from within exception handler
324 // Show a simpler error message for the original exception,
325 // don't try to invoke report()
326 $message = "MediaWiki internal error.\n\n";
327
328 if ( $wgShowExceptionDetails ) {
329 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
330 'Exception caught inside exception handler: ' . $e2->__toString();
331 } else {
332 $message .= "Exception caught inside exception handler.\n\n" .
333 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
334 "to show detailed debugging information.";
335 }
336
337 $message .= "\n";
338
339 if ( $cmdLine ) {
340 wfPrintError( $message );
341 } else {
342 echo nl2br( htmlspecialchars( $message ) ) . "\n";
343 }
344 }
345 } else {
346 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
347 $e->__toString() . "\n";
348
349 if ( $wgShowExceptionDetails ) {
350 $message .= "\n" . $e->getTraceAsString() . "\n";
351 }
352
353 if ( $cmdLine ) {
354 wfPrintError( $message );
355 } else {
356 echo nl2br( htmlspecialchars( $message ) ) . "\n";
357 }
358 }
359 }
360
361 /**
362 * Print a message, if possible to STDERR.
363 * Use this in command line mode only (see isCommandLine)
364 */
365 function wfPrintError( $message ) {
366 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
367 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
368 if ( defined( 'STDERR' ) ) {
369 fwrite( STDERR, $message );
370 } else {
371 echo( $message );
372 }
373 }
374
375 /**
376 * Exception handler which simulates the appropriate catch() handling:
377 *
378 * try {
379 * ...
380 * } catch ( MWException $e ) {
381 * $e->report();
382 * } catch ( Exception $e ) {
383 * echo $e->__toString();
384 * }
385 */
386 function wfExceptionHandler( $e ) {
387 global $wgFullyInitialised;
388
389 wfReportException( $e );
390
391 // Final cleanup, similar to wfErrorExit()
392 if ( $wgFullyInitialised ) {
393 try {
394 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
395 } catch ( Exception $e ) {}
396 }
397
398 // Exit value should be nonzero for the benefit of shell jobs
399 exit( 1 );
400 }