dc5b72d43af6c2df0c57adae57d8ecea9f69e07c
[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' ) || $this->htmlBodyOnly() ) {
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 return "<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 return "</body></html>";
219 }
220
221 /**
222 * headers handled by subclass?
223 */
224 function htmlBodyOnly() {
225 return false;
226 }
227
228 static function isCommandLine() {
229 return !empty( $GLOBALS['wgCommandLineMode'] ) && !defined( 'MEDIAWIKI_INSTALL' );
230 }
231 }
232
233 /**
234 * Exception class which takes an HTML error message, and does not
235 * produce a backtrace. Replacement for OutputPage::fatalError().
236 * @ingroup Exception
237 */
238 class FatalError extends MWException {
239 function getHTML() {
240 return $this->getMessage();
241 }
242
243 function getText() {
244 return $this->getMessage();
245 }
246 }
247
248 /**
249 * @ingroup Exception
250 */
251 class ErrorPageError extends MWException {
252 public $title, $msg;
253
254 /**
255 * Note: these arguments are keys into wfMsg(), not text!
256 */
257 function __construct( $title, $msg ) {
258 $this->title = $title;
259 $this->msg = $msg;
260 parent::__construct( wfMsg( $msg ) );
261 }
262
263 function report() {
264 global $wgOut;
265 $wgOut->showErrorPage( $this->title, $this->msg );
266 $wgOut->output();
267 }
268 }
269
270 /**
271 * Install an exception handler for MediaWiki exception types.
272 */
273 function wfInstallExceptionHandler() {
274 set_exception_handler( 'wfExceptionHandler' );
275 }
276
277 /**
278 * Report an exception to the user
279 */
280 function wfReportException( Exception $e ) {
281 $cmdLine = MWException::isCommandLine();
282 if ( $e instanceof MWException ) {
283 try {
284 $e->report();
285 } catch ( Exception $e2 ) {
286 // Exception occurred from within exception handler
287 // Show a simpler error message for the original exception,
288 // don't try to invoke report()
289 $message = "MediaWiki internal error.\n\n";
290 if ( $GLOBALS['wgShowExceptionDetails'] )
291 $message .= "Original exception: " . $e->__toString();
292 $message .= "\n\nException caught inside exception handler";
293 if ( $GLOBALS['wgShowExceptionDetails'] )
294 $message .= ": " . $e2->__toString();
295 $message .= "\n";
296 if ( $cmdLine ) {
297 wfPrintError( $message );
298 } else {
299 echo nl2br( htmlspecialchars( $message ) ). "\n";
300 }
301 }
302 } else {
303 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
304 $e->__toString() . "\n";
305 if ( $GLOBALS['wgShowExceptionDetails'] ) {
306 $message .= "\n" . $e->getTraceAsString() ."\n";
307 }
308 if ( $cmdLine ) {
309 wfPrintError( $message );
310 } else {
311 echo nl2br( htmlspecialchars( $message ) ). "\n";
312 }
313 }
314 }
315
316 /**
317 * Print a message, if possible to STDERR.
318 * Use this in command line mode only (see isCommandLine)
319 */
320 function wfPrintError( $message ) {
321 #NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
322 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
323 if ( defined( 'STDERR' ) ) {
324 fwrite( STDERR, $message );
325 } else {
326 echo( $message );
327 }
328 }
329
330 /**
331 * Exception handler which simulates the appropriate catch() handling:
332 *
333 * try {
334 * ...
335 * } catch ( MWException $e ) {
336 * $e->report();
337 * } catch ( Exception $e ) {
338 * echo $e->__toString();
339 * }
340 */
341 function wfExceptionHandler( $e ) {
342 global $wgFullyInitialised;
343 wfReportException( $e );
344
345 // Final cleanup, similar to wfErrorExit()
346 if ( $wgFullyInitialised ) {
347 try {
348 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
349 } catch ( Exception $e ) {}
350 }
351
352 // Exit value should be nonzero for the benefit of shell jobs
353 exit( 1 );
354 }