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