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