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