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 if ( self
::isCommandLine() ) {
78 self
::printError( $message );
80 echo nl2br( htmlspecialchars( $message ) ) . "\n";
86 * Run hook to allow extensions to modify the text of the exception
88 * Called by MWException for b/c
90 * @param Exception|Throwable $e
91 * @param string $name Class name of the exception
92 * @param array $args Arguments to pass to the callback functions
93 * @return string|null String to output or null if any hook has been called
95 public static function runHooks( $e, $name, $args = [] ) {
96 global $wgExceptionHooks;
98 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
99 return null; // Just silently ignore
102 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
103 !is_array( $wgExceptionHooks[$name] )
108 $hooks = $wgExceptionHooks[$name];
109 $callargs = array_merge( [ $e ], $args );
111 foreach ( $hooks as $hook ) {
113 is_string( $hook ) ||
114 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
116 // 'function' or [ 'class', 'hook' ]
117 $result = call_user_func_array( $hook, $callargs );
122 if ( is_string( $result ) ) {
131 * @param Exception|Throwable $e
132 * @return bool Should the exception use $wgOut to output the error?
134 private static function useOutputPage( $e ) {
135 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
136 foreach ( $e->getTrace() as $frame ) {
137 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
143 !empty( $GLOBALS['wgFullyInitialised'] ) &&
144 !empty( $GLOBALS['wgOut'] ) &&
145 !defined( 'MEDIAWIKI_INSTALL' )
150 * Output the exception report using HTML
152 * @param Exception|Throwable $e
154 private static function reportHTML( $e ) {
155 global $wgOut, $wgSitename;
157 if ( self
::useOutputPage( $e ) ) {
158 if ( $e instanceof MWException
) {
159 $wgOut->prepareErrorPage( $e->getPageTitle() );
160 } elseif ( $e instanceof DBReadOnlyError
) {
161 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
162 } elseif ( $e instanceof DBExpectedError
) {
163 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
165 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
168 $hookResult = self
::runHooks( $e, get_class( $e ) );
170 $wgOut->addHTML( $hookResult );
172 // Show any custom GUI message before the details
173 if ( $e instanceof MessageSpecifier
) {
174 $wgOut->addHTML( Message
::newFromSpecifier( $e )->escaped() );
176 $wgOut->addHTML( self
::getHTML( $e ) );
181 self
::header( 'Content-Type: text/html; charset=utf-8' );
182 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
183 echo "<!DOCTYPE html>\n" .
185 // Mimick OutputPage::setPageTitle behaviour
187 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
189 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
192 $hookResult = self
::runHooks( $e, get_class( $e ) . 'Raw' );
196 echo self
::getHTML( $e );
199 echo "</body></html>\n";
204 * If $wgShowExceptionDetails is true, return a HTML message with a
205 * backtrace to the error, otherwise show a message to ask to set it to true
206 * to show that information.
208 * @param Exception|Throwable $e
209 * @return string Html to output
211 public static function getHTML( $e ) {
212 if ( self
::showBackTrace( $e ) ) {
213 $html = "<div class=\"errorbox\"><p>" .
214 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
215 '</p><p>Backtrace:</p><p>' .
216 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
219 $logId = WebRequest
::getRequestId();
220 $html = "<div class=\"errorbox\">" .
221 '[' . $logId . '] ' .
222 gmdate( 'Y-m-d H:i:s' ) . ": " .
223 self
::msg( "internalerror-fatal-exception",
224 "Fatal exception of type $1",
227 MWExceptionHandler
::getURL()
229 "<!-- Set \$wgShowExceptionDetails = true; " .
230 "at the bottom of LocalSettings.php to show detailed " .
231 "debugging information. -->";
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 "Set \$wgShowExceptionDetails = true; " .
266 "in LocalSettings.php to show detailed debugging information.\n";
271 * @param Exception|Throwable $e
274 private static function showBackTrace( $e ) {
275 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
278 $wgShowExceptionDetails &&
279 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
286 private static function isCommandLine() {
287 return !empty( $GLOBALS['wgCommandLineMode'] );
291 * @param string $header
293 private static function header( $header ) {
294 if ( !headers_sent() ) {
300 * @param integer $code
302 private static function statusHeader( $code ) {
303 if ( !headers_sent() ) {
304 HttpStatus
::header( $code );
309 * Print a message, if possible to STDERR.
310 * Use this in command line mode only (see isCommandLine)
312 * @param string $message Failure text
314 private static function printError( $message ) {
315 // NOTE: STDERR may not be available, especially if php-cgi is used from the
316 // command line (bug #15602). Try to produce meaningful output anyway. Using
317 // echo may corrupt output to STDOUT though.
318 if ( defined( 'STDERR' ) ) {
319 fwrite( STDERR
, $message );
326 * @param Exception|Throwable $e
328 private static function reportOutageHTML( $e ) {
329 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
331 $sorry = htmlspecialchars( self
::msg(
333 'Sorry! This site is experiencing technical difficulties.'
335 $again = htmlspecialchars( self
::msg(
337 'Try waiting a few minutes and reloading.'
340 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
343 Html
::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
344 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
347 $info = htmlspecialchars( self
::msg(
349 '(Cannot access the database)'
353 MessageCache
::singleton()->disable(); // no DB access
355 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
357 if ( $wgShowDBErrorBacktrace ) {
358 $html .= '<p>Backtrace:</p><pre>' .
359 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
363 $html .= self
::googleSearchForm();
371 private static function googleSearchForm() {
372 global $wgSitename, $wgCanonicalServer, $wgRequest;
374 $usegoogle = htmlspecialchars( self
::msg(
376 'You can try searching via Google in the meantime.'
378 $outofdate = htmlspecialchars( self
::msg(
380 'Note that their indexes of our content may be out of date.'
382 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
383 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
384 $server = htmlspecialchars( $wgCanonicalServer );
385 $sitename = htmlspecialchars( $wgSitename );
387 <div style="margin: 1.5em">$usegoogle<br />
388 <small>$outofdate</small>
390 <form method="get" action="//www.google.com/search" id="googlesearch">
391 <input type="hidden" name="domains" value="$server" />
392 <input type="hidden" name="num" value="50" />
393 <input type="hidden" name="ie" value="UTF-8" />
394 <input type="hidden" name="oe" value="UTF-8" />
395 <input type="text" name="q" size="31" maxlength="255" value="$search" />
396 <input type="submit" name="btnG" value="$googlesearch" />
398 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
399 <label><input type="radio" name="sitesearch" value="" />WWW</label>