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