5387ed411a3dece0ea2cc9fad7dcb131ecedd2d9
[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 // @todo, 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 * Returns true if this database can use functional indexes
453 */
454 function functionalIndexes() {
455 return false;
456 }
457
458 /**#@+
459 * Get function
460 */
461 function lastQuery() { return $this->mLastQuery; }
462 function isOpen() { return $this->mOpened; }
463 /**#@-*/
464
465 function setFlag( $flag ) {
466 $this->mFlags |= $flag;
467 }
468
469 function clearFlag( $flag ) {
470 $this->mFlags &= ~$flag;
471 }
472
473 function getFlag( $flag ) {
474 return !!($this->mFlags & $flag);
475 }
476
477 /**
478 * General read-only accessor
479 */
480 function getProperty( $name ) {
481 return $this->$name;
482 }
483
484 #------------------------------------------------------------------------------
485 # Other functions
486 #------------------------------------------------------------------------------
487
488 /**@{{
489 * Constructor.
490 * @param string $server database server host
491 * @param string $user database user name
492 * @param string $password database user password
493 * @param string $dbname database name
494 * @param failFunction
495 * @param $flags
496 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
497 */
498 function __construct( $server = false, $user = false, $password = false, $dbName = false,
499 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
500
501 global $wgOut, $wgDBprefix, $wgCommandLineMode;
502 # Can't get a reference if it hasn't been set yet
503 if ( !isset( $wgOut ) ) {
504 $wgOut = NULL;
505 }
506 $this->mOut =& $wgOut;
507
508 $this->mFailFunction = $failFunction;
509 $this->mFlags = $flags;
510
511 if ( $this->mFlags & DBO_DEFAULT ) {
512 if ( $wgCommandLineMode ) {
513 $this->mFlags &= ~DBO_TRX;
514 } else {
515 $this->mFlags |= DBO_TRX;
516 }
517 }
518
519 /*
520 // Faster read-only access
521 if ( wfReadOnly() ) {
522 $this->mFlags |= DBO_PERSISTENT;
523 $this->mFlags &= ~DBO_TRX;
524 }*/
525
526 /** Get the default table prefix*/
527 if ( $tablePrefix == 'get from global' ) {
528 $this->mTablePrefix = $wgDBprefix;
529 } else {
530 $this->mTablePrefix = $tablePrefix;
531 }
532
533 if ( $server ) {
534 $this->open( $server, $user, $password, $dbName );
535 }
536 }
537
538 /**
539 * @static
540 * @param failFunction
541 * @param $flags
542 */
543 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
544 {
545 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
546 }
547
548 /**
549 * Usually aborts on failure
550 * If the failFunction is set to a non-zero integer, returns success
551 */
552 function open( $server, $user, $password, $dbName ) {
553 global $wguname;
554 wfProfileIn( __METHOD__ );
555
556 # Test for missing mysql.so
557 # First try to load it
558 if (!@extension_loaded('mysql')) {
559 @dl('mysql.so');
560 }
561
562 # Fail now
563 # Otherwise we get a suppressed fatal error, which is very hard to track down
564 if ( !function_exists( 'mysql_connect' ) ) {
565 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
566 }
567
568 $this->close();
569 $this->mServer = $server;
570 $this->mUser = $user;
571 $this->mPassword = $password;
572 $this->mDBname = $dbName;
573
574 $success = false;
575
576 wfProfileIn("dbconnect-$server");
577
578 # LIVE PATCH by Tim, ask Domas for why: retry loop
579 $this->mConn = false;
580 $max = 3;
581 for ( $i = 0; $i < $max && !$this->mConn; $i++ ) {
582 if ( $i > 1 ) {
583 usleep( 1000 );
584 }
585 if ( $this->mFlags & DBO_PERSISTENT ) {
586 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
587 } else {
588 # Create a new connection...
589 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
590 }
591 if ($this->mConn === false) {
592 #$iplus = $i + 1;
593 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
594 }
595 }
596
597 wfProfileOut("dbconnect-$server");
598
599 if ( $dbName != '' ) {
600 if ( $this->mConn !== false ) {
601 $success = @/**/mysql_select_db( $dbName, $this->mConn );
602 if ( !$success ) {
603 $error = "Error selecting database $dbName on server {$this->mServer} " .
604 "from client host {$wguname['nodename']}\n";
605 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
606 wfDebug( $error );
607 }
608 } else {
609 wfDebug( "DB connection error\n" );
610 wfDebug( "Server: $server, User: $user, Password: " .
611 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
612 $success = false;
613 }
614 } else {
615 # Delay USE query
616 $success = (bool)$this->mConn;
617 }
618
619 if ( $success ) {
620 $version = $this->getServerVersion();
621 if ( version_compare( $version, '4.1' ) >= 0 ) {
622 // Tell the server we're communicating with it in UTF-8.
623 // This may engage various charset conversions.
624 global $wgDBmysql5;
625 if( $wgDBmysql5 ) {
626 $this->query( 'SET NAMES utf8', __METHOD__ );
627 }
628 // Turn off strict mode
629 $this->query( "SET sql_mode = ''", __METHOD__ );
630 }
631
632 // Turn off strict mode if it is on
633 } else {
634 $this->reportConnectionError();
635 }
636
637 $this->mOpened = $success;
638 wfProfileOut( __METHOD__ );
639 return $success;
640 }
641 /**@}}*/
642
643 /**
644 * Closes a database connection.
645 * if it is open : commits any open transactions
646 *
647 * @return bool operation success. true if already closed.
648 */
649 function close()
650 {
651 $this->mOpened = false;
652 if ( $this->mConn ) {
653 if ( $this->trxLevel() ) {
654 $this->immediateCommit();
655 }
656 return mysql_close( $this->mConn );
657 } else {
658 return true;
659 }
660 }
661
662 /**
663 * @param string $error fallback error message, used if none is given by MySQL
664 */
665 function reportConnectionError( $error = 'Unknown error' ) {
666 $myError = $this->lastError();
667 if ( $myError ) {
668 $error = $myError;
669 }
670
671 if ( $this->mFailFunction ) {
672 # Legacy error handling method
673 if ( !is_int( $this->mFailFunction ) ) {
674 $ff = $this->mFailFunction;
675 $ff( $this, $error );
676 }
677 } else {
678 # New method
679 wfLogDBError( "Connection error: $error\n" );
680 throw new DBConnectionError( $this, $error );
681 }
682 }
683
684 /**
685 * Usually aborts on failure. If errors are explicitly ignored, returns success.
686 *
687 * @param $sql String: SQL query
688 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
689 * comment (you can use __METHOD__ or add some extra info)
690 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
691 * maybe best to catch the exception instead?
692 * @return true for a successful write query, ResultWrapper object for a successful read query,
693 * or false on failure if $tempIgnore set
694 * @throws DBQueryError Thrown when the database returns an error of any kind
695 */
696 public function query( $sql, $fname = '', $tempIgnore = false ) {
697 global $wgProfiling;
698
699 if ( $wgProfiling ) {
700 # generalizeSQL will probably cut down the query to reasonable
701 # logging size most of the time. The substr is really just a sanity check.
702
703 # Who's been wasting my precious column space? -- TS
704 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
705
706 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
707 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
708 $totalProf = 'Database::query';
709 } else {
710 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
711 $totalProf = 'Database::query-master';
712 }
713 wfProfileIn( $totalProf );
714 wfProfileIn( $queryProf );
715 }
716
717 $this->mLastQuery = $sql;
718
719 # Add a comment for easy SHOW PROCESSLIST interpretation
720 #if ( $fname ) {
721 global $wgUser;
722 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
723 $userName = $wgUser->getName();
724 if ( strlen( $userName ) > 15 ) {
725 $userName = substr( $userName, 0, 15 ) . '...';
726 }
727 $userName = str_replace( '/', '', $userName );
728 } else {
729 $userName = '';
730 }
731 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
732 #} else {
733 # $commentedSql = $sql;
734 #}
735
736 # If DBO_TRX is set, start a transaction
737 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
738 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
739 ) {
740 $this->begin();
741 }
742
743 if ( $this->debug() ) {
744 $sqlx = substr( $commentedSql, 0, 500 );
745 $sqlx = strtr( $sqlx, "\t\n", ' ' );
746 wfDebug( "SQL: $sqlx\n" );
747 }
748
749 # Do the query and handle errors
750 $ret = $this->doQuery( $commentedSql );
751
752 # Try reconnecting if the connection was lost
753 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
754 # Transaction is gone, like it or not
755 $this->mTrxLevel = 0;
756 wfDebug( "Connection lost, reconnecting...\n" );
757 if ( $this->ping() ) {
758 wfDebug( "Reconnected\n" );
759 $sqlx = substr( $commentedSql, 0, 500 );
760 $sqlx = strtr( $sqlx, "\t\n", ' ' );
761 global $wgRequestTime;
762 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
763 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
764 $ret = $this->doQuery( $commentedSql );
765 } else {
766 wfDebug( "Failed\n" );
767 }
768 }
769
770 if ( false === $ret ) {
771 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
772 }
773
774 if ( $wgProfiling ) {
775 wfProfileOut( $queryProf );
776 wfProfileOut( $totalProf );
777 }
778 return $this->resultObject( $ret );
779 }
780
781 /**
782 * The DBMS-dependent part of query()
783 * @param $sql String: SQL query.
784 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
785 * @access private
786 */
787 /*private*/ function doQuery( $sql ) {
788 if( $this->bufferResults() ) {
789 $ret = mysql_query( $sql, $this->mConn );
790 } else {
791 $ret = mysql_unbuffered_query( $sql, $this->mConn );
792 }
793 return $ret;
794 }
795
796 /**
797 * @param $error
798 * @param $errno
799 * @param $sql
800 * @param string $fname
801 * @param bool $tempIgnore
802 */
803 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
804 global $wgCommandLineMode;
805 # Ignore errors during error handling to avoid infinite recursion
806 $ignore = $this->ignoreErrors( true );
807 ++$this->mErrorCount;
808
809 if( $ignore || $tempIgnore ) {
810 wfDebug("SQL ERROR (ignored): $error\n");
811 $this->ignoreErrors( $ignore );
812 } else {
813 $sql1line = str_replace( "\n", "\\n", $sql );
814 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
815 wfDebug("SQL ERROR: " . $error . "\n");
816 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
817 }
818 }
819
820
821 /**
822 * Intended to be compatible with the PEAR::DB wrapper functions.
823 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
824 *
825 * ? = scalar value, quoted as necessary
826 * ! = raw SQL bit (a function for instance)
827 * & = filename; reads the file and inserts as a blob
828 * (we don't use this though...)
829 */
830 function prepare( $sql, $func = 'Database::prepare' ) {
831 /* MySQL doesn't support prepared statements (yet), so just
832 pack up the query for reference. We'll manually replace
833 the bits later. */
834 return array( 'query' => $sql, 'func' => $func );
835 }
836
837 function freePrepared( $prepared ) {
838 /* No-op for MySQL */
839 }
840
841 /**
842 * Execute a prepared query with the various arguments
843 * @param string $prepared the prepared sql
844 * @param mixed $args Either an array here, or put scalars as varargs
845 */
846 function execute( $prepared, $args = null ) {
847 if( !is_array( $args ) ) {
848 # Pull the var args
849 $args = func_get_args();
850 array_shift( $args );
851 }
852 $sql = $this->fillPrepared( $prepared['query'], $args );
853 return $this->query( $sql, $prepared['func'] );
854 }
855
856 /**
857 * Prepare & execute an SQL statement, quoting and inserting arguments
858 * in the appropriate places.
859 * @param string $query
860 * @param string $args ...
861 */
862 function safeQuery( $query, $args = null ) {
863 $prepared = $this->prepare( $query, 'Database::safeQuery' );
864 if( !is_array( $args ) ) {
865 # Pull the var args
866 $args = func_get_args();
867 array_shift( $args );
868 }
869 $retval = $this->execute( $prepared, $args );
870 $this->freePrepared( $prepared );
871 return $retval;
872 }
873
874 /**
875 * For faking prepared SQL statements on DBs that don't support
876 * it directly.
877 * @param string $preparedSql - a 'preparable' SQL statement
878 * @param array $args - array of arguments to fill it with
879 * @return string executable SQL
880 */
881 function fillPrepared( $preparedQuery, $args ) {
882 reset( $args );
883 $this->preparedArgs =& $args;
884 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
885 array( &$this, 'fillPreparedArg' ), $preparedQuery );
886 }
887
888 /**
889 * preg_callback func for fillPrepared()
890 * The arguments should be in $this->preparedArgs and must not be touched
891 * while we're doing this.
892 *
893 * @param array $matches
894 * @return string
895 * @private
896 */
897 function fillPreparedArg( $matches ) {
898 switch( $matches[1] ) {
899 case '\\?': return '?';
900 case '\\!': return '!';
901 case '\\&': return '&';
902 }
903 list( /* $n */ , $arg ) = each( $this->preparedArgs );
904 switch( $matches[1] ) {
905 case '?': return $this->addQuotes( $arg );
906 case '!': return $arg;
907 case '&':
908 # return $this->addQuotes( file_get_contents( $arg ) );
909 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
910 default:
911 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
912 }
913 }
914
915 /**#@+
916 * @param mixed $res A SQL result
917 */
918 /**
919 * Free a result object
920 */
921 function freeResult( $res ) {
922 if ( $res instanceof ResultWrapper ) {
923 $res = $res->result;
924 }
925 if ( !@/**/mysql_free_result( $res ) ) {
926 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
927 }
928 }
929
930 /**
931 * Fetch the next row from the given result object, in object form.
932 * Fields can be retrieved with $row->fieldname, with fields acting like
933 * member variables.
934 *
935 * @param $res SQL result object as returned from Database::query(), etc.
936 * @return MySQL row object
937 * @throws DBUnexpectedError Thrown if the database returns an error
938 */
939 function fetchObject( $res ) {
940 if ( $res instanceof ResultWrapper ) {
941 $res = $res->result;
942 }
943 @/**/$row = mysql_fetch_object( $res );
944 if( $this->lastErrno() ) {
945 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
946 }
947 return $row;
948 }
949
950 /**
951 * Fetch the next row from the given result object, in associative array
952 * form. Fields are retrieved with $row['fieldname'].
953 *
954 * @param $res SQL result object as returned from Database::query(), etc.
955 * @return MySQL row object
956 * @throws DBUnexpectedError Thrown if the database returns an error
957 */
958 function fetchRow( $res ) {
959 if ( $res instanceof ResultWrapper ) {
960 $res = $res->result;
961 }
962 @/**/$row = mysql_fetch_array( $res );
963 if ( $this->lastErrno() ) {
964 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
965 }
966 return $row;
967 }
968
969 /**
970 * Get the number of rows in a result object
971 */
972 function numRows( $res ) {
973 if ( $res instanceof ResultWrapper ) {
974 $res = $res->result;
975 }
976 @/**/$n = mysql_num_rows( $res );
977 if( $this->lastErrno() ) {
978 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
979 }
980 return $n;
981 }
982
983 /**
984 * Get the number of fields in a result object
985 * See documentation for mysql_num_fields()
986 */
987 function numFields( $res ) {
988 if ( $res instanceof ResultWrapper ) {
989 $res = $res->result;
990 }
991 return mysql_num_fields( $res );
992 }
993
994 /**
995 * Get a field name in a result object
996 * See documentation for mysql_field_name():
997 * http://www.php.net/mysql_field_name
998 */
999 function fieldName( $res, $n ) {
1000 if ( $res instanceof ResultWrapper ) {
1001 $res = $res->result;
1002 }
1003 return mysql_field_name( $res, $n );
1004 }
1005
1006 /**
1007 * Get the inserted value of an auto-increment row
1008 *
1009 * The value inserted should be fetched from nextSequenceValue()
1010 *
1011 * Example:
1012 * $id = $dbw->nextSequenceValue('page_page_id_seq');
1013 * $dbw->insert('page',array('page_id' => $id));
1014 * $id = $dbw->insertId();
1015 */
1016 function insertId() { return mysql_insert_id( $this->mConn ); }
1017
1018 /**
1019 * Change the position of the cursor in a result object
1020 * See mysql_data_seek()
1021 */
1022 function dataSeek( $res, $row ) {
1023 if ( $res instanceof ResultWrapper ) {
1024 $res = $res->result;
1025 }
1026 return mysql_data_seek( $res, $row );
1027 }
1028
1029 /**
1030 * Get the last error number
1031 * See mysql_errno()
1032 */
1033 function lastErrno() {
1034 if ( $this->mConn ) {
1035 return mysql_errno( $this->mConn );
1036 } else {
1037 return mysql_errno();
1038 }
1039 }
1040
1041 /**
1042 * Get a description of the last error
1043 * See mysql_error() for more details
1044 */
1045 function lastError() {
1046 if ( $this->mConn ) {
1047 # Even if it's non-zero, it can still be invalid
1048 wfSuppressWarnings();
1049 $error = mysql_error( $this->mConn );
1050 if ( !$error ) {
1051 $error = mysql_error();
1052 }
1053 wfRestoreWarnings();
1054 } else {
1055 $error = mysql_error();
1056 }
1057 if( $error ) {
1058 $error .= ' (' . $this->mServer . ')';
1059 }
1060 return $error;
1061 }
1062 /**
1063 * Get the number of rows affected by the last write query
1064 * See mysql_affected_rows() for more details
1065 */
1066 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
1067 /**#@-*/ // end of template : @param $result
1068
1069 /**
1070 * Simple UPDATE wrapper
1071 * Usually aborts on failure
1072 * If errors are explicitly ignored, returns success
1073 *
1074 * This function exists for historical reasons, Database::update() has a more standard
1075 * calling convention and feature set
1076 */
1077 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
1078 {
1079 $table = $this->tableName( $table );
1080 $sql = "UPDATE $table SET $var = '" .
1081 $this->strencode( $value ) . "' WHERE ($cond)";
1082 return (bool)$this->query( $sql, $fname );
1083 }
1084
1085 /**
1086 * Simple SELECT wrapper, returns a single field, input must be encoded
1087 * Usually aborts on failure
1088 * If errors are explicitly ignored, returns FALSE on failure
1089 */
1090 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1091 if ( !is_array( $options ) ) {
1092 $options = array( $options );
1093 }
1094 $options['LIMIT'] = 1;
1095
1096 $res = $this->select( $table, $var, $cond, $fname, $options );
1097 if ( $res === false || !$this->numRows( $res ) ) {
1098 return false;
1099 }
1100 $row = $this->fetchRow( $res );
1101 if ( $row !== false ) {
1102 $this->freeResult( $res );
1103 return $row[0];
1104 } else {
1105 return false;
1106 }
1107 }
1108
1109 /**
1110 * Returns an optional USE INDEX clause to go after the table, and a
1111 * string to go at the end of the query
1112 *
1113 * @private
1114 *
1115 * @param array $options an associative array of options to be turned into
1116 * an SQL query, valid keys are listed in the function.
1117 * @return array
1118 */
1119 function makeSelectOptions( $options ) {
1120 $preLimitTail = $postLimitTail = '';
1121 $startOpts = '';
1122
1123 $noKeyOptions = array();
1124 foreach ( $options as $key => $option ) {
1125 if ( is_numeric( $key ) ) {
1126 $noKeyOptions[$option] = true;
1127 }
1128 }
1129
1130 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1131 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1132 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1133
1134 //if (isset($options['LIMIT'])) {
1135 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1136 // isset($options['OFFSET']) ? $options['OFFSET']
1137 // : false);
1138 //}
1139
1140 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1141 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1142 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1143
1144 # Various MySQL extensions
1145 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1146 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1147 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1148 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1149 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1150 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1151 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1152 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1153
1154 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1155 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1156 } else {
1157 $useIndex = '';
1158 }
1159
1160 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1161 }
1162
1163 /**
1164 * SELECT wrapper
1165 *
1166 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1167 * @param mixed $vars Array or string, field name(s) to be retrieved
1168 * @param mixed $conds Array or string, condition(s) for WHERE
1169 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1170 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1171 * see Database::makeSelectOptions code for list of supported stuff
1172 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1173 */
1174 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1175 {
1176 if( is_array( $vars ) ) {
1177 $vars = implode( ',', $vars );
1178 }
1179 if( !is_array( $options ) ) {
1180 $options = array( $options );
1181 }
1182 if( is_array( $table ) ) {
1183 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1184 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1185 else
1186 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1187 } elseif ($table!='') {
1188 if ($table{0}==' ') {
1189 $from = ' FROM ' . $table;
1190 } else {
1191 $from = ' FROM ' . $this->tableName( $table );
1192 }
1193 } else {
1194 $from = '';
1195 }
1196
1197 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1198
1199 if( !empty( $conds ) ) {
1200 if ( is_array( $conds ) ) {
1201 $conds = $this->makeList( $conds, LIST_AND );
1202 }
1203 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1204 } else {
1205 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1206 }
1207
1208 if (isset($options['LIMIT']))
1209 $sql = $this->limitResult($sql, $options['LIMIT'],
1210 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1211 $sql = "$sql $postLimitTail";
1212
1213 if (isset($options['EXPLAIN'])) {
1214 $sql = 'EXPLAIN ' . $sql;
1215 }
1216 return $this->query( $sql, $fname );
1217 }
1218
1219 /**
1220 * Single row SELECT wrapper
1221 * Aborts or returns FALSE on error
1222 *
1223 * $vars: the selected variables
1224 * $conds: a condition map, terms are ANDed together.
1225 * Items with numeric keys are taken to be literal conditions
1226 * Takes an array of selected variables, and a condition map, which is ANDed
1227 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1228 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1229 * $obj- >page_id is the ID of the Astronomy article
1230 *
1231 * @todo migrate documentation to phpdocumentor format
1232 */
1233 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1234 $options['LIMIT'] = 1;
1235 $res = $this->select( $table, $vars, $conds, $fname, $options );
1236 if ( $res === false )
1237 return false;
1238 if ( !$this->numRows($res) ) {
1239 $this->freeResult($res);
1240 return false;
1241 }
1242 $obj = $this->fetchObject( $res );
1243 $this->freeResult( $res );
1244 return $obj;
1245
1246 }
1247
1248 /**
1249 * Estimate rows in dataset
1250 * Returns estimated count, based on EXPLAIN output
1251 * Takes same arguments as Database::select()
1252 */
1253
1254 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1255 $options['EXPLAIN']=true;
1256 $res = $this->select ($table, $vars, $conds, $fname, $options );
1257 if ( $res === false )
1258 return false;
1259 if (!$this->numRows($res)) {
1260 $this->freeResult($res);
1261 return 0;
1262 }
1263
1264 $rows=1;
1265
1266 while( $plan = $this->fetchObject( $res ) ) {
1267 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
1268 }
1269
1270 $this->freeResult($res);
1271 return $rows;
1272 }
1273
1274
1275 /**
1276 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1277 * It's only slightly flawed. Don't use for anything important.
1278 *
1279 * @param string $sql A SQL Query
1280 * @static
1281 */
1282 static function generalizeSQL( $sql ) {
1283 # This does the same as the regexp below would do, but in such a way
1284 # as to avoid crashing php on some large strings.
1285 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1286
1287 $sql = str_replace ( "\\\\", '', $sql);
1288 $sql = str_replace ( "\\'", '', $sql);
1289 $sql = str_replace ( "\\\"", '', $sql);
1290 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1291 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1292
1293 # All newlines, tabs, etc replaced by single space
1294 $sql = preg_replace ( '/\s+/', ' ', $sql);
1295
1296 # All numbers => N
1297 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1298
1299 return $sql;
1300 }
1301
1302 /**
1303 * Determines whether a field exists in a table
1304 * Usually aborts on failure
1305 * If errors are explicitly ignored, returns NULL on failure
1306 */
1307 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1308 $table = $this->tableName( $table );
1309 $res = $this->query( 'DESCRIBE '.$table, $fname );
1310 if ( !$res ) {
1311 return NULL;
1312 }
1313
1314 $found = false;
1315
1316 while ( $row = $this->fetchObject( $res ) ) {
1317 if ( $row->Field == $field ) {
1318 $found = true;
1319 break;
1320 }
1321 }
1322 return $found;
1323 }
1324
1325 /**
1326 * Determines whether an index exists
1327 * Usually aborts on failure
1328 * If errors are explicitly ignored, returns NULL on failure
1329 */
1330 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1331 $info = $this->indexInfo( $table, $index, $fname );
1332 if ( is_null( $info ) ) {
1333 return NULL;
1334 } else {
1335 return $info !== false;
1336 }
1337 }
1338
1339
1340 /**
1341 * Get information about an index into an object
1342 * Returns false if the index does not exist
1343 */
1344 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1345 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1346 # SHOW INDEX should work for 3.x and up:
1347 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1348 $table = $this->tableName( $table );
1349 $sql = 'SHOW INDEX FROM '.$table;
1350 $res = $this->query( $sql, $fname );
1351 if ( !$res ) {
1352 return NULL;
1353 }
1354
1355 $result = array();
1356 while ( $row = $this->fetchObject( $res ) ) {
1357 if ( $row->Key_name == $index ) {
1358 $result[] = $row;
1359 }
1360 }
1361 $this->freeResult($res);
1362
1363 return empty($result) ? false : $result;
1364 }
1365
1366 /**
1367 * Query whether a given table exists
1368 */
1369 function tableExists( $table ) {
1370 $table = $this->tableName( $table );
1371 $old = $this->ignoreErrors( true );
1372 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1373 $this->ignoreErrors( $old );
1374 if( $res ) {
1375 $this->freeResult( $res );
1376 return true;
1377 } else {
1378 return false;
1379 }
1380 }
1381
1382 /**
1383 * mysql_fetch_field() wrapper
1384 * Returns false if the field doesn't exist
1385 *
1386 * @param $table
1387 * @param $field
1388 */
1389 function fieldInfo( $table, $field ) {
1390 $table = $this->tableName( $table );
1391 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1392 $n = mysql_num_fields( $res->result );
1393 for( $i = 0; $i < $n; $i++ ) {
1394 $meta = mysql_fetch_field( $res->result, $i );
1395 if( $field == $meta->name ) {
1396 return new MySQLField($meta);
1397 }
1398 }
1399 return false;
1400 }
1401
1402 /**
1403 * mysql_field_type() wrapper
1404 */
1405 function fieldType( $res, $index ) {
1406 if ( $res instanceof ResultWrapper ) {
1407 $res = $res->result;
1408 }
1409 return mysql_field_type( $res, $index );
1410 }
1411
1412 /**
1413 * Determines if a given index is unique
1414 */
1415 function indexUnique( $table, $index ) {
1416 $indexInfo = $this->indexInfo( $table, $index );
1417 if ( !$indexInfo ) {
1418 return NULL;
1419 }
1420 return !$indexInfo[0]->Non_unique;
1421 }
1422
1423 /**
1424 * INSERT wrapper, inserts an array into a table
1425 *
1426 * $a may be a single associative array, or an array of these with numeric keys, for
1427 * multi-row insert.
1428 *
1429 * Usually aborts on failure
1430 * If errors are explicitly ignored, returns success
1431 */
1432 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1433 # No rows to insert, easy just return now
1434 if ( !count( $a ) ) {
1435 return true;
1436 }
1437
1438 $table = $this->tableName( $table );
1439 if ( !is_array( $options ) ) {
1440 $options = array( $options );
1441 }
1442 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1443 $multi = true;
1444 $keys = array_keys( $a[0] );
1445 } else {
1446 $multi = false;
1447 $keys = array_keys( $a );
1448 }
1449
1450 $sql = 'INSERT ' . implode( ' ', $options ) .
1451 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1452
1453 if ( $multi ) {
1454 $first = true;
1455 foreach ( $a as $row ) {
1456 if ( $first ) {
1457 $first = false;
1458 } else {
1459 $sql .= ',';
1460 }
1461 $sql .= '(' . $this->makeList( $row ) . ')';
1462 }
1463 } else {
1464 $sql .= '(' . $this->makeList( $a ) . ')';
1465 }
1466 return (bool)$this->query( $sql, $fname );
1467 }
1468
1469 /**
1470 * Make UPDATE options for the Database::update function
1471 *
1472 * @private
1473 * @param array $options The options passed to Database::update
1474 * @return string
1475 */
1476 function makeUpdateOptions( $options ) {
1477 if( !is_array( $options ) ) {
1478 $options = array( $options );
1479 }
1480 $opts = array();
1481 if ( in_array( 'LOW_PRIORITY', $options ) )
1482 $opts[] = $this->lowPriorityOption();
1483 if ( in_array( 'IGNORE', $options ) )
1484 $opts[] = 'IGNORE';
1485 return implode(' ', $opts);
1486 }
1487
1488 /**
1489 * UPDATE wrapper, takes a condition array and a SET array
1490 *
1491 * @param string $table The table to UPDATE
1492 * @param array $values An array of values to SET
1493 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1494 * @param string $fname The Class::Function calling this function
1495 * (for the log)
1496 * @param array $options An array of UPDATE options, can be one or
1497 * more of IGNORE, LOW_PRIORITY
1498 * @return bool
1499 */
1500 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1501 $table = $this->tableName( $table );
1502 $opts = $this->makeUpdateOptions( $options );
1503 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1504 if ( $conds != '*' ) {
1505 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1506 }
1507 return $this->query( $sql, $fname );
1508 }
1509
1510 /**
1511 * Makes an encoded list of strings from an array
1512 * $mode:
1513 * LIST_COMMA - comma separated, no field names
1514 * LIST_AND - ANDed WHERE clause (without the WHERE)
1515 * LIST_OR - ORed WHERE clause (without the WHERE)
1516 * LIST_SET - comma separated with field names, like a SET clause
1517 * LIST_NAMES - comma separated field names
1518 */
1519 function makeList( $a, $mode = LIST_COMMA ) {
1520 if ( !is_array( $a ) ) {
1521 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1522 }
1523
1524 $first = true;
1525 $list = '';
1526 foreach ( $a as $field => $value ) {
1527 if ( !$first ) {
1528 if ( $mode == LIST_AND ) {
1529 $list .= ' AND ';
1530 } elseif($mode == LIST_OR) {
1531 $list .= ' OR ';
1532 } else {
1533 $list .= ',';
1534 }
1535 } else {
1536 $first = false;
1537 }
1538 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1539 $list .= "($value)";
1540 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1541 $list .= "$value";
1542 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1543 $list .= $field." IN (".$this->makeList($value).") ";
1544 } elseif( is_null($value) ) {
1545 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1546 $list .= "$field IS ";
1547 } elseif ( $mode == LIST_SET ) {
1548 $list .= "$field = ";
1549 }
1550 $list .= 'NULL';
1551 } else {
1552 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1553 $list .= "$field = ";
1554 }
1555 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1556 }
1557 }
1558 return $list;
1559 }
1560
1561 /**
1562 * Change the current database
1563 */
1564 function selectDB( $db ) {
1565 $this->mDBname = $db;
1566 return mysql_select_db( $db, $this->mConn );
1567 }
1568
1569 /**
1570 * Format a table name ready for use in constructing an SQL query
1571 *
1572 * This does two important things: it quotes table names which as necessary,
1573 * and it adds a table prefix if there is one.
1574 *
1575 * All functions of this object which require a table name call this function
1576 * themselves. Pass the canonical name to such functions. This is only needed
1577 * when calling query() directly.
1578 *
1579 * @param string $name database table name
1580 */
1581 function tableName( $name ) {
1582 global $wgSharedDB;
1583 # Skip quoted literals
1584 if ( $name{0} != '`' ) {
1585 if ( $this->mTablePrefix !== '' && strpos( $name, '.' ) === false ) {
1586 $name = "{$this->mTablePrefix}$name";
1587 }
1588 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1589 $name = "`$wgSharedDB`.`$name`";
1590 } else {
1591 # Standard quoting
1592 $name = "`$name`";
1593 }
1594 }
1595 return $name;
1596 }
1597
1598 /**
1599 * Fetch a number of table names into an array
1600 * This is handy when you need to construct SQL for joins
1601 *
1602 * Example:
1603 * extract($dbr->tableNames('user','watchlist'));
1604 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1605 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1606 */
1607 public function tableNames() {
1608 $inArray = func_get_args();
1609 $retVal = array();
1610 foreach ( $inArray as $name ) {
1611 $retVal[$name] = $this->tableName( $name );
1612 }
1613 return $retVal;
1614 }
1615
1616 /**
1617 * Fetch a number of table names into an zero-indexed numerical array
1618 * This is handy when you need to construct SQL for joins
1619 *
1620 * Example:
1621 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1622 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1623 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1624 */
1625 public function tableNamesN() {
1626 $inArray = func_get_args();
1627 $retVal = array();
1628 foreach ( $inArray as $name ) {
1629 $retVal[] = $this->tableName( $name );
1630 }
1631 return $retVal;
1632 }
1633
1634 /**
1635 * @private
1636 */
1637 function tableNamesWithUseIndex( $tables, $use_index ) {
1638 $ret = array();
1639
1640 foreach ( $tables as $table )
1641 if ( @$use_index[$table] !== null )
1642 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1643 else
1644 $ret[] = $this->tableName( $table );
1645
1646 return implode( ',', $ret );
1647 }
1648
1649 /**
1650 * Wrapper for addslashes()
1651 * @param string $s String to be slashed.
1652 * @return string slashed string.
1653 */
1654 function strencode( $s ) {
1655 return mysql_real_escape_string( $s, $this->mConn );
1656 }
1657
1658 /**
1659 * If it's a string, adds quotes and backslashes
1660 * Otherwise returns as-is
1661 */
1662 function addQuotes( $s ) {
1663 if ( is_null( $s ) ) {
1664 return 'NULL';
1665 } else {
1666 # This will also quote numeric values. This should be harmless,
1667 # and protects against weird problems that occur when they really
1668 # _are_ strings such as article titles and string->number->string
1669 # conversion is not 1:1.
1670 return "'" . $this->strencode( $s ) . "'";
1671 }
1672 }
1673
1674 /**
1675 * Escape string for safe LIKE usage
1676 */
1677 function escapeLike( $s ) {
1678 $s=$this->strencode( $s );
1679 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1680 return $s;
1681 }
1682
1683 /**
1684 * Returns an appropriately quoted sequence value for inserting a new row.
1685 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1686 * subclass will return an integer, and save the value for insertId()
1687 */
1688 function nextSequenceValue( $seqName ) {
1689 return NULL;
1690 }
1691
1692 /**
1693 * USE INDEX clause
1694 * PostgreSQL doesn't have them and returns ""
1695 */
1696 function useIndexClause( $index ) {
1697 return "FORCE INDEX ($index)";
1698 }
1699
1700 /**
1701 * REPLACE query wrapper
1702 * PostgreSQL simulates this with a DELETE followed by INSERT
1703 * $row is the row to insert, an associative array
1704 * $uniqueIndexes is an array of indexes. Each element may be either a
1705 * field name or an array of field names
1706 *
1707 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1708 * However if you do this, you run the risk of encountering errors which wouldn't have
1709 * occurred in MySQL
1710 *
1711 * @todo migrate comment to phodocumentor format
1712 */
1713 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1714 $table = $this->tableName( $table );
1715
1716 # Single row case
1717 if ( !is_array( reset( $rows ) ) ) {
1718 $rows = array( $rows );
1719 }
1720
1721 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1722 $first = true;
1723 foreach ( $rows as $row ) {
1724 if ( $first ) {
1725 $first = false;
1726 } else {
1727 $sql .= ',';
1728 }
1729 $sql .= '(' . $this->makeList( $row ) . ')';
1730 }
1731 return $this->query( $sql, $fname );
1732 }
1733
1734 /**
1735 * DELETE where the condition is a join
1736 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1737 *
1738 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1739 * join condition matches, set $conds='*'
1740 *
1741 * DO NOT put the join condition in $conds
1742 *
1743 * @param string $delTable The table to delete from.
1744 * @param string $joinTable The other table.
1745 * @param string $delVar The variable to join on, in the first table.
1746 * @param string $joinVar The variable to join on, in the second table.
1747 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1748 */
1749 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1750 if ( !$conds ) {
1751 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1752 }
1753
1754 $delTable = $this->tableName( $delTable );
1755 $joinTable = $this->tableName( $joinTable );
1756 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1757 if ( $conds != '*' ) {
1758 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1759 }
1760
1761 return $this->query( $sql, $fname );
1762 }
1763
1764 /**
1765 * Returns the size of a text field, or -1 for "unlimited"
1766 */
1767 function textFieldSize( $table, $field ) {
1768 $table = $this->tableName( $table );
1769 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1770 $res = $this->query( $sql, 'Database::textFieldSize' );
1771 $row = $this->fetchObject( $res );
1772 $this->freeResult( $res );
1773
1774 $m = array();
1775 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1776 $size = $m[1];
1777 } else {
1778 $size = -1;
1779 }
1780 return $size;
1781 }
1782
1783 /**
1784 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1785 */
1786 function lowPriorityOption() {
1787 return 'LOW_PRIORITY';
1788 }
1789
1790 /**
1791 * DELETE query wrapper
1792 *
1793 * Use $conds == "*" to delete all rows
1794 */
1795 function delete( $table, $conds, $fname = 'Database::delete' ) {
1796 if ( !$conds ) {
1797 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1798 }
1799 $table = $this->tableName( $table );
1800 $sql = "DELETE FROM $table";
1801 if ( $conds != '*' ) {
1802 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1803 }
1804 return $this->query( $sql, $fname );
1805 }
1806
1807 /**
1808 * INSERT SELECT wrapper
1809 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1810 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1811 * $conds may be "*" to copy the whole table
1812 * srcTable may be an array of tables.
1813 */
1814 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1815 $insertOptions = array(), $selectOptions = array() )
1816 {
1817 $destTable = $this->tableName( $destTable );
1818 if ( is_array( $insertOptions ) ) {
1819 $insertOptions = implode( ' ', $insertOptions );
1820 }
1821 if( !is_array( $selectOptions ) ) {
1822 $selectOptions = array( $selectOptions );
1823 }
1824 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1825 if( is_array( $srcTable ) ) {
1826 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1827 } else {
1828 $srcTable = $this->tableName( $srcTable );
1829 }
1830 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1831 " SELECT $startOpts " . implode( ',', $varMap ) .
1832 " FROM $srcTable $useIndex ";
1833 if ( $conds != '*' ) {
1834 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1835 }
1836 $sql .= " $tailOpts";
1837 return $this->query( $sql, $fname );
1838 }
1839
1840 /**
1841 * Construct a LIMIT query with optional offset
1842 * This is used for query pages
1843 * $sql string SQL query we will append the limit too
1844 * $limit integer the SQL limit
1845 * $offset integer the SQL offset (default false)
1846 */
1847 function limitResult($sql, $limit, $offset=false) {
1848 if( !is_numeric($limit) ) {
1849 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1850 }
1851 return " $sql LIMIT "
1852 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1853 . "{$limit} ";
1854 }
1855 function limitResultForUpdate($sql, $num) {
1856 return $this->limitResult($sql, $num, 0);
1857 }
1858
1859 /**
1860 * Returns an SQL expression for a simple conditional.
1861 * Uses IF on MySQL.
1862 *
1863 * @param string $cond SQL expression which will result in a boolean value
1864 * @param string $trueVal SQL expression to return if true
1865 * @param string $falseVal SQL expression to return if false
1866 * @return string SQL fragment
1867 */
1868 function conditional( $cond, $trueVal, $falseVal ) {
1869 return " IF($cond, $trueVal, $falseVal) ";
1870 }
1871
1872 /**
1873 * Determines if the last failure was due to a deadlock
1874 */
1875 function wasDeadlock() {
1876 return $this->lastErrno() == 1213;
1877 }
1878
1879 /**
1880 * Perform a deadlock-prone transaction.
1881 *
1882 * This function invokes a callback function to perform a set of write
1883 * queries. If a deadlock occurs during the processing, the transaction
1884 * will be rolled back and the callback function will be called again.
1885 *
1886 * Usage:
1887 * $dbw->deadlockLoop( callback, ... );
1888 *
1889 * Extra arguments are passed through to the specified callback function.
1890 *
1891 * Returns whatever the callback function returned on its successful,
1892 * iteration, or false on error, for example if the retry limit was
1893 * reached.
1894 */
1895 function deadlockLoop() {
1896 $myFname = 'Database::deadlockLoop';
1897
1898 $this->begin();
1899 $args = func_get_args();
1900 $function = array_shift( $args );
1901 $oldIgnore = $this->ignoreErrors( true );
1902 $tries = DEADLOCK_TRIES;
1903 if ( is_array( $function ) ) {
1904 $fname = $function[0];
1905 } else {
1906 $fname = $function;
1907 }
1908 do {
1909 $retVal = call_user_func_array( $function, $args );
1910 $error = $this->lastError();
1911 $errno = $this->lastErrno();
1912 $sql = $this->lastQuery();
1913
1914 if ( $errno ) {
1915 if ( $this->wasDeadlock() ) {
1916 # Retry
1917 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1918 } else {
1919 $this->reportQueryError( $error, $errno, $sql, $fname );
1920 }
1921 }
1922 } while( $this->wasDeadlock() && --$tries > 0 );
1923 $this->ignoreErrors( $oldIgnore );
1924 if ( $tries <= 0 ) {
1925 $this->query( 'ROLLBACK', $myFname );
1926 $this->reportQueryError( $error, $errno, $sql, $fname );
1927 return false;
1928 } else {
1929 $this->query( 'COMMIT', $myFname );
1930 return $retVal;
1931 }
1932 }
1933
1934 /**
1935 * Do a SELECT MASTER_POS_WAIT()
1936 *
1937 * @param string $file the binlog file
1938 * @param string $pos the binlog position
1939 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1940 */
1941 function masterPosWait( $file, $pos, $timeout ) {
1942 $fname = 'Database::masterPosWait';
1943 wfProfileIn( $fname );
1944
1945
1946 # Commit any open transactions
1947 $this->immediateCommit();
1948
1949 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1950 $encFile = $this->strencode( $file );
1951 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1952 $res = $this->doQuery( $sql );
1953 if ( $res && $row = $this->fetchRow( $res ) ) {
1954 $this->freeResult( $res );
1955 wfProfileOut( $fname );
1956 return $row[0];
1957 } else {
1958 wfProfileOut( $fname );
1959 return false;
1960 }
1961 }
1962
1963 /**
1964 * Get the position of the master from SHOW SLAVE STATUS
1965 */
1966 function getSlavePos() {
1967 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1968 $row = $this->fetchObject( $res );
1969 if ( $row ) {
1970 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1971 } else {
1972 return array( false, false );
1973 }
1974 }
1975
1976 /**
1977 * Get the position of the master from SHOW MASTER STATUS
1978 */
1979 function getMasterPos() {
1980 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1981 $row = $this->fetchObject( $res );
1982 if ( $row ) {
1983 return array( $row->File, $row->Position );
1984 } else {
1985 return array( false, false );
1986 }
1987 }
1988
1989 /**
1990 * Begin a transaction, committing any previously open transaction
1991 */
1992 function begin( $fname = 'Database::begin' ) {
1993 $this->query( 'BEGIN', $fname );
1994 $this->mTrxLevel = 1;
1995 }
1996
1997 /**
1998 * End a transaction
1999 */
2000 function commit( $fname = 'Database::commit' ) {
2001 $this->query( 'COMMIT', $fname );
2002 $this->mTrxLevel = 0;
2003 }
2004
2005 /**
2006 * Rollback a transaction
2007 */
2008 function rollback( $fname = 'Database::rollback' ) {
2009 $this->query( 'ROLLBACK', $fname );
2010 $this->mTrxLevel = 0;
2011 }
2012
2013 /**
2014 * Begin a transaction, committing any previously open transaction
2015 * @deprecated use begin()
2016 */
2017 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2018 $this->begin();
2019 }
2020
2021 /**
2022 * Commit transaction, if one is open
2023 * @deprecated use commit()
2024 */
2025 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2026 $this->commit();
2027 }
2028
2029 /**
2030 * Return MW-style timestamp used for MySQL schema
2031 */
2032 function timestamp( $ts=0 ) {
2033 return wfTimestamp(TS_MW,$ts);
2034 }
2035
2036 /**
2037 * Local database timestamp format or null
2038 */
2039 function timestampOrNull( $ts = null ) {
2040 if( is_null( $ts ) ) {
2041 return null;
2042 } else {
2043 return $this->timestamp( $ts );
2044 }
2045 }
2046
2047 /**
2048 * @todo document
2049 */
2050 function resultObject( $result ) {
2051 if( empty( $result ) ) {
2052 return false;
2053 } elseif ( $result instanceof ResultWrapper ) {
2054 return $result;
2055 } elseif ( $result === true ) {
2056 // Successful write query
2057 return $result;
2058 } else {
2059 return new ResultWrapper( $this, $result );
2060 }
2061 }
2062
2063 /**
2064 * Return aggregated value alias
2065 */
2066 function aggregateValue ($valuedata,$valuename='value') {
2067 return $valuename;
2068 }
2069
2070 /**
2071 * @return string wikitext of a link to the server software's web site
2072 */
2073 function getSoftwareLink() {
2074 return "[http://www.mysql.com/ MySQL]";
2075 }
2076
2077 /**
2078 * @return string Version information from the database
2079 */
2080 function getServerVersion() {
2081 return mysql_get_server_info( $this->mConn );
2082 }
2083
2084 /**
2085 * Ping the server and try to reconnect if it there is no connection
2086 */
2087 function ping() {
2088 if( function_exists( 'mysql_ping' ) ) {
2089 return mysql_ping( $this->mConn );
2090 } else {
2091 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2092 return true;
2093 }
2094 }
2095
2096 /**
2097 * Get slave lag.
2098 * At the moment, this will only work if the DB user has the PROCESS privilege
2099 */
2100 function getLag() {
2101 $res = $this->query( 'SHOW PROCESSLIST' );
2102 # Find slave SQL thread
2103 while ( $row = $this->fetchObject( $res ) ) {
2104 /* This should work for most situations - when default db
2105 * for thread is not specified, it had no events executed,
2106 * and therefore it doesn't know yet how lagged it is.
2107 *
2108 * Relay log I/O thread does not select databases.
2109 */
2110 if ( $row->User == 'system user' &&
2111 $row->State != 'Waiting for master to send event' &&
2112 $row->State != 'Connecting to master' &&
2113 $row->State != 'Queueing master event to the relay log' &&
2114 $row->State != 'Waiting for master update' &&
2115 $row->State != 'Requesting binlog dump'
2116 ) {
2117 # This is it, return the time (except -ve)
2118 if ( $row->Time > 0x7fffffff ) {
2119 return false;
2120 } else {
2121 return $row->Time;
2122 }
2123 }
2124 }
2125 return false;
2126 }
2127
2128 /**
2129 * Get status information from SHOW STATUS in an associative array
2130 */
2131 function getStatus($which="%") {
2132 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2133 $status = array();
2134 while ( $row = $this->fetchObject( $res ) ) {
2135 $status[$row->Variable_name] = $row->Value;
2136 }
2137 return $status;
2138 }
2139
2140 /**
2141 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2142 */
2143 function maxListLen() {
2144 return 0;
2145 }
2146
2147 function encodeBlob($b) {
2148 return $b;
2149 }
2150
2151 function decodeBlob($b) {
2152 return $b;
2153 }
2154
2155 /**
2156 * Override database's default connection timeout.
2157 * May be useful for very long batch queries such as
2158 * full-wiki dumps, where a single query reads out
2159 * over hours or days.
2160 * @param int $timeout in seconds
2161 */
2162 public function setTimeout( $timeout ) {
2163 $this->query( "SET net_read_timeout=$timeout" );
2164 $this->query( "SET net_write_timeout=$timeout" );
2165 }
2166
2167 /**
2168 * Read and execute SQL commands from a file.
2169 * Returns true on success, error string on failure
2170 * @param string $filename File name to open
2171 * @param callback $lineCallback Optional function called before reading each line
2172 * @param callback $resultCallback Optional function called for each MySQL result
2173 */
2174 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2175 $fp = fopen( $filename, 'r' );
2176 if ( false === $fp ) {
2177 return "Could not open \"{$filename}\".\n";
2178 }
2179 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2180 fclose( $fp );
2181 return $error;
2182 }
2183
2184 /**
2185 * Read and execute commands from an open file handle
2186 * Returns true on success, error string on failure
2187 * @param string $fp File handle
2188 * @param callback $lineCallback Optional function called before reading each line
2189 * @param callback $resultCallback Optional function called for each MySQL result
2190 */
2191 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2192 $cmd = "";
2193 $done = false;
2194 $dollarquote = false;
2195
2196 while ( ! feof( $fp ) ) {
2197 if ( $lineCallback ) {
2198 call_user_func( $lineCallback );
2199 }
2200 $line = trim( fgets( $fp, 1024 ) );
2201 $sl = strlen( $line ) - 1;
2202
2203 if ( $sl < 0 ) { continue; }
2204 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2205
2206 ## Allow dollar quoting for function declarations
2207 if (substr($line,0,4) == '$mw$') {
2208 if ($dollarquote) {
2209 $dollarquote = false;
2210 $done = true;
2211 }
2212 else {
2213 $dollarquote = true;
2214 }
2215 }
2216 else if (!$dollarquote) {
2217 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2218 $done = true;
2219 $line = substr( $line, 0, $sl );
2220 }
2221 }
2222
2223 if ( '' != $cmd ) { $cmd .= ' '; }
2224 $cmd .= "$line\n";
2225
2226 if ( $done ) {
2227 $cmd = str_replace(';;', ";", $cmd);
2228 $cmd = $this->replaceVars( $cmd );
2229 $res = $this->query( $cmd, __METHOD__, true );
2230 if ( $resultCallback ) {
2231 call_user_func( $resultCallback, $res );
2232 }
2233
2234 if ( false === $res ) {
2235 $err = $this->lastError();
2236 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2237 }
2238
2239 $cmd = '';
2240 $done = false;
2241 }
2242 }
2243 return true;
2244 }
2245
2246
2247 /**
2248 * Replace variables in sourced SQL
2249 */
2250 protected function replaceVars( $ins ) {
2251 $varnames = array(
2252 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2253 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2254 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2255 );
2256
2257 // Ordinary variables
2258 foreach ( $varnames as $var ) {
2259 if( isset( $GLOBALS[$var] ) ) {
2260 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2261 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2262 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2263 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2264 }
2265 }
2266
2267 // Table prefixes
2268 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2269 array( &$this, 'tableNameCallback' ), $ins );
2270 return $ins;
2271 }
2272
2273 /**
2274 * Table name callback
2275 * @private
2276 */
2277 protected function tableNameCallback( $matches ) {
2278 return $this->tableName( $matches[1] );
2279 }
2280
2281 }
2282
2283 /**
2284 * Database abstraction object for mySQL
2285 * Inherit all methods and properties of Database::Database()
2286 *
2287 * @addtogroup Database
2288 * @see Database
2289 */
2290 class DatabaseMysql extends Database {
2291 # Inherit all
2292 }
2293
2294
2295 /**
2296 * Result wrapper for grabbing data queried by someone else
2297 * @addtogroup Database
2298 */
2299 class ResultWrapper implements Iterator {
2300 var $db, $result, $pos = 0, $currentRow = null;
2301
2302 /**
2303 * Create a new result object from a result resource and a Database object
2304 */
2305 function ResultWrapper( $database, $result ) {
2306 $this->db = $database;
2307 if ( $result instanceof ResultWrapper ) {
2308 $this->result = $result->result;
2309 } else {
2310 $this->result = $result;
2311 }
2312 }
2313
2314 /**
2315 * Get the number of rows in a result object
2316 */
2317 function numRows() {
2318 return $this->db->numRows( $this->result );
2319 }
2320
2321 /**
2322 * Fetch the next row from the given result object, in object form.
2323 * Fields can be retrieved with $row->fieldname, with fields acting like
2324 * member variables.
2325 *
2326 * @param $res SQL result object as returned from Database::query(), etc.
2327 * @return MySQL row object
2328 * @throws DBUnexpectedError Thrown if the database returns an error
2329 */
2330 function fetchObject() {
2331 return $this->db->fetchObject( $this->result );
2332 }
2333
2334 /**
2335 * Fetch the next row from the given result object, in associative array
2336 * form. Fields are retrieved with $row['fieldname'].
2337 *
2338 * @param $res SQL result object as returned from Database::query(), etc.
2339 * @return MySQL row object
2340 * @throws DBUnexpectedError Thrown if the database returns an error
2341 */
2342 function fetchRow() {
2343 return $this->db->fetchRow( $this->result );
2344 }
2345
2346 /**
2347 * Free a result object
2348 */
2349 function free() {
2350 $this->db->freeResult( $this->result );
2351 unset( $this->result );
2352 unset( $this->db );
2353 }
2354
2355 /**
2356 * Change the position of the cursor in a result object
2357 * See mysql_data_seek()
2358 */
2359 function seek( $row ) {
2360 $this->db->dataSeek( $this->result, $row );
2361 }
2362
2363 /*********************
2364 * Iterator functions
2365 * Note that using these in combination with the non-iterator functions
2366 * above may cause rows to be skipped or repeated.
2367 */
2368
2369 function rewind() {
2370 if ($this->numRows()) {
2371 $this->db->dataSeek($this->result, 0);
2372 }
2373 $this->pos = 0;
2374 $this->currentRow = null;
2375 }
2376
2377 function current() {
2378 if ( is_null( $this->currentRow ) ) {
2379 $this->next();
2380 }
2381 return $this->currentRow;
2382 }
2383
2384 function key() {
2385 return $this->pos;
2386 }
2387
2388 function next() {
2389 $this->pos++;
2390 $this->currentRow = $this->fetchObject();
2391 return $this->currentRow;
2392 }
2393
2394 function valid() {
2395 return $this->current() !== false;
2396 }
2397 }
2398
2399