Merge "Gracefully handle redirects in SpecialMyLanguage"
[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' ) {
59 return false;
60 }
61 }
62
63 return $wgLang instanceof Language;
64 }
65
66 /**
67 * Run hook to allow extensions to modify the text of the exception
68 *
69 * @param string $name Class name of the exception
70 * @param array $args Arguments to pass to the callback functions
71 * @return string|null String to output or null if any hook has been called
72 */
73 public function runHooks( $name, $args = array() ) {
74 global $wgExceptionHooks;
75
76 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
77 return null; // Just silently ignore
78 }
79
80 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
81 !is_array( $wgExceptionHooks[$name] )
82 ) {
83 return null;
84 }
85
86 $hooks = $wgExceptionHooks[$name];
87 $callargs = array_merge( array( $this ), $args );
88
89 foreach ( $hooks as $hook ) {
90 if (
91 is_string( $hook ) ||
92 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
93 ) {
94 // 'function' or array( 'class', hook' )
95 $result = call_user_func_array( $hook, $callargs );
96 } else {
97 $result = null;
98 }
99
100 if ( is_string( $result ) ) {
101 return $result;
102 }
103 }
104 return null;
105 }
106
107 /**
108 * Get a message from i18n
109 *
110 * @param string $key Message name
111 * @param string $fallback Default message if the message cache can't be
112 * called by the exception
113 * The function also has other parameters that are arguments for the message
114 * @return string Message with arguments replaced
115 */
116 public function msg( $key, $fallback /*[, params...] */ ) {
117 $args = array_slice( func_get_args(), 2 );
118
119 if ( $this->useMessageCache() ) {
120 try {
121 return wfMessage( $key, $args )->text();
122 } catch ( Exception $e ) {}
123 }
124 return wfMsgReplaceArgs( $fallback, $args );
125 }
126
127 /**
128 * If $wgShowExceptionDetails is true, return a HTML message with a
129 * backtrace to the error, otherwise show a message to ask to set it to true
130 * to show that information.
131 *
132 * @return string Html to output
133 */
134 public function getHTML() {
135 global $wgShowExceptionDetails;
136
137 if ( $wgShowExceptionDetails ) {
138 return '<p>' . nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $this ) ) ) .
139 '</p><p>Backtrace:</p><p>' .
140 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $this ) ) ) .
141 "</p>\n";
142 } else {
143 $logId = MWExceptionHandler::getLogId( $this );
144 $type = get_class( $this );
145 return "<div class=\"errorbox\">" .
146 '[' . $logId . '] ' .
147 gmdate( 'Y-m-d H:i:s' ) . ": " .
148 $this->msg( "internalerror-fatal-exception",
149 "Fatal exception of type $1",
150 $type,
151 $logId,
152 MWExceptionHandler::getURL( $this )
153 ) . "</div>\n" .
154 "<!-- Set \$wgShowExceptionDetails = true; " .
155 "at the bottom of LocalSettings.php to show detailed " .
156 "debugging information. -->";
157 }
158 }
159
160 /**
161 * Get the text to display when reporting the error on the command line.
162 * If $wgShowExceptionDetails is true, return a text message with a
163 * backtrace to the error.
164 *
165 * @return string
166 */
167 public function getText() {
168 global $wgShowExceptionDetails;
169
170 if ( $wgShowExceptionDetails ) {
171 return MWExceptionHandler::getLogMessage( $this ) .
172 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $this ) . "\n";
173 } else {
174 return "Set \$wgShowExceptionDetails = true; " .
175 "in LocalSettings.php to show detailed debugging information.\n";
176 }
177 }
178
179 /**
180 * Return the title of the page when reporting this error in a HTTP response.
181 *
182 * @return string
183 */
184 public function getPageTitle() {
185 return $this->msg( 'internalerror', 'Internal error' );
186 }
187
188 /**
189 * Output the exception report using HTML.
190 */
191 public function reportHTML() {
192 global $wgOut, $wgSitename;
193 if ( $this->useOutputPage() ) {
194 $wgOut->prepareErrorPage( $this->getPageTitle() );
195
196 $hookResult = $this->runHooks( get_class( $this ) );
197 if ( $hookResult ) {
198 $wgOut->addHTML( $hookResult );
199 } else {
200 $wgOut->addHTML( $this->getHTML() );
201 }
202
203 $wgOut->output();
204 } else {
205 self::header( 'Content-Type: text/html; charset=utf-8' );
206 echo "<!DOCTYPE html>\n" .
207 '<html><head>' .
208 // Mimick OutputPage::setPageTitle behaviour
209 '<title>' .
210 htmlspecialchars( $this->msg( 'pagetitle', "$1 - $wgSitename", $this->getPageTitle() ) ) .
211 '</title>' .
212 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
213 "</head><body>\n";
214
215 $hookResult = $this->runHooks( get_class( $this ) . 'Raw' );
216 if ( $hookResult ) {
217 echo $hookResult;
218 } else {
219 echo $this->getHTML();
220 }
221
222 echo "</body></html>\n";
223 }
224 }
225
226 /**
227 * Output a report about the exception and takes care of formatting.
228 * It will be either HTML or plain text based on isCommandLine().
229 */
230 public function report() {
231 global $wgMimeType;
232
233 if ( defined( 'MW_API' ) ) {
234 // Unhandled API exception, we can't be sure that format printer is alive
235 self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
236 wfHttpError( 500, 'Internal Server Error', $this->getText() );
237 } elseif ( self::isCommandLine() ) {
238 MWExceptionHandler::printError( $this->getText() );
239 } else {
240 self::header( 'HTTP/1.1 500 MediaWiki exception' );
241 self::header( 'Status: 500 MediaWiki exception' );
242 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
243
244 $this->reportHTML();
245 }
246 }
247
248 /**
249 * Check whether we are in command line mode or not to report the exception
250 * in the correct format.
251 *
252 * @return bool
253 */
254 public static function isCommandLine() {
255 return !empty( $GLOBALS['wgCommandLineMode'] );
256 }
257
258 /**
259 * Send a header, if we haven't already sent them. We shouldn't,
260 * but sometimes we might in a weird case like Export
261 * @param string $header
262 */
263 private static function header( $header ) {
264 if ( !headers_sent() ) {
265 header( $header );
266 }
267 }
268 }