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