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