Play safe and clear the article object internals, too (eg. mTouched).
[lhc/web/wiklou.git] / includes / BagOStuff.php
index 2ec6153..7f40001 100644 (file)
@@ -1,30 +1,33 @@
 <?php
-#
-# Copyright (C) 2003-2004 Brion Vibber <brion@pobox.com>
-# http://www.mediawiki.org/
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License along
-# with this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-# http://www.gnu.org/copyleft/gpl.html
-
 /**
- * @defgroup Cache Cache
+ * Classes to cache objects in PHP accelerators, SQL database or DBA files
+ *
+ * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
+ * http://www.mediawiki.org/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
  *
  * @file
  * @ingroup Cache
  */
 
+/**
+ * @defgroup Cache Cache
+ */
+
 /**
  * interface is intended to be more or less compatible with
  * the PHP memcached client.
@@ -32,7 +35,7 @@
  * backends for local hash array and SQL table included:
  * <code>
  *   $bag = new HashBagOStuff();
- *   $bag = new MediaWikiBagOStuff($tablename); # connect to db first
+ *   $bag = new SqlBagOStuff(); # connect to db first
  * </code>
  *
  * @ingroup Cache
@@ -54,7 +57,7 @@ abstract class BagOStuff {
        abstract public function get( $key );
 
        /**
-        * Set an item. 
+        * Set an item.
         * @param $key string
         * @param $value mixed
         * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
@@ -87,9 +90,11 @@ abstract class BagOStuff {
        /* Better performance can likely be got with custom written versions */
        public function get_multi( $keys ) {
                $out = array();
+
                foreach ( $keys as $key ) {
                        $out[$key] = $this->get( $key );
                }
+
                return $out;
        }
 
@@ -100,8 +105,9 @@ abstract class BagOStuff {
        }
 
        public function add( $key, $value, $exptime = 0 ) {
-               if ( $this->get( $key ) == false ) {
+               if ( !$this->get( $key ) ) {
                        $this->set( $key, $value, $exptime );
+
                        return true;
                }
        }
@@ -124,35 +130,42 @@ abstract class BagOStuff {
                }
        }
 
+       /**
+        * @param $key String: Key to increase
+        * @param $value Integer: Value to add to $key (Default 1)
+        * @return null if lock is not possible else $key value increased by $value
+        */
        public function incr( $key, $value = 1 ) {
                if ( !$this->lock( $key ) ) {
-                       return false;
+                       return null;
                }
+
                $value = intval( $value );
 
-               $n = false;
                if ( ( $n = $this->get( $key ) ) !== false ) {
                        $n += $value;
                        $this->set( $key, $n ); // exptime?
                }
                $this->unlock( $key );
+
                return $n;
        }
 
        public function decr( $key, $value = 1 ) {
-               return $this->incr( $key, -$value );
+               return $this->incr( $key, - $value );
        }
 
        public function debug( $text ) {
-               if ( $this->debugMode )
+               if ( $this->debugMode ) {
                        wfDebug( "BagOStuff debug: $text\n" );
+               }
        }
 
        /**
         * Convert an optionally relative time to an absolute time
         */
        protected function convertExpiry( $exptime ) {
-               if ( ( $exptime != 0 ) && ( $exptime < 3600 * 24 * 30 ) ) {
+               if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
                        return time() + $exptime;
                } else {
                        return $exptime;
@@ -160,7 +173,6 @@ abstract class BagOStuff {
        }
 }
 
-
 /**
  * Functional versions!
  * This is a test of the interface, mainly. It stores things in an associative
@@ -177,10 +189,13 @@ class HashBagOStuff extends BagOStuff {
 
        protected function expire( $key ) {
                $et = $this->bag[$key][1];
+
                if ( ( $et == 0 ) || ( $et > time() ) ) {
                        return false;
                }
+
                $this->delete( $key );
+
                return true;
        }
 
@@ -188,9 +203,11 @@ class HashBagOStuff extends BagOStuff {
                if ( !isset( $this->bag[$key] ) ) {
                        return false;
                }
+
                if ( $this->expire( $key ) ) {
                        return false;
                }
+
                return $this->bag[$key][0];
        }
 
@@ -202,7 +219,9 @@ class HashBagOStuff extends BagOStuff {
                if ( !isset( $this->bag[$key] ) ) {
                        return false;
                }
+
                unset( $this->bag[$key] );
+
                return true;
        }
 
@@ -221,11 +240,20 @@ class SqlBagOStuff extends BagOStuff {
        var $lastExpireAll = 0;
 
        protected function getDB() {
-               if ( !isset( $this->lb ) ) {
-                       $this->lb = wfGetLBFactory()->newMainLB();
-                       $this->db = $this->lb->getConnection( DB_MASTER );
-                       $this->db->clearFlag( DBO_TRX );
+               if ( !isset( $this->db ) ) {
+                       /* We must keep a separate connection to MySQL in order to avoid deadlocks
+                        * However, SQLite has an opposite behaviour.
+                        * @todo Investigate behaviour for other databases
+                        */
+                       if ( wfGetDB( DB_MASTER )->getType() == 'sqlite' ) {
+                               $this->db = wfGetDB( DB_MASTER );
+                       } else {
+                               $this->lb = wfGetLBFactory()->newMainLB();
+                               $this->db = $this->lb->getConnection( DB_MASTER );
+                               $this->db->clearFlag( DBO_TRX );
+                       }
                }
