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