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