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