ported site_stats change from 1.4
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
25
26 /**
27 * Database abstraction object
28 * @package MediaWiki
29 */
30 class Database {
31
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
37 */
38 var $mLastQuery = '';
39
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
42
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 var $mErrorCount = 0;
48 /**#@-*/
49
50 #------------------------------------------------------------------------------
51 # Accessors
52 #------------------------------------------------------------------------------
53 # These optionally set a variable and return the previous state
54
55 /**
56 * Fail function, takes a Database as a parameter
57 * Set to false for default, 1 for ignore errors
58 */
59 function failFunction( $function = NULL ) {
60 return wfSetVar( $this->mFailFunction, $function );
61 }
62
63 /**
64 * Output page, used for reporting errors
65 * FALSE means discard output
66 */
67 function &setOutputPage( &$out ) {
68 $this->mOut =& $out;
69 }
70
71 /**
72 * Boolean, controls output of large amounts of debug information
73 */
74 function debug( $debug = NULL ) {
75 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
76 }
77
78 /**
79 * Turns buffering of SQL result sets on (true) or off (false).
80 * Default is "on" and it should not be changed without good reasons.
81 */
82 function bufferResults( $buffer = NULL ) {
83 if ( is_null( $buffer ) ) {
84 return !(bool)( $this->mFlags & DBO_NOBUFFER );
85 } else {
86 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
87 }
88 }
89
90 /**
91 * Turns on (false) or off (true) the automatic generation and sending
92 * of a "we're sorry, but there has been a database error" page on
93 * database errors. Default is on (false). When turned off, the
94 * code should use wfLastErrno() and wfLastError() to handle the
95 * situation as appropriate.
96 */
97 function ignoreErrors( $ignoreErrors = NULL ) {
98 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
99 }
100
101 /**
102 * The current depth of nested transactions
103 * @param integer $level
104 */
105 function trxLevel( $level = NULL ) {
106 return wfSetVar( $this->mTrxLevel, $level );
107 }
108
109 /**
110 * Number of errors logged, only useful when errors are ignored
111 */
112 function errorCount( $count = NULL ) {
113 return wfSetVar( $this->mErrorCount, $count );
114 }
115
116 /**#@+
117 * Get function
118 */
119 function lastQuery() { return $this->mLastQuery; }
120 function isOpen() { return $this->mOpened; }
121 /**#@-*/
122
123 #------------------------------------------------------------------------------
124 # Other functions
125 #------------------------------------------------------------------------------
126
127 /**#@+
128 * @param string $server database server host
129 * @param string $user database user name
130 * @param string $password database user password
131 * @param string $dbname database name
132 */
133
134 /**
135 * @param failFunction
136 * @param $flags
137 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
138 */
139 function Database( $server = false, $user = false, $password = false, $dbName = false,
140 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
141
142 global $wgOut, $wgDBprefix, $wgCommandLineMode;
143 # Can't get a reference if it hasn't been set yet
144 if ( !isset( $wgOut ) ) {
145 $wgOut = NULL;
146 }
147 $this->mOut =& $wgOut;
148
149 $this->mFailFunction = $failFunction;
150 $this->mFlags = $flags;
151
152 if ( $this->mFlags & DBO_DEFAULT ) {
153 if ( $wgCommandLineMode ) {
154 $this->mFlags &= ~DBO_TRX;
155 } else {
156 $this->mFlags |= DBO_TRX;
157 }
158 }
159
160 /*
161 // Faster read-only access
162 if ( wfReadOnly() ) {
163 $this->mFlags |= DBO_PERSISTENT;
164 $this->mFlags &= ~DBO_TRX;
165 }*/
166
167 /** Get the default table prefix*/
168 if ( $tablePrefix == 'get from global' ) {
169 $this->mTablePrefix = $wgDBprefix;
170 } else {
171 $this->mTablePrefix = $tablePrefix;
172 }
173
174 if ( $server ) {
175 $this->open( $server, $user, $password, $dbName );
176 }
177 }
178
179 /**
180 * @static
181 * @param failFunction
182 * @param $flags
183 */
184 function newFromParams( $server, $user, $password, $dbName,
185 $failFunction = false, $flags = 0 )
186 {
187 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
188 }
189
190 /**
191 * Usually aborts on failure
192 * If the failFunction is set to a non-zero integer, returns success
193 */
194 function open( $server, $user, $password, $dbName ) {
195 # Test for missing mysql.so
196 # First try to load it
197 if (!@extension_loaded('mysql')) {
198 @dl('mysql.so');
199 }
200
201 # Otherwise we get a suppressed fatal error, which is very hard to track down
202 if ( !function_exists( 'mysql_connect' ) ) {
203 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
204 }
205
206 $this->close();
207 $this->mServer = $server;
208 $this->mUser = $user;
209 $this->mPassword = $password;
210 $this->mDBname = $dbName;
211
212 $success = false;
213
214 if ( $this->mFlags & DBO_PERSISTENT ) {
215 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
216 } else {
217 # Create a new connection...
218 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
219 }
220
221 if ( $dbName != '' ) {
222 if ( $this->mConn !== false ) {
223 $success = @/**/mysql_select_db( $dbName, $this->mConn );
224 if ( !$success ) {
225 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
226 }
227 } else {
228 wfDebug( "DB connection error\n" );
229 wfDebug( "Server: $server, User: $user, Password: " .
230 substr( $password, 0, 3 ) . "...\n" );
231 $success = false;
232 }
233 } else {
234 # Delay USE query
235 $success = !!$this->mConn;
236 }
237
238 if ( !$success ) {
239 $this->reportConnectionError();
240 $this->close();
241 }
242 $this->mOpened = $success;
243 return $success;
244 }
245 /**#@-*/
246
247 /**
248 * Closes a database connection.
249 * if it is open : commits any open transactions
250 *
251 * @return bool operation success. true if already closed.
252 */
253 function close()
254 {
255 $this->mOpened = false;
256 if ( $this->mConn ) {
257 if ( $this->trxLevel() ) {
258 $this->immediateCommit();
259 }
260 return mysql_close( $this->mConn );
261 } else {
262 return true;
263 }
264 }
265
266 /**
267 * @access private
268 * @param string $msg error message ?
269 * @todo parameter $msg is not used
270 */
271 function reportConnectionError( $msg = '') {
272 if ( $this->mFailFunction ) {
273 if ( !is_int( $this->mFailFunction ) ) {
274 $ff = $this->mFailFunction;
275 $ff( $this, mysql_error() );
276 }
277 } else {
278 wfEmergencyAbort( $this, mysql_error() );
279 }
280 }
281
282 /**
283 * Usually aborts on failure
284 * If errors are explicitly ignored, returns success
285 */
286 function query( $sql, $fname = '', $tempIgnore = false ) {
287 global $wgProfiling, $wgCommandLineMode;
288
289 if ( $wgProfiling ) {
290 # generalizeSQL will probably cut down the query to reasonable
291 # logging size most of the time. The substr is really just a sanity check.
292 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
293 wfProfileIn( 'Database::query' );
294 wfProfileIn( $profName );
295 }
296
297 $this->mLastQuery = $sql;
298
299 # Add a comment for easy SHOW PROCESSLIST interpretation
300 if ( $fname ) {
301 $commentedSql = "/* $fname */ $sql";
302 } else {
303 $commentedSql = $sql;
304 }
305
306 # If DBO_TRX is set, start a transaction
307 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
308 $this->begin();
309 }
310
311 if ( $this->debug() ) {
312 $sqlx = substr( $commentedSql, 0, 500 );
313 $sqlx = strtr( $sqlx, "\t\n", ' ' );
314 wfDebug( "SQL: $sqlx\n" );
315 }
316
317 # Do the query and handle errors
318 $ret = $this->doQuery( $commentedSql );
319
320 # Try reconnecting if the connection was lost
321 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
322 # Transaction is gone, like it or not
323 $this->mTrxLevel = 0;
324 wfDebug( "Connection lost, reconnecting...\n" );
325 if ( $this->ping() ) {
326 wfDebug( "Reconnected\n" );
327 $ret = $this->doQuery( $commentedSql );
328 } else {
329 wfDebug( "Failed\n" );
330 }
331 }
332
333 if ( false === $ret ) {
334 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
335 }
336
337 if ( $wgProfiling ) {
338 wfProfileOut( $profName );
339 wfProfileOut( 'Database::query' );
340 }
341 return $ret;
342 }
343
344 /**
345 * The DBMS-dependent part of query()
346 * @param string $sql SQL query.
347 */
348 function doQuery( $sql ) {
349 if( $this->bufferResults() ) {
350 $ret = mysql_query( $sql, $this->mConn );
351 } else {
352 $ret = mysql_unbuffered_query( $sql, $this->mConn );
353 }
354 return $ret;
355 }
356
357 /**
358 * @param $error
359 * @param $errno
360 * @param $sql
361 * @param string $fname
362 * @param bool $tempIgnore
363 */
364 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
365 global $wgCommandLineMode, $wgFullyInitialised;
366 # Ignore errors during error handling to avoid infinite recursion
367 $ignore = $this->ignoreErrors( true );
368 $this->mErrorCount ++;
369
370 if( $ignore || $tempIgnore ) {
371 wfDebug("SQL ERROR (ignored): " . $error . "\n");
372 } else {
373 $sql1line = str_replace( "\n", "\\n", $sql );
374 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
375 wfDebug("SQL ERROR: " . $error . "\n");
376 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
377 $message = "A database error has occurred\n" .
378 "Query: $sql\n" .
379 "Function: $fname\n" .
380 "Error: $errno $error\n";
381 if ( !$wgCommandLineMode ) {
382 $message = nl2br( $message );
383 }
384 wfDebugDieBacktrace( $message );
385 } else {
386 // this calls wfAbruptExit()
387 $this->mOut->databaseError( $fname, $sql, $error, $errno );
388 }
389 }
390 $this->ignoreErrors( $ignore );
391 }
392
393
394 /**
395 * Intended to be compatible with the PEAR::DB wrapper functions.
396 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
397 *
398 * ? = scalar value, quoted as necessary
399 * ! = raw SQL bit (a function for instance)
400 * & = filename; reads the file and inserts as a blob
401 * (we don't use this though...)
402 */
403 function prepare( $sql, $func = 'Database::prepare' ) {
404 /* MySQL doesn't support prepared statements (yet), so just
405 pack up the query for reference. We'll manually replace
406 the bits later. */
407 return array( 'query' => $sql, 'func' => $func );
408 }
409
410 function freePrepared( $prepared ) {
411 /* No-op for MySQL */
412 }
413
414 /**
415 * Execute a prepared query with the various arguments
416 * @param string $prepared the prepared sql
417 * @param mixed $args Either an array here, or put scalars as varargs
418 */
419 function execute( $prepared, $args = null ) {
420 if( !is_array( $args ) ) {
421 # Pull the var args
422 $args = func_get_args();
423 array_shift( $args );
424 }
425 $sql = $this->fillPrepared( $prepared['query'], $args );
426 return $this->query( $sql, $prepared['func'] );
427 }
428
429 /**
430 * Prepare & execute an SQL statement, quoting and inserting arguments
431 * in the appropriate places.
432 * @param string $query
433 * @param string $args ...
434 */
435 function safeQuery( $query, $args = null ) {
436 $prepared = $this->prepare( $query, 'Database::safeQuery' );
437 if( !is_array( $args ) ) {
438 # Pull the var args
439 $args = func_get_args();
440 array_shift( $args );
441 }
442 $retval = $this->execute( $prepared, $args );
443 $this->freePrepared( $prepared );
444 return $retval;
445 }
446
447 /**
448 * For faking prepared SQL statements on DBs that don't support
449 * it directly.
450 * @param string $preparedSql - a 'preparable' SQL statement
451 * @param array $args - array of arguments to fill it with
452 * @return string executable SQL
453 */
454 function fillPrepared( $preparedQuery, $args ) {
455 $n = 0;
456 reset( $args );
457 $this->preparedArgs =& $args;
458 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
459 array( &$this, 'fillPreparedArg' ), $preparedQuery );
460 }
461
462 /**
463 * preg_callback func for fillPrepared()
464 * The arguments should be in $this->preparedArgs and must not be touched
465 * while we're doing this.
466 *
467 * @param array $matches
468 * @return string
469 * @access private
470 */
471 function fillPreparedArg( $matches ) {
472 switch( $matches[1] ) {
473 case '\\?': return '?';
474 case '\\!': return '!';
475 case '\\&': return '&';
476 }
477 list( $n, $arg ) = each( $this->preparedArgs );
478 switch( $matches[1] ) {
479 case '?': return $this->addQuotes( $arg );
480 case '!': return $arg;
481 case '&':
482 # return $this->addQuotes( file_get_contents( $arg ) );
483 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
484 default:
485 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
486 }
487 }
488
489 /**#@+
490 * @param mixed $res A SQL result
491 */
492 /**
493 * Free a result object
494 */
495 function freeResult( $res ) {
496 if ( !@/**/mysql_free_result( $res ) ) {
497 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
498 }
499 }
500
501 /**
502 * Fetch the next row from the given result object, in object form
503 */
504 function fetchObject( $res ) {
505 @/**/$row = mysql_fetch_object( $res );
506 if( mysql_errno() ) {
507 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
508 }
509 return $row;
510 }
511
512 /**
513 * Fetch the next row from the given result object
514 * Returns an array
515 */
516 function fetchRow( $res ) {
517 @/**/$row = mysql_fetch_array( $res );
518 if (mysql_errno() ) {
519 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
520 }
521 return $row;
522 }
523
524 /**
525 * Get the number of rows in a result object
526 */
527 function numRows( $res ) {
528 @/**/$n = mysql_num_rows( $res );
529 if( mysql_errno() ) {
530 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
531 }
532 return $n;
533 }
534
535 /**
536 * Get the number of fields in a result object
537 * See documentation for mysql_num_fields()
538 */
539 function numFields( $res ) { return mysql_num_fields( $res ); }
540
541 /**
542 * Get a field name in a result object
543 * See documentation for mysql_field_name()
544 */
545 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
546
547 /**
548 * Get the inserted value of an auto-increment row
549 *
550 * The value inserted should be fetched from nextSequenceValue()
551 *
552 * Example:
553 * $id = $dbw->nextSequenceValue('page_page_id_seq');
554 * $dbw->insert('page',array('page_id' => $id));
555 * $id = $dbw->insertId();
556 */
557 function insertId() { return mysql_insert_id( $this->mConn ); }
558
559 /**
560 * Change the position of the cursor in a result object
561 * See mysql_data_seek()
562 */
563 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
564
565 /**
566 * Get the last error number
567 * See mysql_errno()
568 */
569 function lastErrno() {
570 if ( $this->mConn ) {
571 return mysql_errno( $this->mConn );
572 } else {
573 return mysql_errno();
574 }
575 }
576
577 /**
578 * Get a description of the last error
579 * See mysql_error() for more details
580 */
581 function lastError() {
582 if ( $this->mConn ) {
583 $error = mysql_error( $this->mConn );
584 } else {
585 $error = mysql_error();
586 }
587 if( $error ) {
588 $error .= ' (' . $this->mServer . ')';
589 }
590 return $error;
591 }
592 /**
593 * Get the number of rows affected by the last write query
594 * See mysql_affected_rows() for more details
595 */
596 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
597 /**#@-*/ // end of template : @param $result
598
599 /**
600 * Simple UPDATE wrapper
601 * Usually aborts on failure
602 * If errors are explicitly ignored, returns success
603 *
604 * This function exists for historical reasons, Database::update() has a more standard
605 * calling convention and feature set
606 */
607 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
608 {
609 $table = $this->tableName( $table );
610 $sql = "UPDATE $table SET $var = '" .
611 $this->strencode( $value ) . "' WHERE ($cond)";
612 return !!$this->query( $sql, DB_MASTER, $fname );
613 }
614
615 /**
616 * Simple SELECT wrapper, returns a single field, input must be encoded
617 * Usually aborts on failure
618 * If errors are explicitly ignored, returns FALSE on failure
619 */
620 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
621 if ( !is_array( $options ) ) {
622 $options = array( $options );
623 }
624 $options['LIMIT'] = 1;
625
626 $res = $this->select( $table, $var, $cond, $fname, $options );
627 if ( $res === false || !$this->numRows( $res ) ) {
628 return false;
629 }
630 $row = $this->fetchRow( $res );
631 if ( $row !== false ) {
632 $this->freeResult( $res );
633 return $row[0];
634 } else {
635 return false;
636 }
637 }
638
639 /**
640 * Returns an optional USE INDEX clause to go after the table, and a
641 * string to go at the end of the query
642 *
643 * @access private
644 *
645 * @param array $options an associative array of options to be turned into
646 * an SQL query, valid keys are listed in the function.
647 * @return array
648 */
649 function makeSelectOptions( $options ) {
650 $tailOpts = '';
651
652 if ( isset( $options['ORDER BY'] ) ) {
653 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
654 }
655 if ( isset( $options['LIMIT'] ) ) {
656 $tailOpts .= " LIMIT {$options['LIMIT']}";
657 }
658
659 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
660 $tailOpts .= ' FOR UPDATE';
661 }
662
663 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
664 $tailOpts .= ' LOCK IN SHARE MODE';
665 }
666
667 if ( isset( $options['USE INDEX'] ) ) {
668 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
669 } else {
670 $useIndex = '';
671 }
672 return array( $useIndex, $tailOpts );
673 }
674
675 /**
676 * SELECT wrapper
677 */
678 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
679 {
680 if( is_array( $vars ) ) {
681 $vars = implode( ',', $vars );
682 }
683 if( is_array( $table ) ) {
684 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
685 } elseif ($table!='') {
686 $from = ' FROM ' .$this->tableName( $table );
687 } else {
688 $from = '';
689 }
690
691 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( (array)$options );
692
693 if( !empty( $conds ) ) {
694 if ( is_array( $conds ) ) {
695 $conds = $this->makeList( $conds, LIST_AND );
696 }
697 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
698 } else {
699 $sql = "SELECT $vars $from $useIndex $tailOpts";
700 }
701 return $this->query( $sql, $fname );
702 }
703
704 /**
705 * Single row SELECT wrapper
706 * Aborts or returns FALSE on error
707 *
708 * $vars: the selected variables
709 * $conds: a condition map, terms are ANDed together.
710 * Items with numeric keys are taken to be literal conditions
711 * Takes an array of selected variables, and a condition map, which is ANDed
712 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
713 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
714 * $obj- >page_id is the ID of the Astronomy article
715 *
716 * @todo migrate documentation to phpdocumentor format
717 */
718 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
719 $options['LIMIT'] = 1;
720 $res = $this->select( $table, $vars, $conds, $fname, $options );
721 if ( $res === false || !$this->numRows( $res ) ) {
722 return false;
723 }
724 $obj = $this->fetchObject( $res );
725 $this->freeResult( $res );
726 return $obj;
727
728 }
729
730 /**
731 * Removes most variables from an SQL query and replaces them with X or N for numbers.
732 * It's only slightly flawed. Don't use for anything important.
733 *
734 * @param string $sql A SQL Query
735 * @static
736 */
737 function generalizeSQL( $sql ) {
738 # This does the same as the regexp below would do, but in such a way
739 # as to avoid crashing php on some large strings.
740 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
741
742 $sql = str_replace ( "\\\\", '', $sql);
743 $sql = str_replace ( "\\'", '', $sql);
744 $sql = str_replace ( "\\\"", '', $sql);
745 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
746 $sql = preg_replace ('/".*"/s', "'X'", $sql);
747
748 # All newlines, tabs, etc replaced by single space
749 $sql = preg_replace ( "/\s+/", ' ', $sql);
750
751 # All numbers => N
752 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
753
754 return $sql;
755 }
756
757 /**
758 * Determines whether a field exists in a table
759 * Usually aborts on failure
760 * If errors are explicitly ignored, returns NULL on failure
761 */
762 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
763 $table = $this->tableName( $table );
764 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
765 if ( !$res ) {
766 return NULL;
767 }
768
769 $found = false;
770
771 while ( $row = $this->fetchObject( $res ) ) {
772 if ( $row->Field == $field ) {
773 $found = true;
774 break;
775 }
776 }
777 return $found;
778 }
779
780 /**
781 * Determines whether an index exists
782 * Usually aborts on failure
783 * If errors are explicitly ignored, returns NULL on failure
784 */
785 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
786 $info = $this->indexInfo( $table, $index, $fname );
787 if ( is_null( $info ) ) {
788 return NULL;
789 } else {
790 return $info !== false;
791 }
792 }
793
794
795 /**
796 * Get information about an index into an object
797 * Returns false if the index does not exist
798 */
799 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
800 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
801 # SHOW INDEX should work for 3.x and up:
802 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
803 $table = $this->tableName( $table );
804 $sql = 'SHOW INDEX FROM '.$table;
805 $res = $this->query( $sql, $fname );
806 if ( !$res ) {
807 return NULL;
808 }
809
810 while ( $row = $this->fetchObject( $res ) ) {
811 if ( $row->Key_name == $index ) {
812 return $row;
813 }
814 }
815 return false;
816 }
817
818 /**
819 * Query whether a given table exists
820 */
821 function tableExists( $table ) {
822 $table = $this->tableName( $table );
823 $old = $this->ignoreErrors( true );
824 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
825 $this->ignoreErrors( $old );
826 if( $res ) {
827 $this->freeResult( $res );
828 return true;
829 } else {
830 return false;
831 }
832 }
833
834 /**
835 * mysql_fetch_field() wrapper
836 * Returns false if the field doesn't exist
837 *
838 * @param $table
839 * @param $field
840 */
841 function fieldInfo( $table, $field ) {
842 $table = $this->tableName( $table );
843 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
844 $n = mysql_num_fields( $res );
845 for( $i = 0; $i < $n; $i++ ) {
846 $meta = mysql_fetch_field( $res, $i );
847 if( $field == $meta->name ) {
848 return $meta;
849 }
850 }
851 return false;
852 }
853
854 /**
855 * mysql_field_type() wrapper
856 */
857 function fieldType( $res, $index ) {
858 return mysql_field_type( $res, $index );
859 }
860
861 /**
862 * Determines if a given index is unique
863 */
864 function indexUnique( $table, $index ) {
865 $indexInfo = $this->indexInfo( $table, $index );
866 if ( !$indexInfo ) {
867 return NULL;
868 }
869 return !$indexInfo->Non_unique;
870 }
871
872 /**
873 * INSERT wrapper, inserts an array into a table
874 *
875 * $a may be a single associative array, or an array of these with numeric keys, for
876 * multi-row insert.
877 *
878 * Usually aborts on failure
879 * If errors are explicitly ignored, returns success
880 */
881 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
882 # No rows to insert, easy just return now
883 if ( !count( $a ) ) {
884 return true;
885 }
886
887 $table = $this->tableName( $table );
888 if ( !is_array( $options ) ) {
889 $options = array( $options );
890 }
891 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
892 $multi = true;
893 $keys = array_keys( $a[0] );
894 } else {
895 $multi = false;
896 $keys = array_keys( $a );
897 }
898
899 $sql = 'INSERT ' . implode( ' ', $options ) .
900 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
901
902 if ( $multi ) {
903 $first = true;
904 foreach ( $a as $row ) {
905 if ( $first ) {
906 $first = false;
907 } else {
908 $sql .= ',';
909 }
910 $sql .= '(' . $this->makeList( $row ) . ')';
911 }
912 } else {
913 $sql .= '(' . $this->makeList( $a ) . ')';
914 }
915 return !!$this->query( $sql, $fname );
916 }
917
918 /**
919 * UPDATE wrapper, takes a condition array and a SET array
920 */
921 function update( $table, $values, $conds, $fname = 'Database::update' ) {
922 $table = $this->tableName( $table );
923 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
924 if ( $conds != '*' ) {
925 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
926 }
927 $this->query( $sql, $fname );
928 }
929
930 /**
931 * Makes a wfStrencoded list from an array
932 * $mode: LIST_COMMA - comma separated, no field names
933 * LIST_AND - ANDed WHERE clause (without the WHERE)
934 * LIST_SET - comma separated with field names, like a SET clause
935 * LIST_NAMES - comma separated field names
936 */
937 function makeList( $a, $mode = LIST_COMMA ) {
938 if ( !is_array( $a ) ) {
939 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
940 }
941
942 $first = true;
943 $list = '';
944 foreach ( $a as $field => $value ) {
945 if ( !$first ) {
946 if ( $mode == LIST_AND ) {
947 $list .= ' AND ';
948 } else {
949 $list .= ',';
950 }
951 } else {
952 $first = false;
953 }
954 if ( $mode == LIST_AND && is_numeric( $field ) ) {
955 $list .= "($value)";
956 } elseif ( $mode == LIST_AND && is_array ($value) ) {
957 $list .= $field." IN (".$this->makeList($value).") ";
958 } else {
959 if ( $mode == LIST_AND || $mode == LIST_SET ) {
960 $list .= $field.'=';
961 }
962 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
963 }
964 }
965 return $list;
966 }
967
968 /**
969 * Change the current database
970 */
971 function selectDB( $db ) {
972 $this->mDBname = $db;
973 return mysql_select_db( $db, $this->mConn );
974 }
975
976 /**
977 * Starts a timer which will kill the DB thread after $timeout seconds
978 */
979 function startTimer( $timeout ) {
980 global $IP;
981 if( function_exists( 'mysql_thread_id' ) ) {
982 # This will kill the query if it's still running after $timeout seconds.
983 $tid = mysql_thread_id( $this->mConn );
984 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
985 }
986 }
987
988 /**
989 * Stop a timer started by startTimer()
990 * Currently unimplemented.
991 *
992 */
993 function stopTimer() { }
994
995 /**
996 * Format a table name ready for use in constructing an SQL query
997 *
998 * This does two important things: it quotes table names which as necessary,
999 * and it adds a table prefix if there is one.
1000 *
1001 * All functions of this object which require a table name call this function
1002 * themselves. Pass the canonical name to such functions. This is only needed
1003 * when calling query() directly.
1004 *
1005 * @param string $name database table name
1006 */
1007 function tableName( $name ) {
1008 global $wgSharedDB;
1009 # Skip quoted literals
1010 if ( $name{0} != '`' ) {
1011 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1012 $name = "{$this->mTablePrefix}$name";
1013 }
1014 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1015 $name = "`$wgSharedDB`.`$name`";
1016 } else {
1017 # Standard quoting
1018 $name = "`$name`";
1019 }
1020 }
1021 return $name;
1022 }
1023
1024 /**
1025 * Fetch a number of table names into an array
1026 * This is handy when you need to construct SQL for joins
1027 *
1028 * Example:
1029 * extract($dbr->tableNames('user','watchlist'));
1030 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1031 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1032 */
1033 function tableNames() {
1034 $inArray = func_get_args();
1035 $retVal = array();
1036 foreach ( $inArray as $name ) {
1037 $retVal[$name] = $this->tableName( $name );
1038 }
1039 return $retVal;
1040 }
1041
1042 /**
1043 * Wrapper for addslashes()
1044 * @param string $s String to be slashed.
1045 * @return string slashed string.
1046 */
1047 function strencode( $s ) {
1048 return addslashes( $s );
1049 }
1050
1051 /**
1052 * If it's a string, adds quotes and backslashes
1053 * Otherwise returns as-is
1054 */
1055 function addQuotes( $s ) {
1056 if ( is_null( $s ) ) {
1057 return 'NULL';
1058 } else {
1059 # This will also quote numeric values. This should be harmless,
1060 # and protects against weird problems that occur when they really
1061 # _are_ strings such as article titles and string->number->string
1062 # conversion is not 1:1.
1063 return "'" . $this->strencode( $s ) . "'";
1064 }
1065 }
1066
1067 /**
1068 * Returns an appropriately quoted sequence value for inserting a new row.
1069 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1070 * subclass will return an integer, and save the value for insertId()
1071 */
1072 function nextSequenceValue( $seqName ) {
1073 return NULL;
1074 }
1075
1076 /**
1077 * USE INDEX clause
1078 * PostgreSQL doesn't have them and returns ""
1079 */
1080 function useIndexClause( $index ) {
1081 return "USE INDEX ($index)";
1082 }
1083
1084 /**
1085 * REPLACE query wrapper
1086 * PostgreSQL simulates this with a DELETE followed by INSERT
1087 * $row is the row to insert, an associative array
1088 * $uniqueIndexes is an array of indexes. Each element may be either a
1089 * field name or an array of field names
1090 *
1091 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1092 * However if you do this, you run the risk of encountering errors which wouldn't have
1093 * occurred in MySQL
1094 *
1095 * @todo migrate comment to phodocumentor format
1096 */
1097 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1098 $table = $this->tableName( $table );
1099
1100 # Single row case
1101 if ( !is_array( reset( $rows ) ) ) {
1102 $rows = array( $rows );
1103 }
1104
1105 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1106 $first = true;
1107 foreach ( $rows as $row ) {
1108 if ( $first ) {
1109 $first = false;
1110 } else {
1111 $sql .= ',';
1112 }
1113 $sql .= '(' . $this->makeList( $row ) . ')';
1114 }
1115 return $this->query( $sql, $fname );
1116 }
1117
1118 /**
1119 * DELETE where the condition is a join
1120 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1121 *
1122 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1123 * join condition matches, set $conds='*'
1124 *
1125 * DO NOT put the join condition in $conds
1126 *
1127 * @param string $delTable The table to delete from.
1128 * @param string $joinTable The other table.
1129 * @param string $delVar The variable to join on, in the first table.
1130 * @param string $joinVar The variable to join on, in the second table.
1131 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1132 */
1133 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1134 if ( !$conds ) {
1135 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1136 }
1137
1138 $delTable = $this->tableName( $delTable );
1139 $joinTable = $this->tableName( $joinTable );
1140 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1141 if ( $conds != '*' ) {
1142 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1143 }
1144
1145 return $this->query( $sql, $fname );
1146 }
1147
1148 /**
1149 * Returns the size of a text field, or -1 for "unlimited"
1150 */
1151 function textFieldSize( $table, $field ) {
1152 $table = $this->tableName( $table );
1153 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1154 $res = $this->query( $sql, 'Database::textFieldSize' );
1155 $row = $this->fetchObject( $res );
1156 $this->freeResult( $res );
1157
1158 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1159 $size = $m[1];
1160 } else {
1161 $size = -1;
1162 }
1163 return $size;
1164 }
1165
1166 /**
1167 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1168 */
1169 function lowPriorityOption() {
1170 return 'LOW_PRIORITY';
1171 }
1172
1173 /**
1174 * DELETE query wrapper
1175 *
1176 * Use $conds == "*" to delete all rows
1177 */
1178 function delete( $table, $conds, $fname = 'Database::delete' ) {
1179 if ( !$conds ) {
1180 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1181 }
1182 $table = $this->tableName( $table );
1183 $sql = "DELETE FROM $table";
1184 if ( $conds != '*' ) {
1185 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1186 }
1187 return $this->query( $sql, $fname );
1188 }
1189
1190 /**
1191 * INSERT SELECT wrapper
1192 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1193 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1194 * $conds may be "*" to copy the whole table
1195 * srcTable may be an array of tables.
1196 */
1197 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1198 $destTable = $this->tableName( $destTable );
1199 if( is_array( $srcTable ) ) {
1200 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1201 } else {
1202 $srcTable = $this->tableName( $srcTable );
1203 }
1204 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1205 ' SELECT ' . implode( ',', $varMap ) .
1206 " FROM $srcTable";
1207 if ( $conds != '*' ) {
1208 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1209 }
1210 return $this->query( $sql, $fname );
1211 }
1212
1213 /**
1214 * Construct a LIMIT query with optional offset
1215 * This is used for query pages
1216 */
1217 function limitResult($limit,$offset) {
1218 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1219 }
1220
1221 /**
1222 * Returns an SQL expression for a simple conditional.
1223 * Uses IF on MySQL.
1224 *
1225 * @param string $cond SQL expression which will result in a boolean value
1226 * @param string $trueVal SQL expression to return if true
1227 * @param string $falseVal SQL expression to return if false
1228 * @return string SQL fragment
1229 */
1230 function conditional( $cond, $trueVal, $falseVal ) {
1231 return " IF($cond, $trueVal, $falseVal) ";
1232 }
1233
1234 /**
1235 * Determines if the last failure was due to a deadlock
1236 */
1237 function wasDeadlock() {
1238 return $this->lastErrno() == 1213;
1239 }
1240
1241 /**
1242 * Perform a deadlock-prone transaction.
1243 *
1244 * This function invokes a callback function to perform a set of write
1245 * queries. If a deadlock occurs during the processing, the transaction
1246 * will be rolled back and the callback function will be called again.
1247 *
1248 * Usage:
1249 * $dbw->deadlockLoop( callback, ... );
1250 *
1251 * Extra arguments are passed through to the specified callback function.
1252 *
1253 * Returns whatever the callback function returned on its successful,
1254 * iteration, or false on error, for example if the retry limit was
1255 * reached.
1256 */
1257 function deadlockLoop() {
1258 $myFname = 'Database::deadlockLoop';
1259
1260 $this->query( 'BEGIN', $myFname );
1261 $args = func_get_args();
1262 $function = array_shift( $args );
1263 $oldIgnore = $this->ignoreErrors( true );
1264 $tries = DEADLOCK_TRIES;
1265 if ( is_array( $function ) ) {
1266 $fname = $function[0];
1267 } else {
1268 $fname = $function;
1269 }
1270 do {
1271 $retVal = call_user_func_array( $function, $args );
1272 $error = $this->lastError();
1273 $errno = $this->lastErrno();
1274 $sql = $this->lastQuery();
1275
1276 if ( $errno ) {
1277 if ( $this->wasDeadlock() ) {
1278 # Retry
1279 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1280 } else {
1281 $this->reportQueryError( $error, $errno, $sql, $fname );
1282 }
1283 }
1284 } while( $this->wasDeadlock() && --$tries > 0 );
1285 $this->ignoreErrors( $oldIgnore );
1286 if ( $tries <= 0 ) {
1287 $this->query( 'ROLLBACK', $myFname );
1288 $this->reportQueryError( $error, $errno, $sql, $fname );
1289 return false;
1290 } else {
1291 $this->query( 'COMMIT', $myFname );
1292 return $retVal;
1293 }
1294 }
1295
1296 /**
1297 * Do a SELECT MASTER_POS_WAIT()
1298 *
1299 * @param string $file the binlog file
1300 * @param string $pos the binlog position
1301 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1302 */
1303 function masterPosWait( $file, $pos, $timeout ) {
1304 $fname = 'Database::masterPosWait';
1305 wfProfileIn( $fname );
1306
1307
1308 # Commit any open transactions
1309 $this->immediateCommit();
1310
1311 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1312 $encFile = $this->strencode( $file );
1313 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1314 $res = $this->doQuery( $sql );
1315 if ( $res && $row = $this->fetchRow( $res ) ) {
1316 $this->freeResult( $res );
1317 return $row[0];
1318 } else {
1319 return false;
1320 }
1321 }
1322
1323 /**
1324 * Get the position of the master from SHOW SLAVE STATUS
1325 */
1326 function getSlavePos() {
1327 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1328 $row = $this->fetchObject( $res );
1329 if ( $row ) {
1330 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1331 } else {
1332 return array( false, false );
1333 }
1334 }
1335
1336 /**
1337 * Get the position of the master from SHOW MASTER STATUS
1338 */
1339 function getMasterPos() {
1340 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1341 $row = $this->fetchObject( $res );
1342 if ( $row ) {
1343 return array( $row->File, $row->Position );
1344 } else {
1345 return array( false, false );
1346 }
1347 }
1348
1349 /**
1350 * Begin a transaction, or if a transaction has already started, continue it
1351 */
1352 function begin( $fname = 'Database::begin' ) {
1353 if ( !$this->mTrxLevel ) {
1354 $this->immediateBegin( $fname );
1355 } else {
1356 $this->mTrxLevel++;
1357 }
1358 }
1359
1360 /**
1361 * End a transaction, or decrement the nest level if transactions are nested
1362 */
1363 function commit( $fname = 'Database::commit' ) {
1364 if ( $this->mTrxLevel ) {
1365 $this->mTrxLevel--;
1366 }
1367 if ( !$this->mTrxLevel ) {
1368 $this->immediateCommit( $fname );
1369 }
1370 }
1371
1372 /**
1373 * Rollback a transaction
1374 */
1375 function rollback( $fname = 'Database::rollback' ) {
1376 $this->query( 'ROLLBACK', $fname );
1377 $this->mTrxLevel = 0;
1378 }
1379
1380 /**
1381 * Begin a transaction, committing any previously open transaction
1382 */
1383 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1384 $this->query( 'BEGIN', $fname );
1385 $this->mTrxLevel = 1;
1386 }
1387
1388 /**
1389 * Commit transaction, if one is open
1390 */
1391 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1392 $this->query( 'COMMIT', $fname );
1393 $this->mTrxLevel = 0;
1394 }
1395
1396 /**
1397 * Return MW-style timestamp used for MySQL schema
1398 */
1399 function timestamp( $ts=0 ) {
1400 return wfTimestamp(TS_MW,$ts);
1401 }
1402
1403 /**
1404 * Local database timestamp format or null
1405 */
1406 function timestampOrNull( $ts = null ) {
1407 if( is_null( $ts ) ) {
1408 return null;
1409 } else {
1410 return $this->timestamp( $ts );
1411 }
1412 }
1413
1414 /**
1415 * @todo document
1416 */
1417 function &resultObject( &$result ) {
1418 if( empty( $result ) ) {
1419 return NULL;
1420 } else {
1421 return new ResultWrapper( $this, $result );
1422 }
1423 }
1424
1425 /**
1426 * Return aggregated value alias
1427 */
1428 function aggregateValue ($valuedata,$valuename='value') {
1429 return $valuename;
1430 }
1431
1432 /**
1433 * @return string wikitext of a link to the server software's web site
1434 */
1435 function getSoftwareLink() {
1436 return "[http://www.mysql.com/ MySQL]";
1437 }
1438
1439 /**
1440 * @return string Version information from the database
1441 */
1442 function getServerVersion() {
1443 return mysql_get_server_info();
1444 }
1445
1446 /**
1447 * Ping the server and try to reconnect if it there is no connection
1448 */
1449 function ping() {
1450 return mysql_ping( $this->mConn );
1451 }
1452
1453 /**
1454 * Get slave lag.
1455 * At the moment, this will only work if the DB user has the PROCESS privilege
1456 */
1457 function getLag() {
1458 $res = $this->query( 'SHOW PROCESSLIST' );
1459 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1460 # dubious, but unfortunately there's no easy rigorous way
1461 $slaveThreads = 0;
1462 while ( $row = $this->fetchObject( $res ) ) {
1463 if ( $row->User == 'system user' ) {
1464 if ( ++$slaveThreads == 2 ) {
1465 # This is it, return the time
1466 return $row->Time;
1467 }
1468 }
1469 }
1470 return false;
1471 }
1472
1473 /**
1474 * Get status information from SHOW STATUS in an associative array
1475 */
1476 function getStatus() {
1477 $res = $this->query( 'SHOW STATUS' );
1478 $status = array();
1479 while ( $row = $this->fetchObject( $res ) ) {
1480 $status[$row->Variable_name] = $row->Value;
1481 }
1482 return $status;
1483 }
1484 }
1485
1486 /**
1487 * Database abstraction object for mySQL
1488 * Inherit all methods and properties of Database::Database()
1489 *
1490 * @package MediaWiki
1491 * @see Database
1492 */
1493 class DatabaseMysql extends Database {
1494 # Inherit all
1495 }
1496
1497
1498 /**
1499 * Result wrapper for grabbing data queried by someone else
1500 *
1501 * @package MediaWiki
1502 */
1503 class ResultWrapper {
1504 var $db, $result;
1505
1506 /**
1507 * @todo document
1508 */
1509 function ResultWrapper( $database, $result ) {
1510 $this->db =& $database;
1511 $this->result =& $result;
1512 }
1513
1514 /**
1515 * @todo document
1516 */
1517 function numRows() {
1518 return $this->db->numRows( $this->result );
1519 }
1520
1521 /**
1522 * @todo document
1523 */
1524 function &fetchObject() {
1525 return $this->db->fetchObject( $this->result );
1526 }
1527
1528 /**
1529 * @todo document
1530 */
1531 function &fetchRow() {
1532 return $this->db->fetchRow( $this->result );
1533 }
1534
1535 /**
1536 * @todo document
1537 */
1538 function free() {
1539 $this->db->freeResult( $this->result );
1540 unset( $this->result );
1541 unset( $this->db );
1542 }
1543
1544 function seek( $row ) {
1545 $this->db->dataSeek( $this->result, $row );
1546 }
1547 }
1548
1549 #------------------------------------------------------------------------------
1550 # Global functions
1551 #------------------------------------------------------------------------------
1552
1553 /**
1554 * Standard fail function, called by default when a connection cannot be
1555 * established.
1556 * Displays the file cache if possible
1557 */
1558 function wfEmergencyAbort( &$conn, $error ) {
1559 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1560 global $wgSitename, $wgServer;
1561
1562 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1563 # Hard coding strings instead.
1564
1565 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1566 $1';
1567 $mainpage = 'Main Page';
1568 $searchdisabled = <<<EOT
1569 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1570 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1571 EOT;
1572
1573 $googlesearch = "
1574 <!-- SiteSearch Google -->
1575 <FORM method=GET action=\"http://www.google.com/search\">
1576 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1577 <A HREF=\"http://www.google.com/\">
1578 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1579 border=\"0\" ALT=\"Google\"></A>
1580 </td>
1581 <td>
1582 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1583 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1584 <font size=-1>
1585 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
1586 <input type='hidden' name='ie' value='$2'>
1587 <input type='hidden' name='oe' value='$2'>
1588 </font>
1589 </td></tr></TABLE>
1590 </FORM>
1591 <!-- SiteSearch Google -->";
1592 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1593
1594
1595 if( !headers_sent() ) {
1596 header( 'HTTP/1.0 500 Internal Server Error' );
1597 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1598 /* Don't cache error pages! They cause no end of trouble... */
1599 header( 'Cache-control: none' );
1600 header( 'Pragma: nocache' );
1601 }
1602 $msg = wfGetSiteNotice();
1603 if($msg == '') {
1604 $msg = str_replace( '$1', $error, $noconnect );
1605 }
1606 $text = $msg;
1607
1608 if($wgUseFileCache) {
1609 if($wgTitle) {
1610 $t =& $wgTitle;
1611 } else {
1612 if($title) {
1613 $t = Title::newFromURL( $title );
1614 } elseif (@/**/$_REQUEST['search']) {
1615 $search = $_REQUEST['search'];
1616 echo $searchdisabled;
1617 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1618 $wgInputEncoding ), $googlesearch );
1619 wfErrorExit();
1620 } else {
1621 $t = Title::newFromText( $mainpage );
1622 }
1623 }
1624
1625 $cache = new CacheManager( $t );
1626 if( $cache->isFileCached() ) {
1627 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1628 $cachederror . "</b></p>\n";
1629
1630 $tag = '<div id="article">';
1631 $text = str_replace(
1632 $tag,
1633 $tag . $msg,
1634 $cache->fetchPageText() );
1635 }
1636 }
1637
1638 echo $text;
1639 wfErrorExit();
1640 }
1641
1642 ?>