Merge "Add columns option to Special:PrefixIndex"
[lhc/web/wiklou.git] / includes / db / DatabaseError.php
1 <?php
2 /**
3 * This file contains database error classes.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * Database error base class
26 * @ingroup Database
27 */
28 class DBError extends MWException {
29 /** @var DatabaseBase */
30 public $db;
31
32 /**
33 * Construct a database error
34 * @param DatabaseBase $db Object which threw the error
35 * @param string $error A simple error message to be used for debugging
36 */
37 function __construct( DatabaseBase $db = null, $error ) {
38 $this->db = $db;
39 parent::__construct( $error );
40 }
41 }
42
43 /**
44 * Base class for the more common types of database errors. These are known to occur
45 * frequently, so we try to give friendly error messages for them.
46 *
47 * @ingroup Database
48 * @since 1.23
49 */
50 class DBExpectedError extends DBError {
51 /**
52 * @return string
53 */
54 function getText() {
55 global $wgShowDBErrorBacktrace;
56
57 $s = $this->getTextContent() . "\n";
58
59 if ( $wgShowDBErrorBacktrace ) {
60 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
61 }
62
63 return $s;
64 }
65
66 /**
67 * @return string
68 */
69 function getHTML() {
70 global $wgShowDBErrorBacktrace;
71
72 $s = $this->getHTMLContent();
73
74 if ( $wgShowDBErrorBacktrace ) {
75 $s .= '<p>Backtrace:</p><pre>' . htmlspecialchars( $this->getTraceAsString() ) . '</pre>';
76 }
77
78 return $s;
79 }
80
81 /**
82 * @return string
83 */
84 protected function getTextContent() {
85 return $this->getMessage();
86 }
87
88 /**
89 * @return string
90 */
91 protected function getHTMLContent() {
92 return '<p>' . nl2br( htmlspecialchars( $this->getTextContent() ) ) . '</p>';
93 }
94 }
95
96 /**
97 * @ingroup Database
98 */
99 class DBConnectionError extends DBExpectedError {
100 /** @var string Error text */
101 public $error;
102
103 /**
104 * @param DatabaseBase $db Object throwing the error
105 * @param string $error Error text
106 */
107 function __construct( DatabaseBase $db = null, $error = 'unknown error' ) {
108 $msg = 'DB connection error';
109
110 if ( trim( $error ) != '' ) {
111 $msg .= ": $error";
112 } elseif ( $db ) {
113 $error = $this->db->getServer();
114 }
115
116 parent::__construct( $db, $msg );
117 $this->error = $error;
118 }
119
120 /**
121 * @return bool
122 */
123 function useOutputPage() {
124 // Not likely to work
125 return false;
126 }
127
128 /**
129 * @param string $key
130 * @param string $fallback Unescaped alternative error text in case the
131 * message cache cannot be used. Can contain parameters as in regular
132 * messages, that should be passed as additional parameters.
133 * @return string Unprocessed plain error text with parameters replaced
134 */
135 function msg( $key, $fallback /*[, params...] */ ) {
136 global $wgLang;
137
138 $args = array_slice( func_get_args(), 2 );
139
140 if ( $this->useMessageCache() ) {
141 $message = $wgLang->getMessage( $key );
142 } else {
143 $message = $fallback;
144 }
145
146 return wfMsgReplaceArgs( $message, $args );
147 }
148
149 /**
150 * @return boolean
151 */
152 function isLoggable() {
153 // Don't send to the exception log, already in dberror log
154 return false;
155 }
156
157 /**
158 * @return string Safe HTML
159 */
160 function getHTML() {
161 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
162
163 $sorry = htmlspecialchars( $this->msg(
164 'dberr-problems',
165 'Sorry! This site is experiencing technical difficulties.'
166 ) );
167 $again = htmlspecialchars( $this->msg(
168 'dberr-again',
169 'Try waiting a few minutes and reloading.'
170 ) );
171
172 if ( $wgShowHostnames || $wgShowSQLErrors ) {
173 $info = str_replace(
174 '$1', Html::element( 'span', array( 'dir' => 'ltr' ), $this->error ),
175 htmlspecialchars( $this->msg( 'dberr-info', '(Cannot contact the database server: $1)' ) )
176 );
177 } else {
178 $info = htmlspecialchars( $this->msg(
179 'dberr-info-hidden',
180 '(Cannot contact the database server)'
181 ) );
182 }
183
184 # No database access
185 MessageCache::singleton()->disable();
186
187 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
188
189 if ( $wgShowDBErrorBacktrace ) {
190 $html .= '<p>Backtrace:</p><pre>' . htmlspecialchars( $this->getTraceAsString() ) . '</pre>';
191 }
192
193 $html .= '<hr />';
194 $html .= $this->searchForm();
195
196 return $html;
197 }
198
199 protected function getTextContent() {
200 global $wgShowHostnames, $wgShowSQLErrors;
201
202 if ( $wgShowHostnames || $wgShowSQLErrors ) {
203 return $this->getMessage();
204 } else {
205 return 'DB connection error';
206 }
207 }
208
209 /**
210 * Output the exception report using HTML.
211 *
212 * @return void
213 */
214 public function reportHTML() {
215 global $wgUseFileCache;
216
217 // Check whether we can serve a file-cached copy of the page with the error underneath
218 if ( $wgUseFileCache ) {
219 try {
220 $cache = $this->fileCachedPage();
221 // Cached version on file system?
222 if ( $cache !== null ) {
223 // Hack: extend the body for error messages
224 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
225 // Add cache notice...
226 $cache .= '<div style="border:1px solid #ffd0d0;padding:1em;">' .
227 htmlspecialchars( $this->msg( 'dberr-cachederror',
228 'This is a cached copy of the requested page, and may not be up to date.' ) ) .
229 '</div>';
230
231 // Output cached page with notices on bottom and re-close body
232 echo "{$cache}<hr />{$this->getHTML()}</body></html>";
233
234 return;
235 }
236 } catch ( MWException $e ) {
237 // Do nothing, just use the default page
238 }
239 }
240
241 // We can't, cough and die in the usual fashion
242 parent::reportHTML();
243 }
244
245 /**
246 * @return string
247 */
248 function searchForm() {
249 global $wgSitename, $wgCanonicalServer, $wgRequest;
250
251 $usegoogle = htmlspecialchars( $this->msg(
252 'dberr-usegoogle',
253 'You can try searching via Google in the meantime.'
254 ) );
255 $outofdate = htmlspecialchars( $this->msg(
256 'dberr-outofdate',
257 'Note that their indexes of our content may be out of date.'
258 ) );
259 $googlesearch = htmlspecialchars( $this->msg( 'searchbutton', 'Search' ) );
260
261 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
262
263 $server = htmlspecialchars( $wgCanonicalServer );
264 $sitename = htmlspecialchars( $wgSitename );
265
266 $trygoogle = <<<EOT
267 <div style="margin: 1.5em">$usegoogle<br />
268 <small>$outofdate</small>
269 </div>
270 <form method="get" action="//www.google.com/search" id="googlesearch">
271 <input type="hidden" name="domains" value="$server" />
272 <input type="hidden" name="num" value="50" />
273 <input type="hidden" name="ie" value="UTF-8" />
274 <input type="hidden" name="oe" value="UTF-8" />
275
276 <input type="text" name="q" size="31" maxlength="255" value="$search" />
277 <input type="submit" name="btnG" value="$googlesearch" />
278 <p>
279 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
280 <label><input type="radio" name="sitesearch" value="" />WWW</label>
281 </p>
282 </form>
283 EOT;
284
285 return $trygoogle;
286 }
287
288 /**
289 * @return string
290 */
291 private function fileCachedPage() {
292 $context = RequestContext::getMain();
293
294 if ( $context->getOutput()->isDisabled() ) {
295 // Done already?
296 return '';
297 }
298
299 if ( $context->getTitle() ) {
300 // Use the main context's title if we managed to set it
301 $t = $context->getTitle()->getPrefixedDBkey();
302 } else {
303 // Fallback to the raw title URL param. We can't use the Title
304 // class is it may hit the interwiki table and give a DB error.
305 // We may get a cache miss due to not sanitizing the title though.
306 $t = str_replace( ' ', '_', $context->getRequest()->getVal( 'title' ) );
307 if ( $t == '' ) { // fallback to main page
308 $t = Title::newFromText(
309 $this->msg( 'mainpage', 'Main Page' ) )->getPrefixedDBkey();
310 }
311 }
312
313 $cache = HTMLFileCache::newFromTitle( $t, 'view' );
314 if ( $cache->isCached() ) {
315 return $cache->fetchText();
316 } else {
317 return '';
318 }
319 }
320 }
321
322 /**
323 * @ingroup Database
324 */
325 class DBQueryError extends DBExpectedError {
326 public $error, $errno, $sql, $fname;
327
328 /**
329 * @param DatabaseBase $db
330 * @param string $error
331 * @param int|string $errno
332 * @param string $sql
333 * @param string $fname
334 */
335 function __construct( DatabaseBase $db, $error, $errno, $sql, $fname ) {
336 $message = "A database error has occurred. Did you forget to run " .
337 "maintenance/update.php after upgrading? See: " .
338 "https://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
339 "Query: $sql\n" .
340 "Function: $fname\n" .
341 "Error: $errno $error\n";
342 parent::__construct( $db, $message );
343
344 $this->error = $error;
345 $this->errno = $errno;
346 $this->sql = $sql;
347 $this->fname = $fname;
348 }
349
350 /**
351 * @return bool
352 */
353 function isLoggable() {
354 // Don't send to the exception log, already in dberror log
355 return false;
356 }
357
358 /**
359 * @return string
360 */
361 function getPageTitle() {
362 return $this->msg( 'databaseerror', 'Database error' );
363 }
364
365 /**
366 * @return string
367 */
368 protected function getHTMLContent() {
369 $key = 'databaseerror-text';
370 $s = Html::element( 'p', array(), $this->msg( $key, $this->getFallbackMessage( $key ) ) );
371
372 $details = $this->getTechnicalDetails();
373 if ( $details ) {
374 $s .= '<ul>';
375 foreach ( $details as $key => $detail ) {
376 $s .= str_replace(
377 '$1', call_user_func_array( 'Html::element', $detail ),
378 Html::element( 'li', array(),
379 $this->msg( $key, $this->getFallbackMessage( $key ) )
380 )
381 );
382 }
383 $s .= '</ul>';
384 }
385
386 return $s;
387 }
388
389 /**
390 * @return string
391 */
392 protected function getTextContent() {
393 $key = 'databaseerror-textcl';
394 $s = $this->msg( $key, $this->getFallbackMessage( $key ) ) . "\n";
395
396 foreach ( $this->getTechnicalDetails() as $key => $detail ) {
397 $s .= $this->msg( $key, $this->getFallbackMessage( $key ), $detail[2] ) . "\n";
398 }
399
400 return $s;
401 }
402
403 /**
404 * Make a list of technical details that can be shown to the user. This information can
405 * aid in debugging yet may be useful to an attacker trying to exploit a security weakness
406 * in the software or server configuration.
407 *
408 * Thus no such details are shown by default, though if $wgShowHostnames is true, only the
409 * full SQL query is hidden; in fact, the error message often does contain a hostname, and
410 * sites using this option probably don't care much about "security by obscurity". Of course,
411 * if $wgShowSQLErrors is true, the SQL query *is* shown.
412 *
413 * @return array Keys are message keys; values are arrays of arguments for Html::element().
414 * Array will be empty if users are not allowed to see any of these details at all.
415 */
416 protected function getTechnicalDetails() {
417 global $wgShowHostnames, $wgShowSQLErrors;
418
419 $attribs = array( 'dir' => 'ltr' );
420 $details = array();
421
422 if ( $wgShowSQLErrors ) {
423 $details['databaseerror-query'] = array(
424 'div', array( 'class' => 'mw-code' ) + $attribs, $this->sql );
425 }
426
427 if ( $wgShowHostnames || $wgShowSQLErrors ) {
428 $errorMessage = $this->errno . ' ' . $this->error;
429 $details['databaseerror-function'] = array( 'code', $attribs, $this->fname );
430 $details['databaseerror-error'] = array( 'samp', $attribs, $errorMessage );
431 }
432
433 return $details;
434 }
435
436 /**
437 * @param string $key Message key
438 * @return string English message text
439 */
440 private function getFallbackMessage( $key ) {
441 $messages = array(
442 'databaseerror-text' => 'A database query error has occurred.
443 This may indicate a bug in the software.',
444 'databaseerror-textcl' => 'A database query error has occurred.',
445 'databaseerror-query' => 'Query: $1',
446 'databaseerror-function' => 'Function: $1',
447 'databaseerror-error' => 'Error: $1',
448 );
449
450 return $messages[$key];
451 }
452 }
453
454 /**
455 * @ingroup Database
456 */
457 class DBUnexpectedError extends DBError {
458 }