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