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