14764bd8fd4d0a54e9d45756bc03e53243f636f1
[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 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1013 * @param mixed $vars Array or string, field name(s) to be retrieved
1014 * @param mixed $conds Array or string, condition(s) for WHERE
1015 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1016 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1017 * see Database::makeSelectOptions code for list of supported stuff
1018 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1019 */
1020 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1021 {
1022 if( is_array( $vars ) ) {
1023 $vars = implode( ',', $vars );
1024 }
1025 if( !is_array( $options ) ) {
1026 $options = array( $options );
1027 }
1028 if( is_array( $table ) ) {
1029 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1030 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1031 else
1032 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1033 } elseif ($table!='') {
1034 $from = ' FROM ' . $this->tableName( $table );
1035 } else {
1036 $from = '';
1037 }
1038
1039 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
1040
1041 if( !empty( $conds ) ) {
1042 if ( is_array( $conds ) ) {
1043 $conds = $this->makeList( $conds, LIST_AND );
1044 }
1045 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1046 } else {
1047 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1048 }
1049
1050 return $this->query( $sql, $fname );
1051 }
1052
1053 /**
1054 * Single row SELECT wrapper
1055 * Aborts or returns FALSE on error
1056 *
1057 * $vars: the selected variables
1058 * $conds: a condition map, terms are ANDed together.
1059 * Items with numeric keys are taken to be literal conditions
1060 * Takes an array of selected variables, and a condition map, which is ANDed
1061 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1062 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1063 * $obj- >page_id is the ID of the Astronomy article
1064 *
1065 * @todo migrate documentation to phpdocumentor format
1066 */
1067 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1068 $options['LIMIT'] = 1;
1069 $res = $this->select( $table, $vars, $conds, $fname, $options );
1070 if ( $res === false )
1071 return false;
1072 if ( !$this->numRows($res) ) {
1073 $this->freeResult($res);
1074 return false;
1075 }
1076 $obj = $this->fetchObject( $res );
1077 $this->freeResult( $res );
1078 return $obj;
1079
1080 }
1081
1082 /**
1083 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1084 * It's only slightly flawed. Don't use for anything important.
1085 *
1086 * @param string $sql A SQL Query
1087 * @static
1088 */
1089 static function generalizeSQL( $sql ) {
1090 # This does the same as the regexp below would do, but in such a way
1091 # as to avoid crashing php on some large strings.
1092 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1093
1094 $sql = str_replace ( "\\\\", '', $sql);
1095 $sql = str_replace ( "\\'", '', $sql);
1096 $sql = str_replace ( "\\\"", '', $sql);
1097 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1098 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1099
1100 # All newlines, tabs, etc replaced by single space
1101 $sql = preg_replace ( '/\s+/', ' ', $sql);
1102
1103 # All numbers => N
1104 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1105
1106 return $sql;
1107 }
1108
1109 /**
1110 * Determines whether a field exists in a table
1111 * Usually aborts on failure
1112 * If errors are explicitly ignored, returns NULL on failure
1113 */
1114 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1115 $table = $this->tableName( $table );
1116 $res = $this->query( 'DESCRIBE '.$table, $fname );
1117 if ( !$res ) {
1118 return NULL;
1119 }
1120
1121 $found = false;
1122
1123 while ( $row = $this->fetchObject( $res ) ) {
1124 if ( $row->Field == $field ) {
1125 $found = true;
1126 break;
1127 }
1128 }
1129 return $found;
1130 }
1131
1132 /**
1133 * Determines whether an index exists
1134 * Usually aborts on failure
1135 * If errors are explicitly ignored, returns NULL on failure
1136 */
1137 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1138 $info = $this->indexInfo( $table, $index, $fname );
1139 if ( is_null( $info ) ) {
1140 return NULL;
1141 } else {
1142 return $info !== false;
1143 }
1144 }
1145
1146
1147 /**
1148 * Get information about an index into an object
1149 * Returns false if the index does not exist
1150 */
1151 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1152 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1153 # SHOW INDEX should work for 3.x and up:
1154 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1155 $table = $this->tableName( $table );
1156 $sql = 'SHOW INDEX FROM '.$table;
1157 $res = $this->query( $sql, $fname );
1158 if ( !$res ) {
1159 return NULL;
1160 }
1161
1162 $result = array();
1163 while ( $row = $this->fetchObject( $res ) ) {
1164 if ( $row->Key_name == $index ) {
1165 $result[] = $row;
1166 }
1167 }
1168 $this->freeResult($res);
1169
1170 return empty($result) ? false : $result;
1171 }
1172
1173 /**
1174 * Query whether a given table exists
1175 */
1176 function tableExists( $table ) {
1177 $table = $this->tableName( $table );
1178 $old = $this->ignoreErrors( true );
1179 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1180 $this->ignoreErrors( $old );
1181 if( $res ) {
1182 $this->freeResult( $res );
1183 return true;
1184 } else {
1185 return false;
1186 }
1187 }
1188
1189 /**
1190 * mysql_fetch_field() wrapper
1191 * Returns false if the field doesn't exist
1192 *
1193 * @param $table
1194 * @param $field
1195 */
1196 function fieldInfo( $table, $field ) {
1197 $table = $this->tableName( $table );
1198 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1199 $n = mysql_num_fields( $res );
1200 for( $i = 0; $i < $n; $i++ ) {
1201 $meta = mysql_fetch_field( $res, $i );
1202 if( $field == $meta->name ) {
1203 return $meta;
1204 }
1205 }
1206 return false;
1207 }
1208
1209 /**
1210 * mysql_field_type() wrapper
1211 */
1212 function fieldType( $res, $index ) {
1213 return mysql_field_type( $res, $index );
1214 }
1215
1216 /**
1217 * Determines if a given index is unique
1218 */
1219 function indexUnique( $table, $index ) {
1220 $indexInfo = $this->indexInfo( $table, $index );
1221 if ( !$indexInfo ) {
1222 return NULL;
1223 }
1224 return !$indexInfo[0]->Non_unique;
1225 }
1226
1227 /**
1228 * INSERT wrapper, inserts an array into a table
1229 *
1230 * $a may be a single associative array, or an array of these with numeric keys, for
1231 * multi-row insert.
1232 *
1233 * Usually aborts on failure
1234 * If errors are explicitly ignored, returns success
1235 */
1236 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1237 # No rows to insert, easy just return now
1238 if ( !count( $a ) ) {
1239 return true;
1240 }
1241
1242 $table = $this->tableName( $table );
1243 if ( !is_array( $options ) ) {
1244 $options = array( $options );
1245 }
1246 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1247 $multi = true;
1248 $keys = array_keys( $a[0] );
1249 } else {
1250 $multi = false;
1251 $keys = array_keys( $a );
1252 }
1253
1254 $sql = 'INSERT ' . implode( ' ', $options ) .
1255 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1256
1257 if ( $multi ) {
1258 $first = true;
1259 foreach ( $a as $row ) {
1260 if ( $first ) {
1261 $first = false;
1262 } else {
1263 $sql .= ',';
1264 }
1265 $sql .= '(' . $this->makeList( $row ) . ')';
1266 }
1267 } else {
1268 $sql .= '(' . $this->makeList( $a ) . ')';
1269 }
1270 return (bool)$this->query( $sql, $fname );
1271 }
1272
1273 /**
1274 * Make UPDATE options for the Database::update function
1275 *
1276 * @private
1277 * @param array $options The options passed to Database::update
1278 * @return string
1279 */
1280 function makeUpdateOptions( $options ) {
1281 if( !is_array( $options ) ) {
1282 $options = array( $options );
1283 }
1284 $opts = array();
1285 if ( in_array( 'LOW_PRIORITY', $options ) )
1286 $opts[] = $this->lowPriorityOption();
1287 if ( in_array( 'IGNORE', $options ) )
1288 $opts[] = 'IGNORE';
1289 return implode(' ', $opts);
1290 }
1291
1292 /**
1293 * UPDATE wrapper, takes a condition array and a SET array
1294 *
1295 * @param string $table The table to UPDATE
1296 * @param array $values An array of values to SET
1297 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1298 * @param string $fname The Class::Function calling this function
1299 * (for the log)
1300 * @param array $options An array of UPDATE options, can be one or
1301 * more of IGNORE, LOW_PRIORITY
1302 */
1303 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1304 $table = $this->tableName( $table );
1305 $opts = $this->makeUpdateOptions( $options );
1306 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1307 if ( $conds != '*' ) {
1308 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1309 }
1310 $this->query( $sql, $fname );
1311 }
1312
1313 /**
1314 * Makes an encoded list of strings from an array
1315 * $mode:
1316 * LIST_COMMA - comma separated, no field names
1317 * LIST_AND - ANDed WHERE clause (without the WHERE)
1318 * LIST_OR - ORed WHERE clause (without the WHERE)
1319 * LIST_SET - comma separated with field names, like a SET clause
1320 * LIST_NAMES - comma separated field names
1321 */
1322 function makeList( $a, $mode = LIST_COMMA ) {
1323 if ( !is_array( $a ) ) {
1324 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1325 }
1326
1327 $first = true;
1328 $list = '';
1329 foreach ( $a as $field => $value ) {
1330 if ( !$first ) {
1331 if ( $mode == LIST_AND ) {
1332 $list .= ' AND ';
1333 } elseif($mode == LIST_OR) {
1334 $list .= ' OR ';
1335 } else {
1336 $list .= ',';
1337 }
1338 } else {
1339 $first = false;
1340 }
1341 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1342 $list .= "($value)";
1343 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1344 $list .= "$value";
1345 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1346 $list .= $field." IN (".$this->makeList($value).") ";
1347 } else {
1348 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1349 $list .= "$field = ";
1350 }
1351 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1352 }
1353 }
1354 return $list;
1355 }
1356
1357 /**
1358 * Change the current database
1359 */
1360 function selectDB( $db ) {
1361 $this->mDBname = $db;
1362 return mysql_select_db( $db, $this->mConn );
1363 }
1364
1365 /**
1366 * Format a table name ready for use in constructing an SQL query
1367 *
1368 * This does two important things: it quotes table names which as necessary,
1369 * and it adds a table prefix if there is one.
1370 *
1371 * All functions of this object which require a table name call this function
1372 * themselves. Pass the canonical name to such functions. This is only needed
1373 * when calling query() directly.
1374 *
1375 * @param string $name database table name
1376 */
1377 function tableName( $name ) {
1378 global $wgSharedDB;
1379 # Skip quoted literals
1380 if ( $name{0} != '`' ) {
1381 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1382 $name = "{$this->mTablePrefix}$name";
1383 }
1384 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1385 $name = "`$wgSharedDB`.`$name`";
1386 } else {
1387 # Standard quoting
1388 $name = "`$name`";
1389 }
1390 }
1391 return $name;
1392 }
1393
1394 /**
1395 * Fetch a number of table names into an array
1396 * This is handy when you need to construct SQL for joins
1397 *
1398 * Example:
1399 * extract($dbr->tableNames('user','watchlist'));
1400 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1401 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1402 */
1403 public function tableNames() {
1404 $inArray = func_get_args();
1405 $retVal = array();
1406 foreach ( $inArray as $name ) {
1407 $retVal[$name] = $this->tableName( $name );
1408 }
1409 return $retVal;
1410 }
1411
1412 /**
1413 * @desc: Fetch a number of table names into an zero-indexed numerical array
1414 * This is handy when you need to construct SQL for joins
1415 *
1416 * Example:
1417 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1418 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1419 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1420 */
1421 public function tableNamesN() {
1422 $inArray = func_get_args();
1423 $retVal = array();
1424 foreach ( $inArray as $name ) {
1425 $retVal[] = $this->tableName( $name );
1426 }
1427 return $retVal;
1428 }
1429
1430 /**
1431 * @private
1432 */
1433 function tableNamesWithUseIndex( $tables, $use_index ) {
1434 $ret = array();
1435
1436 foreach ( $tables as $table )
1437 if ( @$use_index[$table] !== null )
1438 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1439 else
1440 $ret[] = $this->tableName( $table );
1441
1442 return implode( ',', $ret );
1443 }
1444
1445 /**
1446 * Wrapper for addslashes()
1447 * @param string $s String to be slashed.
1448 * @return string slashed string.
1449 */
1450 function strencode( $s ) {
1451 return mysql_real_escape_string( $s, $this->mConn );
1452 }
1453
1454 /**
1455 * If it's a string, adds quotes and backslashes
1456 * Otherwise returns as-is
1457 */
1458 function addQuotes( $s ) {
1459 if ( is_null( $s ) ) {
1460 return 'NULL';
1461 } else {
1462 # This will also quote numeric values. This should be harmless,
1463 # and protects against weird problems that occur when they really
1464 # _are_ strings such as article titles and string->number->string
1465 # conversion is not 1:1.
1466 return "'" . $this->strencode( $s ) . "'";
1467 }
1468 }
1469
1470 /**
1471 * Escape string for safe LIKE usage
1472 */
1473 function escapeLike( $s ) {
1474 $s=$this->strencode( $s );
1475 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1476 return $s;
1477 }
1478
1479 /**
1480 * Returns an appropriately quoted sequence value for inserting a new row.
1481 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1482 * subclass will return an integer, and save the value for insertId()
1483 */
1484 function nextSequenceValue( $seqName ) {
1485 return NULL;
1486 }
1487
1488 /**
1489 * USE INDEX clause
1490 * PostgreSQL doesn't have them and returns ""
1491 */
1492 function useIndexClause( $index ) {
1493 return "FORCE INDEX ($index)";
1494 }
1495
1496 /**
1497 * REPLACE query wrapper
1498 * PostgreSQL simulates this with a DELETE followed by INSERT
1499 * $row is the row to insert, an associative array
1500 * $uniqueIndexes is an array of indexes. Each element may be either a
1501 * field name or an array of field names
1502 *
1503 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1504 * However if you do this, you run the risk of encountering errors which wouldn't have
1505 * occurred in MySQL
1506 *
1507 * @todo migrate comment to phodocumentor format
1508 */
1509 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1510 $table = $this->tableName( $table );
1511
1512 # Single row case
1513 if ( !is_array( reset( $rows ) ) ) {
1514 $rows = array( $rows );
1515 }
1516
1517 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1518 $first = true;
1519 foreach ( $rows as $row ) {
1520 if ( $first ) {
1521 $first = false;
1522 } else {
1523 $sql .= ',';
1524 }
1525 $sql .= '(' . $this->makeList( $row ) . ')';
1526 }
1527 return $this->query( $sql, $fname );
1528 }
1529
1530 /**
1531 * DELETE where the condition is a join
1532 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1533 *
1534 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1535 * join condition matches, set $conds='*'
1536 *
1537 * DO NOT put the join condition in $conds
1538 *
1539 * @param string $delTable The table to delete from.
1540 * @param string $joinTable The other table.
1541 * @param string $delVar The variable to join on, in the first table.
1542 * @param string $joinVar The variable to join on, in the second table.
1543 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1544 */
1545 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1546 if ( !$conds ) {
1547 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1548 }
1549
1550 $delTable = $this->tableName( $delTable );
1551 $joinTable = $this->tableName( $joinTable );
1552 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1553 if ( $conds != '*' ) {
1554 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1555 }
1556
1557 return $this->query( $sql, $fname );
1558 }
1559
1560 /**
1561 * Returns the size of a text field, or -1 for "unlimited"
1562 */
1563 function textFieldSize( $table, $field ) {
1564 $table = $this->tableName( $table );
1565 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1566 $res = $this->query( $sql, 'Database::textFieldSize' );
1567 $row = $this->fetchObject( $res );
1568 $this->freeResult( $res );
1569
1570 $m = array();
1571 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1572 $size = $m[1];
1573 } else {
1574 $size = -1;
1575 }
1576 return $size;
1577 }
1578
1579 /**
1580 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1581 */
1582 function lowPriorityOption() {
1583 return 'LOW_PRIORITY';
1584 }
1585
1586 /**
1587 * DELETE query wrapper
1588 *
1589 * Use $conds == "*" to delete all rows
1590 */
1591 function delete( $table, $conds, $fname = 'Database::delete' ) {
1592 if ( !$conds ) {
1593 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1594 }
1595 $table = $this->tableName( $table );
1596 $sql = "DELETE FROM $table";
1597 if ( $conds != '*' ) {
1598 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1599 }
1600 return $this->query( $sql, $fname );
1601 }
1602
1603 /**
1604 * INSERT SELECT wrapper
1605 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1606 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1607 * $conds may be "*" to copy the whole table
1608 * srcTable may be an array of tables.
1609 */
1610 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1611 $insertOptions = array(), $selectOptions = array() )
1612 {
1613 $destTable = $this->tableName( $destTable );
1614 if ( is_array( $insertOptions ) ) {
1615 $insertOptions = implode( ' ', $insertOptions );
1616 }
1617 if( !is_array( $selectOptions ) ) {
1618 $selectOptions = array( $selectOptions );
1619 }
1620 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1621 if( is_array( $srcTable ) ) {
1622 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1623 } else {
1624 $srcTable = $this->tableName( $srcTable );
1625 }
1626 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1627 " SELECT $startOpts " . implode( ',', $varMap ) .
1628 " FROM $srcTable $useIndex ";
1629 if ( $conds != '*' ) {
1630 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1631 }
1632 $sql .= " $tailOpts";
1633 return $this->query( $sql, $fname );
1634 }
1635
1636 /**
1637 * Construct a LIMIT query with optional offset
1638 * This is used for query pages
1639 * $sql string SQL query we will append the limit too
1640 * $limit integer the SQL limit
1641 * $offset integer the SQL offset (default false)
1642 */
1643 function limitResult($sql, $limit, $offset=false) {
1644 if( !is_numeric($limit) ) {
1645 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1646 }
1647 return " $sql LIMIT "
1648 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1649 . "{$limit} ";
1650 }
1651 function limitResultForUpdate($sql, $num) {
1652 return $this->limitResult($sql, $num, 0);
1653 }
1654
1655 /**
1656 * Returns an SQL expression for a simple conditional.
1657 * Uses IF on MySQL.
1658 *
1659 * @param string $cond SQL expression which will result in a boolean value
1660 * @param string $trueVal SQL expression to return if true
1661 * @param string $falseVal SQL expression to return if false
1662 * @return string SQL fragment
1663 */
1664 function conditional( $cond, $trueVal, $falseVal ) {
1665 return " IF($cond, $trueVal, $falseVal) ";
1666 }
1667
1668 /**
1669 * Determines if the last failure was due to a deadlock
1670 */
1671 function wasDeadlock() {
1672 return $this->lastErrno() == 1213;
1673 }
1674
1675 /**
1676 * Perform a deadlock-prone transaction.
1677 *
1678 * This function invokes a callback function to perform a set of write
1679 * queries. If a deadlock occurs during the processing, the transaction
1680 * will be rolled back and the callback function will be called again.
1681 *
1682 * Usage:
1683 * $dbw->deadlockLoop( callback, ... );
1684 *
1685 * Extra arguments are passed through to the specified callback function.
1686 *
1687 * Returns whatever the callback function returned on its successful,
1688 * iteration, or false on error, for example if the retry limit was
1689 * reached.
1690 */
1691 function deadlockLoop() {
1692 $myFname = 'Database::deadlockLoop';
1693
1694 $this->begin();
1695 $args = func_get_args();
1696 $function = array_shift( $args );
1697 $oldIgnore = $this->ignoreErrors( true );
1698 $tries = DEADLOCK_TRIES;
1699 if ( is_array( $function ) ) {
1700 $fname = $function[0];
1701 } else {
1702 $fname = $function;
1703 }
1704 do {
1705 $retVal = call_user_func_array( $function, $args );
1706 $error = $this->lastError();
1707 $errno = $this->lastErrno();
1708 $sql = $this->lastQuery();
1709
1710 if ( $errno ) {
1711 if ( $this->wasDeadlock() ) {
1712 # Retry
1713 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1714 } else {
1715 $this->reportQueryError( $error, $errno, $sql, $fname );
1716 }
1717 }
1718 } while( $this->wasDeadlock() && --$tries > 0 );
1719 $this->ignoreErrors( $oldIgnore );
1720 if ( $tries <= 0 ) {
1721 $this->query( 'ROLLBACK', $myFname );
1722 $this->reportQueryError( $error, $errno, $sql, $fname );
1723 return false;
1724 } else {
1725 $this->query( 'COMMIT', $myFname );
1726 return $retVal;
1727 }
1728 }
1729
1730 /**
1731 * Do a SELECT MASTER_POS_WAIT()
1732 *
1733 * @param string $file the binlog file
1734 * @param string $pos the binlog position
1735 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1736 */
1737 function masterPosWait( $file, $pos, $timeout ) {
1738 $fname = 'Database::masterPosWait';
1739 wfProfileIn( $fname );
1740
1741
1742 # Commit any open transactions
1743 $this->immediateCommit();
1744
1745 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1746 $encFile = $this->strencode( $file );
1747 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1748 $res = $this->doQuery( $sql );
1749 if ( $res && $row = $this->fetchRow( $res ) ) {
1750 $this->freeResult( $res );
1751 wfProfileOut( $fname );
1752 return $row[0];
1753 } else {
1754 wfProfileOut( $fname );
1755 return false;
1756 }
1757 }
1758
1759 /**
1760 * Get the position of the master from SHOW SLAVE STATUS
1761 */
1762 function getSlavePos() {
1763 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1764 $row = $this->fetchObject( $res );
1765 if ( $row ) {
1766 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1767 } else {
1768 return array( false, false );
1769 }
1770 }
1771
1772 /**
1773 * Get the position of the master from SHOW MASTER STATUS
1774 */
1775 function getMasterPos() {
1776 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1777 $row = $this->fetchObject( $res );
1778 if ( $row ) {
1779 return array( $row->File, $row->Position );
1780 } else {
1781 return array( false, false );
1782 }
1783 }
1784
1785 /**
1786 * Begin a transaction, committing any previously open transaction
1787 */
1788 function begin( $fname = 'Database::begin' ) {
1789 $this->query( 'BEGIN', $fname );
1790 $this->mTrxLevel = 1;
1791 }
1792
1793 /**
1794 * End a transaction
1795 */
1796 function commit( $fname = 'Database::commit' ) {
1797 $this->query( 'COMMIT', $fname );
1798 $this->mTrxLevel = 0;
1799 }
1800
1801 /**
1802 * Rollback a transaction
1803 */
1804 function rollback( $fname = 'Database::rollback' ) {
1805 $this->query( 'ROLLBACK', $fname );
1806 $this->mTrxLevel = 0;
1807 }
1808
1809 /**
1810 * Begin a transaction, committing any previously open transaction
1811 * @deprecated use begin()
1812 */
1813 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1814 $this->begin();
1815 }
1816
1817 /**
1818 * Commit transaction, if one is open
1819 * @deprecated use commit()
1820 */
1821 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1822 $this->commit();
1823 }
1824
1825 /**
1826 * Return MW-style timestamp used for MySQL schema
1827 */
1828 function timestamp( $ts=0 ) {
1829 return wfTimestamp(TS_MW,$ts);
1830 }
1831
1832 /**
1833 * Local database timestamp format or null
1834 */
1835 function timestampOrNull( $ts = null ) {
1836 if( is_null( $ts ) ) {
1837 return null;
1838 } else {
1839 return $this->timestamp( $ts );
1840 }
1841 }
1842
1843 /**
1844 * @todo document
1845 */
1846 function resultObject( $result ) {
1847 if( empty( $result ) ) {
1848 return NULL;
1849 } else {
1850 return new ResultWrapper( $this, $result );
1851 }
1852 }
1853
1854 /**
1855 * Return aggregated value alias
1856 */
1857 function aggregateValue ($valuedata,$valuename='value') {
1858 return $valuename;
1859 }
1860
1861 /**
1862 * @return string wikitext of a link to the server software's web site
1863 */
1864 function getSoftwareLink() {
1865 return "[http://www.mysql.com/ MySQL]";
1866 }
1867
1868 /**
1869 * @return string Version information from the database
1870 */
1871 function getServerVersion() {
1872 return mysql_get_server_info( $this->mConn );
1873 }
1874
1875 /**
1876 * Ping the server and try to reconnect if it there is no connection
1877 */
1878 function ping() {
1879 if( function_exists( 'mysql_ping' ) ) {
1880 return mysql_ping( $this->mConn );
1881 } else {
1882 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1883 return true;
1884 }
1885 }
1886
1887 /**
1888 * Get slave lag.
1889 * At the moment, this will only work if the DB user has the PROCESS privilege
1890 */
1891 function getLag() {
1892 $res = $this->query( 'SHOW PROCESSLIST' );
1893 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1894 # dubious, but unfortunately there's no easy rigorous way
1895 while ( $row = $this->fetchObject( $res ) ) {
1896 /* This should work for most situations - when default db
1897 * for thread is not specified, it had no events executed,
1898 * and therefore it doesn't know yet how lagged it is.
1899 *
1900 * Relay log I/O thread does not select databases.
1901 */
1902 if ( $row->User == 'system user' &&
1903 $row->State != 'Waiting for master to send event' &&
1904 $row->State != 'Connecting to master' &&
1905 $row->State != 'Queueing master event to the relay log' &&
1906 $row->State != 'Waiting for master update' &&
1907 $row->State != 'Requesting binlog dump'
1908 ) {
1909 # This is it, return the time (except -ve)
1910 if ( $row->Time > 0x7fffffff ) {
1911 return false;
1912 } else {
1913 return $row->Time;
1914 }
1915 }
1916 }
1917 return false;
1918 }
1919
1920 /**
1921 * Get status information from SHOW STATUS in an associative array
1922 */
1923 function getStatus($which="%") {
1924 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1925 $status = array();
1926 while ( $row = $this->fetchObject( $res ) ) {
1927 $status[$row->Variable_name] = $row->Value;
1928 }
1929 return $status;
1930 }
1931
1932 /**
1933 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1934 */
1935 function maxListLen() {
1936 return 0;
1937 }
1938
1939 function encodeBlob($b) {
1940 return $b;
1941 }
1942
1943 function decodeBlob($b) {
1944 return $b;
1945 }
1946
1947 /**
1948 * Read and execute SQL commands from a file.
1949 * Returns true on success, error string on failure
1950 */
1951 function sourceFile( $filename ) {
1952 $fp = fopen( $filename, 'r' );
1953 if ( false === $fp ) {
1954 return "Could not open \"{$filename}\".\n";
1955 }
1956
1957 $cmd = "";
1958 $done = false;
1959 $dollarquote = false;
1960
1961 while ( ! feof( $fp ) ) {
1962 $line = trim( fgets( $fp, 1024 ) );
1963 $sl = strlen( $line ) - 1;
1964
1965 if ( $sl < 0 ) { continue; }
1966 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1967
1968 ## Allow dollar quoting for function declarations
1969 if (substr($line,0,4) == '$mw$') {
1970 if ($dollarquote) {
1971 $dollarquote = false;
1972 $done = true;
1973 }
1974 else {
1975 $dollarquote = true;
1976 }
1977 }
1978 else if (!$dollarquote) {
1979 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
1980 $done = true;
1981 $line = substr( $line, 0, $sl );
1982 }
1983 }
1984
1985 if ( '' != $cmd ) { $cmd .= ' '; }
1986 $cmd .= "$line\n";
1987
1988 if ( $done ) {
1989 $cmd = str_replace(';;', ";", $cmd);
1990 $cmd = $this->replaceVars( $cmd );
1991 $res = $this->query( $cmd, 'dbsource', true );
1992
1993 if ( false === $res ) {
1994 $err = $this->lastError();
1995 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1996 }
1997
1998 $cmd = '';
1999 $done = false;
2000 }
2001 }
2002 fclose( $fp );
2003 return true;
2004 }
2005
2006 /**
2007 * Replace variables in sourced SQL
2008 */
2009 protected function replaceVars( $ins ) {
2010 $varnames = array(
2011 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2012 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2013 'wgDBadminuser', 'wgDBadminpassword',
2014 );
2015
2016 // Ordinary variables
2017 foreach ( $varnames as $var ) {
2018 if( isset( $GLOBALS[$var] ) ) {
2019 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2020 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2021 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2022 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2023 }
2024 }
2025
2026 // Table prefixes
2027 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2028 array( &$this, 'tableNameCallback' ), $ins );
2029 return $ins;
2030 }
2031
2032 /**
2033 * Table name callback
2034 * @private
2035 */
2036 protected function tableNameCallback( $matches ) {
2037 return $this->tableName( $matches[1] );
2038 }
2039
2040 }
2041
2042 /**
2043 * Database abstraction object for mySQL
2044 * Inherit all methods and properties of Database::Database()
2045 *
2046 * @package MediaWiki
2047 * @see Database
2048 */
2049 class DatabaseMysql extends Database {
2050 # Inherit all
2051 }
2052
2053
2054 /**
2055 * Result wrapper for grabbing data queried by someone else
2056 *
2057 * @package MediaWiki
2058 */
2059 class ResultWrapper {
2060 var $db, $result;
2061
2062 /**
2063 * @todo document
2064 */
2065 function ResultWrapper( &$database, $result ) {
2066 $this->db =& $database;
2067 $this->result =& $result;
2068 }
2069
2070 /**
2071 * @todo document
2072 */
2073 function numRows() {
2074 return $this->db->numRows( $this->result );
2075 }
2076
2077 /**
2078 * @todo document
2079 */
2080 function fetchObject() {
2081 return $this->db->fetchObject( $this->result );
2082 }
2083
2084 /**
2085 * @todo document
2086 */
2087 function fetchRow() {
2088 return $this->db->fetchRow( $this->result );
2089 }
2090
2091 /**
2092 * @todo document
2093 */
2094 function free() {
2095 $this->db->freeResult( $this->result );
2096 unset( $this->result );
2097 unset( $this->db );
2098 }
2099
2100 function seek( $row ) {
2101 $this->db->dataSeek( $this->result, $row );
2102 }
2103
2104 }
2105
2106 ?>