Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 181
0.00% covered (danger)
0.00%
0 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
MWExceptionRenderer
0.00% covered (danger)
0.00%
0 / 180
0.00% covered (danger)
0.00%
0 / 18
3080
0.00% covered (danger)
0.00%
0 / 1
 shouldShowExceptionDetails
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setShowExceptionDetails
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 output
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
132
 useOutputPage
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
90
 reportHTML
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
12
 getHTML
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
6
 msg
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 msgObj
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getText
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 getShowBacktraceError
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getExceptionTitle
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 getCustomMessage
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 isCommandLine
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 header
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 statusHeader
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 printError
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 reportOutageHTML
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
12
 cspHeader
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Exception;
8
9use Exception;
10use MediaWiki\Context\RequestContext;
11use MediaWiki\Html\Html;
12use MediaWiki\Language\LocalisationCache;
13use MediaWiki\Language\RawMessage;
14use MediaWiki\MainConfigNames;
15use MediaWiki\MediaWikiServices;
16use MediaWiki\Message\Message;
17use MediaWiki\Request\ContentSecurityPolicy;
18use MediaWiki\Request\WebRequest;
19use Throwable;
20use Wikimedia\Http\HttpStatus;
21use Wikimedia\Message\MessageParam;
22use Wikimedia\Message\MessageSpecifier;
23use Wikimedia\Rdbms\DBConnectionError;
24use Wikimedia\Rdbms\DBExpectedError;
25use Wikimedia\Rdbms\DBReadOnlyError;
26use Wikimedia\RequestTimeout\RequestTimeoutException;
27
28/**
29 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
30 * @since 1.28
31 */
32class MWExceptionRenderer {
33    public const AS_RAW = 1; // show as text
34    public const AS_PRETTY = 2; // show as HTML
35
36    /**
37     * Whether to print exception details.
38     *
39     * The default is configured by $wgShowExceptionDetails.
40     * May be changed at runtime via MWExceptionRenderer::setShowExceptionDetails().
41     *
42     * @see MainConfigNames::ShowExceptionDetails
43     * @var bool
44     */
45    private static $showExceptionDetails = false;
46
47    /**
48     * @internal For use within core wiring only.
49     * @return bool
50     */
51    public static function shouldShowExceptionDetails(): bool {
52        return self::$showExceptionDetails;
53    }
54
55    /**
56     * @param bool $showDetails
57     * @internal For use by Setup.php and other internal use cases.
58     */
59    public static function setShowExceptionDetails( bool $showDetails ): void {
60        self::$showExceptionDetails = $showDetails;
61    }
62
63    /**
64     * @param Throwable $e Original exception
65     * @param int $mode MWExceptionExposer::AS_* constant
66     * @param Throwable|null $eNew New throwable from attempting to show the first
67     */
68    public static function output( Throwable $e, $mode, ?Throwable $eNew = null ) {
69        $showExceptionDetails = self::shouldShowExceptionDetails();
70        if ( $e instanceof RequestTimeoutException && headers_sent() ) {
71            // Excimer's flag check happens on function return, so, a timeout
72            // can be thrown after exiting, say, `doPostOutputShutdown`, where
73            // headers are sent.  In which case, it's probably fine not to
74            // report this in any user visible way.  The general question of
75            // what to do about reporting an exception when headers have been
76            // sent is still unclear, but you probably don't want to
77            // `useOutputPage`.
78            return;
79        }
80
81        if ( function_exists( 'apache_setenv' ) ) {
82            // The client should not be blocked on "post-send" updates. If apache decides that
83            // a response should be gzipped, it will wait for PHP to finish since it cannot gzip
84            // anything until it has the full response (even with "Transfer-Encoding: chunked").
85            // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
86            @apache_setenv( 'no-gzip', '1' );
87        }
88
89        if ( defined( 'MW_API' ) ) {
90            self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
91        }
92
93        if ( self::isCommandLine() ) {
94            self::printError( self::getText( $e ) );
95        } elseif ( $mode === self::AS_PRETTY ) {
96            self::statusHeader( 500 );
97            ob_start();
98            if ( $e instanceof DBConnectionError ) {
99                self::reportOutageHTML( $e );
100            } else {
101                self::reportHTML( $e );
102            }
103            self::header( "Content-Length: " . ob_get_length() );
104            ob_end_flush();
105        } else {
106            ob_start();
107            self::statusHeader( 500 );
108            self::cspHeader();
109            self::header( 'Content-Type: text/html; charset=UTF-8' );
110            if ( $eNew ) {
111                $message = "MediaWiki internal error.\n\n";
112                if ( $showExceptionDetails ) {
113                    $message .= 'Original exception: ' .
114                        MWExceptionHandler::getLogMessage( $e ) .
115                        "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
116                        "\n\nException caught inside exception handler: " .
117                            MWExceptionHandler::getLogMessage( $eNew ) .
118                        "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
119                } else {
120                    $message .= 'Original exception: ' .
121                        MWExceptionHandler::getPublicLogMessage( $e );
122                    $message .= "\n\nException caught inside exception handler.\n\n" .
123                        self::getShowBacktraceError();
124                }
125                $message .= "\n";
126            } elseif ( $showExceptionDetails ) {
127                $message = MWExceptionHandler::getLogMessage( $e ) .
128                    "\nBacktrace:\n" .
129                    MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
130            } else {
131                $message = MWExceptionHandler::getPublicLogMessage( $e );
132            }
133            print nl2br( htmlspecialchars( $message ) ) . "\n";
134            print '<meta name="color-scheme" content="light dark">';
135            self::header( "Content-Length: " . ob_get_length() );
136            ob_end_flush();
137        }
138    }
139
140    /**
141     * @param Throwable $e
142     * @return bool Should the throwable use $wgOut to output the error?
143     */
144    private static function useOutputPage( Throwable $e ) {
145        // Can the exception use the Message class/wfMessage to get i18n-ed messages?
146        foreach ( $e->getTrace() as $frame ) {
147            if ( isset( $frame['class'] ) && $frame['class'] === LocalisationCache::class ) {
148                return false;
149            }
150        }
151
152        // Don't even bother with OutputPage if there's no Title context set,
153        // (e.g. we're in RL code on load.php) - the Skin system (and probably
154        // most of MediaWiki) won't work.
155        return (
156            !empty( $GLOBALS['wgFullyInitialised'] ) &&
157            !empty( $GLOBALS['wgOut'] ) &&
158            RequestContext::getMain()->getTitle() &&
159            !defined( 'MEDIAWIKI_INSTALL' ) &&
160            // Don't send a skinned HTTP 500 page to API clients.
161            !defined( 'MW_API' ) &&
162            !defined( 'MW_REST_API' )
163        );
164    }
165
166    /**
167     * Output the throwable report using HTML
168     */
169    private static function reportHTML( Throwable $e ) {
170        if ( self::useOutputPage( $e ) ) {
171            $out = RequestContext::getMain()->getOutput();
172            $out->prepareErrorPage();
173            $out->addModuleStyles( 'mediawiki.codex.messagebox.styles' );
174            $out->setPageTitleMsg( self::getExceptionTitle( $e ) );
175
176            // Show any custom GUI message before the details
177            $customMessage = self::getCustomMessage( $e );
178            if ( $customMessage !== null ) {
179                $out->addHTML( Html::element( 'p', [], $customMessage ) );
180            }
181            $out->addHTML( self::getHTML( $e ) );
182            // Content-Type is set by OutputPage::output
183            $out->output();
184        } else {
185            self::cspHeader();
186            self::header( 'Content-Type: text/html; charset=UTF-8' );
187            $pageTitle = self::msg( 'internalerror', 'Internal error' );
188            echo "<!DOCTYPE html>\n" .
189                '<html><head>' .
190                // Mimic OutputPage::setPageTitle behaviour
191                '<title>' .
192                htmlspecialchars( self::msg( 'pagetitle', '$1 - MediaWiki', $pageTitle ) ) .
193                '</title>' .
194                '<meta name="color-scheme" content="light dark" />' .
195                '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
196                "</head><body>\n";
197
198            echo self::getHTML( $e );
199
200            echo "</body></html>\n";
201        }
202    }
203
204    /**
205     * Format an HTML message for the given exception object.
206     *
207     * @param Throwable $e
208     * @return string Html to output
209     */
210    public static function getHTML( Throwable $e ) {
211        if ( self::shouldShowExceptionDetails() ) {
212            $html = '<div dir=ltr>' . Html::errorBox( "<p>" .
213                nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
214                '</p><p>Backtrace:</p><p>' .
215                nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
216                "</p>\n"
217            ) . '</div>';
218        } else {
219            $logId = WebRequest::getRequestId();
220            $html = Html::errorBox(
221                htmlspecialchars(
222                    '[' . $logId . '] ' .
223                    gmdate( 'Y-m-d H:i:s' ) . ": " .
224                    self::msg( "internalerror-fatal-exception",
225                        "Fatal exception of type $1",
226                        get_class( $e ),
227                        $logId,
228                        MWExceptionHandler::getURL()
229                ) )
230            ) . "<!-- " . wordwrap( self::getShowBacktraceError(), 50 ) . " -->";
231        }
232
233        return $html;
234    }
235
236    /**
237     * Get a message string from i18n
238     *
239     * @param string $key Message name
240     * @param string $fallback Default message if the message cache can't be
241     *                  called by the exception
242     * @phpcs:ignore Generic.Files.LineLength
243     * @param MessageParam|MessageSpecifier|string|int|float|list<MessageParam|MessageSpecifier|string|int|float> ...$params
244     *   See Message::params()
245     * @return string Message with arguments replaced
246     */
247    public static function msg( $key, $fallback, ...$params ) {
248        // NOTE: Keep logic in sync with MWException::msg
249        $res = self::msgObj( $key, $fallback, ...$params )->text();
250        return strtr( $res, [
251            '{{SITENAME}}' => 'MediaWiki',
252        ] );
253    }
254
255    /** Get a Message object from i18n.
256     *
257     * @param string $key Message name
258     * @param string $fallback Default message if the message cache can't be
259     *                  called by the exception
260     * @phpcs:ignore Generic.Files.LineLength
261     * @param MessageParam|MessageSpecifier|string|int|float|list<MessageParam|MessageSpecifier|string|int|float> ...$params
262     *   See Message::params()
263     * @return Message|RawMessage
264     */
265    private static function msgObj( string $key, string $fallback, ...$params ): Message {
266        // NOTE: Keep logic in sync with MWException::msg.
267        try {
268            $res = wfMessage( $key, ...$params );
269        } catch ( Exception ) {
270            // Fallback to static message text and generic sitename.
271            // Avoid live config as this must work before Setup/MediaWikiServices finish.
272            $res = new RawMessage( $fallback, $params );
273        }
274        // We are in an error state, best to minimize how much work we do.
275        $res->useDatabase( false );
276        $isSafeToLoad = RequestContext::getMain()->getUser()->isSafeToLoad();
277        if ( !$isSafeToLoad ) {
278            $res->inContentLanguage();
279        }
280        return $res;
281    }
282
283    /**
284     * @param Throwable $e
285     * @return string
286     */
287    private static function getText( Throwable $e ) {
288        // XXX: do we need a parameter to control inclusion of exception details?
289        if ( self::shouldShowExceptionDetails() ) {
290            return MWExceptionHandler::getLogMessage( $e ) .
291                "\nBacktrace:\n" .
292                MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
293        } else {
294            return self::getShowBacktraceError() . "\n";
295        }
296    }
297
298    /**
299     * @return string
300     */
301    private static function getShowBacktraceError() {
302        $var = '$wgShowExceptionDetails = true;';
303        return "Set $var at the bottom of LocalSettings.php to show detailed debugging information.";
304    }
305
306    /**
307     * Get the page title to be used for a given exception.
308     *
309     * @param Throwable $e
310     * @return Message
311     */
312    private static function getExceptionTitle( Throwable $e ): Message {
313        if ( $e instanceof DBReadOnlyError ) {
314            return self::msgObj( 'readonly', 'Database is locked' );
315        } elseif ( $e instanceof DBExpectedError ) {
316            return self::msgObj( 'databaseerror', 'Database error' );
317        } elseif ( $e instanceof RequestTimeoutException ) {
318            return self::msgObj( 'timeouterror', 'Request timeout' );
319        } else {
320            return self::msgObj( 'internalerror', 'Internal error' );
321        }
322    }
323
324    /**
325     * Extract an additional user-visible message from an exception, or null if
326     * it has none.
327     *
328     * @param Throwable $e
329     * @return string|null
330     */
331    private static function getCustomMessage( Throwable $e ) {
332        try {
333            if ( $e instanceof MessageSpecifier ) {
334                $msg = Message::newFromSpecifier( $e );
335            } elseif ( $e instanceof RequestTimeoutException ) {
336                $msg = wfMessage( 'timeouterror-text', $e->getLimit() );
337            } else {
338                return null;
339            }
340            $text = $msg->text();
341        } catch ( Exception ) {
342            return null;
343        }
344        return $text;
345    }
346
347    /**
348     * @return bool
349     */
350    private static function isCommandLine() {
351        return MW_ENTRY_POINT === 'cli';
352    }
353
354    /**
355     * @param string $header
356     */
357    private static function header( $header ) {
358        if ( !headers_sent() ) {
359            header( $header );
360        }
361    }
362
363    /**
364     * @param int $code
365     */
366    private static function statusHeader( $code ) {
367        if ( !headers_sent() ) {
368            HttpStatus::header( $code );
369        }
370    }
371
372    /**
373     * Print a message, if possible to STDERR.
374     * Use this in command line mode only (see isCommandLine)
375     *
376     * @suppress SecurityCheck-XSS
377     * @param string $message Failure text
378     */
379    private static function printError( $message ) {
380        // NOTE: STDERR may not be available, especially if php-cgi is used from the
381        // command line (T17602). Try to produce meaningful output anyway. Using
382        // echo may corrupt output to STDOUT though.
383        if ( !defined( 'MW_PHPUNIT_TEST' ) && defined( 'STDERR' ) ) {
384            fwrite( STDERR, $message );
385        } else {
386            echo $message;
387        }
388    }
389
390    private static function reportOutageHTML( Throwable $e ) {
391        $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
392        $showExceptionDetails = $mainConfig->get( MainConfigNames::ShowExceptionDetails );
393        $showHostnames = $mainConfig->get( MainConfigNames::ShowHostnames );
394        $sorry = htmlspecialchars( self::msg(
395            'dberr-problems',
396            'Sorry! This site is experiencing technical difficulties.'
397        ) );
398        $again = htmlspecialchars( self::msg(
399            'dberr-again',
400            'Try waiting a few minutes and reloading.'
401        ) );
402
403        if ( $showHostnames ) {
404            $info = str_replace(
405                '$1',
406                Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
407                htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
408            );
409        } else {
410            $info = htmlspecialchars( self::msg(
411                'dberr-info-hidden',
412                '(Cannot access the database)'
413            ) );
414        }
415
416        MediaWikiServices::getInstance()->getMessageCache()->disable(); // no DB access
417        $html = "<!DOCTYPE html>\n" .
418                '<html><head>' .
419                '<title>MediaWiki</title>' .
420                '<meta name="color-scheme" content="light dark" />' .
421                '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
422                "</head><body><h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
423
424        if ( $showExceptionDetails ) {
425            $html .= '<p>Backtrace:</p><pre>' .
426                htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
427        }
428
429        $html .= '</body></html>';
430        self::cspHeader();
431        self::header( 'Content-Type: text/html; charset=UTF-8' );
432        echo $html;
433    }
434
435    private static function cspHeader(): void {
436        if ( !headers_sent() ) {
437            ContentSecurityPolicy::sendRestrictiveHeader();
438        }
439    }
440}
441
442/** @deprecated class alias since 1.44 */
443class_alias( MWExceptionRenderer::class, 'MWExceptionRenderer' );