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