documentation
[lhc/web/wiklou.git] / includes / Database.php
index ba08406..59817b2 100644 (file)
@@ -62,6 +62,7 @@ class Database {
        var $mFlags;
        var $mTrxLevel = 0;
        var $mErrorCount = 0;
+       var $mLBInfo = array();
        /**#@-*/
 
 #------------------------------------------------------------------------------
@@ -130,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
         */
@@ -221,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')) {
@@ -229,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();
@@ -258,7 +284,9 @@ class Database {
                        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" );
@@ -274,6 +302,14 @@ class Database {
                if ( !$success ) {
                        $this->reportConnectionError();
                }
+
+               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;
        }
@@ -300,16 +336,21 @@ class Database {
 
        /**
         * @access private
-        * @param string $msg error message ?
+        * @param string $error fallback error message, used if none is given by MySQL
         */
-       function reportConnectionError() {
+       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, $this->lastError() );
+                       wfEmergencyAbort( $this, $error );
                }
        }
 
@@ -318,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 );
                }
@@ -343,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;
                }
@@ -410,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");
@@ -660,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 );
        }
 
        /**
@@ -707,7 +741,7 @@ class Database {
                        $tailOpts .= " ORDER BY {$options['ORDER BY']}";
                }
                if (isset($options['LIMIT'])) {
-                       $tailOpts .= $this->limitResult('', $options['LIMIT'], 
+                       $tailOpts .= $this->limitResult('', $options['LIMIT'],
                                isset($options['OFFSET']) ? $options['OFFSET'] : false);
                }
                if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
@@ -718,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 = '';
@@ -738,9 +772,12 @@ 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 = '';
                }
@@ -822,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;
                }
@@ -990,17 +1027,17 @@ class Database {
                $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
@@ -1021,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 ) ) {
@@ -1064,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
         *
@@ -1130,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.
@@ -1163,7 +1196,7 @@ class Database {
                $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
@@ -1294,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 != '*' ) {
@@ -1575,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;
+                                       }
                                }
                        }
                }
@@ -1586,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;
@@ -1606,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;
        }
-       function isNullTimestamp() {
-               return "= '0'";
+
+       /**
+        * 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;
        }
+
+       /**
+        * Table name callback
+        * @access private
+        */
+       function tableNameCallback( $matches ) {
+               return $this->tableName( $matches[1] );
+       }
+
 }
 
 /**
@@ -1637,7 +1753,7 @@ class ResultWrapper {
        /**
         * @todo document
         */
-       function ResultWrapper( $database, $result ) {
+       function ResultWrapper( &$database, $result ) {
                $this->db =& $database;
                $this->result =& $result;
        }
@@ -1675,8 +1791,10 @@ class ResultWrapper {
        function seek( $row ) {
                $this->db->dataSeek( $this->result, $row );
        }
+
 }
 
+
 #------------------------------------------------------------------------------
 # Global functions
 #------------------------------------------------------------------------------
@@ -1688,13 +1806,12 @@ class ResultWrapper {
  */
 function wfEmergencyAbort( &$conn, $error ) {
        global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
-       global $wgSitename, $wgServer, $wgMessageCache;
+       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.
@@ -1735,12 +1852,15 @@ border=\"0\" ALT=\"Google\"></A>
        if ( is_object( $wgMessageCache ) ) {
                $wgMessageCache->disable();
        }
-       
-       $msg = wfGetSiteNotice();
-       if($msg == '') {
-               $msg = str_replace( '$1', $error, $noconnect );
+
+       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) {