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