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