Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[lhc/web/wiklou.git] / includes / exception / MWException.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 /**
22 * MediaWiki exception
23 *
24 * @ingroup Exception
25 */
26 class MWException extends Exception {
27 /**
28 * Should the exception use $wgOut to output the error?
29 *
30 * @return bool
31 */
32 public function useOutputPage() {
33 return $this->useMessageCache() &&
34 !empty( $GLOBALS['wgFullyInitialised'] ) &&
35 !empty( $GLOBALS['wgOut'] ) &&
36 !defined( 'MEDIAWIKI_INSTALL' );
37 }
38
39 /**
40 * Whether to log this exception in the exception debug log.
41 *
42 * @since 1.23
43 * @return bool
44 */
45 public function isLoggable() {
46 return true;
47 }
48
49 /**
50 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
51 *
52 * @return bool
53 */
54 public function useMessageCache() {
55 global $wgLang;
56
57 foreach ( $this->getTrace() as $frame ) {
58 if ( isset( $frame['class'] ) && $frame['class'] === LocalisationCache::class ) {
59 return false;
60 }
61 }
62
63 return $wgLang instanceof Language;
64 }
65
66 /**
67 * Get a message from i18n
68 *
69 * @param string $key Message name
70 * @param string $fallback Default message if the message cache can't be
71 * called by the exception
72 * @param mixed ...$params To pass to wfMessage()
73 * @return string Message with arguments replaced
74 */
75 public function msg( $key, $fallback, ...$params ) {
76 global $wgSitename;
77
78 // FIXME: Keep logic in sync with MWExceptionRenderer::msg.
79 $res = false;
80 if ( $this->useMessageCache() ) {
81 try {
82 $res = wfMessage( $key, $params )->text();
83 } catch ( Exception $e ) {
84 }
85 }
86 if ( $res === false ) {
87 $res = wfMsgReplaceArgs( $fallback, $params );
88 // If an exception happens inside message rendering,
89 // {{SITENAME}} sometimes won't be replaced.
90 $res = strtr( $res, [
91 '{{SITENAME}}' => $wgSitename,
92 ] );
93 }
94 return $res;
95 }
96
97 /**
98 * If $wgShowExceptionDetails is true, return a HTML message with a
99 * backtrace to the error, otherwise show a message to ask to set it to true
100 * to show that information.
101 *
102 * @return string Html to output
103 */
104 public function getHTML() {
105 global $wgShowExceptionDetails;
106
107 if ( $wgShowExceptionDetails ) {
108 return '<p>' . nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $this ) ) ) .
109 '</p><p>Backtrace:</p><p>' .
110 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $this ) ) ) .
111 "</p>\n";
112 } else {
113 $logId = WebRequest::getRequestId();
114 $type = static::class;
115 return Html::errorBox(
116 htmlspecialchars(
117 '[' . $logId . '] ' .
118 gmdate( 'Y-m-d H:i:s' ) . ": " .
119 $this->msg( "internalerror-fatal-exception",
120 "Fatal exception of type $1",
121 $type,
122 $logId,
123 MWExceptionHandler::getURL()
124 )
125 ) ) .
126 "<!-- Set \$wgShowExceptionDetails = true; " .
127 "at the bottom of LocalSettings.php to show detailed " .
128 "debugging information. -->";
129 }
130 }
131
132 /**
133 * Get the text to display when reporting the error on the command line.
134 * If $wgShowExceptionDetails is true, return a text message with a
135 * backtrace to the error.
136 *
137 * @return string
138 */
139 public function getText() {
140 global $wgShowExceptionDetails;
141
142 if ( $wgShowExceptionDetails ) {
143 return MWExceptionHandler::getLogMessage( $this ) .
144 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $this ) . "\n";
145 } else {
146 return "Set \$wgShowExceptionDetails = true; " .
147 "in LocalSettings.php to show detailed debugging information.\n";
148 }
149 }
150
151 /**
152 * Return the title of the page when reporting this error in a HTTP response.
153 *
154 * @return string
155 */
156 public function getPageTitle() {
157 return $this->msg( 'internalerror', 'Internal error' );
158 }
159
160 /**
161 * Output the exception report using HTML.
162 */
163 public function reportHTML() {
164 global $wgOut, $wgSitename;
165 if ( $this->useOutputPage() ) {
166 $wgOut->prepareErrorPage( $this->getPageTitle() );
167 // Manually set the html title, since sometimes
168 // {{SITENAME}} does not get replaced for exceptions
169 // happening inside message rendering.
170 $wgOut->setHTMLTitle(
171 $this->msg(
172 'pagetitle',
173 "$1 - $wgSitename",
174 $this->getPageTitle()
175 )
176 );
177
178 $wgOut->addHTML( $this->getHTML() );
179
180 $wgOut->output();
181 } else {
182 self::header( 'Content-Type: text/html; charset=utf-8' );
183 echo "<!DOCTYPE html>\n" .
184 '<html><head>' .
185 // Mimick OutputPage::setPageTitle behaviour
186 '<title>' .
187 htmlspecialchars( $this->msg( 'pagetitle', "$1 - $wgSitename", $this->getPageTitle() ) ) .
188 '</title>' .
189 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
190 "</head><body>\n";
191
192 echo $this->getHTML();
193
194 echo "</body></html>\n";
195 }
196 }
197
198 /**
199 * Output a report about the exception and takes care of formatting.
200 * It will be either HTML or plain text based on isCommandLine().
201 */
202 public function report() {
203 global $wgMimeType;
204
205 if ( defined( 'MW_API' ) ) {
206 // Unhandled API exception, we can't be sure that format printer is alive
207 self::header( 'MediaWiki-API-Error: internal_api_error_' . static::class );
208 wfHttpError( 500, 'Internal Server Error', $this->getText() );
209 } elseif ( self::isCommandLine() ) {
210 $message = $this->getText();
211 $this->writeToCommandLine( $message );
212 } else {
213 self::statusHeader( 500 );
214 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
215
216 $this->reportHTML();
217 }
218 }
219
220 /**
221 * Write a message to stderr falling back to stdout if stderr unavailable
222 *
223 * @param string $message
224 * @suppress SecurityCheck-XSS
225 */
226 private function writeToCommandLine( $message ) {
227 // T17602: STDERR may not be available
228 if ( !defined( 'MW_PHPUNIT_TEST' ) && defined( 'STDERR' ) ) {
229 fwrite( STDERR, $message );
230 } else {
231 echo $message;
232 }
233 }
234
235 /**
236 * Check whether we are in command line mode or not to report the exception
237 * in the correct format.
238 *
239 * @return bool
240 */
241 public static function isCommandLine() {
242 return !empty( $GLOBALS['wgCommandLineMode'] );
243 }
244
245 /**
246 * Send a header, if we haven't already sent them. We shouldn't,
247 * but sometimes we might in a weird case like Export
248 * @param string $header
249 */
250 private static function header( $header ) {
251 if ( !headers_sent() ) {
252 header( $header );
253 }
254 }
255
256 private static function statusHeader( $code ) {
257 if ( !headers_sent() ) {
258 HttpStatus::header( $code );
259 }
260 }
261 }