* An attempt to fix bug 11119
[mediawiki.git] / includes / Exception.php
blobe2f76f2a104125bdda7e408ec60bc5c2dc8db786
1 <?php
2 /**
3 * @defgroup Exception Exception
4 */
6 /**
7 * MediaWiki exception
8 * @ingroup Exception
9 */
10 class MWException extends Exception {
12 /**
13 * Should the exception use $wgOut to output the error ?
14 * @return bool
16 function useOutputPage() {
17 return !empty( $GLOBALS['wgFullyInitialised'] ) &&
18 ( !empty( $GLOBALS['wgArticle'] ) || ( !empty( $GLOBALS['wgOut'] ) && !$GLOBALS['wgOut']->isArticle() ) ) &&
19 !empty( $GLOBALS['wgTitle'] );
22 /**
23 * Can the extension use wfMsg() to get i18n messages ?
24 * @return bool
26 function useMessageCache() {
27 global $wgLang;
28 return is_object( $wgLang );
31 /**
32 * Run hook to allow extensions to modify the text of the exception
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
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 );
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;
53 if( is_string( $result ) )
54 return $result;
58 /**
59 * Get a message from i18n
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
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 );
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.
81 * @return String html to output
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>";
96 /**
97 * If $wgShowExceptionDetails is true, return a text message with a
98 * backtrace to the error.
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";
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";
122 * Return the requested URL and point to file and line number from which the
123 * exception occured
125 * @return string
127 function getLogMessage() {
128 global $wgRequest;
129 $file = $this->getFile();
130 $line = $this->getLine();
131 $message = $this->getMessage();
132 return $wgRequest->getRequestURL() . " Exception from line $line of $file: $message";
135 /** Output the exception report using HTML */
136 function reportHTML() {
137 global $wgOut;
138 if ( $this->useOutputPage() ) {
139 $wgOut->setPageTitle( $this->getPageTitle() );
140 $wgOut->setRobotPolicy( "noindex,nofollow" );
141 $wgOut->setArticleRelated( false );
142 $wgOut->enableClientCache( false );
143 $wgOut->redirect( '' );
144 $wgOut->clearHTML();
145 if( $hookResult = $this->runHooks( get_class( $this ) ) ) {
146 $wgOut->addHTML( $hookResult );
147 } else {
148 $wgOut->addHTML( $this->getHTML() );
150 $wgOut->output();
151 } else {
152 if( $hookResult = $this->runHooks( get_class( $this ) . "Raw" ) ) {
153 die( $hookResult );
155 echo $this->htmlHeader();
156 echo $this->getHTML();
157 echo $this->htmlFooter();
162 * Output a report about the exception and takes care of formatting.
163 * It will be either HTML or plain text based on $wgCommandLineMode.
165 function report() {
166 global $wgCommandLineMode;
167 $log = $this->getLogMessage();
168 if ( $log ) {
169 wfDebugLog( 'exception', $log );
171 if ( $wgCommandLineMode ) {
172 wfPrintError( $this->getText() );
173 } else {
174 $this->reportHTML();
179 * Send headers and output the beginning of the html page if not using
180 * $wgOut to output the exception.
182 function htmlHeader() {
183 global $wgLogo, $wgSitename, $wgOutputEncoding;
185 if ( !headers_sent() ) {
186 header( 'HTTP/1.0 500 Internal Server Error' );
187 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
188 /* Don't cache error pages! They cause no end of trouble... */
189 header( 'Cache-control: none' );
190 header( 'Pragma: nocache' );
192 $title = $this->getPageTitle();
193 echo "<html>
194 <head>
195 <title>$title</title>
196 </head>
197 <body>
198 <h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$title</h1>
203 * print the end of the html page if not using $wgOut.
205 function htmlFooter() {
206 echo "</body></html>";
211 * Exception class which takes an HTML error message, and does not
212 * produce a backtrace. Replacement for OutputPage::fatalError().
213 * @ingroup Exception
215 class FatalError extends MWException {
216 function getHTML() {
217 return $this->getMessage();
220 function getText() {
221 return $this->getMessage();
226 * @ingroup Exception
228 class ErrorPageError extends MWException {
229 public $title, $msg;
232 * Note: these arguments are keys into wfMsg(), not text!
234 function __construct( $title, $msg ) {
235 $this->title = $title;
236 $this->msg = $msg;
237 parent::__construct( wfMsg( $msg ) );
240 function report() {
241 global $wgOut;
242 $wgOut->showErrorPage( $this->title, $this->msg );
243 $wgOut->output();
248 * Install an exception handler for MediaWiki exception types.
250 function wfInstallExceptionHandler() {
251 set_exception_handler( 'wfExceptionHandler' );
255 * Report an exception to the user
257 function wfReportException( Exception $e ) {
258 if ( $e instanceof MWException ) {
259 try {
260 $e->report();
261 } catch ( Exception $e2 ) {
262 // Exception occurred from within exception handler
263 // Show a simpler error message for the original exception,
264 // don't try to invoke report()
265 $message = "MediaWiki internal error.\n\n" .
266 "Original exception: " . $e->__toString() .
267 "\n\nException caught inside exception handler: " .
268 $e2->__toString() . "\n";
270 if ( !empty( $GLOBALS['wgCommandLineMode'] ) ) {
271 wfPrintError( $message );
272 } else {
273 echo nl2br( htmlspecialchars( $message ) ). "\n";
276 } else {
277 echo $e->__toString();
282 * Print a message, if possible to STDERR.
283 * Use this in command line mode only (see wgCommandLineMode)
285 function wfPrintError( $message ) {
286 #NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
287 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
288 if ( defined( 'STDERR' ) ) {
289 fwrite( STDERR, $message );
291 else {
292 echo( $message );
297 * Exception handler which simulates the appropriate catch() handling:
299 * try {
300 * ...
301 * } catch ( MWException $e ) {
302 * $e->report();
303 * } catch ( Exception $e ) {
304 * echo $e->__toString();
307 function wfExceptionHandler( $e ) {
308 global $wgFullyInitialised;
309 wfReportException( $e );
311 // Final cleanup, similar to wfErrorExit()
312 if ( $wgFullyInitialised ) {
313 try {
314 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
315 } catch ( Exception $e ) {}
318 // Exit value should be nonzero for the benefit of shell jobs
319 exit( 1 );