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