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