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