3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Aaron Schulz
23 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
26 class MWExceptionRenderer
{
27 const AS_RAW
= 1; // show as text
28 const AS_PRETTY
= 2; // show as HTML
31 * @param Exception $e Original exception
32 * @param integer $mode MWExceptionExposer::AS_* constant
33 * @param Exception|null $eNew New exception from attempting to show the first
35 public static function output( Exception
$e, $mode, Exception
$eNew = null ) {
38 if ( $e instanceof DBConnectionError
) {
39 self
::reportOutageHTML( $e );
43 if ( defined( 'MW_API' ) ) {
44 // Unhandled API exception, we can't be sure that format printer is alive
45 self
::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
46 wfHttpError( 500, 'Internal Server Error', self
::getText( $e ) );
47 } elseif ( self
::isCommandLine() ) {
48 self
::printError( self
::getText( $e ) );
49 } elseif ( $mode === self
::AS_PRETTY
) {
50 self
::statusHeader( 500 );
51 self
::header( "Content-Type: $wgMimeType; charset=utf-8" );
52 self
::reportHTML( $e );
55 $message = "MediaWiki internal error.\n\n";
56 if ( self
::showBackTrace( $e ) ) {
57 $message .= 'Original exception: ' .
58 MWExceptionHandler
::getLogMessage( $e ) .
59 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $e ) .
60 "\n\nException caught inside exception handler: " .
61 MWExceptionHandler
::getLogMessage( $eNew ) .
62 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $eNew );
64 $message .= "Exception caught inside exception handler.\n\n" .
65 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
66 "to show detailed debugging information.";
70 if ( self
::showBackTrace( $e ) ) {
71 $message = MWExceptionHandler
::getLogMessage( $e ) .
73 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
75 $message = MWExceptionHandler
::getPublicLogMessage( $e );
78 if ( self
::isCommandLine() ) {
79 self
::printError( $message );
81 echo nl2br( htmlspecialchars( $message ) ) . "\n";
87 * Run hook to allow extensions to modify the text of the exception
89 * Called by MWException for b/c
92 * @param string $name Class name of the exception
93 * @param array $args Arguments to pass to the callback functions
94 * @return string|null String to output or null if any hook has been called
96 public static function runHooks( Exception
$e, $name, $args = [] ) {
97 global $wgExceptionHooks;
99 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
100 return null; // Just silently ignore
103 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
104 !is_array( $wgExceptionHooks[$name] )
109 $hooks = $wgExceptionHooks[$name];
110 $callargs = array_merge( [ $e ], $args );
112 foreach ( $hooks as $hook ) {
114 is_string( $hook ) ||
115 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
117 // 'function' or [ 'class', 'hook' ]
118 $result = call_user_func_array( $hook, $callargs );
123 if ( is_string( $result ) ) {
132 * @param Exception $e
133 * @return bool Should the exception use $wgOut to output the error?
135 private static function useOutputPage( Exception
$e ) {
136 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
137 $useMessageCache = ( $GLOBALS['wgLang'] instanceof Language
);
138 foreach ( $e->getTrace() as $frame ) {
139 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
140 $useMessageCache = false;
146 !empty( $GLOBALS['wgFullyInitialised'] ) &&
147 !empty( $GLOBALS['wgOut'] ) &&
148 !defined( 'MEDIAWIKI_INSTALL' )
153 * Output the exception report using HTML
155 * @param Exception $e
157 private static function reportHTML( Exception
$e ) {
158 global $wgOut, $wgSitename;
160 if ( self
::useOutputPage( $e ) ) {
161 if ( $e instanceof MWException
) {
162 $wgOut->prepareErrorPage( $e->getPageTitle() );
163 } elseif ( $e instanceof DBReadOnlyError
) {
164 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
165 } elseif ( $e instanceof DBExpectedError
) {
166 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
168 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
171 $hookResult = self
::runHooks( $e, get_class( $e ) );
173 $wgOut->addHTML( $hookResult );
175 $wgOut->addHTML( self
::getHTML( $e ) );
180 self
::header( 'Content-Type: text/html; charset=utf-8' );
181 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
182 echo "<!DOCTYPE html>\n" .
184 // Mimick OutputPage::setPageTitle behaviour
186 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
188 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
191 $hookResult = self
::runHooks( $e, get_class( $e ) . 'Raw' );
195 echo self
::getHTML( $e );
198 echo "</body></html>\n";
203 * If $wgShowExceptionDetails is true, return a HTML message with a
204 * backtrace to the error, otherwise show a message to ask to set it to true
205 * to show that information.
207 * @param Exception $e
208 * @return string Html to output
210 private static function getHTML( Exception
$e ) {
211 if ( self
::showBackTrace( $e ) ) {
213 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
214 '</p><p>Backtrace:</p><p>' .
215 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
218 $logId = WebRequest
::getRequestId();
219 return "<div class=\"errorbox\">" .
220 '[' . $logId . '] ' .
221 gmdate( 'Y-m-d H:i:s' ) . ": " .
222 self
::msg( "internalerror-fatal-exception",
223 "Fatal exception of type $1",
226 MWExceptionHandler
::getURL()
228 "<!-- Set \$wgShowExceptionDetails = true; " .
229 "at the bottom of LocalSettings.php to show detailed " .
230 "debugging information. -->";
235 * Get a message from i18n
237 * @param string $key Message name
238 * @param string $fallback Default message if the message cache can't be
239 * called by the exception
240 * The function also has other parameters that are arguments for the message
241 * @return string Message with arguments replaced
243 private static function msg( $key, $fallback /*[, params...] */ ) {
244 $args = array_slice( func_get_args(), 2 );
246 return wfMessage( $key, $args )->text();
247 } catch ( Exception
$e ) {
248 return wfMsgReplaceArgs( $fallback, $args );
253 * @param Exception $e
256 private function getText( Exception
$e ) {
257 if ( self
::showBackTrace( $e ) ) {
258 return MWExceptionHandler
::getLogMessage( $e ) .
260 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
262 return "Set \$wgShowExceptionDetails = true; " .
263 "in LocalSettings.php to show detailed debugging information.\n";
268 * @param Exception $e
271 private static function showBackTrace( Exception
$e ) {
272 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
275 $wgShowExceptionDetails &&
276 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
283 private static function isCommandLine() {
284 return !empty( $GLOBALS['wgCommandLineMode'] );
288 * @param string $header
290 private static function header( $header ) {
291 if ( !headers_sent() ) {
297 * @param integer $code
299 private static function statusHeader( $code ) {
300 if ( !headers_sent() ) {
301 HttpStatus
::header( $code );
306 * Print a message, if possible to STDERR.
307 * Use this in command line mode only (see isCommandLine)
309 * @param string $message Failure text
311 private static function printError( $message ) {
312 // NOTE: STDERR may not be available, especially if php-cgi is used from the
313 // command line (bug #15602). Try to produce meaningful output anyway. Using
314 // echo may corrupt output to STDOUT though.
315 if ( defined( 'STDERR' ) ) {
316 fwrite( STDERR
, $message );
323 * @param Exception $e
325 private static function reportOutageHTML( Exception
$e ) {
326 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
328 $sorry = htmlspecialchars( self
::msg(
330 'Sorry! This site is experiencing technical difficulties.'
332 $again = htmlspecialchars( self
::msg(
334 'Try waiting a few minutes and reloading.'
337 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
340 Html
::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
341 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
344 $info = htmlspecialchars( self
::msg(
346 '(Cannot access the database)'
350 MessageCache
::singleton()->disable(); // no DB access
352 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
354 if ( $wgShowDBErrorBacktrace ) {
355 $html .= '<p>Backtrace:</p><pre>' .
356 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
360 $html .= self
::googleSearchForm();
368 private static function googleSearchForm() {
369 global $wgSitename, $wgCanonicalServer, $wgRequest;
371 $usegoogle = htmlspecialchars( self
::msg(
373 'You can try searching via Google in the meantime.'
375 $outofdate = htmlspecialchars( self
::msg(
377 'Note that their indexes of our content may be out of date.'
379 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
380 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
381 $server = htmlspecialchars( $wgCanonicalServer );
382 $sitename = htmlspecialchars( $wgSitename );
384 <div style="margin: 1.5em">$usegoogle<br />
385 <small>$outofdate</small>
387 <form method="get" action="//www.google.com/search" id="googlesearch">
388 <input type="hidden" name="domains" value="$server" />
389 <input type="hidden" name="num" value="50" />
390 <input type="hidden" name="ie" value="UTF-8" />
391 <input type="hidden" name="oe" value="UTF-8" />
392 <input type="text" name="q" size="31" maxlength="255" value="$search" />
393 <input type="submit" name="btnG" value="$googlesearch" />
395 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
396 <label><input type="radio" name="sitesearch" value="" />WWW</label>