documentation
[lhc/web/wiklou.git] / includes / Database.php
index 6e8a992..59817b2 100644 (file)
@@ -15,6 +15,7 @@ define( 'LIST_COMMA', 0 );
 define( 'LIST_AND', 1 );
 define( 'LIST_SET', 2 );
 define( 'LIST_NAMES', 3);
+define( 'LIST_OR', 4);
 
 /** Number of times to re-try an operation in case of deadlock */
 define( 'DEADLOCK_TRIES', 4 );
@@ -53,7 +54,7 @@ class Database {
         */
        var $mLastQuery = '';
 
-       var $mServer, $mUser, $mPassword, $mConn, $mDBname;
+       var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
        var $mOut, $mOpened = false;
 
        var $mFailFunction;
@@ -61,6 +62,7 @@ class Database {
        var $mFlags;
        var $mTrxLevel = 0;
        var $mErrorCount = 0;
+       var $mLBInfo = array();
        /**#@-*/
 
 #------------------------------------------------------------------------------
@@ -129,6 +131,29 @@ class Database {
                return wfSetVar( $this->mErrorCount, $count );
        }
 
+       /**
+        * Properties passed down from the server info array of the load balancer
+        */
+       function getLBInfo( $name = NULL ) {
+               if ( is_null( $name ) ) {
+                       return $this->mLBInfo;
+               } else {
+                       if ( array_key_exists( $name, $this->mLBInfo ) ) {
+                               return $this->mLBInfo[$name];
+                       } else {
+                               return NULL;
+                       }
+               }
+       }
+
+       function setLBInfo( $name, $value = NULL ) {
+               if ( is_null( $value ) ) {
+                       $this->mLBInfo = $name;
+               } else {
+                       $this->mLBInfo[$name] = $value;
+               }
+       }
+
        /**#@+
         * Get function
         */
@@ -136,6 +161,18 @@ class Database {
        function isOpen() { return $this->mOpened; }
        /**#@-*/
 
+       function setFlag( $flag ) {
+               $this->mFlags |= $flag;
+       }
+
+       function clearFlag( $flag ) {
+               $this->mFlags &= ~$flag;
+       }
+
+       function getFlag( $flag ) {
+               return !!($this->mFlags & $flag);
+       }
+
 #------------------------------------------------------------------------------
 # Other functions
 #------------------------------------------------------------------------------
@@ -208,6 +245,8 @@ class Database {
         * If the failFunction is set to a non-zero integer, returns success
         */
        function open( $server, $user, $password, $dbName ) {
+               global $wguname;
+
                # Test for missing mysql.so
                # First try to load it
                if (!@extension_loaded('mysql')) {
@@ -216,7 +255,7 @@ class Database {
 
                # Otherwise we get a suppressed fatal error, which is very hard to track down
                if ( !function_exists( 'mysql_connect' ) ) {
-                       die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
+                       wfDie( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
                }
 
                $this->close();
@@ -231,14 +270,23 @@ class Database {
                        @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
                } else {
                        # Create a new connection...
-                       @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
+                       if( version_compare( PHP_VERSION, '4.2.0', 'ge' ) ) {
+                               @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
+                       } else {
+                               # On PHP 4.1 the new_link parameter is not available. We cannot
+                               # guarantee that we'll actually get a new connection, and this
+                               # may cause some operations to fail possibly.
+                               @/**/$this->mConn = mysql_connect( $server, $user, $password );
+                       }
                }
 
                if ( $dbName != '' ) {
                        if ( $this->mConn !== false ) {
                                $success = @/**/mysql_select_db( $dbName, $this->mConn );
                                if ( !$success ) {
-                                       wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
+                                       $error = "Error selecting database $dbName on server {$this->mServer} " .
+                                               "from client host {$wguname['nodename']}\n";
+                                       wfDebug( $error );
                                }
                        } else {
                                wfDebug( "DB connection error\n" );
@@ -253,8 +301,15 @@ class Database {
 
                if ( !$success ) {
                        $this->reportConnectionError();
-                       $this->close();
                }
+
+               global $wgDBmysql5;
+               if( $wgDBmysql5 ) {
+                       // Tell the server we're communicating with it in UTF-8.
+                       // This may engage various charset conversions.
+                       $this->query( 'SET NAMES utf8' );
+               }
+
                $this->mOpened = $success;
                return $success;
        }
@@ -281,17 +336,21 @@ class Database {
 
        /**
         * @access private
-        * @param string $msg error message ?
-        * @todo parameter $msg is not used
+        * @param string $error fallback error message, used if none is given by MySQL
         */
-       function reportConnectionError( $msg = '') {
+       function reportConnectionError( $error = 'Unknown error' ) {
+               $myError = $this->lastError();
+               if ( $myError ) {
+                       $error = $myError;
+               }
+
                if ( $this->mFailFunction ) {
                        if ( !is_int( $this->mFailFunction ) ) {
                                $ff = $this->mFailFunction;
-                               $ff( $this, $this->lastError() );
+                               $ff( $this, $error );
                        }
                } else {
-                       wfEmergencyAbort( $this, mysql_error() );
+                       wfEmergencyAbort( $this, $error );
                }
        }
 
@@ -300,23 +359,16 @@ class Database {
         * If errors are explicitly ignored, returns success
         */
        function query( $sql, $fname = '', $tempIgnore = false ) {
-               global $wgProfiling, $wgCommandLineMode;
-
-               if ( wfReadOnly() ) {
-                       # This is a quick check for the most common kinds of write query used
-                       # in MediaWiki, to provide extra safety in addition to UI-level checks.
-                       # It is not intended to prevent every conceivable write query, or even
-                       # to handle such queries gracefully.
-                       if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
-                               wfDebug( "Write query from $fname blocked\n" );
-                               return false;
-                       }
-               }
+               global $wgProfiling;
 
                if ( $wgProfiling ) {
                        # generalizeSQL will probably cut down the query to reasonable
                        # logging size most of the time. The substr is really just a sanity check.
-                       $profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 ); 
+
+                       # Who's been wasting my precious column space? -- TS
+                       #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
+                       $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
+
                        wfProfileIn( 'Database::query' );
                        wfProfileIn( $profName );
                }
@@ -325,7 +377,7 @@ class Database {
 
                # Add a comment for easy SHOW PROCESSLIST interpretation
                if ( $fname ) {
-                       $commentedSql = "/* $fname */ $sql";
+                       $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
                } else {
                        $commentedSql = $sql;
                }
@@ -392,10 +444,10 @@ class Database {
                global $wgCommandLineMode, $wgFullyInitialised;
                # Ignore errors during error handling to avoid infinite recursion
                $ignore = $this->ignoreErrors( true );
-               $this->mErrorCount ++;
+               ++$this->mErrorCount;
 
                if( $ignore || $tempIgnore ) {
-                       wfDebug("SQL ERROR (ignored): " . $error . "\n");
+                       wfDebug("SQL ERROR (ignored): $error\n");
                } else {
                        $sql1line = str_replace( "\n", "\\n", $sql );
                        wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
@@ -607,7 +659,13 @@ class Database {
         */
        function lastError() {
                if ( $this->mConn ) {
+                       # Even if it's non-zero, it can still be invalid
+                       wfSuppressWarnings();
                        $error = mysql_error( $this->mConn );
+                       if ( !$error ) {
+                               $error = mysql_error();
+                       }
+                       wfRestoreWarnings();
                } else {
                        $error = mysql_error();
                }
@@ -636,7 +694,7 @@ class Database {
                $table = $this->tableName( $table );
                $sql = "UPDATE $table SET $var = '" .
                  $this->strencode( $value ) . "' WHERE ($cond)";
-               return (bool)$this->query( $sql, DB_MASTER, $fname );
+               return (bool)$this->query( $sql, $fname );
        }
 
        /**
@@ -682,7 +740,10 @@ class Database {
                if ( isset( $options['ORDER BY'] ) ) {
                        $tailOpts .= " ORDER BY {$options['ORDER BY']}";
                }
-
+               if (isset($options['LIMIT'])) {
+                       $tailOpts .= $this->limitResult('', $options['LIMIT'],
+                               isset($options['OFFSET']) ? $options['OFFSET'] : false);
+               }
                if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
                        $tailOpts .= ' FOR UPDATE';
                }
@@ -691,7 +752,7 @@ class Database {
                        $tailOpts .= ' LOCK IN SHARE MODE';
                }
 
-               if ( isset( $options['USE INDEX'] ) ) {
+               if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
                        $useIndex = $this->useIndexClause( $options['USE INDEX'] );
                } else {
                        $useIndex = '';
@@ -711,14 +772,17 @@ class Database {
                        $options = array( $options );
                }
                if( is_array( $table ) ) {
-                       $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
+                       if ( @is_array( $options['USE INDEX'] ) )
+                               $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
+                       else
+                               $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
                } elseif ($table!='') {
-                       $from = ' FROM ' .$this->tableName( $table );
+                       $from = ' FROM ' . $this->tableName( $table );
                } else {
                        $from = '';
                }
 
-               list( $useIndex, $tailOpts ) = $this->makeSelectOptions( array($options) );
+               list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
 
                if( !empty( $conds ) ) {
                        if ( is_array( $conds ) ) {
@@ -728,9 +792,7 @@ class Database {
                } else {
                        $sql = "SELECT $vars $from $useIndex $tailOpts";
                }
-               if (isset($options['LIMIT'])) {
-                       $sql = $this->limitResult($sql, $options['LIMIT'], false);
-               }
+
                return $this->query( $sql, $fname );
        }
 
@@ -797,7 +859,7 @@ class Database {
         */
        function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
                $table = $this->tableName( $table );
-               $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
+               $res = $this->query( 'DESCRIBE '.$table, $fname );
                if ( !$res ) {
                        return NULL;
                }
@@ -960,22 +1022,22 @@ class Database {
         */
        function makeUpdateOptions( $options ) {
                if( !is_array( $options ) ) {
-                       wfDebugDieBacktrace( 'makeUpdateOptions given non-array' );
+                       $options = array( $options );
                }
                $opts = array();
                if ( in_array( 'LOW_PRIORITY', $options ) )
                        $opts[] = $this->lowPriorityOption();
-               if ( in_array( 'IGNORE', $options ) ) 
+               if ( in_array( 'IGNORE', $options ) )
                        $opts[] = 'IGNORE';
                return implode(' ', $opts);
        }
-       
+
        /**
         * UPDATE wrapper, takes a condition array and a SET array
         *
         * @param string $table  The table to UPDATE
         * @param array  $values An array of values to SET
-        * @param array  $conds  An array of conditions (WHERE)
+        * @param array  $conds  An array of conditions (WHERE). Use '*' to update all rows.
         * @param string $fname  The Class::Function calling this function
         *                       (for the log)
         * @param array  $options An array of UPDATE options, can be one or
@@ -996,7 +1058,7 @@ class Database {
         * $mode: LIST_COMMA         - comma separated, no field names
         *        LIST_AND           - ANDed WHERE clause (without the WHERE)
         *        LIST_SET           - comma separated with field names, like a SET clause
-        *        LIST_NAMES         - comma separated field names
+        *        LIST_NAMES         - comma separated field names
         */
        function makeList( $a, $mode = LIST_COMMA ) {
                if ( !is_array( $a ) ) {
@@ -1009,18 +1071,20 @@ class Database {
                        if ( !$first ) {
                                if ( $mode == LIST_AND ) {
                                        $list .= ' AND ';
+                               } elseif($mode == LIST_OR) {
+                                       $list .= ' OR ';
                                } else {
                                        $list .= ',';
                                }
                        } else {
                                $first = false;
                        }
-                       if ( $mode == LIST_AND && is_numeric( $field ) ) {
+                       if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
                                $list .= "($value)";
                        } elseif ( $mode == LIST_AND && is_array ($value) ) {
                                $list .= $field." IN (".$this->makeList($value).") ";
                        } else {
-                               if ( $mode == LIST_AND || $mode == LIST_SET ) {
+                               if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
                                        $list .= "$field = ";
                                }
                                $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
@@ -1037,25 +1101,6 @@ class Database {
                return mysql_select_db( $db, $this->mConn );
        }
 
-       /**
-        * Starts a timer which will kill the DB thread after $timeout seconds
-        */
-       function startTimer( $timeout ) {
-               global $IP;
-               if( function_exists( 'mysql_thread_id' ) ) {
-                       # This will kill the query if it's still running after $timeout seconds.
-                       $tid = mysql_thread_id( $this->mConn );
-                       exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
-               }
-       }
-
-       /**
-        * Stop a timer started by startTimer()
-        * Currently unimplemented.
-        *
-        */
-       function stopTimer() { }
-
        /**
         * Format a table name ready for use in constructing an SQL query
         *
@@ -1103,6 +1148,21 @@ class Database {
                return $retVal;
        }
 
+       /**
+        * @access private
+        */
+       function tableNamesWithUseIndex( $tables, $use_index ) {
+               $ret = array();
+
+               foreach ( $tables as $table )
+                       if ( @$use_index[$table] !== null )
+                               $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
+                       else
+                               $ret[] = $this->tableName( $table );
+
+               return implode( ',', $ret );
+       }
+
        /**
         * Wrapper for addslashes()
         * @param string $s String to be slashed.
@@ -1128,6 +1188,15 @@ class Database {
                }
        }
 
+       /**
+        * Escape string for safe LIKE usage
+        */
+       function escapeLike( $s ) {
+               $s=$this->strencode( $s );
+               $s=str_replace(array('%','_'),array('\%','\_'),$s);
+               return $s;
+       }
+
        /**
         * Returns an appropriately quoted sequence value for inserting a new row.
         * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
@@ -1258,14 +1327,19 @@ class Database {
         * $conds may be "*" to copy the whole table
         * srcTable may be an array of tables.
         */
-       function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
+       function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
+               $options = array() )
+       {
                $destTable = $this->tableName( $destTable );
-                if( is_array( $srcTable ) ) {
-                        $srcTable =  implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
+               if ( is_array( $options ) ) {
+                       $options = implode( ' ', $options );
+               }
+               if( is_array( $srcTable ) ) {
+                       $srcTable =  implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
                } else {
                        $srcTable = $this->tableName( $srcTable );
                }
-               $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
+               $sql = "INSERT $options INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
                        ' SELECT ' . implode( ',', $varMap ) .
                        " FROM $srcTable";
                if ( $conds != '*' ) {
@@ -1277,9 +1351,12 @@ class Database {
        /**
         * Construct a LIMIT query with optional offset
         * This is used for query pages
+        * $sql string SQL query we will append the limit too
+        * $limit integer the SQL limit
+        * $offset integer the SQL offset (default false)
         */
-       function limitResult($sql, $limit, $offset) {
-               return "$sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
+       function limitResult($sql, $limit, $offset=false) {
+               return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
        }
        function limitResultForUpdate($sql, $num) {
                return $this->limitResult($sql, $num, 0);
@@ -1483,7 +1560,7 @@ class Database {
        /**
         * @todo document
         */
-       function resultObject( &$result ) {
+       function resultObject( $result ) {
                if( empty( $result ) ) {
                        return NULL;
                } else {
@@ -1536,8 +1613,12 @@ class Database {
                while ( $row = $this->fetchObject( $res ) ) {
                        if ( $row->User == 'system user' ) {
                                if ( ++$slaveThreads == 2 ) {
-                                       # This is it, return the time
-                                       return $row->Time;
+                                       # This is it, return the time (except -ve)
+                                       if ( $row->Time > 1>>31 ) {
+                                               return 0;
+                                       } else {
+                                               return $row->Time;
+                                       }
                                }
                        }
                }
@@ -1547,8 +1628,8 @@ class Database {
        /**
         * Get status information from SHOW STATUS in an associative array
         */
-       function getStatus() {
-               $res = $this->query( 'SHOW STATUS' );
+       function getStatus($which="%") {
+               $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
                $status = array();
                while ( $row = $this->fetchObject( $res ) ) {
                        $status[$row->Variable_name] = $row->Value;
@@ -1567,12 +1648,86 @@ class Database {
                return $b;
        }
 
-       function notNullTimestamp() {
-               return "!= 0";
+       /**
+        * Read and execute SQL commands from a file.
+        * Returns true on success, error string on failure
+        */
+       function sourceFile( $filename ) {
+               $fp = fopen( $filename, 'r' );
+               if ( false === $fp ) {
+                       return "Could not open \"{$fname}\".\n";
+               }
+
+               $cmd = "";
+               $done = false;
+
+               while ( ! feof( $fp ) ) {
+                       $line = trim( fgets( $fp, 1024 ) );
+                       $sl = strlen( $line ) - 1;
+
+                       if ( $sl < 0 ) { continue; }
+                       if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
+
+                       if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
+                               $done = true;
+                               $line = substr( $line, 0, $sl );
+                       }
+
+                       if ( '' != $cmd ) { $cmd .= ' '; }
+                       $cmd .= "$line\n";
+
+                       if ( $done ) {
+                               $cmd = str_replace(';;', ";", $cmd);
+                               $cmd = $this->replaceVars( $cmd );
+                               $res = $this->query( $cmd, 'dbsource', true );
+
+                               if ( false === $res ) {
+                                       $err = $this->lastError();
+                                       return "Query \"{$cmd}\" failed with error code \"$err\".\n";
+                               }
+
+                               $cmd = '';
+                               $done = false;
+                       }
+               }
+               fclose( $fp );
+               return true;
+       }
+
+       /**
+        * Replace variables in sourced SQL
+        */
+       function replaceVars( $ins ) {
+               $varnames = array(
+                       'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
+                       'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
+                       'wgDBadminuser', 'wgDBadminpassword',
+               );
+
+               // Ordinary variables
+               foreach ( $varnames as $var ) {
+                       if( isset( $GLOBALS[$var] ) ) {
+                               $val = addslashes( $GLOBALS[$var] );
+                               $ins = str_replace( '{$' . $var . '}', $val, $ins );
+                               $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
+                               $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
+                       }
+               }
+
+               // Table prefixes
+               $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
+                       array( &$this, 'tableNameCallback' ), $ins );
+               return $ins;
        }
-       function isNullTimestamp() {
-               return "= '0'";
+
+       /**
+        * Table name callback
+        * @access private
+        */
+       function tableNameCallback( $matches ) {
+               return $this->tableName( $matches[1] );
        }
+
 }
 
 /**
@@ -1598,7 +1753,7 @@ class ResultWrapper {
        /**
         * @todo document
         */
-       function ResultWrapper( $database, $result ) {
+       function ResultWrapper( &$database, $result ) {
                $this->db =& $database;
                $this->result =& $result;
        }
@@ -1636,8 +1791,10 @@ class ResultWrapper {
        function seek( $row ) {
                $this->db->dataSeek( $this->result, $row );
        }
+
 }
 
+
 #------------------------------------------------------------------------------
 # Global functions
 #------------------------------------------------------------------------------
@@ -1649,13 +1806,12 @@ class ResultWrapper {
  */
 function wfEmergencyAbort( &$conn, $error ) {
        global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
-       global $wgSitename, $wgServer;
+       global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
 
        # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
        # Hard coding strings instead.
 
-       $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server: $1. <br />
-$1';
+       $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>";
        $mainpage = 'Main Page';
        $searchdisabled = <<<EOT
 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
@@ -1691,11 +1847,20 @@ border=\"0\" ALT=\"Google\"></A>
                header( 'Cache-control: none' );
                header( 'Pragma: nocache' );
        }
-       $msg = wfGetSiteNotice();
-       if($msg == '') {
-               $msg = str_replace( '$1', $error, $noconnect );
+
+       # No database access
+       if ( is_object( $wgMessageCache ) ) {
+               $wgMessageCache->disable();
+       }
+
+       if ( trim( $error ) == '' ) {
+               $error = $this->mServer;
        }
-       $text = $msg;
+
+       wfLogDBError( "Connection error: $error\n" );
+
+       $text = str_replace( '$1', $error, $noconnect );
+       $text .= wfGetSiteNotice();
 
        if($wgUseFileCache) {
                if($wgTitle) {