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