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