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