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