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