+
                return $this->db;
        }
 
@@ -235,20 +263,22 @@ class SqlBagOStuff extends BagOStuff {
                $db = $this->getDB();
                $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
                        array( 'keyname' => $key ), __METHOD__ );
+
                if ( !$row ) {
                        $this->debug( 'get: no matching rows' );
                        return false;
                }
 
                $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
+
                if ( $this->isExpired( $row->exptime ) ) {
                        $this->debug( "get: key has expired, deleting" );
                        try {
                                $db->begin();
-                               # Put the expiry time in the WHERE condition to avoid deleting a 
+                               # Put the expiry time in the WHERE condition to avoid deleting a
                                # newly-inserted value
-                               $db->delete( 'objectcache', 
-                                       array( 
+                               $db->delete( 'objectcache',
+                                       array(
                                                'keyname' => $key,
                                                'exptime' => $row->exptime
                                        ), __METHOD__ );
@@ -256,27 +286,36 @@ class SqlBagOStuff extends BagOStuff {
                        } catch ( DBQueryError $e ) {
                                $this->handleWriteError( $e );
                        }
+
                        return false;
                }
+
                return $this->unserialize( $db->decodeBlob( $row->value ) );
        }
 
        public function set( $key, $value, $exptime = 0 ) {
                $db = $this->getDB();
                $exptime = intval( $exptime );
-               if ( $exptime < 0 ) $exptime = 0;
+
+               if ( $exptime < 0 ) {
+                       $exptime = 0;
+               }
+
                if ( $exptime == 0 ) {
                        $encExpiry = $this->getMaxDateTime();
                } else {
-                       if ( $exptime < 3.16e8 ) # ~10 years
+                       if ( $exptime < 3.16e8 ) # ~10 years
                                $exptime += time();
+                       }
+
                        $encExpiry = $db->timestamp( $exptime );
                }
                try {
                        $db->begin();
-                       $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
-                       $db->insert( 'objectcache', 
-                               array( 
+                       // (bug 24425) use a replace if the db supports it instead of
+                       // delete/insert to avoid clashes with conflicting keynames
+                       $db->replace( 'objectcache', array( 'keyname' ),
+                               array(
                                        'keyname' => $key,
                                        'value' => $db->encodeBlob( $this->serialize( $value ) ),
                                        'exptime' => $encExpiry
@@ -284,21 +323,26 @@ class SqlBagOStuff extends BagOStuff {
                        $db->commit();
                } catch ( DBQueryError $e ) {
                        $this->handleWriteError( $e );
+
                        return false;
                }
+
                return true;
        }
 
        public function delete( $key, $time = 0 ) {
                $db = $this->getDB();
+
                try {
                        $db->begin();
                        $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
                        $db->commit();
                } catch ( DBQueryError $e ) {
                        $this->handleWriteError( $e );
+
                        return false;
                }
+
                return true;
        }
 
@@ -313,13 +357,15 @@ class SqlBagOStuff extends BagOStuff {
                        if ( $row === false ) {
                                // Missing
                                $db->commit();
-                               return false;
+
+                               return null;
                        }
                        $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
                        if ( $this->isExpired( $row->exptime ) ) {
                                // Expired, do not reinsert
                                $db->commit();
-                               return false;
+
+                               return null;
                        }
 
                        $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
@@ -333,18 +379,22 @@ class SqlBagOStuff extends BagOStuff {
                        $db->commit();
                } catch ( DBQueryError $e ) {
                        $this->handleWriteError( $e );
-                       return false;
+
+                       return null;
                }
+
                return $newValue;
        }
 
        public function keys() {
                $db = $this->getDB();
-               $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );     
+               $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );
                $result = array();
+
                foreach ( $res as $row ) {
                        $result[] = $row->keyname;
                }
+
                return $result;
        }
 
@@ -375,6 +425,7 @@ class SqlBagOStuff extends BagOStuff {
        public function expireAll() {
                $db = $this->getDB();
                $now = $db->timestamp();
+
                try {
                        $db->begin();
                        $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__ );
@@ -386,6 +437,7 @@ class SqlBagOStuff extends BagOStuff {
 
        public function deleteAll() {
                $db = $this->getDB();
+
                try {
                        $db->begin();
                        $db->delete( 'objectcache', '*', __METHOD__ );
@@ -405,6 +457,7 @@ class SqlBagOStuff extends BagOStuff {
         */
        protected function serialize( &$data ) {
                $serial = serialize( $data );
+
                if ( function_exists( 'gzdeflate' ) ) {
                        return gzdeflate( $serial );
                } else {
@@ -420,11 +473,14 @@ class SqlBagOStuff extends BagOStuff {
        protected function unserialize( $serial ) {
                if ( function_exists( 'gzinflate' ) ) {
                        $decomp = @gzinflate( $serial );
+
                        if ( false !== $decomp ) {
                                $serial = $decomp;
                        }
                }
+
                $ret = unserialize( $serial );
+
                return $ret;
        }
 
@@ -434,13 +490,16 @@ class SqlBagOStuff extends BagOStuff {
         */
        protected function handleWriteError( $exception ) {
                $db = $this->getDB();
+
                if ( !$db->wasReadOnlyError() ) {
                        throw $exception;
                }
+
                try {
                        $db->rollback();
                } catch ( DBQueryError $e ) {
                }
+
                wfDebug( __METHOD__ . ": ignoring query error\n" );
                $db->ignoreErrors( false );
        }
@@ -449,83 +508,53 @@ class SqlBagOStuff extends BagOStuff {
 /**
  * Backwards compatibility alias
  */
-class MediaWikiBagOStuff extends SqlBagOStuff {}
+class MediaWikiBagOStuff extends SqlBagOStuff { }
 
 /**
- * This is a wrapper for Turck MMCache's shared memory functions.
- *
- * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
- * to use a weird custom serializer that randomly segfaults. So we wrap calls
- * with serialize()/unserialize().
- *
- * The thing I noticed about the Turck serialized data was that unlike ordinary
- * serialize(), it contained the names of methods, and judging by the amount of
- * binary data, perhaps even the bytecode of the methods themselves. It may be
- * that Turck's serializer is faster, so a possible future extension would be
- * to use it for arrays but not for objects.
+ * This is a wrapper for APC's shared memory functions
  *
  * @ingroup Cache
  */
-class TurckBagOStuff extends BagOStuff {
+class APCBagOStuff extends BagOStuff {
        public function get( $key ) {
-               $val = mmcache_get( $key );
+               $val = apc_fetch( $key );
+
                if ( is_string( $val ) ) {
                        $val = unserialize( $val );
                }
+
                return $val;
        }
 
        public function set( $key, $value, $exptime = 0 ) {
-               mmcache_put( $key, serialize( $value ), $exptime );
+               apc_store( $key, serialize( $value ), $exptime );
+
                return true;
        }
 
        public function delete( $key, $time = 0 ) {
-               mmcache_rm( $key );
-               return true;
-       }
+               apc_delete( $key );
 
-       public function lock( $key, $waitTimeout = 0 ) {
-               mmcache_lock( $key );
                return true;
        }
 
-       public function unlock( $key ) {
-               mmcache_unlock( $key );
-               return true;
-       }
-}
+       public function keys() {
+               $info = apc_cache_info( 'user' );
+               $list = $info['cache_list'];
+               $keys = array();
 
-/**
- * This is a wrapper for APC's shared memory functions
- *
- * @ingroup Cache
- */
-class APCBagOStuff extends BagOStuff {
-       public function get( $key ) {
-               $val = apc_fetch( $key );
-               if ( is_string( $val ) ) {
-                       $val = unserialize( $val );
+               foreach ( $list as $entry ) {
+                       $keys[] = $entry['info'];
                }
-               return $val;
-       }
 
-       public function set( $key, $value, $exptime = 0 ) {
-               apc_store( $key, serialize( $value ), $exptime );
-               return true;
-       }
-
-       public function delete( $key, $time = 0 ) {
-               apc_delete( $key );
-               return true;
+               return $keys;
        }
 }
 
-
 /**
  * This is a wrapper for eAccelerator's shared memory functions.
  *
- * This is basically identical to the Turck MMCache version,
+ * This is basically identical to the deceased Turck MMCache version,
  * mostly because eAccelerator is based on Turck MMCache.
  *
  * @ingroup Cache
@@ -533,29 +562,35 @@ class APCBagOStuff extends BagOStuff {
 class eAccelBagOStuff extends BagOStuff {
        public function get( $key ) {
                $val = eaccelerator_get( $key );
+
                if ( is_string( $val ) ) {
                        $val = unserialize( $val );
                }
+
                return $val;
        }
 
        public function set( $key, $value, $exptime = 0 ) {
                eaccelerator_put( $key, serialize( $value ), $exptime );
+
                return true;
        }
 
        public function delete( $key, $time = 0 ) {
                eaccelerator_rm( $key );
+
                return true;
        }
 
        public function lock( $key, $waitTimeout = 0 ) {
                eaccelerator_lock( $key );
+
                return true;
        }
 
        public function unlock( $key ) {
                eaccelerator_unlock( $key );
+
                return true;
        }
 }
@@ -567,7 +602,6 @@ class eAccelBagOStuff extends BagOStuff {
  * @ingroup Cache
  */
 class XCacheBagOStuff extends BagOStuff {
-
        /**
         * Get a value from the XCache object cache
         *
@@ -576,8 +610,11 @@ class XCacheBagOStuff extends BagOStuff {
         */
        public function get( $key ) {
                $val = xcache_get( $key );
-               if ( is_string( $val ) )
+
+               if ( is_string( $val ) ) {
                        $val = unserialize( $val );
+               }
+
                return $val;
        }
 
@@ -591,6 +628,7 @@ class XCacheBagOStuff extends BagOStuff {
         */
        public function set( $key, $value, $expire = 0 ) {
                xcache_set( $key, serialize( $value ), $expire );
+
                return true;
        }
 
@@ -603,15 +641,15 @@ class XCacheBagOStuff extends BagOStuff {
         */
        public function delete( $key, $time = 0 ) {
                xcache_unset( $key );
+
                return true;
        }
-
 }
 
 /**
- * Cache that uses DBA as a backend. 
- * Slow due to the need to constantly open and close the file to avoid holding 
- * writer locks. Intended for development use only,  as a memcached workalike 
+ * Cache that uses DBA as a backend.
+ * Slow due to the need to constantly open and close the file to avoid holding
+ * writer locks. Intended for development use only,  as a memcached workalike
  * for systems that don't have it.
  *
  * @ingroup Cache
@@ -619,15 +657,18 @@ class XCacheBagOStuff extends BagOStuff {
 class DBABagOStuff extends BagOStuff {
        var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
 
-       public function __construct( $handler = 'db3', $dir = false ) {
+       public function __construct( $dir = false ) {
+               global $wgDBAhandler;
+
                if ( $dir === false ) {
                        global $wgTmpDirectory;
                        $dir = $wgTmpDirectory;
                }
+
                $this->mFile = "$dir/mw-cache-" . wfWikiID();
                $this->mFile .= '.db';
                wfDebug( __CLASS__ . ": using cache file {$this->mFile}\n" );
-               $this->mHandler = $handler;
+               $this->mHandler = $wgDBAhandler;
        }
 
        /**
@@ -636,6 +677,7 @@ class DBABagOStuff extends BagOStuff {
        function encode( $value, $expiry ) {
                # Convert to absolute time
                $expiry = $this->convertExpiry( $expiry );
+
                return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
        }
 
@@ -649,7 +691,7 @@ class DBABagOStuff extends BagOStuff {
                        return array(
                                unserialize( substr( $blob, 11 ) ),
                                intval( substr( $blob, 0, 10 ) )
-                       );
+                       );
                }
        }
 
@@ -659,29 +701,36 @@ class DBABagOStuff extends BagOStuff {
                } else {
                        $handle = $this->getWriter();
                }
+
                if ( !$handle ) {
                        wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
                }
+
                return $handle;
        }
 
        function getWriter() {
                $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
+
                if ( !$handle ) {
                        wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
                }
+
                return $handle;
        }
 
        function get( $key ) {
                wfProfileIn( __METHOD__ );
                wfDebug( __METHOD__ . "($key)\n" );
+
                $handle = $this->getReader();
                if ( !$handle ) {
                        return null;
                }
+
                $val = dba_fetch( $key, $handle );
                list( $val, $expiry ) = $this->decode( $val );
+
                # Must close ASAP because locks are held
                dba_close( $handle );
 
@@ -693,6 +742,7 @@ class DBABagOStuff extends BagOStuff {
                        wfDebug( __METHOD__ . ": $key expired\n" );
                        $val = null;
                }
+
                wfProfileOut( __METHOD__ );
                return $val;
        }
@@ -700,13 +750,17 @@ class DBABagOStuff extends BagOStuff {
        function set( $key, $value, $exptime = 0 ) {
                wfProfileIn( __METHOD__ );
                wfDebug( __METHOD__ . "($key)\n" );
+
                $blob = $this->encode( $value, $exptime );
+
                $handle = $this->getWriter();
                if ( !$handle ) {
                        return false;
                }
+
                $ret = dba_replace( $key, $blob, $handle );
                dba_close( $handle );
+
                wfProfileOut( __METHOD__ );
                return $ret;
        }
@@ -714,27 +768,36 @@ class DBABagOStuff extends BagOStuff {
        function delete( $key, $time = 0 ) {
                wfProfileIn( __METHOD__ );
                wfDebug( __METHOD__ . "($key)\n" );
+
                $handle = $this->getWriter();
                if ( !$handle ) {
                        return false;
                }
+
                $ret = dba_delete( $key, $handle );
                dba_close( $handle );
+
                wfProfileOut( __METHOD__ );
                return $ret;
        }
 
        function add( $key, $value, $exptime = 0 ) {
                wfProfileIn( __METHOD__ );
+
                $blob = $this->encode( $value, $exptime );
+
                $handle = $this->getWriter();
+
                if ( !$handle ) {
                        return false;
                }
+
                $ret = dba_insert( $key, $blob, $handle );
+
                # Insert failed, check to see if it failed due to an expired key
                if ( !$ret ) {
                        list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
+
                        if ( $expiry < time() ) {
                                # Yes expired, delete and try again
                                dba_delete( $key, $handle );
@@ -744,6 +807,7 @@ class DBABagOStuff extends BagOStuff {
                }
 
                dba_close( $handle );
+
                wfProfileOut( __METHOD__ );
                return $ret;
        }
@@ -751,13 +815,87 @@ class DBABagOStuff extends BagOStuff {
        function keys() {
                $reader = $this->getReader();
                $k1 = dba_firstkey( $reader );
+
                if ( !$k1 ) {
                        return array();
                }
+
                $result[] = $k1;
+
                while ( $key = dba_nextkey( $reader ) ) {
                        $result[] = $key;
                }
+
                return $result;
        }
 }
+
+/**
+ * Wrapper for WinCache object caching functions; identical interface
+ * to the APC wrapper
+ *
+ * @ingroup Cache
+ */
+class WinCacheBagOStuff extends BagOStuff {
+
+       /**
+        * Get a value from the WinCache object cache
+        *
+        * @param $key String: cache key
+        * @return mixed
+        */
+       public function get( $key ) {
+               $val = wincache_ucache_get( $key );
+
+               if ( is_string( $val ) ) {
+                       $val = unserialize( $val );
+               }
+
+               return $val;
+       }
+
+       /**
+        * Store a value in the WinCache object cache
+        *
+        * @param $key String: cache key
+        * @param $value Mixed: object to store
+        * @param $expire Int: expiration time
+        * @return bool
+        */
+       public function set( $key, $value, $expire = 0 ) {
+               $result = wincache_ucache_set( $key, serialize( $value ), $expire );
+
+               /* wincache_ucache_set returns an empty array on success if $value
+                  was an array, bool otherwise */
+               return ( is_array( $result ) && $result === array() ) || $result;
+       }
+
+       /**
+        * Remove a value from the WinCache object cache
+        *
+        * @param $key String: cache key
+        * @param $time Int: not used in this implementation
+        * @return bool
+        */
+       public function delete( $key, $time = 0 ) {
+               wincache_ucache_delete( $key );
+
+               return true;
+       }
+
+       public function keys() {
+               $info = wincache_ucache_info();
+               $list = $info['ucache_entries'];
+               $keys = array();
+
+               if ( is_null( $list ) ) {
+                       return array();
+               }
+
+               foreach ( $list as $entry ) {
+                       $keys[] = $entry['key_name'];
+               }
+
+               return $keys;
+       }
+}