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