]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/db/Database.php
MediaWiki 1.14.0
[autoinstallsdev/mediawiki.git] / includes / db / Database.php
1 <?php
2 /**
3  * @defgroup Database Database
4  *
5  * @file
6  * @ingroup Database
7  * This file deals with MySQL interface functions
8  * and query specifics/optimisations
9  */
10
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
17
18 /**
19  * Database abstraction object
20  * @ingroup Database
21  */
22 class Database {
23
24 #------------------------------------------------------------------------------
25 # Variables
26 #------------------------------------------------------------------------------
27
28         protected $mLastQuery = '';
29         protected $mPHPError = false;
30
31         protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
32         protected $mOpened = false;
33
34         protected $mFailFunction;
35         protected $mTablePrefix;
36         protected $mFlags;
37         protected $mTrxLevel = 0;
38         protected $mErrorCount = 0;
39         protected $mLBInfo = array();
40         protected $mFakeSlaveLag = null, $mFakeMaster = false;
41
42 #------------------------------------------------------------------------------
43 # Accessors
44 #------------------------------------------------------------------------------
45         # These optionally set a variable and return the previous state
46
47         /**
48          * Fail function, takes a Database as a parameter
49          * Set to false for default, 1 for ignore errors
50          */
51         function failFunction( $function = NULL ) {
52                 return wfSetVar( $this->mFailFunction, $function );
53         }
54
55         /**
56          * Output page, used for reporting errors
57          * FALSE means discard output
58          */
59         function setOutputPage( $out ) {
60                 wfDeprecated( __METHOD__ );
61         }
62
63         /**
64          * Boolean, controls output of large amounts of debug information
65          */
66         function debug( $debug = NULL ) {
67                 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
68         }
69
70         /**
71          * Turns buffering of SQL result sets on (true) or off (false).
72          * Default is "on" and it should not be changed without good reasons.
73          */
74         function bufferResults( $buffer = NULL ) {
75                 if ( is_null( $buffer ) ) {
76                         return !(bool)( $this->mFlags & DBO_NOBUFFER );
77                 } else {
78                         return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
79                 }
80         }
81
82         /**
83          * Turns on (false) or off (true) the automatic generation and sending
84          * of a "we're sorry, but there has been a database error" page on
85          * database errors. Default is on (false). When turned off, the
86          * code should use lastErrno() and lastError() to handle the
87          * situation as appropriate.
88          */
89         function ignoreErrors( $ignoreErrors = NULL ) {
90                 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
91         }
92
93         /**
94          * The current depth of nested transactions
95          * @param $level Integer: , default NULL.
96          */
97         function trxLevel( $level = NULL ) {
98                 return wfSetVar( $this->mTrxLevel, $level );
99         }
100
101         /**
102          * Number of errors logged, only useful when errors are ignored
103          */
104         function errorCount( $count = NULL ) {
105                 return wfSetVar( $this->mErrorCount, $count );
106         }
107
108         function tablePrefix( $prefix = null ) {
109                 return wfSetVar( $this->mTablePrefix, $prefix );
110         }
111
112         /**
113          * Properties passed down from the server info array of the load balancer
114          */
115         function getLBInfo( $name = NULL ) {
116                 if ( is_null( $name ) ) {
117                         return $this->mLBInfo;
118                 } else {
119                         if ( array_key_exists( $name, $this->mLBInfo ) ) {
120                                 return $this->mLBInfo[$name];
121                         } else {
122                                 return NULL;
123                         }
124                 }
125         }
126
127         function setLBInfo( $name, $value = NULL ) {
128                 if ( is_null( $value ) ) {
129                         $this->mLBInfo = $name;
130                 } else {
131                         $this->mLBInfo[$name] = $value;
132                 }
133         }
134
135         /**
136          * Set lag time in seconds for a fake slave
137          */
138         function setFakeSlaveLag( $lag ) {
139                 $this->mFakeSlaveLag = $lag;
140         }
141
142         /**
143          * Make this connection a fake master
144          */
145         function setFakeMaster( $enabled = true ) {
146                 $this->mFakeMaster = $enabled;
147         }
148
149         /**
150          * Returns true if this database supports (and uses) cascading deletes
151          */
152         function cascadingDeletes() {
153                 return false;
154         }
155
156         /**
157          * Returns true if this database supports (and uses) triggers (e.g. on the page table)
158          */
159         function cleanupTriggers() {
160                 return false;
161         }
162
163         /**
164          * Returns true if this database is strict about what can be put into an IP field.
165          * Specifically, it uses a NULL value instead of an empty string.
166          */
167         function strictIPs() {
168                 return false;
169         }
170
171         /**
172          * Returns true if this database uses timestamps rather than integers
173         */
174         function realTimestamps() {
175                 return false;
176         }
177
178         /**
179          * Returns true if this database does an implicit sort when doing GROUP BY
180          */
181         function implicitGroupby() {
182                 return true;
183         }
184
185         /**
186          * Returns true if this database does an implicit order by when the column has an index
187          * For example: SELECT page_title FROM page LIMIT 1
188          */
189         function implicitOrderby() {
190                 return true;
191         }
192
193         /**
194          * Returns true if this database can do a native search on IP columns
195          * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
196          */
197         function searchableIPs() {
198                 return false;
199         }
200
201         /**
202          * Returns true if this database can use functional indexes
203          */
204         function functionalIndexes() {
205                 return false;
206         }
207
208         /**
209          * Return the last query that went through Database::query()
210          * @return String
211          */
212         function lastQuery() { return $this->mLastQuery; }
213         
214         /**
215          * Is a connection to the database open?
216          * @return Boolean
217          */
218         function isOpen() { return $this->mOpened; }
219
220         function setFlag( $flag ) {
221                 $this->mFlags |= $flag;
222         }
223
224         function clearFlag( $flag ) {
225                 $this->mFlags &= ~$flag;
226         }
227
228         function getFlag( $flag ) {
229                 return !!($this->mFlags & $flag);
230         }
231
232         /**
233          * General read-only accessor
234          */
235         function getProperty( $name ) {
236                 return $this->$name;
237         }
238
239         function getWikiID() {
240                 if( $this->mTablePrefix ) {
241                         return "{$this->mDBname}-{$this->mTablePrefix}";
242                 } else {
243                         return $this->mDBname;
244                 }
245         }
246
247 #------------------------------------------------------------------------------
248 # Other functions
249 #------------------------------------------------------------------------------
250
251         /**
252          * Constructor.
253          * @param $server String: database server host
254          * @param $user String: database user name
255          * @param $password String: database user password
256          * @param $dbName String: database name
257          * @param $failFunction
258          * @param $flags
259          * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
260          */
261         function __construct( $server = false, $user = false, $password = false, $dbName = false,
262                 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
263
264                 global $wgOut, $wgDBprefix, $wgCommandLineMode;
265                 # Can't get a reference if it hasn't been set yet
266                 if ( !isset( $wgOut ) ) {
267                         $wgOut = NULL;
268                 }
269
270                 $this->mFailFunction = $failFunction;
271                 $this->mFlags = $flags;
272
273                 if ( $this->mFlags & DBO_DEFAULT ) {
274                         if ( $wgCommandLineMode ) {
275                                 $this->mFlags &= ~DBO_TRX;
276                         } else {
277                                 $this->mFlags |= DBO_TRX;
278                         }
279                 }
280
281                 /*
282                 // Faster read-only access
283                 if ( wfReadOnly() ) {
284                         $this->mFlags |= DBO_PERSISTENT;
285                         $this->mFlags &= ~DBO_TRX;
286                 }*/
287
288                 /** Get the default table prefix*/
289                 if ( $tablePrefix == 'get from global' ) {
290                         $this->mTablePrefix = $wgDBprefix;
291                 } else {
292                         $this->mTablePrefix = $tablePrefix;
293                 }
294
295                 if ( $server ) {
296                         $this->open( $server, $user, $password, $dbName );
297                 }
298         }
299
300         /**
301          * Same as new Database( ... ), kept for backward compatibility
302          * @param $server String: database server host
303          * @param $user String: database user name
304          * @param $password String: database user password
305          * @param $dbName String: database name
306          * @param failFunction
307          * @param $flags
308          */
309         static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
310         {
311                 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
312         }
313
314         /**
315          * Usually aborts on failure
316          * If the failFunction is set to a non-zero integer, returns success
317          * @param $server String: database server host
318          * @param $user String: database user name
319          * @param $password String: database user password
320          * @param $dbName String: database name
321          */
322         function open( $server, $user, $password, $dbName ) {
323                 global $wgAllDBsAreLocalhost;
324                 wfProfileIn( __METHOD__ );
325
326                 # Test for missing mysql.so
327                 # First try to load it
328                 if (!@extension_loaded('mysql')) {
329                         @dl('mysql.so');
330                 }
331
332                 # Fail now
333                 # Otherwise we get a suppressed fatal error, which is very hard to track down
334                 if ( !function_exists( 'mysql_connect' ) ) {
335                         throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
336                 }
337
338                 # Debugging hack -- fake cluster
339                 if ( $wgAllDBsAreLocalhost ) {
340                         $realServer = 'localhost';
341                 } else {
342                         $realServer = $server;
343                 }
344                 $this->close();
345                 $this->mServer = $server;
346                 $this->mUser = $user;
347                 $this->mPassword = $password;
348                 $this->mDBname = $dbName;
349
350                 $success = false;
351
352                 wfProfileIn("dbconnect-$server");
353
354                 # The kernel's default SYN retransmission period is far too slow for us,
355                 # so we use a short timeout plus a manual retry. Retrying means that a small
356                 # but finite rate of SYN packet loss won't cause user-visible errors.
357                 $this->mConn = false;
358                 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
359                         $numAttempts = 2;
360                 } else {
361                         $numAttempts = 1;
362                 }
363                 $this->installErrorHandler();
364                 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
365                         if ( $i > 1 ) {
366                                 usleep( 1000 );
367                         }
368                         if ( $this->mFlags & DBO_PERSISTENT ) {
369                                 $this->mConn = mysql_pconnect( $realServer, $user, $password );
370                         } else {
371                                 # Create a new connection...
372                                 $this->mConn = mysql_connect( $realServer, $user, $password, true );
373                         }
374                         if ($this->mConn === false) {
375                                 #$iplus = $i + 1;
376                                 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n"); 
377                         }
378                 }
379                 $phpError = $this->restoreErrorHandler();
380                 # Always log connection errors
381                 if ( !$this->mConn ) {
382                         $error = $this->lastError();
383                         if ( !$error ) {
384                                 $error = $phpError;
385                         }
386                         wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
387                         wfDebug( "DB connection error\n" );
388                         wfDebug( "Server: $server, User: $user, Password: " .
389                                 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
390                         $success = false;
391                 }
392                 
393                 wfProfileOut("dbconnect-$server");
394
395                 if ( $dbName != '' && $this->mConn !== false ) {
396                         $success = @/**/mysql_select_db( $dbName, $this->mConn );
397                         if ( !$success ) {
398                                 $error = "Error selecting database $dbName on server {$this->mServer} " .
399                                         "from client host " . wfHostname() . "\n";
400                                 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
401                                 wfDebug( $error );
402                         }
403                 } else {
404                         # Delay USE query
405                         $success = (bool)$this->mConn;
406                 }
407
408                 if ( $success ) {
409                         $version = $this->getServerVersion();
410                         if ( version_compare( $version, '4.1' ) >= 0 ) {
411                                 // Tell the server we're communicating with it in UTF-8.
412                                 // This may engage various charset conversions.
413                                 global $wgDBmysql5;
414                                 if( $wgDBmysql5 ) {
415                                         $this->query( 'SET NAMES utf8', __METHOD__ );
416                                 }
417                                 // Turn off strict mode
418                                 $this->query( "SET sql_mode = ''", __METHOD__ );
419                         }
420
421                         // Turn off strict mode if it is on
422                 } else {
423                         $this->reportConnectionError( $phpError );
424                 }
425
426                 $this->mOpened = $success;
427                 wfProfileOut( __METHOD__ );
428                 return $success;
429         }
430
431         protected function installErrorHandler() {
432                 $this->mPHPError = false;
433                 $this->htmlErrors = ini_set( 'html_errors', '0' );
434                 set_error_handler( array( $this, 'connectionErrorHandler' ) );
435         }
436
437         protected function restoreErrorHandler() {
438                 restore_error_handler();
439                 if ( $this->htmlErrors !== false ) {
440                         ini_set( 'html_errors', $this->htmlErrors );
441                 }
442                 if ( $this->mPHPError ) {
443                         $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
444                         $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
445                         return $error;
446                 } else {
447                         return false;
448                 }
449         }
450
451         protected function connectionErrorHandler( $errno,  $errstr ) {
452                 $this->mPHPError = $errstr;
453         }
454
455         /**
456          * Closes a database connection.
457          * if it is open : commits any open transactions
458          *
459          * @return Bool operation success. true if already closed.
460          */
461         function close()
462         {
463                 $this->mOpened = false;
464                 if ( $this->mConn ) {
465                         if ( $this->trxLevel() ) {
466                                 $this->immediateCommit();
467                         }
468                         return mysql_close( $this->mConn );
469                 } else {
470                         return true;
471                 }
472         }
473
474         /**
475          * @param $error String: fallback error message, used if none is given by MySQL
476          */
477         function reportConnectionError( $error = 'Unknown error' ) {
478                 $myError = $this->lastError();
479                 if ( $myError ) {
480                         $error = $myError;
481                 }
482
483                 if ( $this->mFailFunction ) {
484                         # Legacy error handling method
485                         if ( !is_int( $this->mFailFunction ) ) {
486                                 $ff = $this->mFailFunction;
487                                 $ff( $this, $error );
488                         }
489                 } else {
490                         # New method
491                         throw new DBConnectionError( $this, $error );
492                 }
493         }
494
495         /**
496          * Usually aborts on failure.  If errors are explicitly ignored, returns success.
497          *
498          * @param  $sql        String: SQL query
499          * @param  $fname      String: Name of the calling function, for profiling/SHOW PROCESSLIST 
500          *     comment (you can use __METHOD__ or add some extra info)
501          * @param  $tempIgnore Boolean:   Whether to avoid throwing an exception on errors... 
502          *     maybe best to catch the exception instead?
503          * @return true for a successful write query, ResultWrapper object for a successful read query, 
504          *     or false on failure if $tempIgnore set
505          * @throws DBQueryError Thrown when the database returns an error of any kind
506          */
507         public function query( $sql, $fname = '', $tempIgnore = false ) {
508                 global $wgProfiler;
509
510                 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
511                 if ( isset( $wgProfiler ) ) {
512                         # generalizeSQL will probably cut down the query to reasonable
513                         # logging size most of the time. The substr is really just a sanity check.
514
515                         # Who's been wasting my precious column space? -- TS
516                         #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
517
518                         if ( $isMaster ) {
519                                 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
520                                 $totalProf = 'Database::query-master';
521                         } else {
522                                 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
523                                 $totalProf = 'Database::query';
524                         }
525                         wfProfileIn( $totalProf );
526                         wfProfileIn( $queryProf );
527                 }
528
529                 $this->mLastQuery = $sql;
530
531                 # Add a comment for easy SHOW PROCESSLIST interpretation
532                 #if ( $fname ) {
533                         global $wgUser;
534                         if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
535                                 $userName = $wgUser->getName();
536                                 if ( mb_strlen( $userName ) > 15 ) {
537                                         $userName = mb_substr( $userName, 0, 15 ) . '...';
538                                 }
539                                 $userName = str_replace( '/', '', $userName );
540                         } else {
541                                 $userName = '';
542                         }
543                         $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
544                 #} else {
545                 #       $commentedSql = $sql;
546                 #}
547
548                 # If DBO_TRX is set, start a transaction
549                 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && 
550                         $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
551                         // avoid establishing transactions for SHOW and SET statements too -
552                         // that would delay transaction initializations to once connection 
553                         // is really used by application
554                         $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
555                         if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0) 
556                                 $this->begin(); 
557                 }
558
559                 if ( $this->debug() ) {
560                         $sqlx = substr( $commentedSql, 0, 500 );
561                         $sqlx = strtr( $sqlx, "\t\n", '  ' );
562                         if ( $isMaster ) {
563                                 wfDebug( "SQL-master: $sqlx\n" );
564                         } else {
565                                 wfDebug( "SQL: $sqlx\n" );
566                         }
567                 }
568
569                 # Do the query and handle errors
570                 $ret = $this->doQuery( $commentedSql );
571
572                 # Try reconnecting if the connection was lost
573                 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
574                         # Transaction is gone, like it or not
575                         $this->mTrxLevel = 0;
576                         wfDebug( "Connection lost, reconnecting...\n" );
577                         if ( $this->ping() ) {
578                                 wfDebug( "Reconnected\n" );
579                                 $sqlx = substr( $commentedSql, 0, 500 );
580                                 $sqlx = strtr( $sqlx, "\t\n", '  ' );
581                                 global $wgRequestTime;
582                                 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
583                                 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
584                                 $ret = $this->doQuery( $commentedSql );
585                         } else {
586                                 wfDebug( "Failed\n" );
587                         }
588                 }
589
590                 if ( false === $ret ) {
591                         $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
592                 }
593
594                 if ( isset( $wgProfiler ) ) {
595                         wfProfileOut( $queryProf );
596                         wfProfileOut( $totalProf );
597                 }
598                 return $this->resultObject( $ret );
599         }
600
601         /**
602          * The DBMS-dependent part of query()
603          * @param  $sql String: SQL query.
604          * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
605          * @private
606          */
607         /*private*/ function doQuery( $sql ) {
608                 if( $this->bufferResults() ) {
609                         $ret = mysql_query( $sql, $this->mConn );
610                 } else {
611                         $ret = mysql_unbuffered_query( $sql, $this->mConn );
612                 }
613                 return $ret;
614         }
615
616         /**
617          * @param $error String
618          * @param $errno Integer
619          * @param $sql String
620          * @param $fname String
621          * @param $tempIgnore Boolean
622          */
623         function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
624                 global $wgCommandLineMode;
625                 # Ignore errors during error handling to avoid infinite recursion
626                 $ignore = $this->ignoreErrors( true );
627                 ++$this->mErrorCount;
628
629                 if( $ignore || $tempIgnore ) {
630                         wfDebug("SQL ERROR (ignored): $error\n");
631                         $this->ignoreErrors( $ignore );
632                 } else {
633                         $sql1line = str_replace( "\n", "\\n", $sql );
634                         wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
635                         wfDebug("SQL ERROR: " . $error . "\n");
636                         throw new DBQueryError( $this, $error, $errno, $sql, $fname );
637                 }
638         }
639
640
641         /**
642          * Intended to be compatible with the PEAR::DB wrapper functions.
643          * http://pear.php.net/manual/en/package.database.db.intro-execute.php
644          *
645          * ? = scalar value, quoted as necessary
646          * ! = raw SQL bit (a function for instance)
647          * & = filename; reads the file and inserts as a blob
648          *     (we don't use this though...)
649          */
650         function prepare( $sql, $func = 'Database::prepare' ) {
651                 /* MySQL doesn't support prepared statements (yet), so just
652                    pack up the query for reference. We'll manually replace
653                    the bits later. */
654                 return array( 'query' => $sql, 'func' => $func );
655         }
656
657         function freePrepared( $prepared ) {
658                 /* No-op for MySQL */
659         }
660
661         /**
662          * Execute a prepared query with the various arguments
663          * @param $prepared String: the prepared sql
664          * @param $args Mixed: Either an array here, or put scalars as varargs
665          */
666         function execute( $prepared, $args = null ) {
667                 if( !is_array( $args ) ) {
668                         # Pull the var args
669                         $args = func_get_args();
670                         array_shift( $args );
671                 }
672                 $sql = $this->fillPrepared( $prepared['query'], $args );
673                 return $this->query( $sql, $prepared['func'] );
674         }
675
676         /**
677          * Prepare & execute an SQL statement, quoting and inserting arguments
678          * in the appropriate places.
679          * @param $query String
680          * @param $args ...
681          */
682         function safeQuery( $query, $args = null ) {
683                 $prepared = $this->prepare( $query, 'Database::safeQuery' );
684                 if( !is_array( $args ) ) {
685                         # Pull the var args
686                         $args = func_get_args();
687                         array_shift( $args );
688                 }
689                 $retval = $this->execute( $prepared, $args );
690                 $this->freePrepared( $prepared );
691                 return $retval;
692         }
693
694         /**
695          * For faking prepared SQL statements on DBs that don't support
696          * it directly.
697          * @param $preparedQuery String: a 'preparable' SQL statement
698          * @param $args Array of arguments to fill it with
699          * @return string executable SQL
700          */
701         function fillPrepared( $preparedQuery, $args ) {
702                 reset( $args );
703                 $this->preparedArgs =& $args;
704                 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
705                         array( &$this, 'fillPreparedArg' ), $preparedQuery );
706         }
707
708         /**
709          * preg_callback func for fillPrepared()
710          * The arguments should be in $this->preparedArgs and must not be touched
711          * while we're doing this.
712          *
713          * @param $matches Array
714          * @return String
715          * @private
716          */
717         function fillPreparedArg( $matches ) {
718                 switch( $matches[1] ) {
719                         case '\\?': return '?';
720                         case '\\!': return '!';
721                         case '\\&': return '&';
722                 }
723                 list( /* $n */ , $arg ) = each( $this->preparedArgs );
724                 switch( $matches[1] ) {
725                         case '?': return $this->addQuotes( $arg );
726                         case '!': return $arg;
727                         case '&':
728                                 # return $this->addQuotes( file_get_contents( $arg ) );
729                                 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
730                         default:
731                                 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
732                 }
733         }
734
735         /**
736          * Free a result object
737          * @param $res Mixed: A SQL result
738          */
739         function freeResult( $res ) {
740                 if ( $res instanceof ResultWrapper ) {
741                         $res = $res->result;
742                 }
743                 if ( !@/**/mysql_free_result( $res ) ) {
744                         throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
745                 }
746         }
747
748         /**
749          * Fetch the next row from the given result object, in object form.
750          * Fields can be retrieved with $row->fieldname, with fields acting like
751          * member variables.
752          *
753          * @param $res SQL result object as returned from Database::query(), etc.
754          * @return MySQL row object
755          * @throws DBUnexpectedError Thrown if the database returns an error
756          */
757         function fetchObject( $res ) {
758                 if ( $res instanceof ResultWrapper ) {
759                         $res = $res->result;
760                 }
761                 @/**/$row = mysql_fetch_object( $res );
762                 if( $this->lastErrno() ) {
763                         throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
764                 }
765                 return $row;
766         }
767
768         /**
769          * Fetch the next row from the given result object, in associative array
770          * form.  Fields are retrieved with $row['fieldname'].
771          *
772          * @param $res SQL result object as returned from Database::query(), etc.
773          * @return MySQL row object
774          * @throws DBUnexpectedError Thrown if the database returns an error
775          */
776         function fetchRow( $res ) {
777                 if ( $res instanceof ResultWrapper ) {
778                         $res = $res->result;
779                 }
780                 @/**/$row = mysql_fetch_array( $res );
781                 if ( $this->lastErrno() ) {
782                         throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
783                 }
784                 return $row;
785         }
786
787         /**
788          * Get the number of rows in a result object
789          * @param $res Mixed: A SQL result
790          */
791         function numRows( $res ) {
792                 if ( $res instanceof ResultWrapper ) {
793                         $res = $res->result;
794                 }
795                 @/**/$n = mysql_num_rows( $res );
796                 if( $this->lastErrno() ) {
797                         throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
798                 }
799                 return $n;
800         }
801
802         /**
803          * Get the number of fields in a result object
804          * See documentation for mysql_num_fields()
805          * @param $res Mixed: A SQL result
806          */
807         function numFields( $res ) {
808                 if ( $res instanceof ResultWrapper ) {
809                         $res = $res->result;
810                 }
811                 return mysql_num_fields( $res );
812         }
813
814         /**
815          * Get a field name in a result object
816          * See documentation for mysql_field_name():
817          * http://www.php.net/mysql_field_name
818          * @param $res Mixed: A SQL result
819          * @param $n Integer
820          */
821         function fieldName( $res, $n ) {
822                 if ( $res instanceof ResultWrapper ) {
823                         $res = $res->result;
824                 }
825                 return mysql_field_name( $res, $n );
826         }
827
828         /**
829          * Get the inserted value of an auto-increment row
830          *
831          * The value inserted should be fetched from nextSequenceValue()
832          *
833          * Example:
834          * $id = $dbw->nextSequenceValue('page_page_id_seq');
835          * $dbw->insert('page',array('page_id' => $id));
836          * $id = $dbw->insertId();
837          */
838         function insertId() { return mysql_insert_id( $this->mConn ); }
839
840         /**
841          * Change the position of the cursor in a result object
842          * See mysql_data_seek()
843          * @param $res Mixed: A SQL result
844          * @param $row Mixed: Either MySQL row or ResultWrapper
845          */
846         function dataSeek( $res, $row ) {
847                 if ( $res instanceof ResultWrapper ) {
848                         $res = $res->result;
849                 }
850                 return mysql_data_seek( $res, $row );
851         }
852
853         /**
854          * Get the last error number
855          * See mysql_errno()
856          */
857         function lastErrno() {
858                 if ( $this->mConn ) {
859                         return mysql_errno( $this->mConn );
860                 } else {
861                         return mysql_errno();
862                 }
863         }
864
865         /**
866          * Get a description of the last error
867          * See mysql_error() for more details
868          */
869         function lastError() {
870                 if ( $this->mConn ) {
871                         # Even if it's non-zero, it can still be invalid
872                         wfSuppressWarnings();
873                         $error = mysql_error( $this->mConn );
874                         if ( !$error ) {
875                                 $error = mysql_error();
876                         }
877                         wfRestoreWarnings();
878                 } else {
879                         $error = mysql_error();
880                 }
881                 if( $error ) {
882                         $error .= ' (' . $this->mServer . ')';
883                 }
884                 return $error;
885         }
886         /**
887          * Get the number of rows affected by the last write query
888          * See mysql_affected_rows() for more details
889          */
890         function affectedRows() { return mysql_affected_rows( $this->mConn ); }
891
892         /**
893          * Simple UPDATE wrapper
894          * Usually aborts on failure
895          * If errors are explicitly ignored, returns success
896          *
897          * This function exists for historical reasons, Database::update() has a more standard
898          * calling convention and feature set
899          */
900         function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
901                 $table = $this->tableName( $table );
902                 $sql = "UPDATE $table SET $var = '" .
903                   $this->strencode( $value ) . "' WHERE ($cond)";
904                 return (bool)$this->query( $sql, $fname );
905         }
906
907         /**
908          * Simple SELECT wrapper, returns a single field, input must be encoded
909          * Usually aborts on failure
910          * If errors are explicitly ignored, returns FALSE on failure
911          */
912         function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
913                 if ( !is_array( $options ) ) {
914                         $options = array( $options );
915                 }
916                 $options['LIMIT'] = 1;
917
918                 $res = $this->select( $table, $var, $cond, $fname, $options );
919                 if ( $res === false || !$this->numRows( $res ) ) {
920                         return false;
921                 }
922                 $row = $this->fetchRow( $res );
923                 if ( $row !== false ) {
924                         $this->freeResult( $res );
925                         return reset( $row );
926                 } else {
927                         return false;
928                 }
929         }
930
931         /**
932          * Returns an optional USE INDEX clause to go after the table, and a
933          * string to go at the end of the query
934          *
935          * @private
936          *
937          * @param $options Array: associative array of options to be turned into
938          *              an SQL query, valid keys are listed in the function.
939          * @return Array
940          */
941         function makeSelectOptions( $options ) {
942                 $preLimitTail = $postLimitTail = '';
943                 $startOpts = '';
944
945                 $noKeyOptions = array();
946                 foreach ( $options as $key => $option ) {
947                         if ( is_numeric( $key ) ) {
948                                 $noKeyOptions[$option] = true;
949                         }
950                 }
951
952                 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
953                 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
954                 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
955                 
956                 //if (isset($options['LIMIT'])) {
957                 //      $tailOpts .= $this->limitResult('', $options['LIMIT'],
958                 //              isset($options['OFFSET']) ? $options['OFFSET'] 
959                 //              : false);
960                 //}
961
962                 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
963                 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
964                 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
965
966                 # Various MySQL extensions
967                 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
968                 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
969                 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
970                 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
971                 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
972                 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
973                 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
974                 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
975
976                 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
977                         $useIndex = $this->useIndexClause( $options['USE INDEX'] );
978                 } else {
979                         $useIndex = '';
980                 }
981                 
982                 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
983         }
984
985         /**
986          * SELECT wrapper
987          *
988          * @param $table   Mixed:  Array or string, table name(s) (prefix auto-added)
989          * @param $vars    Mixed:  Array or string, field name(s) to be retrieved
990          * @param $conds   Mixed:  Array or string, condition(s) for WHERE
991          * @param $fname   String: Calling function name (use __METHOD__) for logs/profiling
992          * @param $options Array:  Associative array of options (e.g. array('GROUP BY' => 'page_title')),
993          *                         see Database::makeSelectOptions code for list of supported stuff
994          * @param $join_conds Array: Associative array of table join conditions (optional)
995          *                           (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
996          * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
997          */
998         function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
999         {
1000                 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1001                 return $this->query( $sql, $fname );
1002         }
1003         
1004         /**
1005          * SELECT wrapper
1006          *
1007          * @param $table   Mixed:  Array or string, table name(s) (prefix auto-added)
1008          * @param $vars    Mixed:  Array or string, field name(s) to be retrieved
1009          * @param $conds   Mixed:  Array or string, condition(s) for WHERE
1010          * @param $fname   String: Calling function name (use __METHOD__) for logs/profiling
1011          * @param $options Array:  Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1012          *                         see Database::makeSelectOptions code for list of supported stuff
1013          * @param $join_conds Array: Associative array of table join conditions (optional)
1014          *                           (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1015          * @return string, the SQL text
1016          */
1017         function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1018                 if( is_array( $vars ) ) {
1019                         $vars = implode( ',', $vars );
1020                 }
1021                 if( !is_array( $options ) ) {
1022                         $options = array( $options );
1023                 }
1024                 if( is_array( $table ) ) {
1025                         if ( !empty($join_conds) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1026                                 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1027                         else
1028                                 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1029                 } elseif ($table!='') {
1030                         if ($table{0}==' ') {
1031                                 $from = ' FROM ' . $table;
1032                         } else {
1033                                 $from = ' FROM ' . $this->tableName( $table );
1034                         }
1035                 } else {
1036                         $from = '';
1037                 }
1038
1039                 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1040
1041                 if( !empty( $conds ) ) {
1042                         if ( is_array( $conds ) ) {
1043                                 $conds = $this->makeList( $conds, LIST_AND );
1044                         }
1045                         $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1046                 } else {
1047                         $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1048                 }
1049
1050                 if (isset($options['LIMIT']))
1051                         $sql = $this->limitResult($sql, $options['LIMIT'],
1052                                 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1053                 $sql = "$sql $postLimitTail";
1054                 
1055                 if (isset($options['EXPLAIN'])) {
1056                         $sql = 'EXPLAIN ' . $sql;
1057                 }
1058                 return $sql;
1059         }
1060
1061         /**
1062          * Single row SELECT wrapper
1063          * Aborts or returns FALSE on error
1064          *
1065          * @param $table String: table name
1066          * @param $vars String: the selected variables
1067          * @param $conds Array: a condition map, terms are ANDed together.
1068          *   Items with numeric keys are taken to be literal conditions
1069          * Takes an array of selected variables, and a condition map, which is ANDed
1070          * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1071          * NS_MAIN, "page_title" => "Astronomy" ) )   would return an object where
1072          * $obj- >page_id is the ID of the Astronomy article
1073          * @param $fname String: Calling functio name
1074          * @param $options Array
1075          * @param $join_conds Array
1076          *
1077          * @todo migrate documentation to phpdocumentor format
1078          */
1079         function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1080                 $options['LIMIT'] = 1;
1081                 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1082                 if ( $res === false )
1083                         return false;
1084                 if ( !$this->numRows($res) ) {
1085                         $this->freeResult($res);
1086                         return false;
1087                 }
1088                 $obj = $this->fetchObject( $res );
1089                 $this->freeResult( $res );
1090                 return $obj;
1091
1092         }
1093         
1094         /**
1095          * Estimate rows in dataset
1096          * Returns estimated count, based on EXPLAIN output
1097          * Takes same arguments as Database::select()
1098          */
1099         
1100         function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1101                 $options['EXPLAIN']=true;
1102                 $res = $this->select ($table, $vars, $conds, $fname, $options );
1103                 if ( $res === false )
1104                         return false;
1105                 if (!$this->numRows($res)) {
1106                         $this->freeResult($res);
1107                         return 0;
1108                 }
1109                 
1110                 $rows=1;
1111         
1112                 while( $plan = $this->fetchObject( $res ) ) {
1113                         $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
1114                 }
1115                 
1116                 $this->freeResult($res);
1117                 return $rows;           
1118         }
1119         
1120
1121         /**
1122          * Removes most variables from an SQL query and replaces them with X or N for numbers.
1123          * It's only slightly flawed. Don't use for anything important.
1124          *
1125          * @param $sql String: A SQL Query
1126          */
1127         static function generalizeSQL( $sql ) {
1128                 # This does the same as the regexp below would do, but in such a way
1129                 # as to avoid crashing php on some large strings.
1130                 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1131
1132                 $sql = str_replace ( "\\\\", '', $sql);
1133                 $sql = str_replace ( "\\'", '', $sql);
1134                 $sql = str_replace ( "\\\"", '', $sql);
1135                 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1136                 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1137
1138                 # All newlines, tabs, etc replaced by single space
1139                 $sql = preg_replace ( '/\s+/', ' ', $sql);
1140
1141                 # All numbers => N
1142                 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1143
1144                 return $sql;
1145         }
1146
1147         /**
1148          * Determines whether a field exists in a table
1149          * Usually aborts on failure
1150          * If errors are explicitly ignored, returns NULL on failure
1151          */
1152         function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1153                 $table = $this->tableName( $table );
1154                 $res = $this->query( 'DESCRIBE '.$table, $fname );
1155                 if ( !$res ) {
1156                         return NULL;
1157                 }
1158
1159                 $found = false;
1160
1161                 while ( $row = $this->fetchObject( $res ) ) {
1162                         if ( $row->Field == $field ) {
1163                                 $found = true;
1164                                 break;
1165                         }
1166                 }
1167                 return $found;
1168         }
1169
1170         /**
1171          * Determines whether an index exists
1172          * Usually aborts on failure
1173          * If errors are explicitly ignored, returns NULL on failure
1174          */
1175         function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1176                 $info = $this->indexInfo( $table, $index, $fname );
1177                 if ( is_null( $info ) ) {
1178                         return NULL;
1179                 } else {
1180                         return $info !== false;
1181                 }
1182         }
1183
1184
1185         /**
1186          * Get information about an index into an object
1187          * Returns false if the index does not exist
1188          */
1189         function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1190                 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1191                 # SHOW INDEX should work for 3.x and up:
1192                 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1193                 $table = $this->tableName( $table );
1194                 $sql = 'SHOW INDEX FROM '.$table;
1195                 $res = $this->query( $sql, $fname );
1196                 if ( !$res ) {
1197                         return NULL;
1198                 }
1199
1200                 $result = array();
1201                 while ( $row = $this->fetchObject( $res ) ) {
1202                         if ( $row->Key_name == $index ) {
1203                                 $result[] = $row;
1204                         }
1205                 }
1206                 $this->freeResult($res);
1207                 
1208                 return empty($result) ? false : $result;
1209         }
1210
1211         /**
1212          * Query whether a given table exists
1213          */
1214         function tableExists( $table ) {
1215                 $table = $this->tableName( $table );
1216                 $old = $this->ignoreErrors( true );
1217                 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1218                 $this->ignoreErrors( $old );
1219                 if( $res ) {
1220                         $this->freeResult( $res );
1221                         return true;
1222                 } else {
1223                         return false;
1224                 }
1225         }
1226
1227         /**
1228          * mysql_fetch_field() wrapper
1229          * Returns false if the field doesn't exist
1230          *
1231          * @param $table
1232          * @param $field
1233          */
1234         function fieldInfo( $table, $field ) {
1235                 $table = $this->tableName( $table );
1236                 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1237                 $n = mysql_num_fields( $res->result );
1238                 for( $i = 0; $i < $n; $i++ ) {
1239                         $meta = mysql_fetch_field( $res->result, $i );
1240                         if( $field == $meta->name ) {
1241                                 return new MySQLField($meta);
1242                         }
1243                 }
1244                 return false;
1245         }
1246
1247         /**
1248          * mysql_field_type() wrapper
1249          */
1250         function fieldType( $res, $index ) {
1251                 if ( $res instanceof ResultWrapper ) {
1252                         $res = $res->result;
1253                 }
1254                 return mysql_field_type( $res, $index );
1255         }
1256
1257         /**
1258          * Determines if a given index is unique
1259          */
1260         function indexUnique( $table, $index ) {
1261                 $indexInfo = $this->indexInfo( $table, $index );
1262                 if ( !$indexInfo ) {
1263                         return NULL;
1264                 }
1265                 return !$indexInfo[0]->Non_unique;
1266         }
1267
1268         /**
1269          * INSERT wrapper, inserts an array into a table
1270          *
1271          * $a may be a single associative array, or an array of these with numeric keys, for
1272          * multi-row insert.
1273          *
1274          * Usually aborts on failure
1275          * If errors are explicitly ignored, returns success
1276          */
1277         function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1278                 # No rows to insert, easy just return now
1279                 if ( !count( $a ) ) {
1280                         return true;
1281                 }
1282
1283                 $table = $this->tableName( $table );
1284                 if ( !is_array( $options ) ) {
1285                         $options = array( $options );
1286                 }
1287                 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1288                         $multi = true;
1289                         $keys = array_keys( $a[0] );
1290                 } else {
1291                         $multi = false;
1292                         $keys = array_keys( $a );
1293                 }
1294
1295                 $sql = 'INSERT ' . implode( ' ', $options ) .
1296                         " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1297
1298                 if ( $multi ) {
1299                         $first = true;
1300                         foreach ( $a as $row ) {
1301                                 if ( $first ) {
1302                                         $first = false;
1303                                 } else {
1304                                         $sql .= ',';
1305                                 }
1306                                 $sql .= '(' . $this->makeList( $row ) . ')';
1307                         }
1308                 } else {
1309                         $sql .= '(' . $this->makeList( $a ) . ')';
1310                 }
1311                 return (bool)$this->query( $sql, $fname );
1312         }
1313
1314         /**
1315          * Make UPDATE options for the Database::update function
1316          *
1317          * @private
1318          * @param $options Array: The options passed to Database::update
1319          * @return string
1320          */
1321         function makeUpdateOptions( $options ) {
1322                 if( !is_array( $options ) ) {
1323                         $options = array( $options );
1324                 }
1325                 $opts = array();
1326                 if ( in_array( 'LOW_PRIORITY', $options ) )
1327                         $opts[] = $this->lowPriorityOption();
1328                 if ( in_array( 'IGNORE', $options ) )
1329                         $opts[] = 'IGNORE';
1330                 return implode(' ', $opts);
1331         }
1332
1333         /**
1334          * UPDATE wrapper, takes a condition array and a SET array
1335          *
1336          * @param $table  String: The table to UPDATE
1337          * @param $values Array:  An array of values to SET
1338          * @param $conds  Array:  An array of conditions (WHERE). Use '*' to update all rows.
1339          * @param $fname  String: The Class::Function calling this function
1340          *                        (for the log)
1341          * @param $options Array: An array of UPDATE options, can be one or
1342          *                        more of IGNORE, LOW_PRIORITY
1343          * @return Boolean
1344          */
1345         function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1346                 $table = $this->tableName( $table );
1347                 $opts = $this->makeUpdateOptions( $options );
1348                 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1349                 if ( $conds != '*' ) {
1350                         $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1351                 }
1352                 return $this->query( $sql, $fname );
1353         }
1354
1355         /**
1356          * Makes an encoded list of strings from an array
1357          * $mode:
1358          *        LIST_COMMA         - comma separated, no field names
1359          *        LIST_AND           - ANDed WHERE clause (without the WHERE)
1360          *        LIST_OR            - ORed WHERE clause (without the WHERE)
1361          *        LIST_SET           - comma separated with field names, like a SET clause
1362          *        LIST_NAMES         - comma separated field names
1363          */
1364         function makeList( $a, $mode = LIST_COMMA ) {
1365                 if ( !is_array( $a ) ) {
1366                         throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1367                 }
1368
1369                 $first = true;
1370                 $list = '';
1371                 foreach ( $a as $field => $value ) {
1372                         if ( !$first ) {
1373                                 if ( $mode == LIST_AND ) {
1374                                         $list .= ' AND ';
1375                                 } elseif($mode == LIST_OR) {
1376                                         $list .= ' OR ';
1377                                 } else {
1378                                         $list .= ',';
1379                                 }
1380                         } else {
1381                                 $first = false;
1382                         }
1383                         if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1384                                 $list .= "($value)";
1385                         } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1386                                 $list .= "$value";
1387                         } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1388                                 if( count( $value ) == 0 ) {
1389                                         throw new MWException( __METHOD__.': empty input' );
1390                                 } elseif( count( $value ) == 1 ) {
1391                                         // Special-case single values, as IN isn't terribly efficient
1392                                         // Don't necessarily assume the single key is 0; we don't
1393                                         // enforce linear numeric ordering on other arrays here.
1394                                         $value = array_values( $value );
1395                                         $list .= $field." = ".$this->addQuotes( $value[0] );
1396                                 } else {
1397                                         $list .= $field." IN (".$this->makeList($value).") ";
1398                                 }
1399                         } elseif( is_null($value) ) {
1400                                 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1401                                         $list .= "$field IS ";
1402                                 } elseif ( $mode == LIST_SET ) {
1403                                         $list .= "$field = ";
1404                                 }
1405                                 $list .= 'NULL';
1406                         } else {
1407                                 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1408                                         $list .= "$field = ";
1409                                 }
1410                                 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1411                         }
1412                 }
1413                 return $list;
1414         }
1415
1416         /**
1417          * Change the current database
1418          */
1419         function selectDB( $db ) {
1420                 $this->mDBname = $db;
1421                 return mysql_select_db( $db, $this->mConn );
1422         }
1423
1424         /**
1425          * Get the current DB name
1426          */
1427         function getDBname() {
1428                 return $this->mDBname;
1429         }
1430
1431         /**
1432          * Get the server hostname or IP address
1433          */
1434         function getServer() {
1435                 return $this->mServer;
1436         }
1437
1438         /**
1439          * Format a table name ready for use in constructing an SQL query
1440          *
1441          * This does two important things: it quotes the table names to clean them up,
1442          * and it adds a table prefix if only given a table name with no quotes.
1443          *
1444          * All functions of this object which require a table name call this function
1445          * themselves. Pass the canonical name to such functions. This is only needed
1446          * when calling query() directly.
1447          *
1448          * @param $name String: database table name
1449          * @return String: full database name
1450          */
1451         function tableName( $name ) {
1452                 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1453                 # Skip the entire process when we have a string quoted on both ends.
1454                 # Note that we check the end so that we will still quote any use of
1455                 # use of `database`.table. But won't break things if someone wants
1456                 # to query a database table with a dot in the name.
1457                 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1458                 
1459                 # Lets test for any bits of text that should never show up in a table
1460                 # name. Basically anything like JOIN or ON which are actually part of
1461                 # SQL queries, but may end up inside of the table value to combine
1462                 # sql. Such as how the API is doing.
1463                 # Note that we use a whitespace test rather than a \b test to avoid
1464                 # any remote case where a word like on may be inside of a table name
1465                 # surrounded by symbols which may be considered word breaks.
1466                 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1467                 
1468                 # Split database and table into proper variables.
1469                 # We reverse the explode so that database.table and table both output
1470                 # the correct table.
1471                 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1472                 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
1473                 else                         @list( $table ) = $dbDetails;
1474                 $prefix = $this->mTablePrefix; # Default prefix
1475                 
1476                 # A database name has been specified in input. Quote the table name
1477                 # because we don't want any prefixes added.
1478                 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1479                 
1480                 # Note that we use the long format because php will complain in in_array if
1481                 # the input is not an array, and will complain in is_array if it is not set.
1482                 if( !isset( $database ) # Don't use shared database if pre selected.
1483                  && isset( $wgSharedDB ) # We have a shared database
1484                  && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1485                  && isset( $wgSharedTables )
1486                  && is_array( $wgSharedTables )
1487                  && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1488                         $database = $wgSharedDB;
1489                         $prefix   = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1490                 }
1491                 
1492                 # Quote the $database and $table and apply the prefix if not quoted.
1493                 if( isset($database) ) $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1494                 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1495                 
1496                 # Merge our database and table into our final table name.
1497                 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1498                 
1499                 # We're finished, return.
1500                 return $tableName;
1501         }
1502
1503         /**
1504          * Fetch a number of table names into an array
1505          * This is handy when you need to construct SQL for joins
1506          *
1507          * Example:
1508          * extract($dbr->tableNames('user','watchlist'));
1509          * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1510          *         WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1511          */
1512         public function tableNames() {
1513                 $inArray = func_get_args();
1514                 $retVal = array();
1515                 foreach ( $inArray as $name ) {
1516                         $retVal[$name] = $this->tableName( $name );
1517                 }
1518                 return $retVal;
1519         }
1520         
1521         /**
1522          * Fetch a number of table names into an zero-indexed numerical array
1523          * This is handy when you need to construct SQL for joins
1524          *
1525          * Example:
1526          * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1527          * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1528          *         WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1529          */
1530         public function tableNamesN() {
1531                 $inArray = func_get_args();
1532                 $retVal = array();
1533                 foreach ( $inArray as $name ) {
1534                         $retVal[] = $this->tableName( $name );
1535                 }
1536                 return $retVal;
1537         }
1538
1539         /**
1540          * @private
1541          */
1542         function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1543                 $ret = array();
1544                 $retJOIN = array();
1545                 $use_index_safe = is_array($use_index) ? $use_index : array();
1546                 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1547                 foreach ( $tables as $table ) {
1548                         // Is there a JOIN and INDEX clause for this table?
1549                         if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1550                                 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1551                                 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1552                                 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1553                                 $retJOIN[] = $tableClause;
1554                         // Is there an INDEX clause?
1555                         } else if ( isset($use_index_safe[$table]) ) {
1556                                 $tableClause = $this->tableName( $table );
1557                                 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1558                                 $ret[] = $tableClause;
1559                         // Is there a JOIN clause?
1560                         } else if ( isset($join_conds_safe[$table]) ) {
1561                                 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1562                                 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1563                                 $retJOIN[] = $tableClause;
1564                         } else {
1565                                 $tableClause = $this->tableName( $table );
1566                                 $ret[] = $tableClause;
1567                         }
1568                 }
1569                 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1570                 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1571                 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1572                 // Compile our final table clause
1573                 return implode(' ',array($straightJoins,$otherJoins) );
1574         }
1575
1576         /**
1577          * Wrapper for addslashes()
1578          * @param $s String: to be slashed.
1579          * @return String: slashed string.
1580          */
1581         function strencode( $s ) {
1582                 return mysql_real_escape_string( $s, $this->mConn );
1583         }
1584
1585         /**
1586          * If it's a string, adds quotes and backslashes
1587          * Otherwise returns as-is
1588          */
1589         function addQuotes( $s ) {
1590                 if ( is_null( $s ) ) {
1591                         return 'NULL';
1592                 } else {
1593                         # This will also quote numeric values. This should be harmless,
1594                         # and protects against weird problems that occur when they really
1595                         # _are_ strings such as article titles and string->number->string
1596                         # conversion is not 1:1.
1597                         return "'" . $this->strencode( $s ) . "'";
1598                 }
1599         }
1600
1601         /**
1602          * Escape string for safe LIKE usage
1603          */
1604         function escapeLike( $s ) {
1605                 $s=$this->strencode( $s );
1606                 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1607                 return $s;
1608         }
1609
1610         /**
1611          * Returns an appropriately quoted sequence value for inserting a new row.
1612          * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1613          * subclass will return an integer, and save the value for insertId()
1614          */
1615         function nextSequenceValue( $seqName ) {
1616                 return NULL;
1617         }
1618
1619         /**
1620          * USE INDEX clause
1621          * PostgreSQL doesn't have them and returns ""
1622          */
1623         function useIndexClause( $index ) {
1624                 return "FORCE INDEX ($index)";
1625         }
1626
1627         /**
1628          * REPLACE query wrapper
1629          * PostgreSQL simulates this with a DELETE followed by INSERT
1630          * $row is the row to insert, an associative array
1631          * $uniqueIndexes is an array of indexes. Each element may be either a
1632          * field name or an array of field names
1633          *
1634          * It may be more efficient to leave off unique indexes which are unlikely to collide.
1635          * However if you do this, you run the risk of encountering errors which wouldn't have
1636          * occurred in MySQL
1637          *
1638          * @todo migrate comment to phodocumentor format
1639          */
1640         function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1641                 $table = $this->tableName( $table );
1642
1643                 # Single row case
1644                 if ( !is_array( reset( $rows ) ) ) {
1645                         $rows = array( $rows );
1646                 }
1647
1648                 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1649                 $first = true;
1650                 foreach ( $rows as $row ) {
1651                         if ( $first ) {
1652                                 $first = false;
1653                         } else {
1654                                 $sql .= ',';
1655                         }
1656                         $sql .= '(' . $this->makeList( $row ) . ')';
1657                 }
1658                 return $this->query( $sql, $fname );
1659         }
1660
1661         /**
1662          * DELETE where the condition is a join
1663          * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1664          *
1665          * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1666          * join condition matches, set $conds='*'
1667          *
1668          * DO NOT put the join condition in $conds
1669          *
1670          * @param $delTable String: The table to delete from.
1671          * @param $joinTable String: The other table.
1672          * @param $delVar String: The variable to join on, in the first table.
1673          * @param $joinVar String: The variable to join on, in the second table.
1674          * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1675          * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1676          */
1677         function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1678                 if ( !$conds ) {
1679                         throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1680                 }
1681
1682                 $delTable = $this->tableName( $delTable );
1683                 $joinTable = $this->tableName( $joinTable );
1684                 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1685                 if ( $conds != '*' ) {
1686                         $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1687                 }
1688
1689                 return $this->query( $sql, $fname );
1690         }
1691
1692         /**
1693          * Returns the size of a text field, or -1 for "unlimited"
1694          */
1695         function textFieldSize( $table, $field ) {
1696                 $table = $this->tableName( $table );
1697                 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1698                 $res = $this->query( $sql, 'Database::textFieldSize' );
1699                 $row = $this->fetchObject( $res );
1700                 $this->freeResult( $res );
1701
1702                 $m = array();
1703                 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1704                         $size = $m[1];
1705                 } else {
1706                         $size = -1;
1707                 }
1708                 return $size;
1709         }
1710
1711         /**
1712          * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1713          */
1714         function lowPriorityOption() {
1715                 return 'LOW_PRIORITY';
1716         }
1717
1718         /**
1719          * DELETE query wrapper
1720          *
1721          * Use $conds == "*" to delete all rows
1722          */
1723         function delete( $table, $conds, $fname = 'Database::delete' ) {
1724                 if ( !$conds ) {
1725                         throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1726                 }
1727                 $table = $this->tableName( $table );
1728                 $sql = "DELETE FROM $table";
1729                 if ( $conds != '*' ) {
1730                         $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1731                 }
1732                 return $this->query( $sql, $fname );
1733         }
1734
1735         /**
1736          * INSERT SELECT wrapper
1737          * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1738          * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1739          * $conds may be "*" to copy the whole table
1740          * srcTable may be an array of tables.
1741          */
1742         function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1743                 $insertOptions = array(), $selectOptions = array() )
1744         {
1745                 $destTable = $this->tableName( $destTable );
1746                 if ( is_array( $insertOptions ) ) {
1747                         $insertOptions = implode( ' ', $insertOptions );
1748                 }
1749                 if( !is_array( $selectOptions ) ) {
1750                         $selectOptions = array( $selectOptions );
1751                 }
1752                 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1753                 if( is_array( $srcTable ) ) {
1754                         $srcTable =  implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1755                 } else {
1756                         $srcTable = $this->tableName( $srcTable );
1757                 }
1758                 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1759                         " SELECT $startOpts " . implode( ',', $varMap ) .
1760                         " FROM $srcTable $useIndex ";
1761                 if ( $conds != '*' ) {
1762                         $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1763                 }
1764                 $sql .= " $tailOpts";
1765                 return $this->query( $sql, $fname );
1766         }
1767
1768         /**
1769          * Construct a LIMIT query with optional offset
1770          * This is used for query pages
1771          * @param $sql String: SQL query we will append the limit too
1772          * @param $limit Integer: the SQL limit
1773          * @param $offset Integer the SQL offset (default false)
1774          */
1775         function limitResult($sql, $limit, $offset=false) {
1776                 if( !is_numeric($limit) ) {
1777                         throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1778                 }
1779                 return "$sql LIMIT "
1780                                 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1781                                 . "{$limit} ";
1782         }
1783         function limitResultForUpdate($sql, $num) {
1784                 return $this->limitResult($sql, $num, 0);
1785         }
1786
1787         /**
1788          * Returns an SQL expression for a simple conditional.
1789          * Uses IF on MySQL.
1790          *
1791          * @param $cond String: SQL expression which will result in a boolean value
1792          * @param $trueVal String: SQL expression to return if true
1793          * @param $falseVal String: SQL expression to return if false
1794          * @return String: SQL fragment
1795          */
1796         function conditional( $cond, $trueVal, $falseVal ) {
1797                 return " IF($cond, $trueVal, $falseVal) ";
1798         }
1799
1800         /**
1801          * Returns a comand for str_replace function in SQL query.
1802          * Uses REPLACE() in MySQL
1803          *
1804          * @param $orig String: column to modify
1805          * @param $old String: column to seek
1806          * @param $new String: column to replace with
1807          */
1808         function strreplace( $orig, $old, $new ) {
1809                 return "REPLACE({$orig}, {$old}, {$new})";
1810         }
1811
1812         /**
1813          * Determines if the last failure was due to a deadlock
1814          */
1815         function wasDeadlock() {
1816                 return $this->lastErrno() == 1213;
1817         }
1818
1819         /**
1820          * Perform a deadlock-prone transaction.
1821          *
1822          * This function invokes a callback function to perform a set of write
1823          * queries. If a deadlock occurs during the processing, the transaction
1824          * will be rolled back and the callback function will be called again.
1825          *
1826          * Usage:
1827          *   $dbw->deadlockLoop( callback, ... );
1828          *
1829          * Extra arguments are passed through to the specified callback function.
1830          *
1831          * Returns whatever the callback function returned on its successful,
1832          * iteration, or false on error, for example if the retry limit was
1833          * reached.
1834          */
1835         function deadlockLoop() {
1836                 $myFname = 'Database::deadlockLoop';
1837
1838                 $this->begin();
1839                 $args = func_get_args();
1840                 $function = array_shift( $args );
1841                 $oldIgnore = $this->ignoreErrors( true );
1842                 $tries = DEADLOCK_TRIES;
1843                 if ( is_array( $function ) ) {
1844                         $fname = $function[0];
1845                 } else {
1846                         $fname = $function;
1847                 }
1848                 do {
1849                         $retVal = call_user_func_array( $function, $args );
1850                         $error = $this->lastError();
1851                         $errno = $this->lastErrno();
1852                         $sql = $this->lastQuery();
1853
1854                         if ( $errno ) {
1855                                 if ( $this->wasDeadlock() ) {
1856                                         # Retry
1857                                         usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1858                                 } else {
1859                                         $this->reportQueryError( $error, $errno, $sql, $fname );
1860                                 }
1861                         }
1862                 } while( $this->wasDeadlock() && --$tries > 0 );
1863                 $this->ignoreErrors( $oldIgnore );
1864                 if ( $tries <= 0 ) {
1865                         $this->query( 'ROLLBACK', $myFname );
1866                         $this->reportQueryError( $error, $errno, $sql, $fname );
1867                         return false;
1868                 } else {
1869                         $this->query( 'COMMIT', $myFname );
1870                         return $retVal;
1871                 }
1872         }
1873
1874         /**
1875          * Do a SELECT MASTER_POS_WAIT()
1876          *
1877          * @param $pos MySQLMasterPos object
1878          * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1879          */
1880         function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1881                 $fname = 'Database::masterPosWait';
1882                 wfProfileIn( $fname );
1883
1884                 # Commit any open transactions
1885                 if ( $this->mTrxLevel ) {
1886                         $this->immediateCommit();
1887                 }
1888
1889                 if ( !is_null( $this->mFakeSlaveLag ) ) {
1890                         $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1891                         if ( $wait > $timeout * 1e6 ) {
1892                                 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1893                                 wfProfileOut( $fname );
1894                                 return -1;
1895                         } elseif ( $wait > 0 ) {
1896                                 wfDebug( "Fake slave waiting $wait us\n" );
1897                                 usleep( $wait );
1898                                 wfProfileOut( $fname );
1899                                 return 1;
1900                         } else {
1901                                 wfDebug( "Fake slave up to date ($wait us)\n" );
1902                                 wfProfileOut( $fname );
1903                                 return 0;
1904                         }
1905                 }
1906
1907                 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1908                 $encFile = $this->addQuotes( $pos->file );
1909                 $encPos = intval( $pos->pos );
1910                 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1911                 $res = $this->doQuery( $sql );
1912                 if ( $res && $row = $this->fetchRow( $res ) ) {
1913                         $this->freeResult( $res );
1914                         wfProfileOut( $fname );
1915                         return $row[0];
1916                 } else {
1917                         wfProfileOut( $fname );
1918                         return false;
1919                 }
1920         }
1921
1922         /**
1923          * Get the position of the master from SHOW SLAVE STATUS
1924          */
1925         function getSlavePos() {
1926                 if ( !is_null( $this->mFakeSlaveLag ) ) {
1927                         $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1928                         wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1929                         return $pos;
1930                 }
1931                 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1932                 $row = $this->fetchObject( $res );
1933                 if ( $row ) {
1934                         $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1935                         return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1936                 } else {
1937                         return false;
1938                 }
1939         }
1940
1941         /**
1942          * Get the position of the master from SHOW MASTER STATUS
1943          */
1944         function getMasterPos() {
1945                 if ( $this->mFakeMaster ) {
1946                         return new MySQLMasterPos( 'fake', microtime( true ) );
1947                 }
1948                 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1949                 $row = $this->fetchObject( $res );
1950                 if ( $row ) {
1951                         return new MySQLMasterPos( $row->File, $row->Position );
1952                 } else {
1953                         return false;
1954                 }
1955         }
1956
1957         /**
1958          * Begin a transaction, committing any previously open transaction
1959          */
1960         function begin( $fname = 'Database::begin' ) {
1961                 $this->query( 'BEGIN', $fname );
1962                 $this->mTrxLevel = 1;
1963         }
1964
1965         /**
1966          * End a transaction
1967          */
1968         function commit( $fname = 'Database::commit' ) {
1969                 $this->query( 'COMMIT', $fname );
1970                 $this->mTrxLevel = 0;
1971         }
1972
1973         /**
1974          * Rollback a transaction.
1975          * No-op on non-transactional databases.
1976          */
1977         function rollback( $fname = 'Database::rollback' ) {
1978                 $this->query( 'ROLLBACK', $fname, true );
1979                 $this->mTrxLevel = 0;
1980         }
1981
1982         /**
1983          * Begin a transaction, committing any previously open transaction
1984          * @deprecated use begin()
1985          */
1986         function immediateBegin( $fname = 'Database::immediateBegin' ) {
1987                 $this->begin();
1988         }
1989
1990         /**
1991          * Commit transaction, if one is open
1992          * @deprecated use commit()
1993          */
1994         function immediateCommit( $fname = 'Database::immediateCommit' ) {
1995                 $this->commit();
1996         }
1997
1998         /**
1999          * Return MW-style timestamp used for MySQL schema
2000          */
2001         function timestamp( $ts=0 ) {
2002                 return wfTimestamp(TS_MW,$ts);
2003         }
2004
2005         /**
2006          * Local database timestamp format or null
2007          */
2008         function timestampOrNull( $ts = null ) {
2009                 if( is_null( $ts ) ) {
2010                         return null;
2011                 } else {
2012                         return $this->timestamp( $ts );
2013                 }
2014         }
2015
2016         /**
2017          * @todo document
2018          */
2019         function resultObject( $result ) {
2020                 if( empty( $result ) ) {
2021                         return false;
2022                 } elseif ( $result instanceof ResultWrapper ) {
2023                         return $result;
2024                 } elseif ( $result === true ) {
2025                         // Successful write query
2026                         return $result;
2027                 } else {
2028                         return new ResultWrapper( $this, $result );
2029                 }
2030         }
2031
2032         /**
2033          * Return aggregated value alias
2034          */
2035         function aggregateValue ($valuedata,$valuename='value') {
2036                 return $valuename;
2037         }
2038
2039         /**
2040          * @return String: wikitext of a link to the server software's web site
2041          */
2042         function getSoftwareLink() {
2043                 return "[http://www.mysql.com/ MySQL]";
2044         }
2045
2046         /**
2047          * @return String: Version information from the database
2048          */
2049         function getServerVersion() {
2050                 return mysql_get_server_info( $this->mConn );
2051         }
2052
2053         /**
2054          * Ping the server and try to reconnect if it there is no connection
2055          */
2056         function ping() {
2057                 if( !function_exists( 'mysql_ping' ) ) {
2058                         wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2059                         return true;
2060                 }
2061                 $ping = mysql_ping( $this->mConn );
2062                 if ( $ping ) {
2063                         return true;
2064                 }
2065
2066                 // Need to reconnect manually in MySQL client 5.0.13+
2067                 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2068                         mysql_close( $this->mConn );
2069                         $this->mOpened = false;
2070                         $this->mConn = false;
2071                         $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2072                         return true;
2073                 }
2074                 return false;
2075         }
2076
2077         /**
2078          * Get slave lag.
2079          * At the moment, this will only work if the DB user has the PROCESS privilege
2080          */
2081         function getLag() {
2082                 if ( !is_null( $this->mFakeSlaveLag ) ) {
2083                         wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2084                         return $this->mFakeSlaveLag;
2085                 }
2086                 $res = $this->query( 'SHOW PROCESSLIST' );
2087                 # Find slave SQL thread
2088                 while ( $row = $this->fetchObject( $res ) ) {
2089                         /* This should work for most situations - when default db 
2090                          * for thread is not specified, it had no events executed, 
2091                          * and therefore it doesn't know yet how lagged it is.
2092                          *
2093                          * Relay log I/O thread does not select databases.
2094                          */
2095                         if ( $row->User == 'system user' && 
2096                                 $row->State != 'Waiting for master to send event' &&
2097                                 $row->State != 'Connecting to master' && 
2098                                 $row->State != 'Queueing master event to the relay log' &&
2099                                 $row->State != 'Waiting for master update' &&
2100                                 $row->State != 'Requesting binlog dump'
2101                                 ) {
2102                                 # This is it, return the time (except -ve)
2103                                 if ( $row->Time > 0x7fffffff ) {
2104                                         return false;
2105                                 } else {
2106                                         return $row->Time;
2107                                 }
2108                         }
2109                 }
2110                 return false;
2111         }
2112
2113         /**
2114          * Get status information from SHOW STATUS in an associative array
2115          */
2116         function getStatus($which="%") {
2117                 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2118                 $status = array();
2119                 while ( $row = $this->fetchObject( $res ) ) {
2120                         $status[$row->Variable_name] = $row->Value;
2121                 }
2122                 return $status;
2123         }
2124
2125         /**
2126          * Return the maximum number of items allowed in a list, or 0 for unlimited.
2127          */
2128         function maxListLen() {
2129                 return 0;
2130         }
2131
2132         function encodeBlob($b) {
2133                 return $b;
2134         }
2135
2136         function decodeBlob($b) {
2137                 return $b;
2138         }
2139
2140         /**
2141          * Override database's default connection timeout.
2142          * May be useful for very long batch queries such as
2143          * full-wiki dumps, where a single query reads out
2144          * over hours or days.
2145          * @param $timeout Integer in seconds
2146          */
2147         public function setTimeout( $timeout ) {
2148                 $this->query( "SET net_read_timeout=$timeout" );
2149                 $this->query( "SET net_write_timeout=$timeout" );
2150         }
2151
2152         /**
2153          * Read and execute SQL commands from a file.
2154          * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2155          * @param $filename String: File name to open
2156          * @param $lineCallback Callback: Optional function called before reading each line
2157          * @param $resultCallback Callback: Optional function called for each MySQL result
2158          */
2159         function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2160                 $fp = fopen( $filename, 'r' );
2161                 if ( false === $fp ) {
2162                         throw new MWException( "Could not open \"{$filename}\".\n" );
2163                 }
2164                 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2165                 fclose( $fp );
2166                 return $error;
2167         }
2168
2169         /**
2170          * Read and execute commands from an open file handle
2171          * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2172          * @param $fp String: File handle
2173          * @param $lineCallback Callback: Optional function called before reading each line
2174          * @param $resultCallback Callback: Optional function called for each MySQL result
2175          */
2176         function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2177                 $cmd = "";
2178                 $done = false;
2179                 $dollarquote = false;
2180
2181                 while ( ! feof( $fp ) ) {
2182                         if ( $lineCallback ) {
2183                                 call_user_func( $lineCallback );
2184                         }
2185                         $line = trim( fgets( $fp, 1024 ) );
2186                         $sl = strlen( $line ) - 1;
2187
2188                         if ( $sl < 0 ) { continue; }
2189                         if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2190
2191                         ## Allow dollar quoting for function declarations
2192                         if (substr($line,0,4) == '$mw$') {
2193                                 if ($dollarquote) {
2194                                         $dollarquote = false;
2195                                         $done = true;
2196                                 }
2197                                 else {
2198                                         $dollarquote = true;
2199                                 }
2200                         }
2201                         else if (!$dollarquote) {
2202                                 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2203                                         $done = true;
2204                                         $line = substr( $line, 0, $sl );
2205                                 }
2206                         }
2207
2208                         if ( '' != $cmd ) { $cmd .= ' '; }
2209                         $cmd .= "$line\n";
2210
2211                         if ( $done ) {
2212                                 $cmd = str_replace(';;', ";", $cmd);
2213                                 $cmd = $this->replaceVars( $cmd );
2214                                 $res = $this->query( $cmd, __METHOD__ );
2215                                 if ( $resultCallback ) {
2216                                         call_user_func( $resultCallback, $res, $this );
2217                                 }
2218
2219                                 if ( false === $res ) {
2220                                         $err = $this->lastError();
2221                                         return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2222                                 }
2223
2224                                 $cmd = '';
2225                                 $done = false;
2226                         }
2227                 }
2228                 return true;
2229         }
2230
2231
2232         /**
2233          * Replace variables in sourced SQL
2234          */
2235         protected function replaceVars( $ins ) {
2236                 $varnames = array(
2237                         'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2238                         'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2239                         'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2240                 );
2241
2242                 // Ordinary variables
2243                 foreach ( $varnames as $var ) {
2244                         if( isset( $GLOBALS[$var] ) ) {
2245                                 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2246                                 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2247                                 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2248                                 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2249                         }
2250                 }
2251
2252                 // Table prefixes
2253                 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-zA-Z_0-9]*)/',
2254                         array( &$this, 'tableNameCallback' ), $ins );
2255                 return $ins;
2256         }
2257
2258         /**
2259          * Table name callback
2260          * @private
2261          */
2262         protected function tableNameCallback( $matches ) {
2263                 return $this->tableName( $matches[1] );
2264         }
2265
2266         /*
2267          * Build a concatenation list to feed into a SQL query
2268         */
2269         function buildConcat( $stringList ) {
2270                 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2271         }
2272         
2273         /**
2274          * Acquire a lock
2275          * 
2276          * Abstracted from Filestore::lock() so child classes can implement for
2277          * their own needs.
2278          * 
2279          * @param $lockName String: Name of lock to aquire
2280          * @param $method String: Name of method calling us
2281          * @return bool
2282          */
2283         public function lock( $lockName, $method ) {
2284                 $lockName = $this->addQuotes( $lockName );
2285                 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2286                 $row = $this->fetchObject( $result );
2287                 $this->freeResult( $result );
2288
2289                 if( $row->lockstatus == 1 ) {
2290                         return true;
2291                 } else {
2292                         wfDebug( __METHOD__." failed to acquire lock\n" );
2293                         return false;
2294                 }
2295         }
2296         /**
2297          * Release a lock.
2298          * 
2299          * @todo fixme - Figure out a way to return a bool
2300          * based on successful lock release.
2301          * 
2302          * @param $lockName String: Name of lock to release
2303          * @param $method String: Name of method calling us
2304          */
2305         public function unlock( $lockName, $method ) {
2306                 $lockName = $this->addQuotes( $lockName );
2307                 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2308                 $this->freeResult( $result );
2309         }
2310         
2311         /**
2312          * Get search engine class. All subclasses of this
2313          * need to implement this if they wish to use searching.
2314          * 
2315          * @return String
2316          */
2317         public function getSearchEngine() {
2318                 return "SearchMySQL";
2319         }
2320 }
2321
2322 /**
2323  * Database abstraction object for mySQL
2324  * Inherit all methods and properties of Database::Database()
2325  *
2326  * @ingroup Database
2327  * @see Database
2328  */
2329 class DatabaseMysql extends Database {
2330         # Inherit all
2331 }
2332
2333 /******************************************************************************
2334  * Utility classes
2335  *****************************************************************************/
2336
2337 /**
2338  * Utility class.
2339  * @ingroup Database
2340  */
2341 class DBObject {
2342         public $mData;
2343
2344         function DBObject($data) {
2345                 $this->mData = $data;
2346         }
2347
2348         function isLOB() {
2349                 return false;
2350         }
2351
2352         function data() {
2353                 return $this->mData;
2354         }
2355 }
2356
2357 /**
2358  * Utility class
2359  * @ingroup Database
2360  *
2361  * This allows us to distinguish a blob from a normal string and an array of strings
2362  */
2363 class Blob {
2364         private $mData;
2365         function __construct($data) {
2366                 $this->mData = $data;
2367         }
2368         function fetch() {
2369                 return $this->mData;
2370         }
2371 }
2372
2373 /**
2374  * Utility class.
2375  * @ingroup Database
2376  */
2377 class MySQLField {
2378         private $name, $tablename, $default, $max_length, $nullable,
2379                 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2380         function __construct ($info) {
2381                 $this->name = $info->name;
2382                 $this->tablename = $info->table;
2383                 $this->default = $info->def;
2384                 $this->max_length = $info->max_length;
2385                 $this->nullable = !$info->not_null;
2386                 $this->is_pk = $info->primary_key;
2387                 $this->is_unique = $info->unique_key;
2388                 $this->is_multiple = $info->multiple_key;
2389                 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2390                 $this->type = $info->type;
2391         }
2392
2393         function name() {
2394                 return $this->name;
2395         }
2396
2397         function tableName() {
2398                 return $this->tableName;
2399         }
2400
2401         function defaultValue() {
2402                 return $this->default;
2403         }
2404
2405         function maxLength() {
2406                 return $this->max_length;
2407         }
2408
2409         function nullable() {
2410                 return $this->nullable;
2411         }
2412
2413         function isKey() {
2414                 return $this->is_key;
2415         }
2416
2417         function isMultipleKey() {
2418                 return $this->is_multiple;
2419         }
2420
2421         function type() {
2422                 return $this->type;
2423         }
2424 }
2425
2426 /******************************************************************************
2427  * Error classes
2428  *****************************************************************************/
2429
2430 /**
2431  * Database error base class
2432  * @ingroup Database
2433  */
2434 class DBError extends MWException {
2435         public $db;
2436
2437         /**
2438          * Construct a database error
2439          * @param $db Database object which threw the error
2440          * @param $error A simple error message to be used for debugging
2441          */
2442         function __construct( Database &$db, $error ) {
2443                 $this->db =& $db;
2444                 parent::__construct( $error );
2445         }
2446 }
2447
2448 /**
2449  * @ingroup Database
2450  */
2451 class DBConnectionError extends DBError {
2452         public $error;
2453         
2454         function __construct( Database &$db, $error = 'unknown error' ) {
2455                 $msg = 'DB connection error';
2456                 if ( trim( $error ) != '' ) {
2457                         $msg .= ": $error";
2458                 }
2459                 $this->error = $error;
2460                 parent::__construct( $db, $msg );
2461         }
2462
2463         function useOutputPage() {
2464                 // Not likely to work
2465                 return false;
2466         }
2467
2468         function useMessageCache() {
2469                 // Not likely to work
2470                 return false;
2471         }
2472         
2473         function getText() {
2474                 return $this->getMessage() . "\n";
2475         }
2476
2477         function getLogMessage() {
2478                 # Don't send to the exception log
2479                 return false;
2480         }
2481
2482         function getPageTitle() {
2483                 global $wgSitename;
2484                 return "$wgSitename has a problem";
2485         }
2486
2487         function getHTML() {
2488                 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2489                 global $wgSitename, $wgServer, $wgMessageCache;
2490
2491                 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2492                 # Hard coding strings instead.
2493
2494                 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
2495                 $mainpage = 'Main Page';
2496                 $searchdisabled = <<<EOT
2497 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2498 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2499 EOT;
2500
2501                 $googlesearch = "
2502 <!-- SiteSearch Google -->
2503 <FORM method=GET action=\"http://www.google.com/search\">
2504 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2505 <A HREF=\"http://www.google.com/\">
2506 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2507 border=\"0\" ALT=\"Google\"></A>
2508 </td>
2509 <td>
2510 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2511 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2512 <font size=-1>
2513 <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 />
2514 <input type='hidden' name='ie' value='$2'>
2515 <input type='hidden' name='oe' value='$2'>
2516 </font>
2517 </td></tr></TABLE>
2518 </FORM>
2519 <!-- SiteSearch Google -->";
2520                 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2521
2522                 # No database access
2523                 if ( is_object( $wgMessageCache ) ) {
2524                         $wgMessageCache->disable();
2525                 }
2526
2527                 if ( trim( $this->error ) == '' ) {
2528                         $this->error = $this->db->getProperty('mServer');
2529                 }
2530
2531                 $text = str_replace( '$1', $this->error, $noconnect );
2532
2533                 /*
2534                 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2535                         $text .= '</p><p>Backtrace:</p><p>' . 
2536                                 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) . 
2537                                 "</p>\n";
2538                 }*/
2539
2540                 if($wgUseFileCache) {
2541                         if($wgTitle) {
2542                                 $t =& $wgTitle;
2543                         } else {
2544                                 if($title) {
2545                                         $t = Title::newFromURL( $title );
2546                                 } elseif (@/**/$_REQUEST['search']) {
2547                                         $search = $_REQUEST['search'];
2548                                         return $searchdisabled .
2549                                           str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2550                                           $wgInputEncoding ), $googlesearch );
2551                                 } else {
2552                                         $t = Title::newFromText( $mainpage );
2553                                 }
2554                         }
2555
2556                         $cache = new HTMLFileCache( $t );
2557                         if( $cache->isFileCached() ) {
2558                                 // @todo, FIXME: $msg is not defined on the next line.
2559                                 $msg = '<p style="color: red"><b>'.$text."<br />\n" .
2560                                         $cachederror . "</b></p>\n";
2561
2562                                 $tag = '<div id="article">';
2563                                 $text = str_replace(
2564                                         $tag,
2565                                         $tag . $text,
2566                                         $cache->fetchPageText() );
2567                         }
2568                 }
2569
2570                 return $text;
2571         }
2572 }
2573
2574 /**
2575  * @ingroup Database
2576  */
2577 class DBQueryError extends DBError {
2578         public $error, $errno, $sql, $fname;
2579         
2580         function __construct( Database &$db, $error, $errno, $sql, $fname ) {
2581                 $message = "A database error has occurred\n" .
2582                   "Query: $sql\n" .
2583                   "Function: $fname\n" .
2584                   "Error: $errno $error\n";
2585
2586                 parent::__construct( $db, $message );
2587                 $this->error = $error;
2588                 $this->errno = $errno;
2589                 $this->sql = $sql;
2590                 $this->fname = $fname;
2591         }
2592
2593         function getText() {
2594                 if ( $this->useMessageCache() ) {
2595                         return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2596                           htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2597                 } else {
2598                         return $this->getMessage();
2599                 }
2600         }
2601         
2602         function getSQL() {
2603                 global $wgShowSQLErrors;
2604                 if( !$wgShowSQLErrors ) {
2605                         return $this->msg( 'sqlhidden', 'SQL hidden' );
2606                 } else {
2607                         return $this->sql;
2608                 }
2609         }
2610         
2611         function getLogMessage() {
2612                 # Don't send to the exception log
2613                 return false;
2614         }
2615
2616         function getPageTitle() {
2617                 return $this->msg( 'databaseerror', 'Database error' );
2618         }
2619
2620         function getHTML() {
2621                 if ( $this->useMessageCache() ) {
2622                         return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2623                           htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2624                 } else {
2625                         return nl2br( htmlspecialchars( $this->getMessage() ) );
2626                 }
2627         }
2628 }
2629
2630 /**
2631  * @ingroup Database
2632  */
2633 class DBUnexpectedError extends DBError {}
2634
2635
2636 /**
2637  * Result wrapper for grabbing data queried by someone else
2638  * @ingroup Database
2639  */
2640 class ResultWrapper implements Iterator {
2641         var $db, $result, $pos = 0, $currentRow = null;
2642
2643         /**
2644          * Create a new result object from a result resource and a Database object
2645          */
2646         function ResultWrapper( $database, $result ) {
2647                 $this->db = $database;
2648                 if ( $result instanceof ResultWrapper ) {
2649                         $this->result = $result->result;
2650                 } else {
2651                         $this->result = $result;
2652                 }
2653         }
2654
2655         /**
2656          * Get the number of rows in a result object
2657          */
2658         function numRows() {
2659                 return $this->db->numRows( $this->result );
2660         }
2661
2662         /**
2663          * Fetch the next row from the given result object, in object form.
2664          * Fields can be retrieved with $row->fieldname, with fields acting like
2665          * member variables.
2666          *
2667          * @param $res SQL result object as returned from Database::query(), etc.
2668          * @return MySQL row object
2669          * @throws DBUnexpectedError Thrown if the database returns an error
2670          */
2671         function fetchObject() {
2672                 return $this->db->fetchObject( $this->result );
2673         }
2674
2675         /**
2676          * Fetch the next row from the given result object, in associative array
2677          * form.  Fields are retrieved with $row['fieldname'].
2678          *
2679          * @param $res SQL result object as returned from Database::query(), etc.
2680          * @return MySQL row object
2681          * @throws DBUnexpectedError Thrown if the database returns an error
2682          */
2683         function fetchRow() {
2684                 return $this->db->fetchRow( $this->result );
2685         }
2686
2687         /**
2688          * Free a result object
2689          */
2690         function free() {
2691                 $this->db->freeResult( $this->result );
2692                 unset( $this->result );
2693                 unset( $this->db );
2694         }
2695
2696         /**
2697          * Change the position of the cursor in a result object
2698          * See mysql_data_seek()
2699          */
2700         function seek( $row ) {
2701                 $this->db->dataSeek( $this->result, $row );
2702         }
2703
2704         /*********************
2705          * Iterator functions
2706          * Note that using these in combination with the non-iterator functions
2707          * above may cause rows to be skipped or repeated.
2708          */
2709
2710         function rewind() {
2711                 if ($this->numRows()) {
2712                         $this->db->dataSeek($this->result, 0);
2713                 }
2714                 $this->pos = 0;
2715                 $this->currentRow = null;
2716         }
2717
2718         function current() {
2719                 if ( is_null( $this->currentRow ) ) {
2720                         $this->next();
2721                 }
2722                 return $this->currentRow;
2723         }
2724
2725         function key() {
2726                 return $this->pos;
2727         }
2728
2729         function next() {
2730                 $this->pos++;
2731                 $this->currentRow = $this->fetchObject();
2732                 return $this->currentRow;
2733         }
2734
2735         function valid() {
2736                 return $this->current() !== false;
2737         }
2738 }
2739
2740 class MySQLMasterPos {
2741         var $file, $pos;
2742
2743         function __construct( $file, $pos ) {
2744                 $this->file = $file;
2745                 $this->pos = $pos;
2746         }
2747
2748         function __toString() {
2749                 return "{$this->file}/{$this->pos}";
2750         }
2751 }