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|Throwable $e Original exception
32 * @param integer $mode MWExceptionExposer::AS_* constant
33 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
35 public static function output( $e, $mode, $eNew = null ) {
38 if ( defined( 'MW_API' ) ) {
39 // Unhandled API exception, we can't be sure that format printer is alive
40 self
::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
41 wfHttpError( 500, 'Internal Server Error', self
::getText( $e ) );
42 } elseif ( self
::isCommandLine() ) {
43 self
::printError( self
::getText( $e ) );
44 } elseif ( $mode === self
::AS_PRETTY
) {
45 if ( $e instanceof DBConnectionError
) {
46 self
::reportOutageHTML( $e );
48 self
::statusHeader( 500 );
49 self
::header( "Content-Type: $wgMimeType; charset=utf-8" );
50 self
::reportHTML( $e );
54 $message = "MediaWiki internal error.\n\n";
55 if ( self
::showBackTrace( $e ) ) {
56 $message .= 'Original exception: ' .
57 MWExceptionHandler
::getLogMessage( $e ) .
58 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $e ) .
59 "\n\nException caught inside exception handler: " .
60 MWExceptionHandler
::getLogMessage( $eNew ) .
61 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $eNew );
63 $message .= 'Original exception: ' .
64 MWExceptionHandler
::getPublicLogMessage( $e );
65 $message .= "\n\nException caught inside exception handler.\n\n" .
66 self
::getShowBacktraceError( $e );
70 if ( self
::showBackTrace( $e ) ) {
71 $message = MWExceptionHandler
::getLogMessage( $e ) .
73 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
75 $message = MWExceptionHandler
::getPublicLogMessage( $e );
78 echo nl2br( htmlspecialchars( $message ) ) . "\n";
83 * Run hook to allow extensions to modify the text of the exception
85 * Called by MWException for b/c
87 * @param Exception|Throwable $e
88 * @param string $name Class name of the exception
89 * @param array $args Arguments to pass to the callback functions
90 * @return string|null String to output or null if any hook has been called
92 public static function runHooks( $e, $name, $args = [] ) {
93 global $wgExceptionHooks;
95 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
96 return null; // Just silently ignore
99 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
100 !is_array( $wgExceptionHooks[$name] )
105 $hooks = $wgExceptionHooks[$name];
106 $callargs = array_merge( [ $e ], $args );
108 foreach ( $hooks as $hook ) {
110 is_string( $hook ) ||
111 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
113 // 'function' or [ 'class', 'hook' ]
114 $result = call_user_func_array( $hook, $callargs );
119 if ( is_string( $result ) ) {
128 * @param Exception|Throwable $e
129 * @return bool Should the exception use $wgOut to output the error?
131 private static function useOutputPage( $e ) {
132 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
133 foreach ( $e->getTrace() as $frame ) {
134 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
140 !empty( $GLOBALS['wgFullyInitialised'] ) &&
141 !empty( $GLOBALS['wgOut'] ) &&
142 !defined( 'MEDIAWIKI_INSTALL' )
147 * Output the exception report using HTML
149 * @param Exception|Throwable $e
151 private static function reportHTML( $e ) {
152 global $wgOut, $wgSitename;
154 if ( self
::useOutputPage( $e ) ) {
155 if ( $e instanceof MWException
) {
156 $wgOut->prepareErrorPage( $e->getPageTitle() );
157 } elseif ( $e instanceof DBReadOnlyError
) {
158 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
159 } elseif ( $e instanceof DBExpectedError
) {
160 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
162 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
165 $hookResult = self
::runHooks( $e, get_class( $e ) );
167 $wgOut->addHTML( $hookResult );
169 // Show any custom GUI message before the details
170 if ( $e instanceof MessageSpecifier
) {
171 $wgOut->addHTML( Message
::newFromSpecifier( $e )->escaped() );
173 $wgOut->addHTML( self
::getHTML( $e ) );
178 self
::header( 'Content-Type: text/html; charset=utf-8' );
179 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
180 echo "<!DOCTYPE html>\n" .
182 // Mimick OutputPage::setPageTitle behaviour
184 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
186 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
189 $hookResult = self
::runHooks( $e, get_class( $e ) . 'Raw' );
193 echo self
::getHTML( $e );
196 echo "</body></html>\n";
201 * If $wgShowExceptionDetails is true, return a HTML message with a
202 * backtrace to the error, otherwise show a message to ask to set it to true
203 * to show that information.
205 * @param Exception|Throwable $e
206 * @return string Html to output
208 public static function getHTML( $e ) {
209 if ( self
::showBackTrace( $e ) ) {
210 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
211 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
212 '</p><p>Backtrace:</p><p>' .
213 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
216 $logId = WebRequest
::getRequestId();
217 $html = "<div class=\"errorbox mw-content-ltr\">" .
218 '[' . $logId . '] ' .
219 gmdate( 'Y-m-d H:i:s' ) . ": " .
220 self
::msg( "internalerror-fatal-exception",
221 "Fatal exception of type $1",
224 MWExceptionHandler
::getURL()
226 "<!-- " . wordwrap( self
::getShowBacktraceError( $e ), 50 ) . " -->";
233 * Get a message from i18n
235 * @param string $key Message name
236 * @param string $fallback Default message if the message cache can't be
237 * called by the exception
238 * The function also has other parameters that are arguments for the message
239 * @return string Message with arguments replaced
241 private static function msg( $key, $fallback /*[, params...] */ ) {
242 $args = array_slice( func_get_args(), 2 );
244 return wfMessage( $key, $args )->text();
245 } catch ( Exception
$e ) {
246 return wfMsgReplaceArgs( $fallback, $args );
251 * @param Exception|Throwable $e
254 private static function getText( $e ) {
255 if ( self
::showBackTrace( $e ) ) {
256 return MWExceptionHandler
::getLogMessage( $e ) .
258 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
260 return self
::getShowBacktraceError( $e );
265 * @param Exception|Throwable $e
268 private static function showBackTrace( $e ) {
269 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
272 $wgShowExceptionDetails &&
273 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
278 * @param Exception|Throwable $e
281 private static function getShowBacktraceError( $e ) {
282 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
284 if ( !$wgShowExceptionDetails ) {
285 $vars[] = '$wgShowExceptionDetails = true;';
287 if ( $e instanceof DBError
&& !$wgShowDBErrorBacktrace ) {
288 $vars[] = '$wgShowDBErrorBacktrace = true;';
290 $vars = implode( ' and ', $vars );
291 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information";
297 private static function isCommandLine() {
298 return !empty( $GLOBALS['wgCommandLineMode'] );
302 * @param string $header
304 private static function header( $header ) {
305 if ( !headers_sent() ) {
311 * @param integer $code
313 private static function statusHeader( $code ) {
314 if ( !headers_sent() ) {
315 HttpStatus
::header( $code );
320 * Print a message, if possible to STDERR.
321 * Use this in command line mode only (see isCommandLine)
323 * @param string $message Failure text
325 private static function printError( $message ) {
326 // NOTE: STDERR may not be available, especially if php-cgi is used from the
327 // command line (bug #15602). Try to produce meaningful output anyway. Using
328 // echo may corrupt output to STDOUT though.
329 if ( defined( 'STDERR' ) ) {
330 fwrite( STDERR
, $message );
337 * @param Exception|Throwable $e
339 private static function reportOutageHTML( $e ) {
340 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
342 $sorry = htmlspecialchars( self
::msg(
344 'Sorry! This site is experiencing technical difficulties.'
346 $again = htmlspecialchars( self
::msg(
348 'Try waiting a few minutes and reloading.'
351 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
354 Html
::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
355 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
358 $info = htmlspecialchars( self
::msg(
360 '(Cannot access the database)'
364 MessageCache
::singleton()->disable(); // no DB access
366 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
368 if ( $wgShowDBErrorBacktrace ) {
369 $html .= '<p>Backtrace:</p><pre>' .
370 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
374 $html .= self
::googleSearchForm();
382 private static function googleSearchForm() {
383 global $wgSitename, $wgCanonicalServer, $wgRequest;
385 $usegoogle = htmlspecialchars( self
::msg(
387 'You can try searching via Google in the meantime.'
389 $outofdate = htmlspecialchars( self
::msg(
391 'Note that their indexes of our content may be out of date.'
393 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
394 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
395 $server = htmlspecialchars( $wgCanonicalServer );
396 $sitename = htmlspecialchars( $wgSitename );
398 <div style="margin: 1.5em">$usegoogle<br />
399 <small>$outofdate</small>
401 <form method="get" action="//www.google.com/search" id="googlesearch">
402 <input type="hidden" name="domains" value="$server" />
403 <input type="hidden" name="num" value="50" />
404 <input type="hidden" name="ie" value="UTF-8" />
405 <input type="hidden" name="oe" value="UTF-8" />
406 <input type="text" name="q" size="31" maxlength="255" value="$search" />
407 <input type="submit" name="btnG" value="$googlesearch" />
409 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
410 <label><input type="radio" name="sitesearch" value="" />WWW</label>