(bug 17506) Respect $wgShowExceptionDetails when handling exceptions within exception...
[lhc/web/wiklou.git] / includes / Exception.php
1 <?php
2 /**
3 * @defgroup Exception Exception
4 */
5
6 /**
7 * MediaWiki exception
8 * @ingroup Exception
9 */
10 class MWException extends Exception {
11
12 /**
13 * Should the exception use $wgOut to output the error ?
14 * @return bool
15 */
16 function useOutputPage() {
17 return !empty( $GLOBALS['wgFullyInitialised'] ) &&
18 ( !empty( $GLOBALS['wgArticle'] ) || ( !empty( $GLOBALS['wgOut'] ) && !$GLOBALS['wgOut']->isArticle() ) ) &&
19 !empty( $GLOBALS['wgTitle'] );
20 }
21
22 /**
23 * Can the extension use wfMsg() to get i18n messages ?
24 * @return bool
25 */
26 function useMessageCache() {
27 global $wgLang;
28 return is_object( $wgLang );
29 }
30
31 /**
32 * Run hook to allow extensions to modify the text of the exception
33 *
34 * @param String $name class name of the exception
35 * @param Array $args arguments to pass to the callback functions
36 * @return mixed string to output or null if any hook has been called
37 */
38 function runHooks( $name, $args = array() ) {
39 global $wgExceptionHooks;
40 if( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) )
41 return; // Just silently ignore
42 if( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) )
43 return;
44 $hooks = $wgExceptionHooks[ $name ];
45 $callargs = array_merge( array( $this ), $args );
46
47 foreach( $hooks as $hook ) {
48 if( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { //'function' or array( 'class', hook' )
49 $result = call_user_func_array( $hook, $callargs );
50 } else {
51 $result = null;
52 }
53 if( is_string( $result ) )
54 return $result;
55 }
56 }
57
58 /**
59 * Get a message from i18n
60 *
61 * @param String $key message name
62 * @param String $fallback default message if the message cache can't be
63 * called by the exception
64 * The function also has other parameters that are arguments for the message
65 * @return String message with arguments replaced
66 */
67 function msg( $key, $fallback /*[, params...] */ ) {
68 $args = array_slice( func_get_args(), 2 );
69 if ( $this->useMessageCache() ) {
70 return wfMsgReal( $key, $args );
71 } else {
72 return wfMsgReplaceArgs( $fallback, $args );
73 }
74 }
75
76 /**
77 * If $wgShowExceptionDetails is true, return a HTML message with a
78 * backtrace to the error, otherwise show a message to ask to set it to true
79 * to show that information.
80 *
81 * @return String html to output
82 */
83 function getHTML() {
84 global $wgShowExceptionDetails;
85 if( $wgShowExceptionDetails ) {
86 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
87 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
88 "</p>\n";
89 } else {
90 return "<p>Set <b><tt>\$wgShowExceptionDetails = true;</tt></b> " .
91 "at the bottom of LocalSettings.php to show detailed " .
92 "debugging information.</p>";
93 }
94 }
95
96 /**
97 * If $wgShowExceptionDetails is true, return a text message with a
98 * backtrace to the error.
99 */
100 function getText() {
101 global $wgShowExceptionDetails;
102 if( $wgShowExceptionDetails ) {
103 return $this->getMessage() .
104 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
105 } else {
106 return "Set \$wgShowExceptionDetails = true; " .
107 "in LocalSettings.php to show detailed debugging information.\n";
108 }
109 }
110
111 /* Return titles of this error page */
112 function getPageTitle() {
113 if ( $this->useMessageCache() ) {
114 return wfMsg( 'internalerror' );
115 } else {
116 global $wgSitename;
117 return "$wgSitename error";
118 }
119 }
120
121 /**
122 * Return the requested URL and point to file and line number from which the
123 * exception occured
124 *
125 * @return string
126 */
127 function getLogMessage() {
128 global $wgRequest;
129 $file = $this->getFile();
130 $line = $this->getLine();
131 $message = $this->getMessage();
132 if ( isset( $wgRequest ) ) {
133 $url = $wgRequest->getRequestURL();
134 if ( !$url ) {
135 $url = '[no URL]';
136 }
137 } else {
138 $url = '[no req]';
139 }
140
141 return "$url Exception from line $line of $file: $message";
142 }
143
144 /** Output the exception report using HTML */
145 function reportHTML() {
146 global $wgOut;
147 if ( $this->useOutputPage() ) {
148 $wgOut->setPageTitle( $this->getPageTitle() );
149 $wgOut->setRobotPolicy( "noindex,nofollow" );
150 $wgOut->setArticleRelated( false );
151 $wgOut->enableClientCache( false );
152 $wgOut->redirect( '' );
153 $wgOut->clearHTML();
154 if( $hookResult = $this->runHooks( get_class( $this ) ) ) {
155 $wgOut->addHTML( $hookResult );
156 } else {
157 $wgOut->addHTML( $this->getHTML() );
158 }
159 $wgOut->output();
160 } else {
161 if( $hookResult = $this->runHooks( get_class( $this ) . "Raw" ) ) {
162 die( $hookResult );
163 }
164 if ( defined( 'MEDIAWIKI_INSTALL' ) ) {
165 echo $this->getHTML();
166 } else {
167 echo $this->htmlHeader();
168 echo $this->getHTML();
169 echo $this->htmlFooter();
170 }
171 }
172 }
173
174 /**
175 * Output a report about the exception and takes care of formatting.
176 * It will be either HTML or plain text based on isCommandLine().
177 */
178 function report() {
179 $log = $this->getLogMessage();
180 if ( $log ) {
181 wfDebugLog( 'exception', $log );
182 }
183 if ( self::isCommandLine() ) {
184 wfPrintError( $this->getText() );
185 } else {
186 $this->reportHTML();
187 }
188 }
189
190 /**
191 * Send headers and output the beginning of the html page if not using
192 * $wgOut to output the exception.
193 */
194 function htmlHeader() {
195 global $wgLogo, $wgSitename, $wgOutputEncoding;
196
197 if ( !headers_sent() ) {
198 header( 'HTTP/1.0 500 Internal Server Error' );
199 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
200 /* Don't cache error pages! They cause no end of trouble... */
201 header( 'Cache-control: none' );
202 header( 'Pragma: nocache' );
203 }
204 $title = $this->getPageTitle();
205 echo "<html>
206 <head>
207 <title>$title</title>
208 </head>
209 <body>
210 <h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$title</h1>
211 ";
212 }
213
214 /**
215 * print the end of the html page if not using $wgOut.
216 */
217 function htmlFooter() {
218 echo "</body></html>";
219 }
220
221 static function isCommandLine() {
222 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
223 }
224 }
225
226 /**
227 * Exception class which takes an HTML error message, and does not
228 * produce a backtrace. Replacement for OutputPage::fatalError().
229 * @ingroup Exception
230 */
231 class FatalError extends MWException {
232 function getHTML() {
233 return $this->getMessage();
234 }
235
236 function getText() {
237 return $this->getMessage();
238 }
239 }
240
241 /**
242 * @ingroup Exception
243 */
244 class ErrorPageError extends MWException {
245 public $title, $msg;
246
247 /**
248 * Note: these arguments are keys into wfMsg(), not text!
249 */
250 function __construct( $title, $msg ) {
251 $this->title = $title;
252 $this->msg = $msg;
253 parent::__construct( wfMsg( $msg ) );
254 }
255
256 function report() {
257 global $wgOut;
258 $wgOut->showErrorPage( $this->title, $this->msg );
259 $wgOut->output();
260 }
261 }
262
263 /**
264 * Install an exception handler for MediaWiki exception types.
265 */
266 function wfInstallExceptionHandler() {
267 set_exception_handler( 'wfExceptionHandler' );
268 }
269
270 /**
271 * Report an exception to the user
272 */
273 function wfReportException( Exception $e ) {
274 $cmdLine = MWException::isCommandLine();
275 if ( $e instanceof MWException ) {
276 try {
277 $e->report();
278 } catch ( Exception $e2 ) {
279 // Exception occurred from within exception handler
280 // Show a simpler error message for the original exception,
281 // don't try to invoke report()
282 $message = "MediaWiki internal error.\n\n";
283 if ( $GLOBALS['wgShowExceptionDetails'] )
284 $message .= "Original exception: " . $e->__toString();
285 $message .= "\n\nException caught inside exception handler";
286 if ( $GLOBALS['wgShowExceptionDetails'] )
287 $message .= ": " . $e2->__toString();
288 $message .= "\n";
289 if ( $cmdLine ) {
290 wfPrintError( $message );
291 } else {
292 echo nl2br( htmlspecialchars( $message ) ). "\n";
293 }
294 }
295 } else {
296 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
297 $e->__toString() . "\n";
298 if ( $GLOBALS['wgShowExceptionDetails'] ) {
299 $message .= "\n" . $e->getTraceAsString() ."\n";
300 }
301 if ( $cmdLine ) {
302 wfPrintError( $message );
303 } else {
304 echo nl2br( htmlspecialchars( $message ) ). "\n";
305 }
306 }
307 }
308
309 /**
310 * Print a message, if possible to STDERR.
311 * Use this in command line mode only (see isCommandLine)
312 */
313 function wfPrintError( $message ) {
314 #NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
315 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
316 if ( defined( 'STDERR' ) ) {
317 fwrite( STDERR, $message );
318 }
319 else {
320 echo( $message );
321 }
322 }
323
324 /**
325 * Exception handler which simulates the appropriate catch() handling:
326 *
327 * try {
328 * ...
329 * } catch ( MWException $e ) {
330 * $e->report();
331 * } catch ( Exception $e ) {
332 * echo $e->__toString();
333 * }
334 */
335 function wfExceptionHandler( $e ) {
336 global $wgFullyInitialised;
337 wfReportException( $e );
338
339 // Final cleanup, similar to wfErrorExit()
340 if ( $wgFullyInitialised ) {
341 try {
342 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
343 } catch ( Exception $e ) {}
344 }
345
346 // Exit value should be nonzero for the benefit of shell jobs
347 exit( 1 );
348 }