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