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