updated
[lhc/web/wiklou.git] / includes / Database.php
index 54ea219..51d2e74 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;
@@ -136,6 +137,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
 #------------------------------------------------------------------------------
@@ -231,7 +244,14 @@ 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 != '' ) {
@@ -253,7 +273,6 @@ class Database {
 
                if ( !$success ) {
                        $this->reportConnectionError();
-                       $this->close();
                }
                $this->mOpened = $success;
                return $success;
@@ -282,16 +301,15 @@ class Database {
        /**
         * @access private
         * @param string $msg error message ?
-        * @todo parameter $msg is not used
         */
-       function reportConnectionError( $msg = '') {
+       function reportConnectionError() {
                if ( $this->mFailFunction ) {
                        if ( !is_int( $this->mFailFunction ) ) {
                                $ff = $this->mFailFunction;
                                $ff( $this, $this->lastError() );
                        }
                } else {
-                       wfEmergencyAbort( $this, mysql_error() );
+                       wfEmergencyAbort( $this, $this->lastError() );
                }
        }
 
@@ -307,7 +325,7 @@ class Database {
                        # 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 ) ) {
+                       if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
                                wfDebug( "Write query from $fname blocked\n" );
                                return false;
                        }
@@ -392,10 +410,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 +625,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();
                }
@@ -682,7 +706,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 +718,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,9 +738,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 = '';
                }
@@ -728,9 +758,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 );
        }
 
@@ -960,7 +988,7 @@ 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 ) )
@@ -1009,18 +1037,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 );
@@ -1103,6 +1133,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 +1173,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
@@ -1277,9 +1331,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 +1540,7 @@ class Database {
        /**
         * @todo document
         */
-       function resultObject( &$result ) {
+       function resultObject( $result ) {
                if( empty( $result ) ) {
                        return NULL;
                } else {
@@ -1649,13 +1706,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 is currently offline</h1><p><strong>Sorry! This site is experiencing technical difficulties.</strong></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,6 +1747,12 @@ border=\"0\" ALT=\"Google\"></A>
                header( 'Cache-control: none' );
                header( 'Pragma: nocache' );
        }
+
+       # No database access
+       if ( is_object( $wgMessageCache ) ) {
+               $wgMessageCache->disable();
+       }
+       
        $msg = wfGetSiteNotice();
        if($msg == '') {
                $msg = str_replace( '$1', $error, $noconnect );