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
22 use Wikimedia\Rdbms\DBConnectionError
;
23 use Wikimedia\Rdbms\DBError
;
24 use Wikimedia\Rdbms\DBReadOnlyError
;
25 use Wikimedia\Rdbms\DBExpectedError
;
28 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
31 class MWExceptionRenderer
{
32 const AS_RAW
= 1; // show as text
33 const AS_PRETTY
= 2; // show as HTML
36 * @param Exception|Throwable $e Original exception
37 * @param integer $mode MWExceptionExposer::AS_* constant
38 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
40 public static function output( $e, $mode, $eNew = null ) {
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 if ( $e instanceof DBConnectionError
) {
52 self
::reportOutageHTML( $e );
54 self
::header( "Content-Type: $wgMimeType; charset=utf-8" );
55 self
::reportHTML( $e );
59 $message = "MediaWiki internal error.\n\n";
60 if ( self
::showBackTrace( $e ) ) {
61 $message .= 'Original exception: ' .
62 MWExceptionHandler
::getLogMessage( $e ) .
63 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $e ) .
64 "\n\nException caught inside exception handler: " .
65 MWExceptionHandler
::getLogMessage( $eNew ) .
66 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $eNew );
68 $message .= 'Original exception: ' .
69 MWExceptionHandler
::getPublicLogMessage( $e );
70 $message .= "\n\nException caught inside exception handler.\n\n" .
71 self
::getShowBacktraceError( $e );
75 if ( self
::showBackTrace( $e ) ) {
76 $message = MWExceptionHandler
::getLogMessage( $e ) .
78 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
80 $message = MWExceptionHandler
::getPublicLogMessage( $e );
83 echo nl2br( htmlspecialchars( $message ) ) . "\n";
88 * Run hook to allow extensions to modify the text of the exception
90 * Called by MWException for b/c
92 * @param Exception|Throwable $e
93 * @param string $name Class name of the exception
94 * @param array $args Arguments to pass to the callback functions
95 * @return string|null String to output or null if any hook has been called
97 public static function runHooks( $e, $name, $args = [] ) {
98 global $wgExceptionHooks;
100 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
101 return null; // Just silently ignore
104 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
105 !is_array( $wgExceptionHooks[$name] )
110 $hooks = $wgExceptionHooks[$name];
111 $callargs = array_merge( [ $e ], $args );
113 foreach ( $hooks as $hook ) {
115 is_string( $hook ) ||
116 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
118 // 'function' or [ 'class', 'hook' ]
119 $result = call_user_func_array( $hook, $callargs );
124 if ( is_string( $result ) ) {
133 * @param Exception|Throwable $e
134 * @return bool Should the exception use $wgOut to output the error?
136 private static function useOutputPage( $e ) {
137 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
138 foreach ( $e->getTrace() as $frame ) {
139 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
145 !empty( $GLOBALS['wgFullyInitialised'] ) &&
146 !empty( $GLOBALS['wgOut'] ) &&
147 !defined( 'MEDIAWIKI_INSTALL' )
152 * Output the exception report using HTML
154 * @param Exception|Throwable $e
156 private static function reportHTML( $e ) {
157 global $wgOut, $wgSitename;
159 if ( self
::useOutputPage( $e ) ) {
160 if ( $e instanceof MWException
) {
161 $wgOut->prepareErrorPage( $e->getPageTitle() );
162 } elseif ( $e instanceof DBReadOnlyError
) {
163 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
164 } elseif ( $e instanceof DBExpectedError
) {
165 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
167 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
170 $hookResult = self
::runHooks( $e, get_class( $e ) );
172 $wgOut->addHTML( $hookResult );
174 // Show any custom GUI message before the details
175 if ( $e instanceof MessageSpecifier
) {
176 $wgOut->addHTML( Message
::newFromSpecifier( $e )->escaped() );
178 $wgOut->addHTML( self
::getHTML( $e ) );
183 self
::header( 'Content-Type: text/html; charset=utf-8' );
184 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
185 echo "<!DOCTYPE html>\n" .
187 // Mimick OutputPage::setPageTitle behaviour
189 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
191 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
194 $hookResult = self
::runHooks( $e, get_class( $e ) . 'Raw' );
198 echo self
::getHTML( $e );
201 echo "</body></html>\n";
206 * If $wgShowExceptionDetails is true, return a HTML message with a
207 * backtrace to the error, otherwise show a message to ask to set it to true
208 * to show that information.
210 * @param Exception|Throwable $e
211 * @return string Html to output
213 public static function getHTML( $e ) {
214 if ( self
::showBackTrace( $e ) ) {
215 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
216 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
217 '</p><p>Backtrace:</p><p>' .
218 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
221 $logId = WebRequest
::getRequestId();
222 $html = "<div class=\"errorbox mw-content-ltr\">" .
223 '[' . $logId . '] ' .
224 gmdate( 'Y-m-d H:i:s' ) . ": " .
225 self
::msg( "internalerror-fatal-exception",
226 "Fatal exception of type $1",
229 MWExceptionHandler
::getURL()
231 "<!-- " . wordwrap( self
::getShowBacktraceError( $e ), 50 ) . " -->";
238 * Get a message from i18n
240 * @param string $key Message name
241 * @param string $fallback Default message if the message cache can't be
242 * called by the exception
243 * The function also has other parameters that are arguments for the message
244 * @return string Message with arguments replaced
246 private static function msg( $key, $fallback /*[, params...] */ ) {
247 $args = array_slice( func_get_args(), 2 );
249 return wfMessage( $key, $args )->text();
250 } catch ( Exception
$e ) {
251 return wfMsgReplaceArgs( $fallback, $args );
256 * @param Exception|Throwable $e
259 private static function getText( $e ) {
260 if ( self
::showBackTrace( $e ) ) {
261 return MWExceptionHandler
::getLogMessage( $e ) .
263 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
265 return self
::getShowBacktraceError( $e );
270 * @param Exception|Throwable $e
273 private static function showBackTrace( $e ) {
274 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
277 $wgShowExceptionDetails &&
278 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
283 * @param Exception|Throwable $e
286 private static function getShowBacktraceError( $e ) {
287 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
289 if ( !$wgShowExceptionDetails ) {
290 $vars[] = '$wgShowExceptionDetails = true;';
292 if ( $e instanceof DBError
&& !$wgShowDBErrorBacktrace ) {
293 $vars[] = '$wgShowDBErrorBacktrace = true;';
295 $vars = implode( ' and ', $vars );
296 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information\n";
302 private static function isCommandLine() {
303 return !empty( $GLOBALS['wgCommandLineMode'] );
307 * @param string $header
309 private static function header( $header ) {
310 if ( !headers_sent() ) {
316 * @param integer $code
318 private static function statusHeader( $code ) {
319 if ( !headers_sent() ) {
320 HttpStatus
::header( $code );
325 * Print a message, if possible to STDERR.
326 * Use this in command line mode only (see isCommandLine)
328 * @param string $message Failure text
330 private static function printError( $message ) {
331 // NOTE: STDERR may not be available, especially if php-cgi is used from the
332 // command line (bug #15602). Try to produce meaningful output anyway. Using
333 // echo may corrupt output to STDOUT though.
334 if ( defined( 'STDERR' ) ) {
335 fwrite( STDERR
, $message );
342 * @param Exception|Throwable $e
344 private static function reportOutageHTML( $e ) {
345 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
347 $sorry = htmlspecialchars( self
::msg(
349 'Sorry! This site is experiencing technical difficulties.'
351 $again = htmlspecialchars( self
::msg(
353 'Try waiting a few minutes and reloading.'
356 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
359 Html
::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
360 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
363 $info = htmlspecialchars( self
::msg(
365 '(Cannot access the database)'
369 MessageCache
::singleton()->disable(); // no DB access
371 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
373 if ( $wgShowDBErrorBacktrace ) {
374 $html .= '<p>Backtrace:</p><pre>' .
375 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
379 $html .= self
::googleSearchForm();
387 private static function googleSearchForm() {
388 global $wgSitename, $wgCanonicalServer, $wgRequest;
390 $usegoogle = htmlspecialchars( self
::msg(
392 'You can try searching via Google in the meantime.'
394 $outofdate = htmlspecialchars( self
::msg(
396 'Note that their indexes of our content may be out of date.'
398 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
399 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
400 $server = htmlspecialchars( $wgCanonicalServer );
401 $sitename = htmlspecialchars( $wgSitename );
403 <div style="margin: 1.5em">$usegoogle<br />
404 <small>$outofdate</small>
406 <form method="get" action="//www.google.com/search" id="googlesearch">
407 <input type="hidden" name="domains" value="$server" />
408 <input type="hidden" name="num" value="50" />
409 <input type="hidden" name="ie" value="UTF-8" />
410 <input type="hidden" name="oe" value="UTF-8" />
411 <input type="text" name="q" size="31" maxlength="255" value="$search" />
412 <input type="submit" name="btnG" value="$googlesearch" />
414 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
415 <label><input type="radio" name="sitesearch" value="" />WWW</label>