Replace wgShowExceptionDetails with wgShowDBErrorBacktrace on db errors
[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 * @author Aaron Schulz
20 */
21
22 /**
23 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
24 * @since 1.28
25 */
26 class MWExceptionRenderer {
27 const AS_RAW = 1; // show as text
28 const AS_PRETTY = 2; // show as HTML
29
30 /**
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
34 */
35 public static function output( $e, $mode, $eNew = null ) {
36 global $wgMimeType;
37
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 );
47 } else {
48 self::statusHeader( 500 );
49 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
50 self::reportHTML( $e );
51 }
52 } else {
53 if ( $eNew ) {
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 );
62 } else {
63 $message .= "Exception caught inside exception handler.\n\n" .
64 self::getShowBacktraceError( $e );
65 }
66 $message .= "\n";
67 } else {
68 if ( self::showBackTrace( $e ) ) {
69 $message = MWExceptionHandler::getLogMessage( $e ) .
70 "\nBacktrace:\n" .
71 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
72 } else {
73 $message = MWExceptionHandler::getPublicLogMessage( $e );
74 }
75 }
76 if ( self::isCommandLine() ) {
77 self::printError( $message );
78 } else {
79 echo nl2br( htmlspecialchars( $message ) ) . "\n";
80 }
81 }
82 }
83
84 /**
85 * Run hook to allow extensions to modify the text of the exception
86 *
87 * Called by MWException for b/c
88 *
89 * @param Exception|Throwable $e
90 * @param string $name Class name of the exception
91 * @param array $args Arguments to pass to the callback functions
92 * @return string|null String to output or null if any hook has been called
93 */
94 public static function runHooks( $e, $name, $args = [] ) {
95 global $wgExceptionHooks;
96
97 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
98 return null; // Just silently ignore
99 }
100
101 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
102 !is_array( $wgExceptionHooks[$name] )
103 ) {
104 return null;
105 }
106
107 $hooks = $wgExceptionHooks[$name];
108 $callargs = array_merge( [ $e ], $args );
109
110 foreach ( $hooks as $hook ) {
111 if (
112 is_string( $hook ) ||
113 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
114 ) {
115 // 'function' or [ 'class', 'hook' ]
116 $result = call_user_func_array( $hook, $callargs );
117 } else {
118 $result = null;
119 }
120
121 if ( is_string( $result ) ) {
122 return $result;
123 }
124 }
125
126 return null;
127 }
128
129 /**
130 * @param Exception|Throwable $e
131 * @return bool Should the exception use $wgOut to output the error?
132 */
133 private static function useOutputPage( $e ) {
134 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
135 foreach ( $e->getTrace() as $frame ) {
136 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
137 return false;
138 }
139 }
140
141 return (
142 !empty( $GLOBALS['wgFullyInitialised'] ) &&
143 !empty( $GLOBALS['wgOut'] ) &&
144 !defined( 'MEDIAWIKI_INSTALL' )
145 );
146 }
147
148 /**
149 * Output the exception report using HTML
150 *
151 * @param Exception|Throwable $e
152 */
153 private static function reportHTML( $e ) {
154 global $wgOut, $wgSitename;
155
156 if ( self::useOutputPage( $e ) ) {
157 if ( $e instanceof MWException ) {
158 $wgOut->prepareErrorPage( $e->getPageTitle() );
159 } elseif ( $e instanceof DBReadOnlyError ) {
160 $wgOut->prepareErrorPage( self::msg( 'readonly', 'Database is locked' ) );
161 } elseif ( $e instanceof DBExpectedError ) {
162 $wgOut->prepareErrorPage( self::msg( 'databaseerror', 'Database error' ) );
163 } else {
164 $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
165 }
166
167 $hookResult = self::runHooks( $e, get_class( $e ) );
168 if ( $hookResult ) {
169 $wgOut->addHTML( $hookResult );
170 } else {
171 // Show any custom GUI message before the details
172 if ( $e instanceof MessageSpecifier ) {
173 $wgOut->addHTML( Message::newFromSpecifier( $e )->escaped() );
174 }
175 $wgOut->addHTML( self::getHTML( $e ) );
176 }
177
178 $wgOut->output();
179 } else {
180 self::header( 'Content-Type: text/html; charset=utf-8' );
181 $pageTitle = self::msg( 'internalerror', 'Internal error' );
182 echo "<!DOCTYPE html>\n" .
183 '<html><head>' .
184 // Mimick OutputPage::setPageTitle behaviour
185 '<title>' .
186 htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
187 '</title>' .
188 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
189 "</head><body>\n";
190
191 $hookResult = self::runHooks( $e, get_class( $e ) . 'Raw' );
192 if ( $hookResult ) {
193 echo $hookResult;
194 } else {
195 echo self::getHTML( $e );
196 }
197
198 echo "</body></html>\n";
199 }
200 }
201
202 /**
203 * If $wgShowExceptionDetails is true, return a HTML message with a
204 * backtrace to the error, otherwise show a message to ask to set it to true
205 * to show that information.
206 *
207 * @param Exception|Throwable $e
208 * @return string Html to output
209 */
210 public static function getHTML( $e ) {
211 if ( self::showBackTrace( $e ) ) {
212 $html = "<div class=\"errorbox\"><p>" .
213 nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
214 '</p><p>Backtrace:</p><p>' .
215 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
216 "</p></div>\n";
217 } else {
218 $logId = WebRequest::getRequestId();
219 $html = "<div class=\"errorbox\">" .
220 '[' . $logId . '] ' .
221 gmdate( 'Y-m-d H:i:s' ) . ": " .
222 self::msg( "internalerror-fatal-exception",
223 "Fatal exception of type $1",
224 get_class( $e ),
225 $logId,
226 MWExceptionHandler::getURL()
227 ) . "</div>\n" .
228 "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
229 }
230
231 return $html;
232 }
233
234 /**
235 * Get a message from i18n
236 *
237 * @param string $key Message name
238 * @param string $fallback Default message if the message cache can't be
239 * called by the exception
240 * The function also has other parameters that are arguments for the message
241 * @return string Message with arguments replaced
242 */
243 private static function msg( $key, $fallback /*[, params...] */ ) {
244 $args = array_slice( func_get_args(), 2 );
245 try {
246 return wfMessage( $key, $args )->text();
247 } catch ( Exception $e ) {
248 return wfMsgReplaceArgs( $fallback, $args );
249 }
250 }
251
252 /**
253 * @param Exception|Throwable $e
254 * @return string
255 */
256 private static function getText( $e ) {
257 if ( self::showBackTrace( $e ) ) {
258 return MWExceptionHandler::getLogMessage( $e ) .
259 "\nBacktrace:\n" .
260 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
261 } else {
262 return self::getShowBacktraceError( $e );
263 }
264 }
265
266 /**
267 * @param Exception|Throwable $e
268 * @return bool
269 */
270 private static function showBackTrace( $e ) {
271 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
272
273 return (
274 $wgShowExceptionDetails &&
275 ( !( $e instanceof DBError ) || $wgShowDBErrorBacktrace )
276 );
277 }
278
279 /**
280 * @param Exception|Throwable $e
281 * @return string
282 */
283 private static function getShowBacktraceError( $e ) {
284 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
285 $vars = [];
286 if ( !$wgShowExceptionDetails ) {
287 $vars[] = '$wgShowExceptionDetails = true;';
288 }
289 if ( $e instanceof DBError && !$wgShowDBErrorBacktrace ) {
290 $vars[] = '$wgShowDBErrorBacktrace = true;';
291 }
292 $vars = implode( ' and ', $vars );
293 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information";
294 }
295
296 /**
297 * @return bool
298 */
299 private static function isCommandLine() {
300 return !empty( $GLOBALS['wgCommandLineMode'] );
301 }
302
303 /**
304 * @param string $header
305 */
306 private static function header( $header ) {
307 if ( !headers_sent() ) {
308 header( $header );
309 }
310 }
311
312 /**
313 * @param integer $code
314 */
315 private static function statusHeader( $code ) {
316 if ( !headers_sent() ) {
317 HttpStatus::header( $code );
318 }
319 }
320
321 /**
322 * Print a message, if possible to STDERR.
323 * Use this in command line mode only (see isCommandLine)
324 *
325 * @param string $message Failure text
326 */
327 private static function printError( $message ) {
328 // NOTE: STDERR may not be available, especially if php-cgi is used from the
329 // command line (bug #15602). Try to produce meaningful output anyway. Using
330 // echo may corrupt output to STDOUT though.
331 if ( defined( 'STDERR' ) ) {
332 fwrite( STDERR, $message );
333 } else {
334 echo $message;
335 }
336 }
337
338 /**
339 * @param Exception|Throwable $e
340 */
341 private static function reportOutageHTML( $e ) {
342 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
343
344 $sorry = htmlspecialchars( self::msg(
345 'dberr-problems',
346 'Sorry! This site is experiencing technical difficulties.'
347 ) );
348 $again = htmlspecialchars( self::msg(
349 'dberr-again',
350 'Try waiting a few minutes and reloading.'
351 ) );
352
353 if ( $wgShowHostnames || $wgShowSQLErrors ) {
354 $info = str_replace(
355 '$1',
356 Html::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
357 htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
358 );
359 } else {
360 $info = htmlspecialchars( self::msg(
361 'dberr-info-hidden',
362 '(Cannot access the database)'
363 ) );
364 }
365
366 MessageCache::singleton()->disable(); // no DB access
367
368 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
369
370 if ( $wgShowDBErrorBacktrace ) {
371 $html .= '<p>Backtrace:</p><pre>' .
372 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
373 }
374
375 $html .= '<hr />';
376 $html .= self::googleSearchForm();
377
378 echo $html;
379 }
380
381 /**
382 * @return string
383 */
384 private static function googleSearchForm() {
385 global $wgSitename, $wgCanonicalServer, $wgRequest;
386
387 $usegoogle = htmlspecialchars( self::msg(
388 'dberr-usegoogle',
389 'You can try searching via Google in the meantime.'
390 ) );
391 $outofdate = htmlspecialchars( self::msg(
392 'dberr-outofdate',
393 'Note that their indexes of our content may be out of date.'
394 ) );
395 $googlesearch = htmlspecialchars( self::msg( 'searchbutton', 'Search' ) );
396 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
397 $server = htmlspecialchars( $wgCanonicalServer );
398 $sitename = htmlspecialchars( $wgSitename );
399 $trygoogle = <<<EOT
400 <div style="margin: 1.5em">$usegoogle<br />
401 <small>$outofdate</small>
402 </div>
403 <form method="get" action="//www.google.com/search" id="googlesearch">
404 <input type="hidden" name="domains" value="$server" />
405 <input type="hidden" name="num" value="50" />
406 <input type="hidden" name="ie" value="UTF-8" />
407 <input type="hidden" name="oe" value="UTF-8" />
408 <input type="text" name="q" size="31" maxlength="255" value="$search" />
409 <input type="submit" name="btnG" value="$googlesearch" />
410 <p>
411 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
412 <label><input type="radio" name="sitesearch" value="" />WWW</label>
413 </p>
414 </form>
415 EOT;
416 return $trygoogle;
417 }
418 }