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