Lessons learnt from installing MediaWiki with safe_mode, especially support for uploa...
[mediawiki.git] / includes / Database.php
blob458d054407cf3f435e3b5b7a8a2d6924a73764a9
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
8 /**
9 * Depends on the CacheManager
11 require_once( 'CacheManager.php' );
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
26 /**
27 * Database abstraction object
28 * @package MediaWiki
30 class Database {
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
38 var $mLastQuery = '';
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 /**#@-*/
49 #------------------------------------------------------------------------------
50 # Accessors
51 #------------------------------------------------------------------------------
52 # These optionally set a variable and return the previous state
54 /**
55 * Fail function, takes a Database as a parameter
56 * Set to false for default, 1 for ignore errors
58 function failFunction( $function = NULL ) {
59 return wfSetVar( $this->mFailFunction, $function );
62 /**
63 * Output page, used for reporting errors
64 * FALSE means discard output
66 function &setOutputPage( &$out ) {
67 $this->mOut =& $out;
70 /**
71 * Boolean, controls output of large amounts of debug information
73 function debug( $debug = NULL ) {
74 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
77 /**
78 * Turns buffering of SQL result sets on (true) or off (false).
79 * Default is "on" and it should not be changed without good reasons.
81 function bufferResults( $buffer = NULL ) {
82 if ( is_null( $buffer ) ) {
83 return !(bool)( $this->mFlags & DBO_NOBUFFER );
84 } else {
85 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
89 /**
90 * Turns on (false) or off (true) the automatic generation and sending
91 * of a "we're sorry, but there has been a database error" page on
92 * database errors. Default is on (false). When turned off, the
93 * code should use wfLastErrno() and wfLastError() to handle the
94 * situation as appropriate.
96 function ignoreErrors( $ignoreErrors = NULL ) {
97 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
101 * The current depth of nested transactions
102 * @param integer $level
104 function trxLevel( $level = NULL ) {
105 return wfSetVar( $this->mTrxLevel, $level );
108 /**#@+
109 * Get function
111 function lastQuery() { return $this->mLastQuery; }
112 function isOpen() { return $this->mOpened; }
113 /**#@-*/
115 #------------------------------------------------------------------------------
116 # Other functions
117 #------------------------------------------------------------------------------
119 /**#@+
120 * @param string $server database server host
121 * @param string $user database user name
122 * @param string $password database user password
123 * @param string $dbname database name
127 * @param failFunction
128 * @param $flags
129 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
131 function Database( $server = false, $user = false, $password = false, $dbName = false,
132 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
134 global $wgOut, $wgDBprefix, $wgCommandLineMode;
135 # Can't get a reference if it hasn't been set yet
136 if ( !isset( $wgOut ) ) {
137 $wgOut = NULL;
139 $this->mOut =& $wgOut;
141 $this->mFailFunction = $failFunction;
142 $this->mFlags = $flags;
144 if ( $this->mFlags & DBO_DEFAULT ) {
145 if ( $wgCommandLineMode ) {
146 $this->mFlags &= ~DBO_TRX;
147 } else {
148 $this->mFlags |= DBO_TRX;
153 // Faster read-only access
154 if ( wfReadOnly() ) {
155 $this->mFlags |= DBO_PERSISTENT;
156 $this->mFlags &= ~DBO_TRX;
159 /** Get the default table prefix*/
160 if ( $tablePrefix == 'get from global' ) {
161 $this->mTablePrefix = $wgDBprefix;
162 } else {
163 $this->mTablePrefix = $tablePrefix;
166 if ( $server ) {
167 $this->open( $server, $user, $password, $dbName );
172 * @static
173 * @param failFunction
174 * @param $flags
176 function newFromParams( $server, $user, $password, $dbName,
177 $failFunction = false, $flags = 0 )
179 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
183 * Usually aborts on failure
184 * If the failFunction is set to a non-zero integer, returns success
186 function open( $server, $user, $password, $dbName ) {
187 # Test for missing mysql.so
188 # First try to load it
189 if (!@extension_loaded('mysql')) {
190 @dl('mysql.so');
193 # Otherwise we get a suppressed fatal error, which is very hard to track down
194 if ( !function_exists( 'mysql_connect' ) ) {
195 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
198 $this->close();
199 $this->mServer = $server;
200 $this->mUser = $user;
201 $this->mPassword = $password;
202 $this->mDBname = $dbName;
204 $success = false;
206 if ( $this->mFlags & DBO_PERSISTENT ) {
207 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
208 } else {
209 @/**/$this->mConn = mysql_connect( $server, $user, $password );
212 if ( $dbName != '' ) {
213 if ( $this->mConn !== false ) {
214 $success = @/**/mysql_select_db( $dbName, $this->mConn );
215 if ( !$success ) {
216 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
218 } else {
219 wfDebug( "DB connection error\n" );
220 wfDebug( "Server: $server, User: $user, Password: " .
221 substr( $password, 0, 3 ) . "...\n" );
222 $success = false;
224 } else {
225 # Delay USE query
226 $success = !!$this->mConn;
229 if ( !$success ) {
230 $this->reportConnectionError();
231 $this->close();
233 $this->mOpened = $success;
234 return $success;
236 /**#@-*/
239 * Closes a database connection.
240 * if it is open : commits any open transactions
242 * @return bool operation success. true if already closed.
244 function close()
246 $this->mOpened = false;
247 if ( $this->mConn ) {
248 if ( $this->trxLevel() ) {
249 $this->immediateCommit();
251 return mysql_close( $this->mConn );
252 } else {
253 return true;
258 * @access private
259 * @param string $msg error message ?
260 * @todo parameter $msg is not used
262 function reportConnectionError( $msg = '') {
263 if ( $this->mFailFunction ) {
264 if ( !is_int( $this->mFailFunction ) ) {
265 $ff = $this->mFailFunction;
266 $ff( $this, mysql_error() );
268 } else {
269 wfEmergencyAbort( $this, mysql_error() );
274 * Usually aborts on failure
275 * If errors are explicitly ignored, returns success
277 function query( $sql, $fname = '', $tempIgnore = false ) {
278 global $wgProfiling, $wgCommandLineMode;
280 if ( $wgProfiling ) {
281 # generalizeSQL will probably cut down the query to reasonable
282 # logging size most of the time. The substr is really just a sanity check.
283 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
284 wfProfileIn( $profName );
287 $this->mLastQuery = $sql;
289 # Add a comment for easy SHOW PROCESSLIST interpretation
290 if ( $fname ) {
291 $commentedSql = "/* $fname */ $sql";
292 } else {
293 $commentedSql = $sql;
296 # If DBO_TRX is set, start a transaction
297 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
298 $this->begin();
301 if ( $this->debug() ) {
302 $sqlx = substr( $sql, 0, 500 );
303 $sqlx = strtr($sqlx,"\t\n",' ');
304 wfDebug( "SQL: $sqlx\n" );
307 # Do the query and handle errors
308 $ret = $this->doQuery( $commentedSql );
309 if ( false === $ret ) {
310 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
313 if ( $wgProfiling ) {
314 wfProfileOut( $profName );
316 return $ret;
320 * The DBMS-dependent part of query()
321 * @param string $sql SQL query.
323 function doQuery( $sql ) {
324 if( $this->bufferResults() ) {
325 $ret = mysql_query( $sql, $this->mConn );
326 } else {
327 $ret = mysql_unbuffered_query( $sql, $this->mConn );
329 return $ret;
333 * @param $error
334 * @param $errno
335 * @param $sql
336 * @param string $fname
337 * @param bool $tempIgnore
339 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
340 global $wgCommandLineMode, $wgFullyInitialised;
341 # Ignore errors during error handling to avoid infinite recursion
342 $ignore = $this->ignoreErrors( true );
344 if( $ignore || $tempIgnore ) {
345 wfDebug("SQL ERROR (ignored): " . $error . "\n");
346 } else {
347 $sql1line = str_replace( "\n", "\\n", $sql );
348 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
349 wfDebug("SQL ERROR: " . $error . "\n");
350 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
351 $message = "A database error has occurred\n" .
352 "Query: $sql\n" .
353 "Function: $fname\n" .
354 "Error: $errno $error\n";
355 if ( !$wgCommandLineMode ) {
356 $message = nl2br( $message );
358 wfDebugDieBacktrace( $message );
359 } else {
360 // this calls wfAbruptExit()
361 $this->mOut->databaseError( $fname, $sql, $error, $errno );
364 $this->ignoreErrors( $ignore );
369 * Intended to be compatible with the PEAR::DB wrapper functions.
370 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
372 * ? = scalar value, quoted as necessary
373 * ! = raw SQL bit (a function for instance)
374 * & = filename; reads the file and inserts as a blob
375 * (we don't use this though...)
377 function prepare( $sql, $func = 'Database::prepare' ) {
378 /* MySQL doesn't support prepared statements (yet), so just
379 pack up the query for reference. We'll manually replace
380 the bits later. */
381 return array( 'query' => $sql, 'func' => $func );
384 function freePrepared( $prepared ) {
385 /* No-op for MySQL */
389 * Execute a prepared query with the various arguments
390 * @param string $prepared the prepared sql
391 * @param mixed $args Either an array here, or put scalars as varargs
393 function execute( $prepared, $args = null ) {
394 if( !is_array( $args ) ) {
395 # Pull the var args
396 $args = func_get_args();
397 array_shift( $args );
399 $sql = $this->fillPrepared( $prepared['query'], $args );
400 return $this->query( $sql, $prepared['func'] );
404 * Prepare & execute an SQL statement, quoting and inserting arguments
405 * in the appropriate places.
406 * @param string $query
407 * @param string $args (default null)
409 function safeQuery( $query, $args = null ) {
410 $prepared = $this->prepare( $query, 'Database::safeQuery' );
411 if( !is_array( $args ) ) {
412 # Pull the var args
413 $args = func_get_args();
414 array_shift( $args );
416 $retval = $this->execute( $prepared, $args );
417 $this->freePrepared( $prepared );
418 return $retval;
422 * For faking prepared SQL statements on DBs that don't support
423 * it directly.
424 * @param string $preparedSql - a 'preparable' SQL statement
425 * @param array $args - array of arguments to fill it with
426 * @return string executable SQL
428 function fillPrepared( $preparedQuery, $args ) {
429 $n = 0;
430 reset( $args );
431 $this->preparedArgs =& $args;
432 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
433 array( &$this, 'fillPreparedArg' ), $preparedQuery );
437 * preg_callback func for fillPrepared()
438 * The arguments should be in $this->preparedArgs and must not be touched
439 * while we're doing this.
441 * @param array $matches
442 * @return string
443 * @access private
445 function fillPreparedArg( $matches ) {
446 switch( $matches[1] ) {
447 case '\\?': return '?';
448 case '\\!': return '!';
449 case '\\&': return '&';
451 list( $n, $arg ) = each( $this->preparedArgs );
452 switch( $matches[1] ) {
453 case '?': return $this->addQuotes( $arg );
454 case '!': return $arg;
455 case '&':
456 # return $this->addQuotes( file_get_contents( $arg ) );
457 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
458 default:
459 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
463 /**#@+
464 * @param mixed $res A SQL result
467 * Free a result object
469 function freeResult( $res ) {
470 if ( !@/**/mysql_free_result( $res ) ) {
471 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
476 * Fetch the next row from the given result object, in object form
478 function fetchObject( $res ) {
479 @/**/$row = mysql_fetch_object( $res );
480 if( mysql_errno() ) {
481 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
483 return $row;
487 * Fetch the next row from the given result object
488 * Returns an array
490 function fetchRow( $res ) {
491 @/**/$row = mysql_fetch_array( $res );
492 if (mysql_errno() ) {
493 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
495 return $row;
499 * Get the number of rows in a result object
501 function numRows( $res ) {
502 @/**/$n = mysql_num_rows( $res );
503 if( mysql_errno() ) {
504 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
506 return $n;
510 * Get the number of fields in a result object
511 * See documentation for mysql_num_fields()
513 function numFields( $res ) { return mysql_num_fields( $res ); }
516 * Get a field name in a result object
517 * See documentation for mysql_field_name()
519 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
522 * Get the inserted value of an auto-increment row
524 * The value inserted should be fetched from nextSequenceValue()
526 * Example:
527 * $id = $dbw->nextSequenceValue('page_page_id_seq');
528 * $dbw->insert('page',array('page_id' => $id));
529 * $id = $dbw->insertId();
531 function insertId() { return mysql_insert_id( $this->mConn ); }
534 * Change the position of the cursor in a result object
535 * See mysql_data_seek()
537 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
540 * Get the last error number
541 * See mysql_errno()
543 function lastErrno() {
544 if ( $this->mConn ) {
545 return mysql_errno( $this->mConn );
546 } else {
547 return mysql_errno();
552 * Get a description of the last error
553 * See mysql_error() for more details
555 function lastError() {
556 if ( $this->mConn ) {
557 $error = mysql_error( $this->mConn );
558 } else {
559 $error = mysql_error();
561 if( $error ) {
562 $error .= ' (' . $this->mServer . ')';
564 return $error;
567 * Get the number of rows affected by the last write query
568 * See mysql_affected_rows() for more details
570 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
571 /**#@-*/ // end of template : @param $result
574 * Simple UPDATE wrapper
575 * Usually aborts on failure
576 * If errors are explicitly ignored, returns success
578 * This function exists for historical reasons, Database::update() has a more standard
579 * calling convention and feature set
581 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
583 $table = $this->tableName( $table );
584 $sql = "UPDATE $table SET $var = '" .
585 $this->strencode( $value ) . "' WHERE ($cond)";
586 return !!$this->query( $sql, DB_MASTER, $fname );
590 * Simple SELECT wrapper, returns a single field, input must be encoded
591 * Usually aborts on failure
592 * If errors are explicitly ignored, returns FALSE on failure
594 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
595 if ( !is_array( $options ) ) {
596 $options = array( $options );
598 $options['LIMIT'] = 1;
600 $res = $this->select( $table, $var, $cond, $fname, $options );
601 if ( $res === false || !$this->numRows( $res ) ) {
602 return false;
604 $row = $this->fetchRow( $res );
605 if ( $row !== false ) {
606 $this->freeResult( $res );
607 return $row[0];
608 } else {
609 return false;
614 * Returns an optional USE INDEX clause to go after the table, and a
615 * string to go at the end of the query
617 function makeSelectOptions( $options ) {
618 if ( !is_array( $options ) ) {
619 $options = array( $options );
622 $tailOpts = '';
624 if ( isset( $options['ORDER BY'] ) ) {
625 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
627 if ( isset( $options['LIMIT'] ) ) {
628 $tailOpts .= " LIMIT {$options['LIMIT']}";
631 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
632 $tailOpts .= ' FOR UPDATE';
635 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
636 $tailOpts .= ' LOCK IN SHARE MODE';
639 if ( isset( $options['USE INDEX'] ) ) {
640 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
641 } else {
642 $useIndex = '';
644 return array( $useIndex, $tailOpts );
648 * SELECT wrapper
650 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
652 if( is_array( $vars ) ) {
653 $vars = implode( ',', $vars );
655 if( is_array( $table ) ) {
656 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
657 } elseif ($table!='') {
658 $from = ' FROM ' .$this->tableName( $table );
659 } else {
660 $from = '';
663 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
665 if( !empty( $conds ) ) {
666 if ( is_array( $conds ) ) {
667 $conds = $this->makeList( $conds, LIST_AND );
669 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
670 } else {
671 $sql = "SELECT $vars $from $useIndex $tailOpts";
673 return $this->query( $sql, $fname );
677 * Single row SELECT wrapper
678 * Aborts or returns FALSE on error
680 * $vars: the selected variables
681 * $conds: a condition map, terms are ANDed together.
682 * Items with numeric keys are taken to be literal conditions
683 * Takes an array of selected variables, and a condition map, which is ANDed
684 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
685 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
686 * $obj- >page_id is the ID of the Astronomy article
688 * @todo migrate documentation to phpdocumentor format
690 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
691 $options['LIMIT'] = 1;
692 $res = $this->select( $table, $vars, $conds, $fname, $options );
693 if ( $res === false || !$this->numRows( $res ) ) {
694 return false;
696 $obj = $this->fetchObject( $res );
697 $this->freeResult( $res );
698 return $obj;
703 * Removes most variables from an SQL query and replaces them with X or N for numbers.
704 * It's only slightly flawed. Don't use for anything important.
706 * @param string $sql A SQL Query
707 * @static
709 function generalizeSQL( $sql ) {
710 # This does the same as the regexp below would do, but in such a way
711 # as to avoid crashing php on some large strings.
712 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
714 $sql = str_replace ( "\\\\", '', $sql);
715 $sql = str_replace ( "\\'", '', $sql);
716 $sql = str_replace ( "\\\"", '', $sql);
717 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
718 $sql = preg_replace ('/".*"/s', "'X'", $sql);
720 # All newlines, tabs, etc replaced by single space
721 $sql = preg_replace ( "/\s+/", ' ', $sql);
723 # All numbers => N
724 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
726 return $sql;
730 * Determines whether a field exists in a table
731 * Usually aborts on failure
732 * If errors are explicitly ignored, returns NULL on failure
734 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
735 $table = $this->tableName( $table );
736 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
737 if ( !$res ) {
738 return NULL;
741 $found = false;
743 while ( $row = $this->fetchObject( $res ) ) {
744 if ( $row->Field == $field ) {
745 $found = true;
746 break;
749 return $found;
753 * Determines whether an index exists
754 * Usually aborts on failure
755 * If errors are explicitly ignored, returns NULL on failure
757 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
758 $info = $this->indexInfo( $table, $index, $fname );
759 if ( is_null( $info ) ) {
760 return NULL;
761 } else {
762 return $info !== false;
768 * Get information about an index into an object
769 * Returns false if the index does not exist
771 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
772 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
773 # SHOW INDEX should work for 3.x and up:
774 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
775 $table = $this->tableName( $table );
776 $sql = 'SHOW INDEX FROM '.$table;
777 $res = $this->query( $sql, $fname );
778 if ( !$res ) {
779 return NULL;
782 while ( $row = $this->fetchObject( $res ) ) {
783 if ( $row->Key_name == $index ) {
784 return $row;
787 return false;
791 * Query whether a given table exists
793 function tableExists( $table ) {
794 $table = $this->tableName( $table );
795 $old = $this->ignoreErrors( true );
796 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
797 $this->ignoreErrors( $old );
798 if( $res ) {
799 $this->freeResult( $res );
800 return true;
801 } else {
802 return false;
807 * mysql_fetch_field() wrapper
808 * Returns false if the field doesn't exist
810 * @param $table
811 * @param $field
813 function fieldInfo( $table, $field ) {
814 $table = $this->tableName( $table );
815 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
816 $n = mysql_num_fields( $res );
817 for( $i = 0; $i < $n; $i++ ) {
818 $meta = mysql_fetch_field( $res, $i );
819 if( $field == $meta->name ) {
820 return $meta;
823 return false;
827 * mysql_field_type() wrapper
829 function fieldType( $res, $index ) {
830 return mysql_field_type( $res, $index );
834 * Determines if a given index is unique
836 function indexUnique( $table, $index ) {
837 $indexInfo = $this->indexInfo( $table, $index );
838 if ( !$indexInfo ) {
839 return NULL;
841 return !$indexInfo->Non_unique;
845 * INSERT wrapper, inserts an array into a table
847 * $a may be a single associative array, or an array of these with numeric keys, for
848 * multi-row insert.
850 * Usually aborts on failure
851 * If errors are explicitly ignored, returns success
853 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
854 # No rows to insert, easy just return now
855 if ( !count( $a ) ) {
856 return true;
859 $table = $this->tableName( $table );
860 if ( !is_array( $options ) ) {
861 $options = array( $options );
863 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
864 $multi = true;
865 $keys = array_keys( $a[0] );
866 } else {
867 $multi = false;
868 $keys = array_keys( $a );
871 $sql = 'INSERT ' . implode( ' ', $options ) .
872 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
874 if ( $multi ) {
875 $first = true;
876 foreach ( $a as $row ) {
877 if ( $first ) {
878 $first = false;
879 } else {
880 $sql .= ',';
882 $sql .= '(' . $this->makeList( $row ) . ')';
884 } else {
885 $sql .= '(' . $this->makeList( $a ) . ')';
887 return !!$this->query( $sql, $fname );
891 * UPDATE wrapper, takes a condition array and a SET array
893 function update( $table, $values, $conds, $fname = 'Database::update' ) {
894 $table = $this->tableName( $table );
895 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
896 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
897 $this->query( $sql, $fname );
901 * Makes a wfStrencoded list from an array
902 * $mode: LIST_COMMA - comma separated, no field names
903 * LIST_AND - ANDed WHERE clause (without the WHERE)
904 * LIST_SET - comma separated with field names, like a SET clause
905 * LIST_NAMES - comma separated field names
907 function makeList( $a, $mode = LIST_COMMA ) {
908 if ( !is_array( $a ) ) {
909 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
912 $first = true;
913 $list = '';
914 foreach ( $a as $field => $value ) {
915 if ( !$first ) {
916 if ( $mode == LIST_AND ) {
917 $list .= ' AND ';
918 } else {
919 $list .= ',';
921 } else {
922 $first = false;
924 if ( $mode == LIST_AND && is_numeric( $field ) ) {
925 $list .= "($value)";
926 } elseif ( $mode == LIST_AND && is_array ($value) ) {
927 $list .= $field." IN (".$this->makeList($value).") ";
928 } else {
929 if ( $mode == LIST_AND || $mode == LIST_SET ) {
930 $list .= $field.'=';
932 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
935 return $list;
939 * Change the current database
941 function selectDB( $db ) {
942 $this->mDBname = $db;
943 return mysql_select_db( $db, $this->mConn );
947 * Starts a timer which will kill the DB thread after $timeout seconds
949 function startTimer( $timeout ) {
950 global $IP;
951 if( function_exists( 'mysql_thread_id' ) ) {
952 # This will kill the query if it's still running after $timeout seconds.
953 $tid = mysql_thread_id( $this->mConn );
954 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
959 * Stop a timer started by startTimer()
960 * Currently unimplemented.
963 function stopTimer() { }
966 * Format a table name ready for use in constructing an SQL query
968 * This does two important things: it quotes table names which as necessary,
969 * and it adds a table prefix if there is one.
971 * All functions of this object which require a table name call this function
972 * themselves. Pass the canonical name to such functions. This is only needed
973 * when calling query() directly.
975 * @param string $name database table name
977 function tableName( $name ) {
978 global $wgSharedDB;
979 # Skip quoted literals
980 if ( $name{0} != '`' ) {
981 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
982 $name = "{$this->mTablePrefix}$name";
984 if ( isset( $wgSharedDB ) && 'user' == $name ) {
985 $name = "`$wgSharedDB`.`$name`";
986 } else {
987 # Standard quoting
988 $name = "`$name`";
991 return $name;
995 * Fetch a number of table names into an array
996 * This is handy when you need to construct SQL for joins
998 * Example:
999 * extract($dbr->tableNames('user','watchlist'));
1000 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1001 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1003 function tableNames() {
1004 $inArray = func_get_args();
1005 $retVal = array();
1006 foreach ( $inArray as $name ) {
1007 $retVal[$name] = $this->tableName( $name );
1009 return $retVal;
1013 * Wrapper for addslashes()
1014 * @param string $s String to be slashed.
1015 * @return string slashed string.
1017 function strencode( $s ) {
1018 return addslashes( $s );
1022 * If it's a string, adds quotes and backslashes
1023 * Otherwise returns as-is
1025 function addQuotes( $s ) {
1026 if ( is_null( $s ) ) {
1027 $s = 'NULL';
1028 } else {
1029 # This will also quote numeric values. This should be harmless,
1030 # and protects against weird problems that occur when they really
1031 # _are_ strings such as article titles and string->number->string
1032 # conversion is not 1:1.
1033 $s = "'" . $this->strencode( $s ) . "'";
1035 return $s;
1039 * Returns an appropriately quoted sequence value for inserting a new row.
1040 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1041 * subclass will return an integer, and save the value for insertId()
1043 function nextSequenceValue( $seqName ) {
1044 return NULL;
1048 * USE INDEX clause
1049 * PostgreSQL doesn't have them and returns ""
1051 function useIndexClause( $index ) {
1052 return 'USE INDEX ('.$index.')';
1056 * REPLACE query wrapper
1057 * PostgreSQL simulates this with a DELETE followed by INSERT
1058 * $row is the row to insert, an associative array
1059 * $uniqueIndexes is an array of indexes. Each element may be either a
1060 * field name or an array of field names
1062 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1063 * However if you do this, you run the risk of encountering errors which wouldn't have
1064 * occurred in MySQL
1066 * @todo migrate comment to phodocumentor format
1068 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1069 $table = $this->tableName( $table );
1071 # Single row case
1072 if ( !is_array( reset( $rows ) ) ) {
1073 $rows = array( $rows );
1076 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1077 $first = true;
1078 foreach ( $rows as $row ) {
1079 if ( $first ) {
1080 $first = false;
1081 } else {
1082 $sql .= ',';
1084 $sql .= '(' . $this->makeList( $row ) . ')';
1086 return $this->query( $sql, $fname );
1090 * DELETE where the condition is a join
1091 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1093 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1094 * join condition matches, set $conds='*'
1096 * DO NOT put the join condition in $conds
1098 * @param string $delTable The table to delete from.
1099 * @param string $joinTable The other table.
1100 * @param string $delVar The variable to join on, in the first table.
1101 * @param string $joinVar The variable to join on, in the second table.
1102 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1104 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1105 if ( !$conds ) {
1106 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1109 $delTable = $this->tableName( $delTable );
1110 $joinTable = $this->tableName( $joinTable );
1111 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1112 if ( $conds != '*' ) {
1113 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1116 return $this->query( $sql, $fname );
1120 * Returns the size of a text field, or -1 for "unlimited"
1122 function textFieldSize( $table, $field ) {
1123 $table = $this->tableName( $table );
1124 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1125 $res = $this->query( $sql, 'Database::textFieldSize' );
1126 $row = $this->fetchObject( $res );
1127 $this->freeResult( $res );
1129 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1130 $size = $m[1];
1131 } else {
1132 $size = -1;
1134 return $size;
1138 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1140 function lowPriorityOption() {
1141 return 'LOW_PRIORITY';
1145 * DELETE query wrapper
1147 * Use $conds == "*" to delete all rows
1149 function delete( $table, $conds, $fname = 'Database::delete' ) {
1150 if ( !$conds ) {
1151 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1153 $table = $this->tableName( $table );
1154 $sql = "DELETE FROM $table ";
1155 if ( $conds != '*' ) {
1156 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1158 return $this->query( $sql, $fname );
1162 * INSERT SELECT wrapper
1163 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1164 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1165 * $conds may be "*" to copy the whole table
1166 * srcTable may be an array of tables.
1168 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1169 $destTable = $this->tableName( $destTable );
1170 if( is_array( $srcTable ) ) {
1171 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1172 } else {
1173 $srcTable = $this->tableName( $srcTable );
1175 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1176 ' SELECT ' . implode( ',', $varMap ) .
1177 " FROM $srcTable";
1178 if ( $conds != '*' ) {
1179 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1181 return $this->query( $sql, $fname );
1185 * Construct a LIMIT query with optional offset
1186 * This is used for query pages
1188 function limitResult($limit,$offset) {
1189 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1193 * Returns an SQL expression for a simple conditional.
1194 * Uses IF on MySQL.
1196 * @param string $cond SQL expression which will result in a boolean value
1197 * @param string $trueVal SQL expression to return if true
1198 * @param string $falseVal SQL expression to return if false
1199 * @return string SQL fragment
1201 function conditional( $cond, $trueVal, $falseVal ) {
1202 return " IF($cond, $trueVal, $falseVal) ";
1206 * Determines if the last failure was due to a deadlock
1208 function wasDeadlock() {
1209 return $this->lastErrno() == 1213;
1213 * Perform a deadlock-prone transaction.
1215 * This function invokes a callback function to perform a set of write
1216 * queries. If a deadlock occurs during the processing, the transaction
1217 * will be rolled back and the callback function will be called again.
1219 * Usage:
1220 * $dbw->deadlockLoop( callback, ... );
1222 * Extra arguments are passed through to the specified callback function.
1224 * Returns whatever the callback function returned on its successful,
1225 * iteration, or false on error, for example if the retry limit was
1226 * reached.
1228 function deadlockLoop() {
1229 $myFname = 'Database::deadlockLoop';
1231 $this->query( 'BEGIN', $myFname );
1232 $args = func_get_args();
1233 $function = array_shift( $args );
1234 $oldIgnore = $this->ignoreErrors( true );
1235 $tries = DEADLOCK_TRIES;
1236 if ( is_array( $function ) ) {
1237 $fname = $function[0];
1238 } else {
1239 $fname = $function;
1241 do {
1242 $retVal = call_user_func_array( $function, $args );
1243 $error = $this->lastError();
1244 $errno = $this->lastErrno();
1245 $sql = $this->lastQuery();
1247 if ( $errno ) {
1248 if ( $this->wasDeadlock() ) {
1249 # Retry
1250 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1251 } else {
1252 $this->reportQueryError( $error, $errno, $sql, $fname );
1255 } while( $this->wasDeadlock() && --$tries > 0 );
1256 $this->ignoreErrors( $oldIgnore );
1257 if ( $tries <= 0 ) {
1258 $this->query( 'ROLLBACK', $myFname );
1259 $this->reportQueryError( $error, $errno, $sql, $fname );
1260 return false;
1261 } else {
1262 $this->query( 'COMMIT', $myFname );
1263 return $retVal;
1268 * Do a SELECT MASTER_POS_WAIT()
1270 * @param string $file the binlog file
1271 * @param string $pos the binlog position
1272 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1274 function masterPosWait( $file, $pos, $timeout ) {
1275 $fname = 'Database::masterPosWait';
1276 wfProfileIn( $fname );
1279 # Commit any open transactions
1280 $this->immediateCommit();
1282 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1283 $encFile = $this->strencode( $file );
1284 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1285 $res = $this->doQuery( $sql );
1286 if ( $res && $row = $this->fetchRow( $res ) ) {
1287 $this->freeResult( $res );
1288 return $row[0];
1289 } else {
1290 return false;
1295 * Get the position of the master from SHOW SLAVE STATUS
1297 function getSlavePos() {
1298 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1299 $row = $this->fetchObject( $res );
1300 if ( $row ) {
1301 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1302 } else {
1303 return array( false, false );
1308 * Get the position of the master from SHOW MASTER STATUS
1310 function getMasterPos() {
1311 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1312 $row = $this->fetchObject( $res );
1313 if ( $row ) {
1314 return array( $row->File, $row->Position );
1315 } else {
1316 return array( false, false );
1321 * Begin a transaction, or if a transaction has already started, continue it
1323 function begin( $fname = 'Database::begin' ) {
1324 if ( !$this->mTrxLevel ) {
1325 $this->immediateBegin( $fname );
1326 } else {
1327 $this->mTrxLevel++;
1332 * End a transaction, or decrement the nest level if transactions are nested
1334 function commit( $fname = 'Database::commit' ) {
1335 if ( $this->mTrxLevel ) {
1336 $this->mTrxLevel--;
1338 if ( !$this->mTrxLevel ) {
1339 $this->immediateCommit( $fname );
1344 * Rollback a transaction
1346 function rollback( $fname = 'Database::rollback' ) {
1347 $this->query( 'ROLLBACK', $fname );
1348 $this->mTrxLevel = 0;
1352 * Begin a transaction, committing any previously open transaction
1354 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1355 $this->query( 'BEGIN', $fname );
1356 $this->mTrxLevel = 1;
1360 * Commit transaction, if one is open
1362 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1363 $this->query( 'COMMIT', $fname );
1364 $this->mTrxLevel = 0;
1368 * Return MW-style timestamp used for MySQL schema
1370 function timestamp( $ts=0 ) {
1371 return wfTimestamp(TS_MW,$ts);
1375 * @todo document
1377 function &resultObject( &$result ) {
1378 if( empty( $result ) ) {
1379 return NULL;
1380 } else {
1381 return new ResultWrapper( $this, $result );
1386 * Return aggregated value alias
1388 function aggregateValue ($valuedata,$valuename='value') {
1389 return $valuename;
1393 * @return string wikitext of a link to the server software's web site
1395 function getSoftwareLink() {
1396 return "[http://www.mysql.com/ MySQL]";
1400 * @return string Version information from the database
1402 function getServerVersion() {
1403 return mysql_get_server_info();
1408 * Database abstraction object for mySQL
1409 * Inherit all methods and properties of Database::Database()
1411 * @package MediaWiki
1412 * @see Database
1414 class DatabaseMysql extends Database {
1415 # Inherit all
1420 * Result wrapper for grabbing data queried by someone else
1422 * @package MediaWiki
1424 class ResultWrapper {
1425 var $db, $result;
1428 * @todo document
1430 function ResultWrapper( $database, $result ) {
1431 $this->db =& $database;
1432 $this->result =& $result;
1436 * @todo document
1438 function numRows() {
1439 return $this->db->numRows( $this->result );
1443 * @todo document
1445 function &fetchObject() {
1446 return $this->db->fetchObject( $this->result );
1450 * @todo document
1452 function &fetchRow() {
1453 return $this->db->fetchRow( $this->result );
1457 * @todo document
1459 function free() {
1460 $this->db->freeResult( $this->result );
1461 unset( $this->result );
1462 unset( $this->db );
1465 function seek( $row ) {
1466 $this->db->dataSeek( $this->result, $row );
1470 #------------------------------------------------------------------------------
1471 # Global functions
1472 #------------------------------------------------------------------------------
1475 * Standard fail function, called by default when a connection cannot be
1476 * established.
1477 * Displays the file cache if possible
1479 function wfEmergencyAbort( &$conn, $error ) {
1480 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1481 global $wgSitename, $wgServer;
1483 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1484 # Hard coding strings instead.
1486 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1487 $1';
1488 $mainpage = 'Main Page';
1489 $searchdisabled = <<<EOT
1490 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1491 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1492 EOT;
1494 $googlesearch = "
1495 <!-- SiteSearch Google -->
1496 <FORM method=GET action=\"http://www.google.com/search\">
1497 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1498 <A HREF=\"http://www.google.com/\">
1499 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1500 border=\"0\" ALT=\"Google\"></A>
1501 </td>
1502 <td>
1503 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1504 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1505 <font size=-1>
1506 <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 />
1507 <input type='hidden' name='ie' value='$2'>
1508 <input type='hidden' name='oe' value='$2'>
1509 </font>
1510 </td></tr></TABLE>
1511 </FORM>
1512 <!-- SiteSearch Google -->";
1513 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1516 if( !headers_sent() ) {
1517 header( 'HTTP/1.0 500 Internal Server Error' );
1518 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1519 /* Don't cache error pages! They cause no end of trouble... */
1520 header( 'Cache-control: none' );
1521 header( 'Pragma: nocache' );
1523 $msg = wfGetSiteNotice();
1524 if($msg == '') {
1525 $msg = str_replace( '$1', $error, $noconnect );
1527 $text = $msg;
1529 if($wgUseFileCache) {
1530 if($wgTitle) {
1531 $t =& $wgTitle;
1532 } else {
1533 if($title) {
1534 $t = Title::newFromURL( $title );
1535 } elseif (@/**/$_REQUEST['search']) {
1536 $search = $_REQUEST['search'];
1537 echo $searchdisabled;
1538 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1539 $wgInputEncoding ), $googlesearch );
1540 wfErrorExit();
1541 } else {
1542 $t = Title::newFromText( $mainpage );
1546 $cache = new CacheManager( $t );
1547 if( $cache->isFileCached() ) {
1548 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1549 $cachederror . "</b></p>\n";
1551 $tag = '<div id="article">';
1552 $text = str_replace(
1553 $tag,
1554 $tag . $msg,
1555 $cache->fetchPageText() );
1559 echo $text;
1560 wfErrorExit();