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