Dump silly 'dontcountme=s'; old webalizer hack, it's not consistently used anyway.
[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) || 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 @list( $table, $database ) = array_reverse( explode( '.', $name, 2 ) );
1421 $prefix = $this->mTablePrefix; # Default prefix
1422
1423 # A database name has been specified in input. Quote the table name
1424 # because we don't want any prefixes added.
1425 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1426
1427 # Note that we use the long format because php will complain in in_array if
1428 # the input is not an array, and will complain in is_array if it is not set.
1429 if( !isset( $database ) # Don't use shared database if pre selected.
1430 && isset( $wgSharedDB ) # We have a shared database
1431 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1432 && isset( $wgSharedTables )
1433 && is_array( $wgSharedTables )
1434 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1435 $database = $wgSharedDB;
1436 $prefix = isset( $wgSharedprefix ) ? $wgSharedprefix : $prefix;
1437 }
1438
1439 # Quote the $database and $table and apply the prefix if not quoted.
1440 if( isset($database) ) $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1441 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1442
1443 # Merge our database and table into our final table name.
1444 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1445
1446 # We're finished, return.
1447 return $tableName;
1448 }
1449
1450 /**
1451 * Fetch a number of table names into an array
1452 * This is handy when you need to construct SQL for joins
1453 *
1454 * Example:
1455 * extract($dbr->tableNames('user','watchlist'));
1456 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1457 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1458 */
1459 public function tableNames() {
1460 $inArray = func_get_args();
1461 $retVal = array();
1462 foreach ( $inArray as $name ) {
1463 $retVal[$name] = $this->tableName( $name );
1464 }
1465 return $retVal;
1466 }
1467
1468 /**
1469 * Fetch a number of table names into an zero-indexed numerical array
1470 * This is handy when you need to construct SQL for joins
1471 *
1472 * Example:
1473 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1474 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1475 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1476 */
1477 public function tableNamesN() {
1478 $inArray = func_get_args();
1479 $retVal = array();
1480 foreach ( $inArray as $name ) {
1481 $retVal[] = $this->tableName( $name );
1482 }
1483 return $retVal;
1484 }
1485
1486 /**
1487 * @private
1488 */
1489 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1490 $ret = array();
1491 $retJOIN = array();
1492 $use_index_safe = is_array($use_index) ? $use_index : array();
1493 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1494 foreach ( $tables as $table ) {
1495 // Is there a JOIN and INDEX clause for this table?
1496 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1497 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1498 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1499 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1500 $retJOIN[] = $tableClause;
1501 // Is there an INDEX clause?
1502 } else if ( isset($use_index_safe[$table]) ) {
1503 $tableClause = $this->tableName( $table );
1504 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1505 $ret[] = $tableClause;
1506 // Is there a JOIN clause?
1507 } else if ( isset($join_conds_safe[$table]) ) {
1508 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1509 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1510 $retJOIN[] = $tableClause;
1511 } else {
1512 $tableClause = $this->tableName( $table );
1513 $ret[] = $tableClause;
1514 }
1515 }
1516 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1517 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1518 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1519 // Compile our final table clause
1520 return implode(' ',array($straightJoins,$otherJoins) );
1521 }
1522
1523 /**
1524 * Wrapper for addslashes()
1525 * @param string $s String to be slashed.
1526 * @return string slashed string.
1527 */
1528 function strencode( $s ) {
1529 return mysql_real_escape_string( $s, $this->mConn );
1530 }
1531
1532 /**
1533 * If it's a string, adds quotes and backslashes
1534 * Otherwise returns as-is
1535 */
1536 function addQuotes( $s ) {
1537 if ( is_null( $s ) ) {
1538 return 'NULL';
1539 } else {
1540 # This will also quote numeric values. This should be harmless,
1541 # and protects against weird problems that occur when they really
1542 # _are_ strings such as article titles and string->number->string
1543 # conversion is not 1:1.
1544 return "'" . $this->strencode( $s ) . "'";
1545 }
1546 }
1547
1548 /**
1549 * Escape string for safe LIKE usage
1550 */
1551 function escapeLike( $s ) {
1552 $s=$this->strencode( $s );
1553 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1554 return $s;
1555 }
1556
1557 /**
1558 * Returns an appropriately quoted sequence value for inserting a new row.
1559 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1560 * subclass will return an integer, and save the value for insertId()
1561 */
1562 function nextSequenceValue( $seqName ) {
1563 return NULL;
1564 }
1565
1566 /**
1567 * USE INDEX clause
1568 * PostgreSQL doesn't have them and returns ""
1569 */
1570 function useIndexClause( $index ) {
1571 return "FORCE INDEX ($index)";
1572 }
1573
1574 /**
1575 * REPLACE query wrapper
1576 * PostgreSQL simulates this with a DELETE followed by INSERT
1577 * $row is the row to insert, an associative array
1578 * $uniqueIndexes is an array of indexes. Each element may be either a
1579 * field name or an array of field names
1580 *
1581 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1582 * However if you do this, you run the risk of encountering errors which wouldn't have
1583 * occurred in MySQL
1584 *
1585 * @todo migrate comment to phodocumentor format
1586 */
1587 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1588 $table = $this->tableName( $table );
1589
1590 # Single row case
1591 if ( !is_array( reset( $rows ) ) ) {
1592 $rows = array( $rows );
1593 }
1594
1595 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1596 $first = true;
1597 foreach ( $rows as $row ) {
1598 if ( $first ) {
1599 $first = false;
1600 } else {
1601 $sql .= ',';
1602 }
1603 $sql .= '(' . $this->makeList( $row ) . ')';
1604 }
1605 return $this->query( $sql, $fname );
1606 }
1607
1608 /**
1609 * DELETE where the condition is a join
1610 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1611 *
1612 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1613 * join condition matches, set $conds='*'
1614 *
1615 * DO NOT put the join condition in $conds
1616 *
1617 * @param string $delTable The table to delete from.
1618 * @param string $joinTable The other table.
1619 * @param string $delVar The variable to join on, in the first table.
1620 * @param string $joinVar The variable to join on, in the second table.
1621 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1622 */
1623 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1624 if ( !$conds ) {
1625 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1626 }
1627
1628 $delTable = $this->tableName( $delTable );
1629 $joinTable = $this->tableName( $joinTable );
1630 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1631 if ( $conds != '*' ) {
1632 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1633 }
1634
1635 return $this->query( $sql, $fname );
1636 }
1637
1638 /**
1639 * Returns the size of a text field, or -1 for "unlimited"
1640 */
1641 function textFieldSize( $table, $field ) {
1642 $table = $this->tableName( $table );
1643 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1644 $res = $this->query( $sql, 'Database::textFieldSize' );
1645 $row = $this->fetchObject( $res );
1646 $this->freeResult( $res );
1647
1648 $m = array();
1649 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1650 $size = $m[1];
1651 } else {
1652 $size = -1;
1653 }
1654 return $size;
1655 }
1656
1657 /**
1658 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1659 */
1660 function lowPriorityOption() {
1661 return 'LOW_PRIORITY';
1662 }
1663
1664 /**
1665 * DELETE query wrapper
1666 *
1667 * Use $conds == "*" to delete all rows
1668 */
1669 function delete( $table, $conds, $fname = 'Database::delete' ) {
1670 if ( !$conds ) {
1671 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1672 }
1673 $table = $this->tableName( $table );
1674 $sql = "DELETE FROM $table";
1675 if ( $conds != '*' ) {
1676 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1677 }
1678 return $this->query( $sql, $fname );
1679 }
1680
1681 /**
1682 * INSERT SELECT wrapper
1683 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1684 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1685 * $conds may be "*" to copy the whole table
1686 * srcTable may be an array of tables.
1687 */
1688 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1689 $insertOptions = array(), $selectOptions = array() )
1690 {
1691 $destTable = $this->tableName( $destTable );
1692 if ( is_array( $insertOptions ) ) {
1693 $insertOptions = implode( ' ', $insertOptions );
1694 }
1695 if( !is_array( $selectOptions ) ) {
1696 $selectOptions = array( $selectOptions );
1697 }
1698 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1699 if( is_array( $srcTable ) ) {
1700 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1701 } else {
1702 $srcTable = $this->tableName( $srcTable );
1703 }
1704 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1705 " SELECT $startOpts " . implode( ',', $varMap ) .
1706 " FROM $srcTable $useIndex ";
1707 if ( $conds != '*' ) {
1708 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1709 }
1710 $sql .= " $tailOpts";
1711 return $this->query( $sql, $fname );
1712 }
1713
1714 /**
1715 * Construct a LIMIT query with optional offset
1716 * This is used for query pages
1717 * $sql string SQL query we will append the limit too
1718 * $limit integer the SQL limit
1719 * $offset integer the SQL offset (default false)
1720 */
1721 function limitResult($sql, $limit, $offset=false) {
1722 if( !is_numeric($limit) ) {
1723 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1724 }
1725 return "$sql LIMIT "
1726 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1727 . "{$limit} ";
1728 }
1729 function limitResultForUpdate($sql, $num) {
1730 return $this->limitResult($sql, $num, 0);
1731 }
1732
1733 /**
1734 * Returns an SQL expression for a simple conditional.
1735 * Uses IF on MySQL.
1736 *
1737 * @param string $cond SQL expression which will result in a boolean value
1738 * @param string $trueVal SQL expression to return if true
1739 * @param string $falseVal SQL expression to return if false
1740 * @return string SQL fragment
1741 */
1742 function conditional( $cond, $trueVal, $falseVal ) {
1743 return " IF($cond, $trueVal, $falseVal) ";
1744 }
1745
1746 /**
1747 * Returns a comand for str_replace function in SQL query.
1748 * Uses REPLACE() in MySQL
1749 *
1750 * @param string $orig String or column to modify
1751 * @param string $old String or column to seek
1752 * @param string $new String or column to replace with
1753 */
1754 function strreplace( $orig, $old, $new ) {
1755 return "REPLACE({$orig}, {$old}, {$new})";
1756 }
1757
1758 /**
1759 * Determines if the last failure was due to a deadlock
1760 */
1761 function wasDeadlock() {
1762 return $this->lastErrno() == 1213;
1763 }
1764
1765 /**
1766 * Perform a deadlock-prone transaction.
1767 *
1768 * This function invokes a callback function to perform a set of write
1769 * queries. If a deadlock occurs during the processing, the transaction
1770 * will be rolled back and the callback function will be called again.
1771 *
1772 * Usage:
1773 * $dbw->deadlockLoop( callback, ... );
1774 *
1775 * Extra arguments are passed through to the specified callback function.
1776 *
1777 * Returns whatever the callback function returned on its successful,
1778 * iteration, or false on error, for example if the retry limit was
1779 * reached.
1780 */
1781 function deadlockLoop() {
1782 $myFname = 'Database::deadlockLoop';
1783
1784 $this->begin();
1785 $args = func_get_args();
1786 $function = array_shift( $args );
1787 $oldIgnore = $this->ignoreErrors( true );
1788 $tries = DEADLOCK_TRIES;
1789 if ( is_array( $function ) ) {
1790 $fname = $function[0];
1791 } else {
1792 $fname = $function;
1793 }
1794 do {
1795 $retVal = call_user_func_array( $function, $args );
1796 $error = $this->lastError();
1797 $errno = $this->lastErrno();
1798 $sql = $this->lastQuery();
1799
1800 if ( $errno ) {
1801 if ( $this->wasDeadlock() ) {
1802 # Retry
1803 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1804 } else {
1805 $this->reportQueryError( $error, $errno, $sql, $fname );
1806 }
1807 }
1808 } while( $this->wasDeadlock() && --$tries > 0 );
1809 $this->ignoreErrors( $oldIgnore );
1810 if ( $tries <= 0 ) {
1811 $this->query( 'ROLLBACK', $myFname );
1812 $this->reportQueryError( $error, $errno, $sql, $fname );
1813 return false;
1814 } else {
1815 $this->query( 'COMMIT', $myFname );
1816 return $retVal;
1817 }
1818 }
1819
1820 /**
1821 * Do a SELECT MASTER_POS_WAIT()
1822 *
1823 * @param string $file the binlog file
1824 * @param string $pos the binlog position
1825 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1826 */
1827 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1828 $fname = 'Database::masterPosWait';
1829 wfProfileIn( $fname );
1830
1831 # Commit any open transactions
1832 if ( $this->mTrxLevel ) {
1833 $this->immediateCommit();
1834 }
1835
1836 if ( !is_null( $this->mFakeSlaveLag ) ) {
1837 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1838 if ( $wait > $timeout * 1e6 ) {
1839 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1840 wfProfileOut( $fname );
1841 return -1;
1842 } elseif ( $wait > 0 ) {
1843 wfDebug( "Fake slave waiting $wait us\n" );
1844 usleep( $wait );
1845 wfProfileOut( $fname );
1846 return 1;
1847 } else {
1848 wfDebug( "Fake slave up to date ($wait us)\n" );
1849 wfProfileOut( $fname );
1850 return 0;
1851 }
1852 }
1853
1854 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1855 $encFile = $this->addQuotes( $pos->file );
1856 $encPos = intval( $pos->pos );
1857 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1858 $res = $this->doQuery( $sql );
1859 if ( $res && $row = $this->fetchRow( $res ) ) {
1860 $this->freeResult( $res );
1861 wfProfileOut( $fname );
1862 return $row[0];
1863 } else {
1864 wfProfileOut( $fname );
1865 return false;
1866 }
1867 }
1868
1869 /**
1870 * Get the position of the master from SHOW SLAVE STATUS
1871 */
1872 function getSlavePos() {
1873 if ( !is_null( $this->mFakeSlaveLag ) ) {
1874 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1875 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1876 return $pos;
1877 }
1878 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1879 $row = $this->fetchObject( $res );
1880 if ( $row ) {
1881 return new MySQLMasterPos( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1882 } else {
1883 return false;
1884 }
1885 }
1886
1887 /**
1888 * Get the position of the master from SHOW MASTER STATUS
1889 */
1890 function getMasterPos() {
1891 if ( $this->mFakeMaster ) {
1892 return new MySQLMasterPos( 'fake', microtime( true ) );
1893 }
1894 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1895 $row = $this->fetchObject( $res );
1896 if ( $row ) {
1897 return new MySQLMasterPos( $row->File, $row->Position );
1898 } else {
1899 return false;
1900 }
1901 }
1902
1903 /**
1904 * Begin a transaction, committing any previously open transaction
1905 */
1906 function begin( $fname = 'Database::begin' ) {
1907 $this->query( 'BEGIN', $fname );
1908 $this->mTrxLevel = 1;
1909 }
1910
1911 /**
1912 * End a transaction
1913 */
1914 function commit( $fname = 'Database::commit' ) {
1915 $this->query( 'COMMIT', $fname );
1916 $this->mTrxLevel = 0;
1917 }
1918
1919 /**
1920 * Rollback a transaction.
1921 * No-op on non-transactional databases.
1922 */
1923 function rollback( $fname = 'Database::rollback' ) {
1924 $this->query( 'ROLLBACK', $fname, true );
1925 $this->mTrxLevel = 0;
1926 }
1927
1928 /**
1929 * Begin a transaction, committing any previously open transaction
1930 * @deprecated use begin()
1931 */
1932 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1933 $this->begin();
1934 }
1935
1936 /**
1937 * Commit transaction, if one is open
1938 * @deprecated use commit()
1939 */
1940 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1941 $this->commit();
1942 }
1943
1944 /**
1945 * Return MW-style timestamp used for MySQL schema
1946 */
1947 function timestamp( $ts=0 ) {
1948 return wfTimestamp(TS_MW,$ts);
1949 }
1950
1951 /**
1952 * Local database timestamp format or null
1953 */
1954 function timestampOrNull( $ts = null ) {
1955 if( is_null( $ts ) ) {
1956 return null;
1957 } else {
1958 return $this->timestamp( $ts );
1959 }
1960 }
1961
1962 /**
1963 * @todo document
1964 */
1965 function resultObject( $result ) {
1966 if( empty( $result ) ) {
1967 return false;
1968 } elseif ( $result instanceof ResultWrapper ) {
1969 return $result;
1970 } elseif ( $result === true ) {
1971 // Successful write query
1972 return $result;
1973 } else {
1974 return new ResultWrapper( $this, $result );
1975 }
1976 }
1977
1978 /**
1979 * Return aggregated value alias
1980 */
1981 function aggregateValue ($valuedata,$valuename='value') {
1982 return $valuename;
1983 }
1984
1985 /**
1986 * @return string wikitext of a link to the server software's web site
1987 */
1988 function getSoftwareLink() {
1989 return "[http://www.mysql.com/ MySQL]";
1990 }
1991
1992 /**
1993 * @return string Version information from the database
1994 */
1995 function getServerVersion() {
1996 return mysql_get_server_info( $this->mConn );
1997 }
1998
1999 /**
2000 * Ping the server and try to reconnect if it there is no connection
2001 */
2002 function ping() {
2003 if( !function_exists( 'mysql_ping' ) ) {
2004 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2005 return true;
2006 }
2007 $ping = mysql_ping( $this->mConn );
2008 if ( $ping ) {
2009 return true;
2010 }
2011
2012 // Need to reconnect manually in MySQL client 5.0.13+
2013 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2014 mysql_close( $this->mConn );
2015 $this->mOpened = false;
2016 $this->mConn = false;
2017 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2018 return true;
2019 }
2020 return false;
2021 }
2022
2023 /**
2024 * Get slave lag.
2025 * At the moment, this will only work if the DB user has the PROCESS privilege
2026 */
2027 function getLag() {
2028 if ( !is_null( $this->mFakeSlaveLag ) ) {
2029 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2030 return $this->mFakeSlaveLag;
2031 }
2032 $res = $this->query( 'SHOW PROCESSLIST' );
2033 # Find slave SQL thread
2034 while ( $row = $this->fetchObject( $res ) ) {
2035 /* This should work for most situations - when default db
2036 * for thread is not specified, it had no events executed,
2037 * and therefore it doesn't know yet how lagged it is.
2038 *
2039 * Relay log I/O thread does not select databases.
2040 */
2041 if ( $row->User == 'system user' &&
2042 $row->State != 'Waiting for master to send event' &&
2043 $row->State != 'Connecting to master' &&
2044 $row->State != 'Queueing master event to the relay log' &&
2045 $row->State != 'Waiting for master update' &&
2046 $row->State != 'Requesting binlog dump'
2047 ) {
2048 # This is it, return the time (except -ve)
2049 if ( $row->Time > 0x7fffffff ) {
2050 return false;
2051 } else {
2052 return $row->Time;
2053 }
2054 }
2055 }
2056 return false;
2057 }
2058
2059 /**
2060 * Get status information from SHOW STATUS in an associative array
2061 */
2062 function getStatus($which="%") {
2063 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2064 $status = array();
2065 while ( $row = $this->fetchObject( $res ) ) {
2066 $status[$row->Variable_name] = $row->Value;
2067 }
2068 return $status;
2069 }
2070
2071 /**
2072 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2073 */
2074 function maxListLen() {
2075 return 0;
2076 }
2077
2078 function encodeBlob($b) {
2079 return $b;
2080 }
2081
2082 function decodeBlob($b) {
2083 return $b;
2084 }
2085
2086 /**
2087 * Override database's default connection timeout.
2088 * May be useful for very long batch queries such as
2089 * full-wiki dumps, where a single query reads out
2090 * over hours or days.
2091 * @param int $timeout in seconds
2092 */
2093 public function setTimeout( $timeout ) {
2094 $this->query( "SET net_read_timeout=$timeout" );
2095 $this->query( "SET net_write_timeout=$timeout" );
2096 }
2097
2098 /**
2099 * Read and execute SQL commands from a file.
2100 * Returns true on success, error string on failure
2101 * @param string $filename File name to open
2102 * @param callback $lineCallback Optional function called before reading each line
2103 * @param callback $resultCallback Optional function called for each MySQL result
2104 */
2105 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2106 $fp = fopen( $filename, 'r' );
2107 if ( false === $fp ) {
2108 return "Could not open \"{$filename}\".\n";
2109 }
2110 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2111 fclose( $fp );
2112 return $error;
2113 }
2114
2115 /**
2116 * Read and execute commands from an open file handle
2117 * Returns true on success, error string on failure
2118 * @param string $fp File handle
2119 * @param callback $lineCallback Optional function called before reading each line
2120 * @param callback $resultCallback Optional function called for each MySQL result
2121 */
2122 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2123 $cmd = "";
2124 $done = false;
2125 $dollarquote = false;
2126
2127 while ( ! feof( $fp ) ) {
2128 if ( $lineCallback ) {
2129 call_user_func( $lineCallback );
2130 }
2131 $line = trim( fgets( $fp, 1024 ) );
2132 $sl = strlen( $line ) - 1;
2133
2134 if ( $sl < 0 ) { continue; }
2135 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2136
2137 ## Allow dollar quoting for function declarations
2138 if (substr($line,0,4) == '$mw$') {
2139 if ($dollarquote) {
2140 $dollarquote = false;
2141 $done = true;
2142 }
2143 else {
2144 $dollarquote = true;
2145 }
2146 }
2147 else if (!$dollarquote) {
2148 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2149 $done = true;
2150 $line = substr( $line, 0, $sl );
2151 }
2152 }
2153
2154 if ( '' != $cmd ) { $cmd .= ' '; }
2155 $cmd .= "$line\n";
2156
2157 if ( $done ) {
2158 $cmd = str_replace(';;', ";", $cmd);
2159 $cmd = $this->replaceVars( $cmd );
2160 $res = $this->query( $cmd, __METHOD__, true );
2161 if ( $resultCallback ) {
2162 call_user_func( $resultCallback, $res );
2163 }
2164
2165 if ( false === $res ) {
2166 $err = $this->lastError();
2167 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2168 }
2169
2170 $cmd = '';
2171 $done = false;
2172 }
2173 }
2174 return true;
2175 }
2176
2177
2178 /**
2179 * Replace variables in sourced SQL
2180 */
2181 protected function replaceVars( $ins ) {
2182 $varnames = array(
2183 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2184 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2185 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2186 );
2187
2188 // Ordinary variables
2189 foreach ( $varnames as $var ) {
2190 if( isset( $GLOBALS[$var] ) ) {
2191 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2192 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2193 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2194 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2195 }
2196 }
2197
2198 // Table prefixes
2199 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2200 array( &$this, 'tableNameCallback' ), $ins );
2201 return $ins;
2202 }
2203
2204 /**
2205 * Table name callback
2206 * @private
2207 */
2208 protected function tableNameCallback( $matches ) {
2209 return $this->tableName( $matches[1] );
2210 }
2211
2212 /*
2213 * Build a concatenation list to feed into a SQL query
2214 */
2215 function buildConcat( $stringList ) {
2216 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2217 }
2218
2219 }
2220
2221 /**
2222 * Database abstraction object for mySQL
2223 * Inherit all methods and properties of Database::Database()
2224 *
2225 * @ingroup Database
2226 * @see Database
2227 */
2228 class DatabaseMysql extends Database {
2229 # Inherit all
2230 }
2231
2232 /******************************************************************************
2233 * Utility classes
2234 *****************************************************************************/
2235
2236 /**
2237 * Utility class.
2238 * @ingroup Database
2239 */
2240 class DBObject {
2241 public $mData;
2242
2243 function DBObject($data) {
2244 $this->mData = $data;
2245 }
2246
2247 function isLOB() {
2248 return false;
2249 }
2250
2251 function data() {
2252 return $this->mData;
2253 }
2254 }
2255
2256 /**
2257 * Utility class
2258 * @ingroup Database
2259 *
2260 * This allows us to distinguish a blob from a normal string and an array of strings
2261 */
2262 class Blob {
2263 private $mData;
2264 function __construct($data) {
2265 $this->mData = $data;
2266 }
2267 function fetch() {
2268 return $this->mData;
2269 }
2270 }
2271
2272 /**
2273 * Utility class.
2274 * @ingroup Database
2275 */
2276 class MySQLField {
2277 private $name, $tablename, $default, $max_length, $nullable,
2278 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2279 function __construct ($info) {
2280 $this->name = $info->name;
2281 $this->tablename = $info->table;
2282 $this->default = $info->def;
2283 $this->max_length = $info->max_length;
2284 $this->nullable = !$info->not_null;
2285 $this->is_pk = $info->primary_key;
2286 $this->is_unique = $info->unique_key;
2287 $this->is_multiple = $info->multiple_key;
2288 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2289 $this->type = $info->type;
2290 }
2291
2292 function name() {
2293 return $this->name;
2294 }
2295
2296 function tableName() {
2297 return $this->tableName;
2298 }
2299
2300 function defaultValue() {
2301 return $this->default;
2302 }
2303
2304 function maxLength() {
2305 return $this->max_length;
2306 }
2307
2308 function nullable() {
2309 return $this->nullable;
2310 }
2311
2312 function isKey() {
2313 return $this->is_key;
2314 }
2315
2316 function isMultipleKey() {
2317 return $this->is_multiple;
2318 }
2319
2320 function type() {
2321 return $this->type;
2322 }
2323 }
2324
2325 /******************************************************************************
2326 * Error classes
2327 *****************************************************************************/
2328
2329 /**
2330 * Database error base class
2331 * @ingroup Database
2332 */
2333 class DBError extends MWException {
2334 public $db;
2335
2336 /**
2337 * Construct a database error
2338 * @param Database $db The database object which threw the error
2339 * @param string $error A simple error message to be used for debugging
2340 */
2341 function __construct( Database &$db, $error ) {
2342 $this->db =& $db;
2343 parent::__construct( $error );
2344 }
2345 }
2346
2347 /**
2348 * @ingroup Database
2349 */
2350 class DBConnectionError extends DBError {
2351 public $error;
2352
2353 function __construct( Database &$db, $error = 'unknown error' ) {
2354 $msg = 'DB connection error';
2355 if ( trim( $error ) != '' ) {
2356 $msg .= ": $error";
2357 }
2358 $this->error = $error;
2359 parent::__construct( $db, $msg );
2360 }
2361
2362 function useOutputPage() {
2363 // Not likely to work
2364 return false;
2365 }
2366
2367 function useMessageCache() {
2368 // Not likely to work
2369 return false;
2370 }
2371
2372 function getText() {
2373 return $this->getMessage() . "\n";
2374 }
2375
2376 function getLogMessage() {
2377 # Don't send to the exception log
2378 return false;
2379 }
2380
2381 function getPageTitle() {
2382 global $wgSitename;
2383 return "$wgSitename has a problem";
2384 }
2385
2386 function getHTML() {
2387 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2388 global $wgSitename, $wgServer, $wgMessageCache;
2389
2390 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2391 # Hard coding strings instead.
2392
2393 $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>";
2394 $mainpage = 'Main Page';
2395 $searchdisabled = <<<EOT
2396 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2397 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2398 EOT;
2399
2400 $googlesearch = "
2401 <!-- SiteSearch Google -->
2402 <FORM method=GET action=\"http://www.google.com/search\">
2403 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2404 <A HREF=\"http://www.google.com/\">
2405 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2406 border=\"0\" ALT=\"Google\"></A>
2407 </td>
2408 <td>
2409 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2410 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2411 <font size=-1>
2412 <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 />
2413 <input type='hidden' name='ie' value='$2'>
2414 <input type='hidden' name='oe' value='$2'>
2415 </font>
2416 </td></tr></TABLE>
2417 </FORM>
2418 <!-- SiteSearch Google -->";
2419 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2420
2421 # No database access
2422 if ( is_object( $wgMessageCache ) ) {
2423 $wgMessageCache->disable();
2424 }
2425
2426 if ( trim( $this->error ) == '' ) {
2427 $this->error = $this->db->getProperty('mServer');
2428 }
2429
2430 $text = str_replace( '$1', $this->error, $noconnect );
2431 $text .= wfGetSiteNotice();
2432
2433 if($wgUseFileCache) {
2434 if($wgTitle) {
2435 $t =& $wgTitle;
2436 } else {
2437 if($title) {
2438 $t = Title::newFromURL( $title );
2439 } elseif (@/**/$_REQUEST['search']) {
2440 $search = $_REQUEST['search'];
2441 return $searchdisabled .
2442 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2443 $wgInputEncoding ), $googlesearch );
2444 } else {
2445 $t = Title::newFromText( $mainpage );
2446 }
2447 }
2448
2449 $cache = new HTMLFileCache( $t );
2450 if( $cache->isFileCached() ) {
2451 // @todo, FIXME: $msg is not defined on the next line.
2452 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2453 $cachederror . "</b></p>\n";
2454
2455 $tag = '<div id="article">';
2456 $text = str_replace(
2457 $tag,
2458 $tag . $msg,
2459 $cache->fetchPageText() );
2460 }
2461 }
2462
2463 return $text;
2464 }
2465 }
2466
2467 /**
2468 * @ingroup Database
2469 */
2470 class DBQueryError extends DBError {
2471 public $error, $errno, $sql, $fname;
2472
2473 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
2474 $message = "A database error has occurred\n" .
2475 "Query: $sql\n" .
2476 "Function: $fname\n" .
2477 "Error: $errno $error\n";
2478
2479 parent::__construct( $db, $message );
2480 $this->error = $error;
2481 $this->errno = $errno;
2482 $this->sql = $sql;
2483 $this->fname = $fname;
2484 }
2485
2486 function getText() {
2487 if ( $this->useMessageCache() ) {
2488 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2489 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2490 } else {
2491 return $this->getMessage();
2492 }
2493 }
2494
2495 function getSQL() {
2496 global $wgShowSQLErrors;
2497 if( !$wgShowSQLErrors ) {
2498 return $this->msg( 'sqlhidden', 'SQL hidden' );
2499 } else {
2500 return $this->sql;
2501 }
2502 }
2503
2504 function getLogMessage() {
2505 # Don't send to the exception log
2506 return false;
2507 }
2508
2509 function getPageTitle() {
2510 return $this->msg( 'databaseerror', 'Database error' );
2511 }
2512
2513 function getHTML() {
2514 if ( $this->useMessageCache() ) {
2515 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2516 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2517 } else {
2518 return nl2br( htmlspecialchars( $this->getMessage() ) );
2519 }
2520 }
2521 }
2522
2523 /**
2524 * @ingroup Database
2525 */
2526 class DBUnexpectedError extends DBError {}
2527
2528
2529 /**
2530 * Result wrapper for grabbing data queried by someone else
2531 * @ingroup Database
2532 */
2533 class ResultWrapper implements Iterator {
2534 var $db, $result, $pos = 0, $currentRow = null;
2535
2536 /**
2537 * Create a new result object from a result resource and a Database object
2538 */
2539 function ResultWrapper( $database, $result ) {
2540 $this->db = $database;
2541 if ( $result instanceof ResultWrapper ) {
2542 $this->result = $result->result;
2543 } else {
2544 $this->result = $result;
2545 }
2546 }
2547
2548 /**
2549 * Get the number of rows in a result object
2550 */
2551 function numRows() {
2552 return $this->db->numRows( $this->result );
2553 }
2554
2555 /**
2556 * Fetch the next row from the given result object, in object form.
2557 * Fields can be retrieved with $row->fieldname, with fields acting like
2558 * member variables.
2559 *
2560 * @param $res SQL result object as returned from Database::query(), etc.
2561 * @return MySQL row object
2562 * @throws DBUnexpectedError Thrown if the database returns an error
2563 */
2564 function fetchObject() {
2565 return $this->db->fetchObject( $this->result );
2566 }
2567
2568 /**
2569 * Fetch the next row from the given result object, in associative array
2570 * form. Fields are retrieved with $row['fieldname'].
2571 *
2572 * @param $res SQL result object as returned from Database::query(), etc.
2573 * @return MySQL row object
2574 * @throws DBUnexpectedError Thrown if the database returns an error
2575 */
2576 function fetchRow() {
2577 return $this->db->fetchRow( $this->result );
2578 }
2579
2580 /**
2581 * Free a result object
2582 */
2583 function free() {
2584 $this->db->freeResult( $this->result );
2585 unset( $this->result );
2586 unset( $this->db );
2587 }
2588
2589 /**
2590 * Change the position of the cursor in a result object
2591 * See mysql_data_seek()
2592 */
2593 function seek( $row ) {
2594 $this->db->dataSeek( $this->result, $row );
2595 }
2596
2597 /*********************
2598 * Iterator functions
2599 * Note that using these in combination with the non-iterator functions
2600 * above may cause rows to be skipped or repeated.
2601 */
2602
2603 function rewind() {
2604 if ($this->numRows()) {
2605 $this->db->dataSeek($this->result, 0);
2606 }
2607 $this->pos = 0;
2608 $this->currentRow = null;
2609 }
2610
2611 function current() {
2612 if ( is_null( $this->currentRow ) ) {
2613 $this->next();
2614 }
2615 return $this->currentRow;
2616 }
2617
2618 function key() {
2619 return $this->pos;
2620 }
2621
2622 function next() {
2623 $this->pos++;
2624 $this->currentRow = $this->fetchObject();
2625 return $this->currentRow;
2626 }
2627
2628 function valid() {
2629 return $this->current() !== false;
2630 }
2631 }
2632
2633 class MySQLMasterPos {
2634 var $file, $pos;
2635
2636 function __construct( $file, $pos ) {
2637 $this->file = $file;
2638 $this->pos = $pos;
2639 }
2640
2641 function __toString() {
2642 return "{$this->file}/{$this->pos}";
2643 }
2644 }