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 .= "Exception caught inside exception handler.\n\n" .
64 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
65 "to show detailed debugging information.";
69 if ( self
::showBackTrace( $e ) ) {
70 $message = MWExceptionHandler
::getLogMessage( $e ) .
72 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
74 $message = MWExceptionHandler
::getPublicLogMessage( $e );
77 echo nl2br( htmlspecialchars( $message ) ) . "\n";
82 * Run hook to allow extensions to modify the text of the exception
84 * Called by MWException for b/c
86 * @param Exception|Throwable $e
87 * @param string $name Class name of the exception
88 * @param array $args Arguments to pass to the callback functions
89 * @return string|null String to output or null if any hook has been called
91 public static function runHooks( $e, $name, $args = [] ) {
92 global $wgExceptionHooks;
94 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
95 return null; // Just silently ignore
98 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
99 !is_array( $wgExceptionHooks[$name] )
104 $hooks = $wgExceptionHooks[$name];
105 $callargs = array_merge( [ $e ], $args );
107 foreach ( $hooks as $hook ) {
109 is_string( $hook ) ||
110 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
112 // 'function' or [ 'class', 'hook' ]
113 $result = call_user_func_array( $hook, $callargs );
118 if ( is_string( $result ) ) {
127 * @param Exception|Throwable $e
128 * @return bool Should the exception use $wgOut to output the error?
130 private static function useOutputPage( $e ) {
131 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
132 foreach ( $e->getTrace() as $frame ) {
133 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
139 !empty( $GLOBALS['wgFullyInitialised'] ) &&
140 !empty( $GLOBALS['wgOut'] ) &&
141 !defined( 'MEDIAWIKI_INSTALL' )
146 * Output the exception report using HTML
148 * @param Exception|Throwable $e
150 private static function reportHTML( $e ) {
151 global $wgOut, $wgSitename;
153 if ( self
::useOutputPage( $e ) ) {
154 if ( $e instanceof MWException
) {
155 $wgOut->prepareErrorPage( $e->getPageTitle() );
156 } elseif ( $e instanceof DBReadOnlyError
) {
157 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
158 } elseif ( $e instanceof DBExpectedError
) {
159 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
161 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
164 $hookResult = self
::runHooks( $e, get_class( $e ) );
166 $wgOut->addHTML( $hookResult );
168 // Show any custom GUI message before the details
169 if ( $e instanceof MessageSpecifier
) {
170 $wgOut->addHTML( Message
::newFromSpecifier( $e )->escaped() );
172 $wgOut->addHTML( self
::getHTML( $e ) );
177 self
::header( 'Content-Type: text/html; charset=utf-8' );
178 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
179 echo "<!DOCTYPE html>\n" .
181 // Mimick OutputPage::setPageTitle behaviour
183 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
185 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
188 $hookResult = self
::runHooks( $e, get_class( $e ) . 'Raw' );
192 echo self
::getHTML( $e );
195 echo "</body></html>\n";
200 * If $wgShowExceptionDetails is true, return a HTML message with a
201 * backtrace to the error, otherwise show a message to ask to set it to true
202 * to show that information.
204 * @param Exception|Throwable $e
205 * @return string Html to output
207 public static function getHTML( $e ) {
208 if ( self
::showBackTrace( $e ) ) {
209 $html = "<div class=\"errorbox\"><p>" .
210 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
211 '</p><p>Backtrace:</p><p>' .
212 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
215 $logId = WebRequest
::getRequestId();
216 $html = "<div class=\"errorbox\">" .
217 '[' . $logId . '] ' .
218 gmdate( 'Y-m-d H:i:s' ) . ": " .
219 self
::msg( "internalerror-fatal-exception",
220 "Fatal exception of type $1",
223 MWExceptionHandler
::getURL()
225 "<!-- Set \$wgShowExceptionDetails = true; " .
226 "at the bottom of LocalSettings.php to show detailed " .
227 "debugging information. -->";
234 * Get a message from i18n
236 * @param string $key Message name
237 * @param string $fallback Default message if the message cache can't be
238 * called by the exception
239 * The function also has other parameters that are arguments for the message
240 * @return string Message with arguments replaced
242 private static function msg( $key, $fallback /*[, params...] */ ) {
243 $args = array_slice( func_get_args(), 2 );
245 return wfMessage( $key, $args )->text();
246 } catch ( Exception
$e ) {
247 return wfMsgReplaceArgs( $fallback, $args );
252 * @param Exception|Throwable $e
255 private static function getText( $e ) {
256 if ( self
::showBackTrace( $e ) ) {
257 return MWExceptionHandler
::getLogMessage( $e ) .
259 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
261 return "Set \$wgShowExceptionDetails = true; " .
262 "in LocalSettings.php to show detailed debugging information.\n";
267 * @param Exception|Throwable $e
270 private static function showBackTrace( $e ) {
271 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
274 $wgShowExceptionDetails &&
275 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
282 private static function isCommandLine() {
283 return !empty( $GLOBALS['wgCommandLineMode'] );
287 * @param string $header
289 private static function header( $header ) {
290 if ( !headers_sent() ) {
296 * @param integer $code
298 private static function statusHeader( $code ) {
299 if ( !headers_sent() ) {
300 HttpStatus
::header( $code );
305 * Print a message, if possible to STDERR.
306 * Use this in command line mode only (see isCommandLine)
308 * @param string $message Failure text
310 private static function printError( $message ) {
311 // NOTE: STDERR may not be available, especially if php-cgi is used from the
312 // command line (bug #15602). Try to produce meaningful output anyway. Using
313 // echo may corrupt output to STDOUT though.
314 if ( defined( 'STDERR' ) ) {
315 fwrite( STDERR
, $message );
322 * @param Exception|Throwable $e
324 private static function reportOutageHTML( $e ) {
325 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
327 $sorry = htmlspecialchars( self
::msg(
329 'Sorry! This site is experiencing technical difficulties.'
331 $again = htmlspecialchars( self
::msg(
333 'Try waiting a few minutes and reloading.'
336 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
339 Html
::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
340 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
343 $info = htmlspecialchars( self
::msg(
345 '(Cannot access the database)'
349 MessageCache
::singleton()->disable(); // no DB access
351 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
353 if ( $wgShowDBErrorBacktrace ) {
354 $html .= '<p>Backtrace:</p><pre>' .
355 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
359 $html .= self
::googleSearchForm();
367 private static function googleSearchForm() {
368 global $wgSitename, $wgCanonicalServer, $wgRequest;
370 $usegoogle = htmlspecialchars( self
::msg(
372 'You can try searching via Google in the meantime.'
374 $outofdate = htmlspecialchars( self
::msg(
376 'Note that their indexes of our content may be out of date.'
378 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
379 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
380 $server = htmlspecialchars( $wgCanonicalServer );
381 $sitename = htmlspecialchars( $wgSitename );
383 <div style="margin: 1.5em">$usegoogle<br />
384 <small>$outofdate</small>
386 <form method="get" action="//www.google.com/search" id="googlesearch">
387 <input type="hidden" name="domains" value="$server" />
388 <input type="hidden" name="num" value="50" />
389 <input type="hidden" name="ie" value="UTF-8" />
390 <input type="hidden" name="oe" value="UTF-8" />
391 <input type="text" name="q" size="31" maxlength="255" value="$search" />
392 <input type="submit" name="btnG" value="$googlesearch" />
394 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
395 <label><input type="radio" name="sitesearch" value="" />WWW</label>