Merge "Simplify HTMLTitleTextField::validate"
[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 * The function also has other parameters that are arguments for the message
73 * @return string Message with arguments replaced
74 */
75 public function msg( $key, $fallback /*[, params...] */ ) {
76 global $wgSitename;
77 $args = array_slice( func_get_args(), 2 );
78
79 $res = false;
80 if ( $this->useMessageCache() ) {
81 try {
82 $res = wfMessage( $key, $args )->text();
83 } catch ( Exception $e ) {
84 }
85 }
86 if ( $res === false ) {
87 $res = wfMsgReplaceArgs( $fallback, $args );
88 // If an exception happens inside message rendering,
89 // {{SITENAME}} sometimes won't be replaced.
90 $res = preg_replace( '/\{\{SITENAME\}\}/', $wgSitename, $res );
91 }
92 return $res;
93 }
94
95 /**
96 * If $wgShowExceptionDetails is true, return a HTML message with a
97 * backtrace to the error, otherwise show a message to ask to set it to true
98 * to show that information.
99 *
100 * @return string Html to output
101 */
102 public function getHTML() {
103 global $wgShowExceptionDetails;
104
105 if ( $wgShowExceptionDetails ) {
106 return '<p>' . nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $this ) ) ) .
107 '</p><p>Backtrace:</p><p>' .
108 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $this ) ) ) .
109 "</p>\n";
110 } else {
111 $logId = WebRequest::getRequestId();
112 $type = static::class;
113 return Html::errorBox(
114 htmlspecialchars(
115 '[' . $logId . '] ' .
116 gmdate( 'Y-m-d H:i:s' ) . ": " .
117 $this->msg( "internalerror-fatal-exception",
118 "Fatal exception of type $1",
119 $type,
120 $logId,
121 MWExceptionHandler::getURL( $this )
122 )
123 ) ) .
124 "<!-- Set \$wgShowExceptionDetails = true; " .
125 "at the bottom of LocalSettings.php to show detailed " .
126 "debugging information. -->";
127 }
128 }
129
130 /**
131 * Get the text to display when reporting the error on the command line.
132 * If $wgShowExceptionDetails is true, return a text message with a
133 * backtrace to the error.
134 *
135 * @return string
136 */
137 public function getText() {
138 global $wgShowExceptionDetails;
139
140 if ( $wgShowExceptionDetails ) {
141 return MWExceptionHandler::getLogMessage( $this ) .
142 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $this ) . "\n";
143 } else {
144 return "Set \$wgShowExceptionDetails = true; " .
145 "in LocalSettings.php to show detailed debugging information.\n";
146 }
147 }
148
149 /**
150 * Return the title of the page when reporting this error in a HTTP response.
151 *
152 * @return string
153 */
154 public function getPageTitle() {
155 return $this->msg( 'internalerror', 'Internal error' );
156 }
157
158 /**
159 * Output the exception report using HTML.
160 */
161 public function reportHTML() {
162 global $wgOut, $wgSitename;
163 if ( $this->useOutputPage() ) {
164 $wgOut->prepareErrorPage( $this->getPageTitle() );
165 // Manually set the html title, since sometimes
166 // {{SITENAME}} does not get replaced for exceptions
167 // happening inside message rendering.
168 $wgOut->setHTMLTitle(
169 $this->msg(
170 'pagetitle',
171 "$1 - $wgSitename",
172 $this->getPageTitle()
173 )
174 );
175
176 $wgOut->addHTML( $this->getHTML() );
177
178 $wgOut->output();
179 } else {
180 self::header( 'Content-Type: text/html; charset=utf-8' );
181 echo "<!DOCTYPE html>\n" .
182 '<html><head>' .
183 // Mimick OutputPage::setPageTitle behaviour
184 '<title>' .
185 htmlspecialchars( $this->msg( 'pagetitle', "$1 - $wgSitename", $this->getPageTitle() ) ) .
186 '</title>' .
187 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
188 "</head><body>\n";
189
190 echo $this->getHTML();
191
192 echo "</body></html>\n";
193 }
194 }
195
196 /**
197 * Output a report about the exception and takes care of formatting.
198 * It will be either HTML or plain text based on isCommandLine().
199 */
200 public function report() {
201 global $wgMimeType;
202
203 if ( defined( 'MW_API' ) ) {
204 // Unhandled API exception, we can't be sure that format printer is alive
205 self::header( 'MediaWiki-API-Error: internal_api_error_' . static::class );
206 wfHttpError( 500, 'Internal Server Error', $this->getText() );
207 } elseif ( self::isCommandLine() ) {
208 $message = $this->getText();
209 // T17602: STDERR may not be available
210 if ( !defined( 'MW_PHPUNIT_TEST' ) && defined( 'STDERR' ) ) {
211 fwrite( STDERR, $message );
212 } else {
213 echo $message;
214 }
215 } else {
216 self::statusHeader( 500 );
217 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
218
219 $this->reportHTML();
220 }
221 }
222
223 /**
224 * Check whether we are in command line mode or not to report the exception
225 * in the correct format.
226 *
227 * @return bool
228 */
229 public static function isCommandLine() {
230 return !empty( $GLOBALS['wgCommandLineMode'] );
231 }
232
233 /**
234 * Send a header, if we haven't already sent them. We shouldn't,
235 * but sometimes we might in a weird case like Export
236 * @param string $header
237 */
238 private static function header( $header ) {
239 if ( !headers_sent() ) {
240 header( $header );
241 }
242 }
243 private static function statusHeader( $code ) {
244 if ( !headers_sent() ) {
245 HttpStatus::header( $code );
246 }
247 }
248 }