]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/db/Database.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.git] / includes / db / Database.php
1 <?php
2 /**
3  * @defgroup Database Database
4  *
5  * @file
6  * @ingroup Database
7  * This file deals with database 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  * Base interface for all DBMS-specific code. At a bare minimum, all of the
20  * following must be implemented to support MediaWiki
21  *
22  * @file
23  * @ingroup Database
24  */
25 interface DatabaseType {
26         /**
27          * Get the type of the DBMS, as it appears in $wgDBtype.
28          *
29          * @return string
30          */
31         public function getType();
32
33         /**
34          * Open a connection to the database. Usually aborts on failure
35          *
36          * @param $server String: database server host
37          * @param $user String: database user name
38          * @param $password String: database user password
39          * @param $dbName String: database name
40          * @return bool
41          * @throws DBConnectionError
42          */
43         public function open( $server, $user, $password, $dbName );
44
45         /**
46          * The DBMS-dependent part of query()
47          * @todo Fixme: Make this private someday
48          *
49          * @param  $sql String: SQL query.
50          * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
51          * @private
52          */
53         /*private*/ function doQuery( $sql );
54
55         /**
56          * Fetch the next row from the given result object, in object form.
57          * Fields can be retrieved with $row->fieldname, with fields acting like
58          * member variables.
59          *
60          * @param $res SQL result object as returned from DatabaseBase::query(), etc.
61          * @return Row object
62          * @throws DBUnexpectedError Thrown if the database returns an error
63          */
64         public function fetchObject( $res );
65
66         /**
67          * Fetch the next row from the given result object, in associative array
68          * form.  Fields are retrieved with $row['fieldname'].
69          *
70          * @param $res SQL result object as returned from DatabaseBase::query(), etc.
71          * @return Row object
72          * @throws DBUnexpectedError Thrown if the database returns an error
73          */
74         public function fetchRow( $res );
75
76         /**
77          * Get the number of rows in a result object
78          *
79          * @param $res Mixed: A SQL result
80          * @return int
81          */
82         public function numRows( $res );
83
84         /**
85          * Get the number of fields in a result object
86          * @see http://www.php.net/mysql_num_fields
87          *
88          * @param $res Mixed: A SQL result
89          * @return int
90          */
91         public function numFields( $res );
92
93         /**
94          * Get a field name in a result object
95          * @see http://www.php.net/mysql_field_name
96          *
97          * @param $res Mixed: A SQL result
98          * @param $n Integer
99          * @return string
100          */
101         public function fieldName( $res, $n );
102
103         /**
104          * Get the inserted value of an auto-increment row
105          *
106          * The value inserted should be fetched from nextSequenceValue()
107          *
108          * Example:
109          * $id = $dbw->nextSequenceValue('page_page_id_seq');
110          * $dbw->insert('page',array('page_id' => $id));
111          * $id = $dbw->insertId();
112          *
113          * @return int
114          */
115         public function insertId();
116
117         /**
118          * Change the position of the cursor in a result object
119          * @see http://www.php.net/mysql_data_seek
120          *
121          * @param $res Mixed: A SQL result
122          * @param $row Mixed: Either MySQL row or ResultWrapper
123          */
124         public function dataSeek( $res, $row );
125
126         /**
127          * Get the last error number
128          * @see http://www.php.net/mysql_errno
129          *
130          * @return int
131          */
132         public function lastErrno();
133
134         /**
135          * Get a description of the last error
136          * @see http://www.php.net/mysql_error
137          *
138          * @return string
139          */
140         public function lastError();
141
142         /**
143          * mysql_fetch_field() wrapper
144          * Returns false if the field doesn't exist
145          *
146          * @param $table string: table name
147          * @param $field string: field name
148          */
149         public function fieldInfo( $table, $field );
150
151         /**
152          * Get information about an index into an object
153          * @param $table string: Table name
154          * @param $index string: Index name
155          * @param $fname string: Calling function name
156          * @return Mixed: Database-specific index description class or false if the index does not exist
157          */
158         function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
159
160         /**
161          * Get the number of rows affected by the last write query
162          * @see http://www.php.net/mysql_affected_rows
163          *
164          * @return int
165          */
166         public function affectedRows();
167
168         /**
169          * Wrapper for addslashes()
170          *
171          * @param $s string: to be slashed.
172          * @return string: slashed string.
173          */
174         public function strencode( $s );
175
176         /**
177          * Returns a wikitext link to the DB's website, e.g.,
178          *     return "[http://www.mysql.com/ MySQL]";
179          * Should at least contain plain text, if for some reason
180          * your database has no website.
181          *
182          * @return string: wikitext of a link to the server software's web site
183          */
184         public static function getSoftwareLink();
185
186         /**
187          * A string describing the current software version, like from
188          * mysql_get_server_info().
189          *
190          * @return string: Version information from the database server.
191          */
192         public function getServerVersion();
193
194         /**
195          * A string describing the current software version, and possibly
196          * other details in a user-friendly way.  Will be listed on Special:Version, etc.
197          * Use getServerVersion() to get machine-friendly information.
198          *
199          * @return string: Version information from the database server
200          */
201         public function getServerInfo();
202 }
203
204 /**
205  * Database abstraction object
206  * @ingroup Database
207  */
208 abstract class DatabaseBase implements DatabaseType {
209
210 # ------------------------------------------------------------------------------
211 # Variables
212 # ------------------------------------------------------------------------------
213
214         protected $mLastQuery = '';
215         protected $mDoneWrites = false;
216         protected $mPHPError = false;
217
218         protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
219         protected $mOpened = false;
220
221         protected $mTablePrefix;
222         protected $mFlags;
223         protected $mTrxLevel = 0;
224         protected $mErrorCount = 0;
225         protected $mLBInfo = array();
226         protected $mFakeSlaveLag = null, $mFakeMaster = false;
227         protected $mDefaultBigSelects = null;
228         protected $mSchemaVars = false;
229
230 # ------------------------------------------------------------------------------
231 # Accessors
232 # ------------------------------------------------------------------------------
233         # These optionally set a variable and return the previous state
234
235         /**
236          * A string describing the current software version, and possibly
237          * other details in a user-friendly way.  Will be listed on Special:Version, etc.
238          * Use getServerVersion() to get machine-friendly information.
239          *
240          * @return string: Version information from the database server
241          */
242         public function getServerInfo() {
243                 return $this->getServerVersion();
244         }
245
246         /**
247          * Boolean, controls output of large amounts of debug information
248          */
249         function debug( $debug = null ) {
250                 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
251         }
252
253         /**
254          * Turns buffering of SQL result sets on (true) or off (false).
255          * Default is "on" and it should not be changed without good reasons.
256          */
257         function bufferResults( $buffer = null ) {
258                 if ( is_null( $buffer ) ) {
259                         return !(bool)( $this->mFlags & DBO_NOBUFFER );
260                 } else {
261                         return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
262                 }
263         }
264
265         /**
266          * Turns on (false) or off (true) the automatic generation and sending
267          * of a "we're sorry, but there has been a database error" page on
268          * database errors. Default is on (false). When turned off, the
269          * code should use lastErrno() and lastError() to handle the
270          * situation as appropriate.
271          */
272         function ignoreErrors( $ignoreErrors = null ) {
273                 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
274         }
275
276         /**
277          * The current depth of nested transactions
278          * @param $level Integer: , default NULL.
279          */
280         function trxLevel( $level = null ) {
281                 return wfSetVar( $this->mTrxLevel, $level );
282         }
283
284         /**
285          * Number of errors logged, only useful when errors are ignored
286          */
287         function errorCount( $count = null ) {
288                 return wfSetVar( $this->mErrorCount, $count );
289         }
290
291         function tablePrefix( $prefix = null ) {
292                 return wfSetVar( $this->mTablePrefix, $prefix );
293         }
294
295         /**
296          * Properties passed down from the server info array of the load balancer
297          */
298         function getLBInfo( $name = null ) {
299                 if ( is_null( $name ) ) {
300                         return $this->mLBInfo;
301                 } else {
302                         if ( array_key_exists( $name, $this->mLBInfo ) ) {
303                                 return $this->mLBInfo[$name];
304                         } else {
305                                 return null;
306                         }
307                 }
308         }
309
310         function setLBInfo( $name, $value = null ) {
311                 if ( is_null( $value ) ) {
312                         $this->mLBInfo = $name;
313                 } else {
314                         $this->mLBInfo[$name] = $value;
315                 }
316         }
317
318         /**
319          * Set lag time in seconds for a fake slave
320          */
321         function setFakeSlaveLag( $lag ) {
322                 $this->mFakeSlaveLag = $lag;
323         }
324
325         /**
326          * Make this connection a fake master
327          */
328         function setFakeMaster( $enabled = true ) {
329                 $this->mFakeMaster = $enabled;
330         }
331
332         /**
333          * Returns true if this database supports (and uses) cascading deletes
334          */
335         function cascadingDeletes() {
336                 return false;
337         }
338
339         /**
340          * Returns true if this database supports (and uses) triggers (e.g. on the page table)
341          */
342         function cleanupTriggers() {
343                 return false;
344         }
345
346         /**
347          * Returns true if this database is strict about what can be put into an IP field.
348          * Specifically, it uses a NULL value instead of an empty string.
349          */
350         function strictIPs() {
351                 return false;
352         }
353
354         /**
355          * Returns true if this database uses timestamps rather than integers
356         */
357         function realTimestamps() {
358                 return false;
359         }
360
361         /**
362          * Returns true if this database does an implicit sort when doing GROUP BY
363          */
364         function implicitGroupby() {
365                 return true;
366         }
367
368         /**
369          * Returns true if this database does an implicit order by when the column has an index
370          * For example: SELECT page_title FROM page LIMIT 1
371          */
372         function implicitOrderby() {
373                 return true;
374         }
375
376         /**
377          * Returns true if this database requires that SELECT DISTINCT queries require that all
378            ORDER BY expressions occur in the SELECT list per the SQL92 standard
379          */
380         function standardSelectDistinct() {
381                 return true;
382         }
383
384         /**
385          * Returns true if this database can do a native search on IP columns
386          * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
387          */
388         function searchableIPs() {
389                 return false;
390         }
391
392         /**
393          * Returns true if this database can use functional indexes
394          */
395         function functionalIndexes() {
396                 return false;
397         }
398
399         /**
400          * Return the last query that went through DatabaseBase::query()
401          * @return String
402          */
403         function lastQuery() { return $this->mLastQuery; }
404
405
406         /**
407          * Returns true if the connection may have been used for write queries.
408          * Should return true if unsure.
409          */
410         function doneWrites() { return $this->mDoneWrites; }
411
412         /**
413          * Is a connection to the database open?
414          * @return Boolean
415          */
416         function isOpen() { return $this->mOpened; }
417
418         /**
419          * Set a flag for this connection
420          *
421          * @param $flag Integer: DBO_* constants from Defines.php:
422          *   - DBO_DEBUG: output some debug info (same as debug())
423          *   - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
424          *   - DBO_IGNORE: ignore errors (same as ignoreErrors())
425          *   - DBO_TRX: automatically start transactions
426          *   - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
427          *       and removes it in command line mode
428          *   - DBO_PERSISTENT: use persistant database connection
429          */
430         function setFlag( $flag ) {
431                 $this->mFlags |= $flag;
432         }
433
434         /**
435          * Clear a flag for this connection
436          *
437          * @param $flag: same as setFlag()'s $flag param
438          */
439         function clearFlag( $flag ) {
440                 $this->mFlags &= ~$flag;
441         }
442
443         /**
444          * Returns a boolean whether the flag $flag is set for this connection
445          *
446          * @param $flag: same as setFlag()'s $flag param
447          * @return Boolean
448          */
449         function getFlag( $flag ) {
450                 return !!( $this->mFlags & $flag );
451         }
452
453         /**
454          * General read-only accessor
455          */
456         function getProperty( $name ) {
457                 return $this->$name;
458         }
459
460         function getWikiID() {
461                 if ( $this->mTablePrefix ) {
462                         return "{$this->mDBname}-{$this->mTablePrefix}";
463                 } else {
464                         return $this->mDBname;
465                 }
466         }
467
468         /**
469          * Return a path to the DBMS-specific schema, otherwise default to tables.sql
470          */
471         public function getSchema() {
472                 global $IP;
473                 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
474                         return "$IP/maintenance/" . $this->getType() . "/tables.sql";
475                 } else {
476                         return "$IP/maintenance/tables.sql";
477                 }
478         }
479
480 # ------------------------------------------------------------------------------
481 # Other functions
482 # ------------------------------------------------------------------------------
483
484         /**
485          * Constructor.
486          * @param $server String: database server host
487          * @param $user String: database user name
488          * @param $password String: database user password
489          * @param $dbName String: database name
490          * @param $flags
491          * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
492          */
493         function __construct( $server = false, $user = false, $password = false, $dbName = false,
494                 $flags = 0, $tablePrefix = 'get from global'
495         ) {
496                 global $wgOut, $wgDBprefix, $wgCommandLineMode;
497
498                 # Can't get a reference if it hasn't been set yet
499                 if ( !isset( $wgOut ) ) {
500                         $wgOut = null;
501                 }
502                 $this->mFlags = $flags;
503
504                 if ( $this->mFlags & DBO_DEFAULT ) {
505                         if ( $wgCommandLineMode ) {
506                                 $this->mFlags &= ~DBO_TRX;
507                         } else {
508                                 $this->mFlags |= DBO_TRX;
509                         }
510                 }
511
512                 /*
513                 // Faster read-only access
514                 if ( wfReadOnly() ) {
515                         $this->mFlags |= DBO_PERSISTENT;
516                         $this->mFlags &= ~DBO_TRX;
517                 }*/
518
519                 /** Get the default table prefix*/
520                 if ( $tablePrefix == 'get from global' ) {
521                         $this->mTablePrefix = $wgDBprefix;
522                 } else {
523                         $this->mTablePrefix = $tablePrefix;
524                 }
525
526                 if ( $server ) {
527                         $this->open( $server, $user, $password, $dbName );
528                 }
529         }
530
531         /**
532          * Same as new DatabaseMysql( ... ), kept for backward compatibility
533          * @deprecated
534          */
535         static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
536                 wfDeprecated( __METHOD__ );
537                 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
538         }
539
540         /**
541          * Given a DB type, construct the name of the appropriate child class of
542          * DatabaseBase. This is designed to replace all of the manual stuff like:
543          *      $class = 'Database' . ucfirst( strtolower( $type ) );
544          * as well as validate against the canonical list of DB types we have
545          *
546          * This factory function is mostly useful for when you need to connect to a
547          * database other than the MediaWiki default (such as for external auth,
548          * an extension, et cetera). Do not use this to connect to the MediaWiki
549          * database. Example uses in core:
550          * @see LoadBalancer::reallyOpenConnection()
551          * @see ExternalUser_MediaWiki::initFromCond()
552          * @see ForeignDBRepo::getMasterDB()
553          * @see WebInstaller_DBConnect::execute()
554          *
555          * @param $dbType String A possible DB type
556          * @param $p Array An array of options to pass to the constructor.
557          *    Valid options are: host, user, password, dbname, flags, tableprefix
558          * @return DatabaseBase subclass or null
559          */
560         public final static function newFromType( $dbType, $p = array() ) {
561                 $canonicalDBTypes = array(
562                         'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
563                 );
564                 $dbType = strtolower( $dbType );
565
566                 if( in_array( $dbType, $canonicalDBTypes ) ) {
567                         $class = 'Database' . ucfirst( $dbType );
568                         return new $class(
569                                 isset( $p['host'] ) ? $p['host'] : false,
570                                 isset( $p['user'] ) ? $p['user'] : false,
571                                 isset( $p['password'] ) ? $p['password'] : false,
572                                 isset( $p['dbname'] ) ? $p['dbname'] : false,
573                                 isset( $p['flags'] ) ? $p['flags'] : 0,
574                                 isset( $p['tableprefix'] ) ? $p['tableprefix'] : 'get from global'
575                         );
576                 } else {
577                         return null;
578                 }
579         }
580
581         protected function installErrorHandler() {
582                 $this->mPHPError = false;
583                 $this->htmlErrors = ini_set( 'html_errors', '0' );
584                 set_error_handler( array( $this, 'connectionErrorHandler' ) );
585         }
586
587         protected function restoreErrorHandler() {
588                 restore_error_handler();
589                 if ( $this->htmlErrors !== false ) {
590                         ini_set( 'html_errors', $this->htmlErrors );
591                 }
592                 if ( $this->mPHPError ) {
593                         $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
594                         $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
595                         return $error;
596                 } else {
597                         return false;
598                 }
599         }
600
601         protected function connectionErrorHandler( $errno,  $errstr ) {
602                 $this->mPHPError = $errstr;
603         }
604
605         /**
606          * Closes a database connection.
607          * if it is open : commits any open transactions
608          *
609          * @return Bool operation success. true if already closed.
610          */
611         function close() {
612                 # Stub, should probably be overridden
613                 return true;
614         }
615
616         /**
617          * @param $error String: fallback error message, used if none is given by DB
618          */
619         function reportConnectionError( $error = 'Unknown error' ) {
620                 $myError = $this->lastError();
621                 if ( $myError ) {
622                         $error = $myError;
623                 }
624
625                 # New method
626                 throw new DBConnectionError( $this, $error );
627         }
628
629         /**
630          * Determine whether a query writes to the DB.
631          * Should return true if unsure.
632          */
633         function isWriteQuery( $sql ) {
634                 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
635         }
636
637         /**
638          * Usually aborts on failure.  If errors are explicitly ignored, returns success.
639          *
640          * @param  $sql        String: SQL query
641          * @param  $fname      String: Name of the calling function, for profiling/SHOW PROCESSLIST
642          *     comment (you can use __METHOD__ or add some extra info)
643          * @param  $tempIgnore Boolean:   Whether to avoid throwing an exception on errors...
644          *     maybe best to catch the exception instead?
645          * @return boolean or ResultWrapper. true for a successful write query, ResultWrapper object for a successful read query,
646          *     or false on failure if $tempIgnore set
647          * @throws DBQueryError Thrown when the database returns an error of any kind
648          */
649         public function query( $sql, $fname = '', $tempIgnore = false ) {
650                 global $wgProfiler;
651
652                 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
653                 if ( isset( $wgProfiler ) ) {
654                         # generalizeSQL will probably cut down the query to reasonable
655                         # logging size most of the time. The substr is really just a sanity check.
656
657                         # Who's been wasting my precious column space? -- TS
658                         # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
659
660                         if ( $isMaster ) {
661                                 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
662                                 $totalProf = 'DatabaseBase::query-master';
663                         } else {
664                                 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
665                                 $totalProf = 'DatabaseBase::query';
666                         }
667
668                         wfProfileIn( $totalProf );
669                         wfProfileIn( $queryProf );
670                 }
671
672                 $this->mLastQuery = $sql;
673                 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
674                         // Set a flag indicating that writes have been done
675                         wfDebug( __METHOD__ . ": Writes done: $sql\n" );
676                         $this->mDoneWrites = true;
677                 }
678
679                 # Add a comment for easy SHOW PROCESSLIST interpretation
680                 # if ( $fname ) {
681                         global $wgUser;
682                         if ( is_object( $wgUser ) && $wgUser->mDataLoaded ) {
683                                 $userName = $wgUser->getName();
684                                 if ( mb_strlen( $userName ) > 15 ) {
685                                         $userName = mb_substr( $userName, 0, 15 ) . '...';
686                                 }
687                                 $userName = str_replace( '/', '', $userName );
688                         } else {
689                                 $userName = '';
690                         }
691                         $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
692                 # } else {
693                 #       $commentedSql = $sql;
694                 # }
695
696                 # If DBO_TRX is set, start a transaction
697                 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
698                         $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
699                         // avoid establishing transactions for SHOW and SET statements too -
700                         // that would delay transaction initializations to once connection
701                         // is really used by application
702                         $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
703                         if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
704                                 $this->begin();
705                 }
706
707                 if ( $this->debug() ) {
708                         static $cnt = 0;
709
710                         $cnt++;
711                         $sqlx = substr( $commentedSql, 0, 500 );
712                         $sqlx = strtr( $sqlx, "\t\n", '  ' );
713
714                         if ( $isMaster ) {
715                                 wfDebug( "Query $cnt (master): $sqlx\n" );
716                         } else {
717                                 wfDebug( "Query $cnt (slave): $sqlx\n" );
718                         }
719                 }
720
721                 if ( istainted( $sql ) & TC_MYSQL ) {
722                         throw new MWException( 'Tainted query found' );
723                 }
724
725                 # Do the query and handle errors
726                 $ret = $this->doQuery( $commentedSql );
727
728                 # Try reconnecting if the connection was lost
729                 if ( false === $ret && $this->wasErrorReissuable() ) {
730                         # Transaction is gone, like it or not
731                         $this->mTrxLevel = 0;
732                         wfDebug( "Connection lost, reconnecting...\n" );
733
734                         if ( $this->ping() ) {
735                                 wfDebug( "Reconnected\n" );
736                                 $sqlx = substr( $commentedSql, 0, 500 );
737                                 $sqlx = strtr( $sqlx, "\t\n", '  ' );
738                                 global $wgRequestTime;
739                                 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
740                                 if ( $elapsed < 300 ) {
741                                         # Not a database error to lose a transaction after a minute or two
742                                         wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
743                                 }
744                                 $ret = $this->doQuery( $commentedSql );
745                         } else {
746                                 wfDebug( "Failed\n" );
747                         }
748                 }
749
750                 if ( false === $ret ) {
751                         $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
752                 }
753
754                 if ( isset( $wgProfiler ) ) {
755                         wfProfileOut( $queryProf );
756                         wfProfileOut( $totalProf );
757                 }
758
759                 return $this->resultObject( $ret );
760         }
761
762         /**
763          * @param $error String
764          * @param $errno Integer
765          * @param $sql String
766          * @param $fname String
767          * @param $tempIgnore Boolean
768          */
769         function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
770                 # Ignore errors during error handling to avoid infinite recursion
771                 $ignore = $this->ignoreErrors( true );
772                 ++$this->mErrorCount;
773
774                 if ( $ignore || $tempIgnore ) {
775                         wfDebug( "SQL ERROR (ignored): $error\n" );
776                         $this->ignoreErrors( $ignore );
777                 } else {
778                         $sql1line = str_replace( "\n", "\\n", $sql );
779                         wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
780                         wfDebug( "SQL ERROR: " . $error . "\n" );
781                         throw new DBQueryError( $this, $error, $errno, $sql, $fname );
782                 }
783         }
784
785
786         /**
787          * Intended to be compatible with the PEAR::DB wrapper functions.
788          * http://pear.php.net/manual/en/package.database.db.intro-execute.php
789          *
790          * ? = scalar value, quoted as necessary
791          * ! = raw SQL bit (a function for instance)
792          * & = filename; reads the file and inserts as a blob
793          *     (we don't use this though...)
794          */
795         function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
796                 /* MySQL doesn't support prepared statements (yet), so just
797                    pack up the query for reference. We'll manually replace
798                    the bits later. */
799                 return array( 'query' => $sql, 'func' => $func );
800         }
801
802         function freePrepared( $prepared ) {
803                 /* No-op by default */
804         }
805
806         /**
807          * Execute a prepared query with the various arguments
808          * @param $prepared String: the prepared sql
809          * @param $args Mixed: Either an array here, or put scalars as varargs
810          */
811         function execute( $prepared, $args = null ) {
812                 if ( !is_array( $args ) ) {
813                         # Pull the var args
814                         $args = func_get_args();
815                         array_shift( $args );
816                 }
817
818                 $sql = $this->fillPrepared( $prepared['query'], $args );
819
820                 return $this->query( $sql, $prepared['func'] );
821         }
822
823         /**
824          * Prepare & execute an SQL statement, quoting and inserting arguments
825          * in the appropriate places.
826          * @param $query String
827          * @param $args ...
828          */
829         function safeQuery( $query, $args = null ) {
830                 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
831
832                 if ( !is_array( $args ) ) {
833                         # Pull the var args
834                         $args = func_get_args();
835                         array_shift( $args );
836                 }
837
838                 $retval = $this->execute( $prepared, $args );
839                 $this->freePrepared( $prepared );
840
841                 return $retval;
842         }
843
844         /**
845          * For faking prepared SQL statements on DBs that don't support
846          * it directly.
847          * @param $preparedQuery String: a 'preparable' SQL statement
848          * @param $args Array of arguments to fill it with
849          * @return string executable SQL
850          */
851         function fillPrepared( $preparedQuery, $args ) {
852                 reset( $args );
853                 $this->preparedArgs =& $args;
854
855                 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
856                         array( &$this, 'fillPreparedArg' ), $preparedQuery );
857         }
858
859         /**
860          * preg_callback func for fillPrepared()
861          * The arguments should be in $this->preparedArgs and must not be touched
862          * while we're doing this.
863          *
864          * @param $matches Array
865          * @return String
866          * @private
867          */
868         function fillPreparedArg( $matches ) {
869                 switch( $matches[1] ) {
870                         case '\\?': return '?';
871                         case '\\!': return '!';
872                         case '\\&': return '&';
873                 }
874
875                 list( /* $n */ , $arg ) = each( $this->preparedArgs );
876
877                 switch( $matches[1] ) {
878                         case '?': return $this->addQuotes( $arg );
879                         case '!': return $arg;
880                         case '&':
881                                 # return $this->addQuotes( file_get_contents( $arg ) );
882                                 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
883                         default:
884                                 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
885                 }
886         }
887
888         /**
889          * Free a result object
890          * @param $res Mixed: A SQL result
891          */
892         function freeResult( $res ) {
893                 # Stub.  Might not really need to be overridden, since results should
894                 # be freed by PHP when the variable goes out of scope anyway.
895         }
896
897         /**
898          * Simple UPDATE wrapper
899          * Usually aborts on failure
900          * If errors are explicitly ignored, returns success
901          *
902          * This function exists for historical reasons, DatabaseBase::update() has a more standard
903          * calling convention and feature set
904          */
905         function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
906                 $table = $this->tableName( $table );
907                 $sql = "UPDATE $table SET $var = '" .
908                   $this->strencode( $value ) . "' WHERE ($cond)";
909
910                 return (bool)$this->query( $sql, $fname );
911         }
912
913         /**
914          * Simple SELECT wrapper, returns a single field, input must be encoded
915          * Usually aborts on failure
916          * If errors are explicitly ignored, returns FALSE on failure
917          */
918         function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
919                 if ( !is_array( $options ) ) {
920                         $options = array( $options );
921                 }
922
923                 $options['LIMIT'] = 1;
924
925                 $res = $this->select( $table, $var, $cond, $fname, $options );
926
927                 if ( $res === false || !$this->numRows( $res ) ) {
928                         return false;
929                 }
930
931                 $row = $this->fetchRow( $res );
932
933                 if ( $row !== false ) {
934                         return reset( $row );
935                 } else {
936                         return false;
937                 }
938         }
939
940         /**
941          * Returns an optional USE INDEX clause to go after the table, and a
942          * string to go at the end of the query
943          *
944          * @private
945          *
946          * @param $options Array: associative array of options to be turned into
947          *              an SQL query, valid keys are listed in the function.
948          * @return Array
949          */
950         function makeSelectOptions( $options ) {
951                 $preLimitTail = $postLimitTail = '';
952                 $startOpts = '';
953
954                 $noKeyOptions = array();
955
956                 foreach ( $options as $key => $option ) {
957                         if ( is_numeric( $key ) ) {
958                                 $noKeyOptions[$option] = true;
959                         }
960                 }
961
962                 if ( isset( $options['GROUP BY'] ) ) {
963                         $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
964                 }
965
966                 if ( isset( $options['HAVING'] ) ) {
967                         $preLimitTail .= " HAVING {$options['HAVING']}";
968                 }
969
970                 if ( isset( $options['ORDER BY'] ) ) {
971                         $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
972                 }
973
974                 // if (isset($options['LIMIT'])) {
975                 //      $tailOpts .= $this->limitResult('', $options['LIMIT'],
976                 //              isset($options['OFFSET']) ? $options['OFFSET']
977                 //              : false);
978                 // }
979
980                 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
981                         $postLimitTail .= ' FOR UPDATE';
982                 }
983
984                 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
985                         $postLimitTail .= ' LOCK IN SHARE MODE';
986                 }
987
988                 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
989                         $startOpts .= 'DISTINCT';
990                 }
991
992                 # Various MySQL extensions
993                 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
994                         $startOpts .= ' /*! STRAIGHT_JOIN */';
995                 }
996
997                 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
998                         $startOpts .= ' HIGH_PRIORITY';
999                 }
1000
1001                 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1002                         $startOpts .= ' SQL_BIG_RESULT';
1003                 }
1004
1005                 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1006                         $startOpts .= ' SQL_BUFFER_RESULT';
1007                 }
1008
1009                 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1010                         $startOpts .= ' SQL_SMALL_RESULT';
1011                 }
1012
1013                 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1014                         $startOpts .= ' SQL_CALC_FOUND_ROWS';
1015                 }
1016
1017                 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1018                         $startOpts .= ' SQL_CACHE';
1019                 }
1020
1021                 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1022                         $startOpts .= ' SQL_NO_CACHE';
1023                 }
1024
1025                 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1026                         $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1027                 } else {
1028                         $useIndex = '';
1029                 }
1030
1031                 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1032         }
1033
1034         /**
1035          * SELECT wrapper
1036          *
1037          * @param $table   Mixed:  Array or string, table name(s) (prefix auto-added)
1038          * @param $vars    Mixed:  Array or string, field name(s) to be retrieved
1039          * @param $conds   Mixed:  Array or string, condition(s) for WHERE
1040          * @param $fname   String: Calling function name (use __METHOD__) for logs/profiling
1041          * @param $options Array:  Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1042          *                         see DatabaseBase::makeSelectOptions code for list of supported stuff
1043          * @param $join_conds Array: Associative array of table join conditions (optional)
1044          *                           (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1045          * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
1046          */
1047         function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1048                 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1049
1050                 return $this->query( $sql, $fname );
1051         }
1052
1053         /**
1054          * SELECT wrapper
1055          *
1056          * @param $table   Mixed:  Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1057          * @param $vars    Mixed:  Array or string, field name(s) to be retrieved
1058          * @param $conds   Mixed:  Array or string, condition(s) for WHERE
1059          * @param $fname   String: Calling function name (use __METHOD__) for logs/profiling
1060          * @param $options Array:  Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1061          *                         see DatabaseBase::makeSelectOptions code for list of supported stuff
1062          * @param $join_conds Array: Associative array of table join conditions (optional)
1063          *                           (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1064          * @return string, the SQL text
1065          */
1066         function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1067                 if ( is_array( $vars ) ) {
1068                         $vars = implode( ',', $vars );
1069                 }
1070
1071                 if ( !is_array( $options ) ) {
1072                         $options = array( $options );
1073                 }
1074
1075                 if ( is_array( $table ) ) {
1076                         if ( !empty( $join_conds ) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1077                                 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1078                         } else {
1079                                 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1080                         }
1081                 } elseif ( $table != '' ) {
1082                         if ( $table { 0 } == ' ' ) {
1083                                 $from = ' FROM ' . $table;
1084                         } else {
1085                                 $from = ' FROM ' . $this->tableName( $table );
1086                         }
1087                 } else {
1088                         $from = '';
1089                 }
1090
1091                 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1092
1093                 if ( !empty( $conds ) ) {
1094                         if ( is_array( $conds ) ) {
1095                                 $conds = $this->makeList( $conds, LIST_AND );
1096                         }
1097                         $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1098                 } else {
1099                         $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1100                 }
1101
1102                 if ( isset( $options['LIMIT'] ) )
1103                         $sql = $this->limitResult( $sql, $options['LIMIT'],
1104                                 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1105                 $sql = "$sql $postLimitTail";
1106
1107                 if ( isset( $options['EXPLAIN'] ) ) {
1108                         $sql = 'EXPLAIN ' . $sql;
1109                 }
1110
1111                 return $sql;
1112         }
1113
1114         /**
1115          * Single row SELECT wrapper
1116          * Aborts or returns FALSE on error
1117          *
1118          * @param $table String: table name
1119          * @param $vars String: the selected variables
1120          * @param $conds Array: a condition map, terms are ANDed together.
1121          *   Items with numeric keys are taken to be literal conditions
1122          * Takes an array of selected variables, and a condition map, which is ANDed
1123          * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1124          * NS_MAIN, "page_title" => "Astronomy" ) )   would return an object where
1125          * $obj- >page_id is the ID of the Astronomy article
1126          * @param $fname String: Calling function name
1127          * @param $options Array
1128          * @param $join_conds Array
1129          *
1130          * @todo migrate documentation to phpdocumentor format
1131          */
1132         function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1133                 $options['LIMIT'] = 1;
1134                 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1135
1136                 if ( $res === false ) {
1137                         return false;
1138                 }
1139
1140                 if ( !$this->numRows( $res ) ) {
1141                         return false;
1142                 }
1143
1144                 $obj = $this->fetchObject( $res );
1145
1146                 return $obj;
1147         }
1148
1149         /**
1150          * Estimate rows in dataset
1151          * Returns estimated count - not necessarily an accurate estimate across different databases,
1152          * so use sparingly
1153          * Takes same arguments as DatabaseBase::select()
1154          *
1155          * @param $table String: table name
1156          * @param $vars Array: unused
1157          * @param $conds Array: filters on the table
1158          * @param $fname String: function name for profiling
1159          * @param $options Array: options for select
1160          * @return Integer: row count
1161          */
1162         public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1163                 $rows = 0;
1164                 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1165
1166                 if ( $res ) {
1167                         $row = $this->fetchRow( $res );
1168                         $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1169                 }
1170
1171                 return $rows;
1172         }
1173
1174         /**
1175          * Removes most variables from an SQL query and replaces them with X or N for numbers.
1176          * It's only slightly flawed. Don't use for anything important.
1177          *
1178          * @param $sql String: A SQL Query
1179          */
1180         static function generalizeSQL( $sql ) {
1181                 # This does the same as the regexp below would do, but in such a way
1182                 # as to avoid crashing php on some large strings.
1183                 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1184
1185                 $sql = str_replace ( "\\\\", '', $sql );
1186                 $sql = str_replace ( "\\'", '', $sql );
1187                 $sql = str_replace ( "\\\"", '', $sql );
1188                 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1189                 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1190
1191                 # All newlines, tabs, etc replaced by single space
1192                 $sql = preg_replace ( '/\s+/', ' ', $sql );
1193
1194                 # All numbers => N
1195                 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1196
1197                 return $sql;
1198         }
1199
1200         /**
1201          * Determines whether a field exists in a table
1202          *
1203          * @param $table String: table name
1204          * @param $field String: filed to check on that table
1205          * @param $fname String: calling function name (optional)
1206          * @return Boolean: whether $table has filed $field
1207          */
1208         function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1209                 $info = $this->fieldInfo( $table, $field );
1210
1211                 return (bool)$info;
1212         }
1213
1214         /**
1215          * Determines whether an index exists
1216          * Usually aborts on failure
1217          * If errors are explicitly ignored, returns NULL on failure
1218          */
1219         function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1220                 $info = $this->indexInfo( $table, $index, $fname );
1221                 if ( is_null( $info ) ) {
1222                         return null;
1223                 } else {
1224                         return $info !== false;
1225                 }
1226         }
1227
1228         /**
1229          * Query whether a given table exists
1230          */
1231         function tableExists( $table ) {
1232                 $table = $this->tableName( $table );
1233                 $old = $this->ignoreErrors( true );
1234                 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__ );
1235                 $this->ignoreErrors( $old );
1236
1237                 return (bool)$res;
1238         }
1239
1240         /**
1241          * mysql_field_type() wrapper
1242          */
1243         function fieldType( $res, $index ) {
1244                 if ( $res instanceof ResultWrapper ) {
1245                         $res = $res->result;
1246                 }
1247
1248                 return mysql_field_type( $res, $index );
1249         }
1250
1251         /**
1252          * Determines if a given index is unique
1253          */
1254         function indexUnique( $table, $index ) {
1255                 $indexInfo = $this->indexInfo( $table, $index );
1256
1257                 if ( !$indexInfo ) {
1258                         return null;
1259                 }
1260
1261                 return !$indexInfo[0]->Non_unique;
1262         }
1263
1264         /**
1265          * INSERT wrapper, inserts an array into a table
1266          *
1267          * $a may be a single associative array, or an array of these with numeric keys, for
1268          * multi-row insert.
1269          *
1270          * Usually aborts on failure
1271          * If errors are explicitly ignored, returns success
1272          *
1273          * @param $table   String: table name (prefix auto-added)
1274          * @param $a       Array: Array of rows to insert
1275          * @param $fname   String: Calling function name (use __METHOD__) for logs/profiling
1276          * @param $options Mixed: Associative array of options
1277          *
1278          * @return bool
1279          */
1280         function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1281                 # No rows to insert, easy just return now
1282                 if ( !count( $a ) ) {
1283                         return true;
1284                 }
1285
1286                 $table = $this->tableName( $table );
1287
1288                 if ( !is_array( $options ) ) {
1289                         $options = array( $options );
1290                 }
1291
1292                 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1293                         $multi = true;
1294                         $keys = array_keys( $a[0] );
1295                 } else {
1296                         $multi = false;
1297                         $keys = array_keys( $a );
1298                 }
1299
1300                 $sql = 'INSERT ' . implode( ' ', $options ) .
1301                         " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1302
1303                 if ( $multi ) {
1304                         $first = true;
1305                         foreach ( $a as $row ) {
1306                                 if ( $first ) {
1307                                         $first = false;
1308                                 } else {
1309                                         $sql .= ',';
1310                                 }
1311                                 $sql .= '(' . $this->makeList( $row ) . ')';
1312                         }
1313                 } else {
1314                         $sql .= '(' . $this->makeList( $a ) . ')';
1315                 }
1316
1317                 return (bool)$this->query( $sql, $fname );
1318         }
1319
1320         /**
1321          * Make UPDATE options for the DatabaseBase::update function
1322          *
1323          * @private
1324          * @param $options Array: The options passed to DatabaseBase::update
1325          * @return string
1326          */
1327         function makeUpdateOptions( $options ) {
1328                 if ( !is_array( $options ) ) {
1329                         $options = array( $options );
1330                 }
1331
1332                 $opts = array();
1333
1334                 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1335                         $opts[] = $this->lowPriorityOption();
1336                 }
1337
1338                 if ( in_array( 'IGNORE', $options ) ) {
1339                         $opts[] = 'IGNORE';
1340                 }
1341
1342                 return implode( ' ', $opts );
1343         }
1344
1345         /**
1346          * UPDATE wrapper, takes a condition array and a SET array
1347          *
1348          * @param $table  String: The table to UPDATE
1349          * @param $values Array:  An array of values to SET
1350          * @param $conds  Array:  An array of conditions (WHERE). Use '*' to update all rows.
1351          * @param $fname  String: The Class::Function calling this function
1352          *                        (for the log)
1353          * @param $options Array: An array of UPDATE options, can be one or
1354          *                        more of IGNORE, LOW_PRIORITY
1355          * @return Boolean
1356          */
1357         function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1358                 $table = $this->tableName( $table );
1359                 $opts = $this->makeUpdateOptions( $options );
1360                 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1361
1362                 if ( $conds != '*' ) {
1363                         $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1364                 }
1365
1366                 return $this->query( $sql, $fname );
1367         }
1368
1369         /**
1370          * Makes an encoded list of strings from an array
1371          * $mode:
1372          *        LIST_COMMA         - comma separated, no field names
1373          *        LIST_AND           - ANDed WHERE clause (without the WHERE)
1374          *        LIST_OR            - ORed WHERE clause (without the WHERE)
1375          *        LIST_SET           - comma separated with field names, like a SET clause
1376          *        LIST_NAMES         - comma separated field names
1377          */
1378         function makeList( $a, $mode = LIST_COMMA ) {
1379                 if ( !is_array( $a ) ) {
1380                         throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1381                 }
1382
1383                 $first = true;
1384                 $list = '';
1385
1386                 foreach ( $a as $field => $value ) {
1387                         if ( !$first ) {
1388                                 if ( $mode == LIST_AND ) {
1389                                         $list .= ' AND ';
1390                                 } elseif ( $mode == LIST_OR ) {
1391                                         $list .= ' OR ';
1392                                 } else {
1393                                         $list .= ',';
1394                                 }
1395                         } else {
1396                                 $first = false;
1397                         }
1398
1399                         if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1400                                 $list .= "($value)";
1401                         } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1402                                 $list .= "$value";
1403                         } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1404                                 if ( count( $value ) == 0 ) {
1405                                         throw new MWException( __METHOD__ . ': empty input' );
1406                                 } elseif ( count( $value ) == 1 ) {
1407                                         // Special-case single values, as IN isn't terribly efficient
1408                                         // Don't necessarily assume the single key is 0; we don't
1409                                         // enforce linear numeric ordering on other arrays here.
1410                                         $value = array_values( $value );
1411                                         $list .= $field . " = " . $this->addQuotes( $value[0] );
1412                                 } else {
1413                                         $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1414                                 }
1415                         } elseif ( $value === null ) {
1416                                 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1417                                         $list .= "$field IS ";
1418                                 } elseif ( $mode == LIST_SET ) {
1419                                         $list .= "$field = ";
1420                                 }
1421                                 $list .= 'NULL';
1422                         } else {
1423                                 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1424                                         $list .= "$field = ";
1425                                 }
1426                                 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1427                         }
1428                 }
1429
1430                 return $list;
1431         }
1432
1433         /**
1434          * Build a partial where clause from a 2-d array such as used for LinkBatch.
1435          * The keys on each level may be either integers or strings.
1436          *
1437          * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1438          * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1439          * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1440          * @return Mixed: string SQL fragment, or false if no items in array.
1441          */
1442         function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1443                 $conds = array();
1444
1445                 foreach ( $data as $base => $sub ) {
1446                         if ( count( $sub ) ) {
1447                                 $conds[] = $this->makeList(
1448                                         array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1449                                         LIST_AND );
1450                         }
1451                 }
1452
1453                 if ( $conds ) {
1454                         return $this->makeList( $conds, LIST_OR );
1455                 } else {
1456                         // Nothing to search for...
1457                         return false;
1458                 }
1459         }
1460
1461         /**
1462          * Bitwise operations
1463          */
1464
1465         function bitNot( $field ) {
1466                 return "(~$field)";
1467         }
1468
1469         function bitAnd( $fieldLeft, $fieldRight ) {
1470                 return "($fieldLeft & $fieldRight)";
1471         }
1472
1473         function bitOr( $fieldLeft, $fieldRight ) {
1474                 return "($fieldLeft | $fieldRight)";
1475         }
1476
1477         /**
1478          * Change the current database
1479          *
1480          * @todo Explain what exactly will fail if this is not overridden.
1481          * @return bool Success or failure
1482          */
1483         function selectDB( $db ) {
1484                 # Stub.  Shouldn't cause serious problems if it's not overridden, but
1485                 # if your database engine supports a concept similar to MySQL's
1486                 # databases you may as well.
1487                 return true;
1488         }
1489
1490         /**
1491          * Get the current DB name
1492          */
1493         function getDBname() {
1494                 return $this->mDBname;
1495         }
1496
1497         /**
1498          * Get the server hostname or IP address
1499          */
1500         function getServer() {
1501                 return $this->mServer;
1502         }
1503
1504         /**
1505          * Format a table name ready for use in constructing an SQL query
1506          *
1507          * This does two important things: it quotes the table names to clean them up,
1508          * and it adds a table prefix if only given a table name with no quotes.
1509          *
1510          * All functions of this object which require a table name call this function
1511          * themselves. Pass the canonical name to such functions. This is only needed
1512          * when calling query() directly.
1513          *
1514          * @param $name String: database table name
1515          * @return String: full database name
1516          */
1517         function tableName( $name ) {
1518                 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1519                 # Skip the entire process when we have a string quoted on both ends.
1520                 # Note that we check the end so that we will still quote any use of
1521                 # use of `database`.table. But won't break things if someone wants
1522                 # to query a database table with a dot in the name.
1523                 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1524                         return $name;
1525                 }
1526
1527                 # Lets test for any bits of text that should never show up in a table
1528                 # name. Basically anything like JOIN or ON which are actually part of
1529                 # SQL queries, but may end up inside of the table value to combine
1530                 # sql. Such as how the API is doing.
1531                 # Note that we use a whitespace test rather than a \b test to avoid
1532                 # any remote case where a word like on may be inside of a table name
1533                 # surrounded by symbols which may be considered word breaks.
1534                 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1535                         return $name;
1536                 }
1537
1538                 # Split database and table into proper variables.
1539                 # We reverse the explode so that database.table and table both output
1540                 # the correct table.
1541                 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1542                 if ( isset( $dbDetails[1] ) ) {
1543                         @list( $table, $database ) = $dbDetails;
1544                 } else {
1545                         @list( $table ) = $dbDetails;
1546                 }
1547                 $prefix = $this->mTablePrefix; # Default prefix
1548
1549                 # A database name has been specified in input. Quote the table name
1550                 # because we don't want any prefixes added.
1551                 if ( isset( $database ) ) {
1552                         $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1553                 }
1554
1555                 # Note that we use the long format because php will complain in in_array if
1556                 # the input is not an array, and will complain in is_array if it is not set.
1557                 if ( !isset( $database ) # Don't use shared database if pre selected.
1558                  && isset( $wgSharedDB ) # We have a shared database
1559                  && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1560                  && isset( $wgSharedTables )
1561                  && is_array( $wgSharedTables )
1562                  && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1563                         $database = $wgSharedDB;
1564                         $prefix   = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1565                 }
1566
1567                 # Quote the $database and $table and apply the prefix if not quoted.
1568                 if ( isset( $database ) ) {
1569                         $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1570                 }
1571                 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1572
1573                 # Merge our database and table into our final table name.
1574                 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
1575
1576                 return $tableName;
1577         }
1578
1579         /**
1580          * Fetch a number of table names into an array
1581          * This is handy when you need to construct SQL for joins
1582          *
1583          * Example:
1584          * extract($dbr->tableNames('user','watchlist'));
1585          * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1586          *         WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1587          */
1588         public function tableNames() {
1589                 $inArray = func_get_args();
1590                 $retVal = array();
1591
1592                 foreach ( $inArray as $name ) {
1593                         $retVal[$name] = $this->tableName( $name );
1594                 }
1595
1596                 return $retVal;
1597         }
1598
1599         /**
1600          * Fetch a number of table names into an zero-indexed numerical array
1601          * This is handy when you need to construct SQL for joins
1602          *
1603          * Example:
1604          * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1605          * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1606          *         WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1607          */
1608         public function tableNamesN() {
1609                 $inArray = func_get_args();
1610                 $retVal = array();
1611
1612                 foreach ( $inArray as $name ) {
1613                         $retVal[] = $this->tableName( $name );
1614                 }
1615
1616                 return $retVal;
1617         }
1618
1619         /**
1620          * Get an aliased table name
1621          * e.g. tableName AS newTableName
1622          *
1623          * @param $name string Table name, see tableName()
1624          * @param $alias string Alias (optional)
1625          * @return string SQL name for aliased table. Will not alias a table to its own name
1626          */
1627         public function tableNameWithAlias( $name, $alias = false ) {
1628                 if ( !$alias || $alias == $name ) {
1629                         return $this->tableName( $name );
1630                 } else {
1631                         return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1632                 }
1633         }
1634
1635         /**
1636          * Gets an array of aliased table names
1637          *
1638          * @param $tables array( [alias] => table )
1639          * @return array of strings, see tableNameWithAlias()
1640          */
1641         public function tableNamesWithAlias( $tables ) {
1642                 $retval = array();
1643                 foreach ( $tables as $alias => $table ) {
1644                         if ( is_numeric( $alias ) ) {
1645                                 $alias = $table;
1646                         }
1647                         $retval[] = $this->tableNameWithAlias( $table, $alias );
1648                 }
1649                 return $retval;
1650         }
1651
1652         /**
1653          * @private
1654          */
1655         function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1656                 $ret = array();
1657                 $retJOIN = array();
1658                 $use_index_safe = is_array( $use_index ) ? $use_index : array();
1659                 $join_conds_safe = is_array( $join_conds ) ? $join_conds : array();
1660
1661                 foreach ( $tables as $alias => $table ) {
1662                         if ( !is_string( $alias ) ) {
1663                                 // No alias? Set it equal to the table name
1664                                 $alias = $table;
1665                         }
1666                         // Is there a JOIN and INDEX clause for this table?
1667                         if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1668                                 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1669                                 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1670                                 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND );
1671                                 if ( $on != '' ) {
1672                                         $tableClause .= ' ON (' . $on . ')';
1673                                 }
1674
1675                                 $retJOIN[] = $tableClause;
1676                         // Is there an INDEX clause?
1677                         } else if ( isset( $use_index_safe[$alias] ) ) {
1678                                 $tableClause = $this->tableNameWithAlias( $table, $alias );
1679                                 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1680                                 $ret[] = $tableClause;
1681                         // Is there a JOIN clause?
1682                         } else if ( isset( $join_conds_safe[$alias] ) ) {
1683                                 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1684                                 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND );
1685                                 if ( $on != '' ) {
1686                                         $tableClause .= ' ON (' . $on . ')';
1687                                 }
1688
1689                                 $retJOIN[] = $tableClause;
1690                         } else {
1691                                 $tableClause = $this->tableNameWithAlias( $table, $alias );
1692                                 $ret[] = $tableClause;
1693                         }
1694                 }
1695
1696                 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1697                 $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1698                 $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1699
1700                 // Compile our final table clause
1701                 return implode( ' ', array( $straightJoins, $otherJoins ) );
1702         }
1703
1704         /**
1705          * Get the name of an index in a given table
1706          */
1707         function indexName( $index ) {
1708                 // Backwards-compatibility hack
1709                 $renamed = array(
1710                         'ar_usertext_timestamp' => 'usertext_timestamp',
1711                         'un_user_id'            => 'user_id',
1712                         'un_user_ip'            => 'user_ip',
1713                 );
1714
1715                 if ( isset( $renamed[$index] ) ) {
1716                         return $renamed[$index];
1717                 } else {
1718                         return $index;
1719                 }
1720         }
1721
1722         /**
1723          * If it's a string, adds quotes and backslashes
1724          * Otherwise returns as-is
1725          */
1726         function addQuotes( $s ) {
1727                 if ( $s === null ) {
1728                         return 'NULL';
1729                 } else {
1730                         # This will also quote numeric values. This should be harmless,
1731                         # and protects against weird problems that occur when they really
1732                         # _are_ strings such as article titles and string->number->string
1733                         # conversion is not 1:1.
1734                         return "'" . $this->strencode( $s ) . "'";
1735                 }
1736         }
1737
1738         /**
1739          * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1740          * MySQL uses `backticks` while basically everything else uses double quotes.
1741          * Since MySQL is the odd one out here the double quotes are our generic
1742          * and we implement backticks in DatabaseMysql.
1743          */      
1744         public function addIdentifierQuotes( $s ) {
1745                 return '"' . str_replace( '"', '""', $s ) . '"';
1746         }
1747
1748         /**
1749          * Backwards compatibility, identifier quoting originated in DatabasePostgres
1750          * which used quote_ident which does not follow our naming conventions
1751          * was renamed to addIdentifierQuotes.
1752          * @deprecated use addIdentifierQuotes
1753          */
1754         function quote_ident( $s ) {
1755                 wfDeprecated( __METHOD__ );
1756                 return $this->addIdentifierQuotes( $s );
1757         }
1758
1759         /**
1760          * Escape string for safe LIKE usage.
1761          * WARNING: you should almost never use this function directly,
1762          * instead use buildLike() that escapes everything automatically
1763          * Deprecated in 1.17, warnings in 1.17, removed in ???
1764          */
1765         public function escapeLike( $s ) {
1766                 wfDeprecated( __METHOD__ );
1767                 return $this->escapeLikeInternal( $s );
1768         }
1769
1770         protected function escapeLikeInternal( $s ) {
1771                 $s = str_replace( '\\', '\\\\', $s );
1772                 $s = $this->strencode( $s );
1773                 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1774
1775                 return $s;
1776         }
1777
1778         /**
1779          * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1780          * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1781          * Alternatively, the function could be provided with an array of aforementioned parameters.
1782          *
1783          * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1784          * for subpages of 'My page title'.
1785          * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1786          *
1787          * @since 1.16
1788          * @return String: fully built LIKE statement
1789          */
1790         function buildLike() {
1791                 $params = func_get_args();
1792
1793                 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1794                         $params = $params[0];
1795                 }
1796
1797                 $s = '';
1798
1799                 foreach ( $params as $value ) {
1800                         if ( $value instanceof LikeMatch ) {
1801                                 $s .= $value->toString();
1802                         } else {
1803                                 $s .= $this->escapeLikeInternal( $value );
1804                         }
1805                 }
1806
1807                 return " LIKE '" . $s . "' ";
1808         }
1809
1810         /**
1811          * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1812          */
1813         function anyChar() {
1814                 return new LikeMatch( '_' );
1815         }
1816
1817         /**
1818          * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1819          */
1820         function anyString() {
1821                 return new LikeMatch( '%' );
1822         }
1823
1824         /**
1825          * Returns an appropriately quoted sequence value for inserting a new row.
1826          * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1827          * subclass will return an integer, and save the value for insertId()
1828          */
1829         function nextSequenceValue( $seqName ) {
1830                 return null;
1831         }
1832
1833         /**
1834          * USE INDEX clause.  Unlikely to be useful for anything but MySQL.  This
1835          * is only needed because a) MySQL must be as efficient as possible due to
1836          * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1837          * which index to pick.  Anyway, other databases might have different
1838          * indexes on a given table.  So don't bother overriding this unless you're
1839          * MySQL.
1840          */
1841         function useIndexClause( $index ) {
1842                 return '';
1843         }
1844
1845         /**
1846          * REPLACE query wrapper
1847          * PostgreSQL simulates this with a DELETE followed by INSERT
1848          * $row is the row to insert, an associative array
1849          * $uniqueIndexes is an array of indexes. Each element may be either a
1850          * field name or an array of field names
1851          *
1852          * It may be more efficient to leave off unique indexes which are unlikely to collide.
1853          * However if you do this, you run the risk of encountering errors which wouldn't have
1854          * occurred in MySQL
1855          *
1856          * @param $table String: The table to replace the row(s) in.
1857          * @param $uniqueIndexes Array: An associative array of indexes
1858          * @param $rows Array: Array of rows to replace
1859          * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1860          */
1861         function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1862                 $table = $this->tableName( $table );
1863
1864                 # Single row case
1865                 if ( !is_array( reset( $rows ) ) ) {
1866                         $rows = array( $rows );
1867                 }
1868
1869                 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1870                 $first = true;
1871
1872                 foreach ( $rows as $row ) {
1873                         if ( $first ) {
1874                                 $first = false;
1875                         } else {
1876                                 $sql .= ',';
1877                         }
1878
1879                         $sql .= '(' . $this->makeList( $row ) . ')';
1880                 }
1881
1882                 return $this->query( $sql, $fname );
1883         }
1884
1885         /**
1886          * DELETE where the condition is a join
1887          * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1888          *
1889          * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1890          * join condition matches, set $conds='*'
1891          *
1892          * DO NOT put the join condition in $conds
1893          *
1894          * @param $delTable String: The table to delete from.
1895          * @param $joinTable String: The other table.
1896          * @param $delVar String: The variable to join on, in the first table.
1897          * @param $joinVar String: The variable to join on, in the second table.
1898          * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1899          * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1900          */
1901         function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1902                 if ( !$conds ) {
1903                         throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1904                 }
1905
1906                 $delTable = $this->tableName( $delTable );
1907                 $joinTable = $this->tableName( $joinTable );
1908                 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1909
1910                 if ( $conds != '*' ) {
1911                         $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1912                 }
1913
1914                 return $this->query( $sql, $fname );
1915         }
1916
1917         /**
1918          * Returns the size of a text field, or -1 for "unlimited"
1919          */
1920         function textFieldSize( $table, $field ) {
1921                 $table = $this->tableName( $table );
1922                 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1923                 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1924                 $row = $this->fetchObject( $res );
1925
1926                 $m = array();
1927
1928                 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1929                         $size = $m[1];
1930                 } else {
1931                         $size = -1;
1932                 }
1933
1934                 return $size;
1935         }
1936
1937         /**
1938          * A string to insert into queries to show that they're low-priority, like
1939          * MySQL's LOW_PRIORITY.  If no such feature exists, return an empty
1940          * string and nothing bad should happen.
1941          *
1942          * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1943          */
1944         function lowPriorityOption() {
1945                 return '';
1946         }
1947
1948         /**
1949          * DELETE query wrapper
1950          *
1951          * Use $conds == "*" to delete all rows
1952          */
1953         function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1954                 if ( !$conds ) {
1955                         throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1956                 }
1957
1958                 $table = $this->tableName( $table );
1959                 $sql = "DELETE FROM $table";
1960
1961                 if ( $conds != '*' ) {
1962                         $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1963                 }
1964
1965                 return $this->query( $sql, $fname );
1966         }
1967
1968         /**
1969          * INSERT SELECT wrapper
1970          * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1971          * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1972          * $conds may be "*" to copy the whole table
1973          * srcTable may be an array of tables.
1974          */
1975         function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1976                 $insertOptions = array(), $selectOptions = array() )
1977         {
1978                 $destTable = $this->tableName( $destTable );
1979
1980                 if ( is_array( $insertOptions ) ) {
1981                         $insertOptions = implode( ' ', $insertOptions );
1982                 }
1983
1984                 if ( !is_array( $selectOptions ) ) {
1985                         $selectOptions = array( $selectOptions );
1986                 }
1987
1988                 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1989
1990                 if ( is_array( $srcTable ) ) {
1991                         $srcTable =  implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1992                 } else {
1993                         $srcTable = $this->tableName( $srcTable );
1994                 }
1995
1996                 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1997                         " SELECT $startOpts " . implode( ',', $varMap ) .
1998                         " FROM $srcTable $useIndex ";
1999
2000                 if ( $conds != '*' ) {
2001                         $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
2002                 }
2003
2004                 $sql .= " $tailOpts";
2005
2006                 return $this->query( $sql, $fname );
2007         }
2008
2009         /**
2010          * Construct a LIMIT query with optional offset.  This is used for query
2011          * pages.  The SQL should be adjusted so that only the first $limit rows
2012          * are returned.  If $offset is provided as well, then the first $offset
2013          * rows should be discarded, and the next $limit rows should be returned.
2014          * If the result of the query is not ordered, then the rows to be returned
2015          * are theoretically arbitrary.
2016          *
2017          * $sql is expected to be a SELECT, if that makes a difference.  For
2018          * UPDATE, limitResultForUpdate should be used.
2019          *
2020          * The version provided by default works in MySQL and SQLite.  It will very
2021          * likely need to be overridden for most other DBMSes.
2022          *
2023          * @param $sql String: SQL query we will append the limit too
2024          * @param $limit Integer: the SQL limit
2025          * @param $offset Integer the SQL offset (default false)
2026          */
2027         function limitResult( $sql, $limit, $offset = false ) {
2028                 if ( !is_numeric( $limit ) ) {
2029                         throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2030                 }
2031
2032                 return "$sql LIMIT "
2033                                 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2034                                 . "{$limit} ";
2035         }
2036
2037         function limitResultForUpdate( $sql, $num ) {
2038                 return $this->limitResult( $sql, $num, 0 );
2039         }
2040
2041         /**
2042          * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2043          * within the UNION construct.
2044          * @return Boolean
2045          */
2046         function unionSupportsOrderAndLimit() {
2047                 return true; // True for almost every DB supported
2048         }
2049
2050         /**
2051          * Construct a UNION query
2052          * This is used for providing overload point for other DB abstractions
2053          * not compatible with the MySQL syntax.
2054          * @param $sqls Array: SQL statements to combine
2055          * @param $all Boolean: use UNION ALL
2056          * @return String: SQL fragment
2057          */
2058         function unionQueries( $sqls, $all ) {
2059                 $glue = $all ? ') UNION ALL (' : ') UNION (';
2060                 return '(' . implode( $glue, $sqls ) . ')';
2061         }
2062
2063         /**
2064          * Returns an SQL expression for a simple conditional.  This doesn't need
2065          * to be overridden unless CASE isn't supported in your DBMS.
2066          *
2067          * @param $cond String: SQL expression which will result in a boolean value
2068          * @param $trueVal String: SQL expression to return if true
2069          * @param $falseVal String: SQL expression to return if false
2070          * @return String: SQL fragment
2071          */
2072         function conditional( $cond, $trueVal, $falseVal ) {
2073                 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2074         }
2075
2076         /**
2077          * Returns a comand for str_replace function in SQL query.
2078          * Uses REPLACE() in MySQL
2079          *
2080          * @param $orig String: column to modify
2081          * @param $old String: column to seek
2082          * @param $new String: column to replace with
2083          */
2084         function strreplace( $orig, $old, $new ) {
2085                 return "REPLACE({$orig}, {$old}, {$new})";
2086         }
2087
2088         /**
2089          * Convert a field to an unix timestamp
2090          *
2091          * @param $field String: field name
2092          * @return String: SQL statement
2093          */
2094         public function unixTimestamp( $field ) {
2095                 return "EXTRACT(epoch FROM $field)";
2096         }
2097
2098         /**
2099          * Determines if the last failure was due to a deadlock
2100          * STUB
2101          */
2102         function wasDeadlock() {
2103                 return false;
2104         }
2105
2106         /**
2107          * Determines if the last query error was something that should be dealt
2108          * with by pinging the connection and reissuing the query.
2109          * STUB
2110          */
2111         function wasErrorReissuable() {
2112                 return false;
2113         }
2114
2115         /**
2116          * Determines if the last failure was due to the database being read-only.
2117          * STUB
2118          */
2119         function wasReadOnlyError() {
2120                 return false;
2121         }
2122
2123         /**
2124          * Perform a deadlock-prone transaction.
2125          *
2126          * This function invokes a callback function to perform a set of write
2127          * queries. If a deadlock occurs during the processing, the transaction
2128          * will be rolled back and the callback function will be called again.
2129          *
2130          * Usage:
2131          *   $dbw->deadlockLoop( callback, ... );
2132          *
2133          * Extra arguments are passed through to the specified callback function.
2134          *
2135          * Returns whatever the callback function returned on its successful,
2136          * iteration, or false on error, for example if the retry limit was
2137          * reached.
2138          */
2139         function deadlockLoop() {
2140                 $myFname = 'DatabaseBase::deadlockLoop';
2141
2142                 $this->begin();
2143                 $args = func_get_args();
2144                 $function = array_shift( $args );
2145                 $oldIgnore = $this->ignoreErrors( true );
2146                 $tries = DEADLOCK_TRIES;
2147
2148                 if ( is_array( $function ) ) {
2149                         $fname = $function[0];
2150                 } else {
2151                         $fname = $function;
2152                 }
2153
2154                 do {
2155                         $retVal = call_user_func_array( $function, $args );
2156                         $error = $this->lastError();
2157                         $errno = $this->lastErrno();
2158                         $sql = $this->lastQuery();
2159
2160                         if ( $errno ) {
2161                                 if ( $this->wasDeadlock() ) {
2162                                         # Retry
2163                                         usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
2164                                 } else {
2165                                         $this->reportQueryError( $error, $errno, $sql, $fname );
2166                                 }
2167                         }
2168                 } while ( $this->wasDeadlock() && --$tries > 0 );
2169
2170                 $this->ignoreErrors( $oldIgnore );
2171
2172                 if ( $tries <= 0 ) {
2173                         $this->rollback( $myFname );
2174                         $this->reportQueryError( $error, $errno, $sql, $fname );
2175                         return false;
2176                 } else {
2177                         $this->commit( $myFname );
2178                         return $retVal;
2179                 }
2180         }
2181
2182         /**
2183          * Do a SELECT MASTER_POS_WAIT()
2184          *
2185          * @param $pos MySQLMasterPos object
2186          * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2187          */
2188         function masterPosWait( MySQLMasterPos $pos, $timeout ) {
2189                 $fname = 'DatabaseBase::masterPosWait';
2190                 wfProfileIn( $fname );
2191
2192                 # Commit any open transactions
2193                 if ( $this->mTrxLevel ) {
2194                         $this->commit();
2195                 }
2196
2197                 if ( !is_null( $this->mFakeSlaveLag ) ) {
2198                         $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
2199
2200                         if ( $wait > $timeout * 1e6 ) {
2201                                 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2202                                 wfProfileOut( $fname );
2203                                 return -1;
2204                         } elseif ( $wait > 0 ) {
2205                                 wfDebug( "Fake slave waiting $wait us\n" );
2206                                 usleep( $wait );
2207                                 wfProfileOut( $fname );
2208                                 return 1;
2209                         } else {
2210                                 wfDebug( "Fake slave up to date ($wait us)\n" );
2211                                 wfProfileOut( $fname );
2212                                 return 0;
2213                         }
2214                 }
2215
2216                 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2217                 $encFile = $this->addQuotes( $pos->file );
2218                 $encPos = intval( $pos->pos );
2219                 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2220                 $res = $this->doQuery( $sql );
2221
2222                 if ( $res && $row = $this->fetchRow( $res ) ) {
2223                         wfProfileOut( $fname );
2224                         return $row[0];
2225                 } else {
2226                         wfProfileOut( $fname );
2227                         return false;
2228                 }
2229         }
2230
2231         /**
2232          * Get the position of the master from SHOW SLAVE STATUS
2233          */
2234         function getSlavePos() {
2235                 if ( !is_null( $this->mFakeSlaveLag ) ) {
2236                         $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
2237                         wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
2238                         return $pos;
2239                 }
2240
2241                 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2242                 $row = $this->fetchObject( $res );
2243
2244                 if ( $row ) {
2245                         $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
2246                         return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
2247                 } else {
2248                         return false;
2249                 }
2250         }
2251
2252         /**
2253          * Get the position of the master from SHOW MASTER STATUS
2254          */
2255         function getMasterPos() {
2256                 if ( $this->mFakeMaster ) {
2257                         return new MySQLMasterPos( 'fake', microtime( true ) );
2258                 }
2259
2260                 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2261                 $row = $this->fetchObject( $res );
2262
2263                 if ( $row ) {
2264                         return new MySQLMasterPos( $row->File, $row->Position );
2265                 } else {
2266                         return false;
2267                 }
2268         }
2269
2270         /**
2271          * Begin a transaction, committing any previously open transaction
2272          */
2273         function begin( $fname = 'DatabaseBase::begin' ) {
2274                 $this->query( 'BEGIN', $fname );
2275                 $this->mTrxLevel = 1;
2276         }
2277
2278         /**
2279          * End a transaction
2280          */
2281         function commit( $fname = 'DatabaseBase::commit' ) {
2282                 if ( $this->mTrxLevel ) {
2283                         $this->query( 'COMMIT', $fname );
2284                         $this->mTrxLevel = 0;
2285                 }
2286         }
2287
2288         /**
2289          * Rollback a transaction.
2290          * No-op on non-transactional databases.
2291          */
2292         function rollback( $fname = 'DatabaseBase::rollback' ) {
2293                 if ( $this->mTrxLevel ) {
2294                         $this->query( 'ROLLBACK', $fname, true );
2295                         $this->mTrxLevel = 0;
2296                 }
2297         }
2298
2299         /**
2300          * Begin a transaction, committing any previously open transaction
2301          * @deprecated use begin()
2302          */
2303         function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2304                 wfDeprecated( __METHOD__ );
2305                 $this->begin();
2306         }
2307
2308         /**
2309          * Commit transaction, if one is open
2310          * @deprecated use commit()
2311          */
2312         function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2313                 wfDeprecated( __METHOD__ );
2314                 $this->commit();
2315         }
2316
2317         /**
2318          * Creates a new table with structure copied from existing table
2319          * Note that unlike most database abstraction functions, this function does not
2320          * automatically append database prefix, because it works at a lower
2321          * abstraction level.
2322          *
2323          * @param $oldName String: name of table whose structure should be copied
2324          * @param $newName String: name of table to be created
2325          * @param $temporary Boolean: whether the new table should be temporary
2326          * @param $fname String: calling function name
2327          * @return Boolean: true if operation was successful
2328          */
2329         function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2330                 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2331         }
2332
2333         /**
2334          * Return MW-style timestamp used for MySQL schema
2335          */
2336         function timestamp( $ts = 0 ) {
2337                 return wfTimestamp( TS_MW, $ts );
2338         }
2339
2340         /**
2341          * Local database timestamp format or null
2342          */
2343         function timestampOrNull( $ts = null ) {
2344                 if ( is_null( $ts ) ) {
2345                         return null;
2346                 } else {
2347                         return $this->timestamp( $ts );
2348                 }
2349         }
2350
2351         /**
2352          * @todo document
2353          */
2354         function resultObject( $result ) {
2355                 if ( empty( $result ) ) {
2356                         return false;
2357                 } elseif ( $result instanceof ResultWrapper ) {
2358                         return $result;
2359                 } elseif ( $result === true ) {
2360                         // Successful write query
2361                         return $result;
2362                 } else {
2363                         return new ResultWrapper( $this, $result );
2364                 }
2365         }
2366
2367         /**
2368          * Return aggregated value alias
2369          */
2370         function aggregateValue ( $valuedata, $valuename = 'value' ) {
2371                 return $valuename;
2372         }
2373
2374         /**
2375          * Ping the server and try to reconnect if it there is no connection
2376          *
2377          * @return bool Success or failure
2378          */
2379         function ping() {
2380                 # Stub.  Not essential to override.
2381                 return true;
2382         }
2383
2384         /**
2385          * Get slave lag.
2386          * Currently supported only by MySQL
2387          * @return Database replication lag in seconds
2388          */
2389         function getLag() {
2390                 return intval( $this->mFakeSlaveLag );
2391         }
2392
2393         /**
2394          * Get status information from SHOW STATUS in an associative array
2395          */
2396         function getStatus( $which = "%" ) {
2397                 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2398                 $status = array();
2399
2400                 foreach ( $res as $row ) {
2401                         $status[$row->Variable_name] = $row->Value;
2402                 }
2403
2404                 return $status;
2405         }
2406
2407         /**
2408          * Return the maximum number of items allowed in a list, or 0 for unlimited.
2409          */
2410         function maxListLen() {
2411                 return 0;
2412         }
2413
2414         function encodeBlob( $b ) {
2415                 return $b;
2416         }
2417
2418         function decodeBlob( $b ) {
2419                 return $b;
2420         }
2421
2422         /**
2423          * Override database's default connection timeout.  May be useful for very
2424          * long batch queries such as full-wiki dumps, where a single query reads
2425          * out over hours or days.  May or may not be necessary for non-MySQL
2426          * databases.  For most purposes, leaving it as a no-op should be fine.
2427          *
2428          * @param $timeout Integer in seconds
2429          */
2430         public function setTimeout( $timeout ) {}
2431
2432         /**
2433          * Read and execute SQL commands from a file.
2434          * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2435          * @param $filename String: File name to open
2436          * @param $lineCallback Callback: Optional function called before reading each line
2437          * @param $resultCallback Callback: Optional function called for each MySQL result
2438          * @param $fname String: Calling function name or false if name should be generated dynamically
2439          *              using $filename
2440          */
2441         function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2442                 $fp = fopen( $filename, 'r' );
2443
2444                 if ( false === $fp ) {
2445                         if ( !defined( "MEDIAWIKI_INSTALL" ) )
2446                                 throw new MWException( "Could not open \"{$filename}\".\n" );
2447                         else
2448                                 return "Could not open \"{$filename}\".\n";
2449                 }
2450
2451                 if ( !$fname ) {
2452                         $fname = __METHOD__ . "( $filename )";
2453                 }
2454
2455                 try {
2456                         $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2457                 }
2458                 catch ( MWException $e ) {
2459                         if ( defined( "MEDIAWIKI_INSTALL" ) ) {
2460                                 $error = $e->getMessage();
2461                         } else {
2462                                 fclose( $fp );
2463                                 throw $e;
2464                         }
2465                 }
2466
2467                 fclose( $fp );
2468
2469                 return $error;
2470         }
2471
2472         /**
2473          * Get the full path of a patch file. Originally based on archive()
2474          * from updaters.inc. Keep in mind this always returns a patch, as
2475          * it fails back to MySQL if no DB-specific patch can be found
2476          *
2477          * @param $patch String The name of the patch, like patch-something.sql
2478          * @return String Full path to patch file
2479          */
2480         public function patchPath( $patch ) {
2481                 global $IP;
2482
2483                 $dbType = $this->getType();
2484                 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2485                         return "$IP/maintenance/$dbType/archives/$patch";
2486                 } else {
2487                         return "$IP/maintenance/archives/$patch";
2488                 }
2489         }
2490
2491         /**
2492          * Set variables to be used in sourceFile/sourceStream, in preference to the
2493          * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at 
2494          * all. If it's set to false, $GLOBALS will be used.
2495          *
2496          * @param $vars False, or array mapping variable name to value.
2497          */
2498         function setSchemaVars( $vars ) {
2499                 $this->mSchemaVars = $vars;
2500         }
2501
2502         /**
2503          * Read and execute commands from an open file handle
2504          * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2505          * @param $fp String: File handle
2506          * @param $lineCallback Callback: Optional function called before reading each line
2507          * @param $resultCallback Callback: Optional function called for each MySQL result
2508          * @param $fname String: Calling function name
2509          */
2510         function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2511                 $cmd = "";
2512                 $done = false;
2513                 $dollarquote = false;
2514
2515                 while ( ! feof( $fp ) ) {
2516                         if ( $lineCallback ) {
2517                                 call_user_func( $lineCallback );
2518                         }
2519
2520                         $line = trim( fgets( $fp, 1024 ) );
2521                         $sl = strlen( $line ) - 1;
2522
2523                         if ( $sl < 0 ) {
2524                                 continue;
2525                         }
2526
2527                         if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2528                                 continue;
2529                         }
2530
2531                         # # Allow dollar quoting for function declarations
2532                         if ( substr( $line, 0, 4 ) == '$mw$' ) {
2533                                 if ( $dollarquote ) {
2534                                         $dollarquote = false;
2535                                         $done = true;
2536                                 }
2537                                 else {
2538                                         $dollarquote = true;
2539                                 }
2540                         }
2541                         else if ( !$dollarquote ) {
2542                                 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
2543                                         $done = true;
2544                                         $line = substr( $line, 0, $sl );
2545                                 }
2546                         }
2547
2548                         if ( $cmd != '' ) {
2549                                 $cmd .= ' ';
2550                         }
2551
2552                         $cmd .= "$line\n";
2553
2554                         if ( $done ) {
2555                                 $cmd = str_replace( ';;', ";", $cmd );
2556                                 $cmd = $this->replaceVars( $cmd );
2557                                 $res = $this->query( $cmd, $fname );
2558
2559                                 if ( $resultCallback ) {
2560                                         call_user_func( $resultCallback, $res, $this );
2561                                 }
2562
2563                                 if ( false === $res ) {
2564                                         $err = $this->lastError();
2565                                         return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2566                                 }
2567
2568                                 $cmd = '';
2569                                 $done = false;
2570                         }
2571                 }
2572
2573                 return true;
2574         }
2575
2576         /**
2577          * Database independent variable replacement, replaces a set of variables
2578          * in a sql statement with their contents as given by $this->getSchemaVars().
2579          * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2580          * 
2581          * '{$var}' should be used for text and is passed through the database's addQuotes method
2582          * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2583          *          the database's addIdentifierQuotes method which can be overridden if the database
2584          *          uses something other than backticks.
2585          * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2586          * 
2587          * @param $ins String: SQL statement to replace variables in
2588          * @return String The new SQL statement with variables replaced
2589          */
2590         protected function replaceSchemaVars( $ins ) {
2591                 $vars = $this->getSchemaVars();
2592                 foreach ( $vars as $var => $value ) {
2593                         // replace '{$var}'
2594                         $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2595                         // replace `{$var}`
2596                         $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2597                         // replace /*$var*/
2598                         $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2599                 }
2600                 return $ins;
2601         }
2602
2603         /**
2604          * Replace variables in sourced SQL
2605          */
2606         protected function replaceVars( $ins ) {
2607                 $ins = $this->replaceSchemaVars( $ins );
2608
2609                 // Table prefixes
2610                 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2611                         array( $this, 'tableNameCallback' ), $ins );
2612
2613                 // Index names
2614                 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2615                         array( $this, 'indexNameCallback' ), $ins );
2616
2617                 return $ins;
2618         }
2619
2620         /**
2621          * Get schema variables. If none have been set via setSchemaVars(), then
2622          * use some defaults from the current object.
2623          */
2624         protected function getSchemaVars() {
2625                 if ( $this->mSchemaVars ) {
2626                         return $this->mSchemaVars;
2627                 } else {
2628                         return $this->getDefaultSchemaVars();
2629                 }
2630         }
2631
2632         /**
2633          * Get schema variables to use if none have been set via setSchemaVars().
2634          * Override this in derived classes to provide variables for tables.sql 
2635          * and SQL patch files. 
2636          */
2637         protected function getDefaultSchemaVars() {
2638                 return array();
2639         }
2640
2641         /**
2642          * Table name callback
2643          * @private
2644          */
2645         protected function tableNameCallback( $matches ) {
2646                 return $this->tableName( $matches[1] );
2647         }
2648
2649         /**
2650          * Index name callback
2651          */
2652         protected function indexNameCallback( $matches ) {
2653                 return $this->indexName( $matches[1] );
2654         }
2655
2656         /**
2657          * Build a concatenation list to feed into a SQL query
2658          * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2659          * @return String
2660          */
2661         function buildConcat( $stringList ) {
2662                 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2663         }
2664
2665         /**
2666          * Acquire a named lock
2667          *
2668          * Abstracted from Filestore::lock() so child classes can implement for
2669          * their own needs.
2670          *
2671          * @param $lockName String: name of lock to aquire
2672          * @param $method String: name of method calling us
2673          * @param $timeout Integer: timeout
2674          * @return Boolean
2675          */
2676         public function lock( $lockName, $method, $timeout = 5 ) {
2677                 return true;
2678         }
2679
2680         /**
2681          * Release a lock.
2682          *
2683          * @param $lockName String: Name of lock to release
2684          * @param $method String: Name of method calling us
2685          *
2686          * @return Returns 1 if the lock was released, 0 if the lock was not established
2687          * by this thread (in which case the lock is not released), and NULL if the named
2688          * lock did not exist
2689          */
2690         public function unlock( $lockName, $method ) {
2691                 return true;
2692         }
2693
2694         /**
2695          * Lock specific tables
2696          *
2697          * @param $read Array of tables to lock for read access
2698          * @param $write Array of tables to lock for write access
2699          * @param $method String name of caller
2700          * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2701          */
2702         public function lockTables( $read, $write, $method, $lowPriority = true ) {
2703                 return true;
2704         }
2705
2706         /**
2707          * Unlock specific tables
2708          *
2709          * @param $method String the caller
2710          */
2711         public function unlockTables( $method ) {
2712                 return true;
2713         }
2714
2715         /**
2716          * Get search engine class. All subclasses of this need to implement this
2717          * if they wish to use searching.
2718          *
2719          * @return String
2720          */
2721         public function getSearchEngine() {
2722                 return 'SearchEngineDummy';
2723         }
2724
2725         /**
2726          * Allow or deny "big selects" for this session only. This is done by setting
2727          * the sql_big_selects session variable.
2728          *
2729          * This is a MySQL-specific feature.
2730          *
2731          * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2732          */
2733         public function setBigSelects( $value = true ) {
2734                 // no-op
2735         }
2736 }
2737
2738 /******************************************************************************
2739  * Utility classes
2740  *****************************************************************************/
2741
2742 /**
2743  * Utility class.
2744  * @ingroup Database
2745  */
2746 class DBObject {
2747         public $mData;
2748
2749         function __construct( $data ) {
2750                 $this->mData = $data;
2751         }
2752
2753         function isLOB() {
2754                 return false;
2755         }
2756
2757         function data() {
2758                 return $this->mData;
2759         }
2760 }
2761
2762 /**
2763  * Utility class
2764  * @ingroup Database
2765  *
2766  * This allows us to distinguish a blob from a normal string and an array of strings
2767  */
2768 class Blob {
2769         private $mData;
2770
2771         function __construct( $data ) {
2772                 $this->mData = $data;
2773         }
2774
2775         function fetch() {
2776                 return $this->mData;
2777         }
2778 }
2779
2780 /**
2781  * Base for all database-specific classes representing information about database fields
2782  * @ingroup Database
2783  */
2784 interface Field {
2785         /**
2786          * Field name
2787          * @return string
2788          */
2789         function name();
2790
2791         /**
2792          * Name of table this field belongs to
2793          * @return string
2794          */
2795         function tableName();
2796
2797         /**
2798          * Database type
2799          * @return string
2800          */
2801         function type();
2802
2803         /**
2804          * Whether this field can store NULL values
2805          * @return bool
2806          */
2807         function isNullable();
2808 }
2809
2810 /******************************************************************************
2811  * Error classes
2812  *****************************************************************************/
2813
2814 /**
2815  * Database error base class
2816  * @ingroup Database
2817  */
2818 class DBError extends MWException {
2819         public $db;
2820
2821         /**
2822          * Construct a database error
2823          * @param $db Database object which threw the error
2824          * @param $error A simple error message to be used for debugging
2825          */
2826         function __construct( DatabaseBase &$db, $error ) {
2827                 $this->db =& $db;
2828                 parent::__construct( $error );
2829         }
2830
2831         function getText() {
2832                 global $wgShowDBErrorBacktrace;
2833
2834                 $s = $this->getMessage() . "\n";
2835
2836                 if ( $wgShowDBErrorBacktrace ) {
2837                         $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2838                 }
2839
2840                 return $s;
2841         }
2842 }
2843
2844 /**
2845  * @ingroup Database
2846  */
2847 class DBConnectionError extends DBError {
2848         public $error;
2849
2850         function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2851                 $msg = 'DB connection error';
2852
2853                 if ( trim( $error ) != '' ) {
2854                         $msg .= ": $error";
2855                 }
2856
2857                 $this->error = $error;
2858
2859                 parent::__construct( $db, $msg );
2860         }
2861
2862         function useOutputPage() {
2863                 // Not likely to work
2864                 return false;
2865         }
2866
2867         function useMessageCache() {
2868                 // Not likely to work
2869                 return false;
2870         }
2871
2872         function getLogMessage() {
2873                 # Don't send to the exception log
2874                 return false;
2875         }
2876
2877         function getPageTitle() {
2878                 global $wgSitename, $wgLang;
2879
2880                 $header = "$wgSitename has a problem";
2881
2882                 if ( $wgLang instanceof Language ) {
2883                         $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2884                 }
2885
2886                 return $header;
2887         }
2888
2889         function getHTML() {
2890                 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2891
2892                 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2893                 $again = 'Try waiting a few minutes and reloading.';
2894                 $info  = '(Can\'t contact the database server: $1)';
2895
2896                 if ( $wgLang instanceof Language ) {
2897                         $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2898                         $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2899                         $info  = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2900                 }
2901
2902                 # No database access
2903                 if ( is_object( $wgMessageCache ) ) {
2904                         $wgMessageCache->disable();
2905                 }
2906
2907                 if ( trim( $this->error ) == '' ) {
2908                         $this->error = $this->db->getProperty( 'mServer' );
2909                 }
2910
2911                 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2912                 $text = str_replace( '$1', $this->error, $noconnect );
2913
2914                 if ( $wgShowDBErrorBacktrace ) {
2915                         $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2916                 }
2917
2918                 $extra = $this->searchForm();
2919
2920                 if ( $wgUseFileCache ) {
2921                         try {
2922                                 $cache = $this->fileCachedPage();
2923                                 # Cached version on file system?
2924                                 if ( $cache !== null ) {
2925                                         # Hack: extend the body for error messages
2926                                         $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2927                                         # Add cache notice...
2928                                         $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2929
2930                                         # Localize it if possible...
2931                                         if ( $wgLang instanceof Language ) {
2932                                                 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2933                                         }
2934
2935                                         $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2936
2937                                         # Output cached page with notices on bottom and re-close body
2938                                         return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2939                                 }
2940                         } catch ( MWException $e ) {
2941                                 // Do nothing, just use the default page
2942                         }
2943                 }
2944
2945                 # Headers needed here - output is just the error message
2946                 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2947         }
2948
2949         function searchForm() {
2950                 global $wgSitename, $wgServer, $wgLang;
2951
2952                 $usegoogle = "You can try searching via Google in the meantime.";
2953                 $outofdate = "Note that their indexes of our content may be out of date.";
2954                 $googlesearch = "Search";
2955
2956                 if ( $wgLang instanceof Language ) {
2957                         $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2958                         $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2959                         $googlesearch  = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2960                 }
2961
2962                 $search = htmlspecialchars( @$_REQUEST['search'] );
2963
2964                 $server = htmlspecialchars( $wgServer );
2965                 $sitename = htmlspecialchars( $wgSitename );
2966
2967                 $trygoogle = <<<EOT
2968 <div style="margin: 1.5em">$usegoogle<br />
2969 <small>$outofdate</small></div>
2970 <!-- SiteSearch Google -->
2971 <form method="get" action="http://www.google.com/search" id="googlesearch">
2972         <input type="hidden" name="domains" value="$server" />
2973         <input type="hidden" name="num" value="50" />
2974         <input type="hidden" name="ie" value="UTF-8" />
2975         <input type="hidden" name="oe" value="UTF-8" />
2976
2977         <input type="text" name="q" size="31" maxlength="255" value="$search" />
2978         <input type="submit" name="btnG" value="$googlesearch" />
2979   <div>
2980         <input type="radio" name="sitesearch" id="gwiki" value="$server" checked="checked" /><label for="gwiki">$sitename</label>
2981         <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2982   </div>
2983 </form>
2984 <!-- SiteSearch Google -->
2985 EOT;
2986                 return $trygoogle;
2987         }
2988
2989         function fileCachedPage() {
2990                 global $wgTitle, $wgLang, $wgOut;
2991
2992                 if ( $wgOut->isDisabled() ) {
2993                         return; // Done already?
2994                 }
2995
2996                 $mainpage = 'Main Page';
2997
2998                 if ( $wgLang instanceof Language ) {
2999                         $mainpage    = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
3000                 }
3001
3002                 if ( $wgTitle ) {
3003                         $t =& $wgTitle;
3004                 } else {
3005                         $t = Title::newFromText( $mainpage );
3006                 }
3007
3008                 $cache = new HTMLFileCache( $t );
3009                 if ( $cache->isFileCached() ) {
3010                         return $cache->fetchPageText();
3011                 } else {
3012                         return '';
3013                 }
3014         }
3015
3016         function htmlBodyOnly() {
3017                 return true;
3018         }
3019 }
3020
3021 /**
3022  * @ingroup Database
3023  */
3024 class DBQueryError extends DBError {
3025         public $error, $errno, $sql, $fname;
3026
3027         function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
3028                 $message = "A database error has occurred.  Did you forget to run maintenance/update.php after upgrading?  See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
3029                   "Query: $sql\n" .
3030                   "Function: $fname\n" .
3031                   "Error: $errno $error\n";
3032
3033                 parent::__construct( $db, $message );
3034
3035                 $this->error = $error;
3036                 $this->errno = $errno;
3037                 $this->sql = $sql;
3038                 $this->fname = $fname;
3039         }
3040
3041         function getText() {
3042                 global $wgShowDBErrorBacktrace;
3043
3044                 if ( $this->useMessageCache() ) {
3045                         $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
3046                                 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
3047
3048                         if ( $wgShowDBErrorBacktrace ) {
3049                                 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
3050                         }
3051
3052                         return $s;
3053                 } else {
3054                         return parent::getText();
3055                 }
3056         }
3057
3058         function getSQL() {
3059                 global $wgShowSQLErrors;
3060
3061                 if ( !$wgShowSQLErrors ) {
3062                         return $this->msg( 'sqlhidden', 'SQL hidden' );
3063                 } else {
3064                         return $this->sql;
3065                 }
3066         }
3067
3068         function getLogMessage() {
3069                 # Don't send to the exception log
3070                 return false;
3071         }
3072
3073         function getPageTitle() {
3074                 return $this->msg( 'databaseerror', 'Database error' );
3075         }
3076
3077         function getHTML() {
3078                 global $wgShowDBErrorBacktrace;
3079
3080                 if ( $this->useMessageCache() ) {
3081                         $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
3082                           htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
3083                 } else {
3084                         $s = nl2br( htmlspecialchars( $this->getMessage() ) );
3085                 }
3086
3087                 if ( $wgShowDBErrorBacktrace ) {
3088                         $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
3089                 }
3090
3091                 return $s;
3092         }
3093 }
3094
3095 /**
3096  * @ingroup Database
3097  */
3098 class DBUnexpectedError extends DBError {}
3099
3100
3101 /**
3102  * Result wrapper for grabbing data queried by someone else
3103  * @ingroup Database
3104  */
3105 class ResultWrapper implements Iterator {
3106         var $db, $result, $pos = 0, $currentRow = null;
3107
3108         /**
3109          * Create a new result object from a result resource and a Database object
3110          */
3111         function __construct( $database, $result ) {
3112                 $this->db = $database;
3113
3114                 if ( $result instanceof ResultWrapper ) {
3115                         $this->result = $result->result;
3116                 } else {
3117                         $this->result = $result;
3118                 }
3119         }
3120
3121         /**
3122          * Get the number of rows in a result object
3123          */
3124         function numRows() {
3125                 return $this->db->numRows( $this );
3126         }
3127
3128         /**
3129          * Fetch the next row from the given result object, in object form.
3130          * Fields can be retrieved with $row->fieldname, with fields acting like
3131          * member variables.
3132          *
3133          * @return MySQL row object
3134          * @throws DBUnexpectedError Thrown if the database returns an error
3135          */
3136         function fetchObject() {
3137                 return $this->db->fetchObject( $this );
3138         }
3139
3140         /**
3141          * Fetch the next row from the given result object, in associative array
3142          * form.  Fields are retrieved with $row['fieldname'].
3143          *
3144          * @return MySQL row object
3145          * @throws DBUnexpectedError Thrown if the database returns an error
3146          */
3147         function fetchRow() {
3148                 return $this->db->fetchRow( $this );
3149         }
3150
3151         /**
3152          * Free a result object
3153          */
3154         function free() {
3155                 $this->db->freeResult( $this );
3156                 unset( $this->result );
3157                 unset( $this->db );
3158         }
3159
3160         /**
3161          * Change the position of the cursor in a result object
3162          * See mysql_data_seek()
3163          */
3164         function seek( $row ) {
3165                 $this->db->dataSeek( $this, $row );
3166         }
3167
3168         /*********************
3169          * Iterator functions
3170          * Note that using these in combination with the non-iterator functions
3171          * above may cause rows to be skipped or repeated.
3172          */
3173
3174         function rewind() {
3175                 if ( $this->numRows() ) {
3176                         $this->db->dataSeek( $this, 0 );
3177                 }
3178                 $this->pos = 0;
3179                 $this->currentRow = null;
3180         }
3181
3182         function current() {
3183                 if ( is_null( $this->currentRow ) ) {
3184                         $this->next();
3185                 }
3186                 return $this->currentRow;
3187         }
3188
3189         function key() {
3190                 return $this->pos;
3191         }
3192
3193         function next() {
3194                 $this->pos++;
3195                 $this->currentRow = $this->fetchObject();
3196                 return $this->currentRow;
3197         }
3198
3199         function valid() {
3200                 return $this->current() !== false;
3201         }
3202 }
3203
3204 /**
3205  * Overloads the relevant methods of the real ResultsWrapper so it
3206  * doesn't go anywhere near an actual database.
3207  */
3208 class FakeResultWrapper extends ResultWrapper {
3209         var $result     = array();
3210         var $db         = null; // And it's going to stay that way :D
3211         var $pos        = 0;
3212         var $currentRow = null;
3213
3214         function __construct( $array ) {
3215                 $this->result = $array;
3216         }
3217
3218         function numRows() {
3219                 return count( $this->result );
3220         }
3221
3222         function fetchRow() {
3223                 $this->currentRow = $this->result[$this->pos++];
3224                 return $this->currentRow;
3225         }
3226
3227         function seek( $row ) {
3228                 $this->pos = $row;
3229         }
3230
3231         function free() {}
3232
3233         // Callers want to be able to access fields with $this->fieldName
3234         function fetchObject() {
3235                 $this->currentRow = $this->result[$this->pos++];
3236                 return (object)$this->currentRow;
3237         }
3238
3239         function rewind() {
3240                 $this->pos = 0;
3241                 $this->currentRow = null;
3242         }
3243 }
3244
3245 /**
3246  * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3247  * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3248  */
3249 class LikeMatch {
3250         private $str;
3251
3252         public function __construct( $s ) {
3253                 $this->str = $s;
3254         }
3255
3256         public function toString() {
3257                 return $this->str;
3258         }
3259 }