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