eb7159861c26222567d84b66fae0e09ad4910dda
[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 echo $this->htmlHeader();
165 echo $this->getHTML();
166 echo $this->htmlFooter();
167 }
168 }
169
170 /**
171 * Output a report about the exception and takes care of formatting.
172 * It will be either HTML or plain text based on $wgCommandLineMode.
173 */
174 function report() {
175 global $wgCommandLineMode;
176 $log = $this->getLogMessage();
177 if ( $log ) {
178 wfDebugLog( 'exception', $log );
179 }
180 if ( $wgCommandLineMode ) {
181 wfPrintError( $this->getText() );
182 } else {
183 $this->reportHTML();
184 }
185 }
186
187 /**
188 * Send headers and output the beginning of the html page if not using
189 * $wgOut to output the exception.
190 */
191 function htmlHeader() {
192 global $wgLogo, $wgSitename, $wgOutputEncoding;
193
194 if ( !headers_sent() ) {
195 header( 'HTTP/1.0 500 Internal Server Error' );
196 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
197 /* Don't cache error pages! They cause no end of trouble... */
198 header( 'Cache-control: none' );
199 header( 'Pragma: nocache' );
200 }
201 $title = $this->getPageTitle();
202 echo "<html>
203 <head>
204 <title>$title</title>
205 </head>
206 <body>
207 <h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$title</h1>
208 ";
209 }
210
211 /**
212 * print the end of the html page if not using $wgOut.
213 */
214 function htmlFooter() {
215 echo "</body></html>";
216 }
217 }
218
219 /**
220 * Exception class which takes an HTML error message, and does not
221 * produce a backtrace. Replacement for OutputPage::fatalError().
222 * @ingroup Exception
223 */
224 class FatalError extends MWException {
225 function getHTML() {
226 return $this->getMessage();
227 }
228
229 function getText() {
230 return $this->getMessage();
231 }
232 }
233
234 /**
235 * @ingroup Exception
236 */
237 class ErrorPageError extends MWException {
238 public $title, $msg;
239
240 /**
241 * Note: these arguments are keys into wfMsg(), not text!
242 */
243 function __construct( $title, $msg ) {
244 $this->title = $title;
245 $this->msg = $msg;
246 parent::__construct( wfMsg( $msg ) );
247 }
248
249 function report() {
250 global $wgOut;
251 $wgOut->showErrorPage( $this->title, $this->msg );
252 $wgOut->output();
253 }
254 }
255
256 /**
257 * Install an exception handler for MediaWiki exception types.
258 */
259 function wfInstallExceptionHandler() {
260 set_exception_handler( 'wfExceptionHandler' );
261 }
262
263 /**
264 * Report an exception to the user
265 */
266 function wfReportException( Exception $e ) {
267 if ( $e instanceof MWException ) {
268 try {
269 $e->report();
270 } catch ( Exception $e2 ) {
271 // Exception occurred from within exception handler
272 // Show a simpler error message for the original exception,
273 // don't try to invoke report()
274 $message = "MediaWiki internal error.\n\n" .
275 "Original exception: " . $e->__toString() .
276 "\n\nException caught inside exception handler: " .
277 $e2->__toString() . "\n";
278
279 if ( !empty( $GLOBALS['wgCommandLineMode'] ) ) {
280 wfPrintError( $message );
281 } else {
282 echo nl2br( htmlspecialchars( $message ) ). "\n";
283 }
284 }
285 } else {
286 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
287 $e->__toString() . "\n";
288 if ( $GLOBALS['wgShowExceptionDetails'] ) {
289 $message .= "\n" . $e->getTraceAsString() ."\n";
290 }
291 if ( !empty( $GLOBALS['wgCommandLineMode'] ) ) {
292 wfPrintError( $message );
293 } else {
294 echo nl2br( htmlspecialchars( $message ) ). "\n";
295 }
296 }
297 }
298
299 /**
300 * Print a message, if possible to STDERR.
301 * Use this in command line mode only (see wgCommandLineMode)
302 */
303 function wfPrintError( $message ) {
304 #NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
305 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
306 if ( defined( 'STDERR' ) ) {
307 fwrite( STDERR, $message );
308 }
309 else {
310 echo( $message );
311 }
312 }
313
314 /**
315 * Exception handler which simulates the appropriate catch() handling:
316 *
317 * try {
318 * ...
319 * } catch ( MWException $e ) {
320 * $e->report();
321 * } catch ( Exception $e ) {
322 * echo $e->__toString();
323 * }
324 */
325 function wfExceptionHandler( $e ) {
326 global $wgFullyInitialised;
327 wfReportException( $e );
328
329 // Final cleanup, similar to wfErrorExit()
330 if ( $wgFullyInitialised ) {
331 try {
332 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
333 } catch ( Exception $e ) {}
334 }
335
336 // Exit value should be nonzero for the benefit of shell jobs
337 exit( 1 );
338 }