Merge "RevisionStoreDbTestBase, remove redundant needsDB override"
[lhc/web/wiklou.git] / includes / exception / MWExceptionRenderer.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 use Wikimedia\Rdbms\DBConnectionError;
22 use Wikimedia\Rdbms\DBReadOnlyError;
23 use Wikimedia\Rdbms\DBExpectedError;
24
25 /**
26 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
27 * @since 1.28
28 */
29 class MWExceptionRenderer {
30 const AS_RAW = 1; // show as text
31 const AS_PRETTY = 2; // show as HTML
32
33 /**
34 * @param Exception|Throwable $e Original exception
35 * @param int $mode MWExceptionExposer::AS_* constant
36 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
37 */
38 public static function output( $e, $mode, $eNew = null ) {
39 global $wgMimeType, $wgShowExceptionDetails;
40
41 if ( defined( 'MW_API' ) ) {
42 // Unhandled API exception, we can't be sure that format printer is alive
43 self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
44 wfHttpError( 500, 'Internal Server Error', self::getText( $e ) );
45 } elseif ( self::isCommandLine() ) {
46 self::printError( self::getText( $e ) );
47 } elseif ( $mode === self::AS_PRETTY ) {
48 self::statusHeader( 500 );
49 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
50 if ( $e instanceof DBConnectionError ) {
51 self::reportOutageHTML( $e );
52 } else {
53 self::reportHTML( $e );
54 }
55 } else {
56 self::statusHeader( 500 );
57 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
58 if ( $eNew ) {
59 $message = "MediaWiki internal error.\n\n";
60 if ( $wgShowExceptionDetails ) {
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 );
67 } else {
68 $message .= 'Original exception: ' .
69 MWExceptionHandler::getPublicLogMessage( $e );
70 $message .= "\n\nException caught inside exception handler.\n\n" .
71 self::getShowBacktraceError( $e );
72 }
73 $message .= "\n";
74 } else {
75 if ( $wgShowExceptionDetails ) {
76 $message = MWExceptionHandler::getLogMessage( $e ) .
77 "\nBacktrace:\n" .
78 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
79 } else {
80 $message = MWExceptionHandler::getPublicLogMessage( $e );
81 }
82 }
83 echo nl2br( htmlspecialchars( $message ) ) . "\n";
84 }
85 }
86
87 /**
88 * @param Exception|Throwable $e
89 * @return bool Should the exception use $wgOut to output the error?
90 */
91 private static function useOutputPage( $e ) {
92 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
93 foreach ( $e->getTrace() as $frame ) {
94 if ( isset( $frame['class'] ) && $frame['class'] === LocalisationCache::class ) {
95 return false;
96 }
97 }
98
99 // Don't even bother with OutputPage if there's no Title context set,
100 // (e.g. we're in RL code on load.php) - the Skin system (and probably
101 // most of MediaWiki) won't work.
102
103 return (
104 !empty( $GLOBALS['wgFullyInitialised'] ) &&
105 !empty( $GLOBALS['wgOut'] ) &&
106 RequestContext::getMain()->getTitle() &&
107 !defined( 'MEDIAWIKI_INSTALL' )
108 );
109 }
110
111 /**
112 * Output the exception report using HTML
113 *
114 * @param Exception|Throwable $e
115 */
116 private static function reportHTML( $e ) {
117 global $wgOut, $wgSitename;
118
119 if ( self::useOutputPage( $e ) ) {
120 if ( $e instanceof MWException ) {
121 $wgOut->prepareErrorPage( $e->getPageTitle() );
122 } elseif ( $e instanceof DBReadOnlyError ) {
123 $wgOut->prepareErrorPage( self::msg( 'readonly', 'Database is locked' ) );
124 } elseif ( $e instanceof DBExpectedError ) {
125 $wgOut->prepareErrorPage( self::msg( 'databaseerror', 'Database error' ) );
126 } else {
127 $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
128 }
129
130 // Show any custom GUI message before the details
131 if ( $e instanceof MessageSpecifier ) {
132 $wgOut->addHTML( Html::element( 'p', [], Message::newFromSpecifier( $e )->text() ) );
133 }
134 $wgOut->addHTML( self::getHTML( $e ) );
135
136 $wgOut->output();
137 } else {
138 self::header( 'Content-Type: text/html; charset=utf-8' );
139 $pageTitle = self::msg( 'internalerror', 'Internal error' );
140 echo "<!DOCTYPE html>\n" .
141 '<html><head>' .
142 // Mimick OutputPage::setPageTitle behaviour
143 '<title>' .
144 htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
145 '</title>' .
146 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
147 "</head><body>\n";
148
149 echo self::getHTML( $e );
150
151 echo "</body></html>\n";
152 }
153 }
154
155 /**
156 * If $wgShowExceptionDetails is true, return a HTML message with a
157 * backtrace to the error, otherwise show a message to ask to set it to true
158 * to show that information.
159 *
160 * @param Exception|Throwable $e
161 * @return string Html to output
162 */
163 public static function getHTML( $e ) {
164 global $wgShowExceptionDetails;
165
166 if ( $wgShowExceptionDetails ) {
167 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
168 nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
169 '</p><p>Backtrace:</p><p>' .
170 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
171 "</p></div>\n";
172 } else {
173 $logId = WebRequest::getRequestId();
174 $html = "<div class=\"errorbox mw-content-ltr\">" .
175 htmlspecialchars(
176 '[' . $logId . '] ' .
177 gmdate( 'Y-m-d H:i:s' ) . ": " .
178 self::msg( "internalerror-fatal-exception",
179 "Fatal exception of type $1",
180 get_class( $e ),
181 $logId,
182 MWExceptionHandler::getURL()
183 ) ) . "</div>\n" .
184 "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
185 }
186
187 return $html;
188 }
189
190 /**
191 * Get a message from i18n
192 *
193 * @param string $key Message name
194 * @param string $fallback Default message if the message cache can't be
195 * called by the exception
196 * The function also has other parameters that are arguments for the message
197 * @return string Message with arguments replaced
198 */
199 private static function msg( $key, $fallback /*[, params...] */ ) {
200 global $wgSitename;
201 $args = array_slice( func_get_args(), 2 );
202 try {
203 $res = wfMessage( $key, $args )->text();
204 } catch ( Exception $e ) {
205 $res = wfMsgReplaceArgs( $fallback, $args );
206 // If an exception happens inside message rendering,
207 // {{SITENAME}} sometimes won't be replaced.
208 $res = preg_replace( '/\{\{SITENAME\}\}/', $wgSitename, $res );
209 }
210 return $res;
211 }
212
213 /**
214 * @param Exception|Throwable $e
215 * @return string
216 */
217 private static function getText( $e ) {
218 global $wgShowExceptionDetails;
219
220 if ( $wgShowExceptionDetails ) {
221 return MWExceptionHandler::getLogMessage( $e ) .
222 "\nBacktrace:\n" .
223 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
224 } else {
225 return self::getShowBacktraceError( $e ) . "\n";
226 }
227 }
228
229 /**
230 * @param Exception|Throwable $e
231 * @return string
232 */
233 private static function getShowBacktraceError( $e ) {
234 $var = '$wgShowExceptionDetails = true;';
235 return "Set $var at the bottom of LocalSettings.php to show detailed debugging information.";
236 }
237
238 /**
239 * @return bool
240 */
241 private static function isCommandLine() {
242 return !empty( $GLOBALS['wgCommandLineMode'] );
243 }
244
245 /**
246 * @param string $header
247 */
248 private static function header( $header ) {
249 if ( !headers_sent() ) {
250 header( $header );
251 }
252 }
253
254 /**
255 * @param int $code
256 */
257 private static function statusHeader( $code ) {
258 if ( !headers_sent() ) {
259 HttpStatus::header( $code );
260 }
261 }
262
263 /**
264 * Print a message, if possible to STDERR.
265 * Use this in command line mode only (see isCommandLine)
266 *
267 * @param string $message Failure text
268 */
269 private static function printError( $message ) {
270 // NOTE: STDERR may not be available, especially if php-cgi is used from the
271 // command line (bug #15602). Try to produce meaningful output anyway. Using
272 // echo may corrupt output to STDOUT though.
273 if ( defined( 'STDERR' ) ) {
274 fwrite( STDERR, $message );
275 } else {
276 echo $message;
277 }
278 }
279
280 /**
281 * @param Exception|Throwable $e
282 */
283 private static function reportOutageHTML( $e ) {
284 global $wgShowExceptionDetails, $wgShowHostnames, $wgSitename;
285
286 $sorry = htmlspecialchars( self::msg(
287 'dberr-problems',
288 'Sorry! This site is experiencing technical difficulties.'
289 ) );
290 $again = htmlspecialchars( self::msg(
291 'dberr-again',
292 'Try waiting a few minutes and reloading.'
293 ) );
294
295 if ( $wgShowHostnames ) {
296 $info = str_replace(
297 '$1',
298 Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
299 htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
300 );
301 } else {
302 $info = htmlspecialchars( self::msg(
303 'dberr-info-hidden',
304 '(Cannot access the database)'
305 ) );
306 }
307
308 MessageCache::singleton()->disable(); // no DB access
309 $html = "<!DOCTYPE html>\n" .
310 '<html><head>' .
311 '<title>' .
312 htmlspecialchars( $wgSitename ) .
313 '</title>' .
314 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
315 "</head><body><h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
316
317 if ( $wgShowExceptionDetails ) {
318 $html .= '<p>Backtrace:</p><pre>' .
319 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
320 }
321
322 $html .= '<hr />';
323 $html .= self::googleSearchForm();
324 $html .= '</body></html>';
325 echo $html;
326 }
327
328 /**
329 * @return string
330 */
331 private static function googleSearchForm() {
332 global $wgSitename, $wgCanonicalServer, $wgRequest;
333
334 $usegoogle = htmlspecialchars( self::msg(
335 'dberr-usegoogle',
336 'You can try searching via Google in the meantime.'
337 ) );
338 $outofdate = htmlspecialchars( self::msg(
339 'dberr-outofdate',
340 'Note that their indexes of our content may be out of date.'
341 ) );
342 $googlesearch = htmlspecialchars( self::msg( 'searchbutton', 'Search' ) );
343 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
344 $server = htmlspecialchars( $wgCanonicalServer );
345 $sitename = htmlspecialchars( $wgSitename );
346 $trygoogle = <<<EOT
347 <div style="margin: 1.5em">$usegoogle<br />
348 <small>$outofdate</small>
349 </div>
350 <form method="get" action="//www.google.com/search" id="googlesearch">
351 <input type="hidden" name="domains" value="$server" />
352 <input type="hidden" name="num" value="50" />
353 <input type="hidden" name="ie" value="UTF-8" />
354 <input type="hidden" name="oe" value="UTF-8" />
355 <input type="text" name="q" size="31" maxlength="255" value="$search" />
356 <input type="submit" name="btnG" value="$googlesearch" />
357 <p>
358 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
359 <label><input type="radio" name="sitesearch" value="" />WWW</label>
360 </p>
361 </form>
362 EOT;
363 return $trygoogle;
364 }
365 }