]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/cache.php
Misses this file to merge. I like the comments.
[quix0rs-gnu-social.git] / lib / cache.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Cache interface plus default in-memory cache implementation
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Cache
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @copyright 2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 /**
31  * Interface for caching
32  *
33  * An abstract interface for caching. Because we originally used the
34  * Memcache plugin directly, the interface uses a small subset of the
35  * Memcache interface.
36  *
37  * @category  Cache
38  * @package   StatusNet
39  * @author    Evan Prodromou <evan@status.net>
40  * @copyright 2009 StatusNet, Inc.
41  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
42  * @link      http://status.net/
43  */
44 class Cache
45 {
46     /**
47      * @var array additional in-process cache for web requests;
48      *      disabled on CLI, unsafe for long-running daemons
49      */
50     var $_items = array();
51     var $_inlineCache = true;
52     static $_inst = null;
53
54     const COMPRESSED = 1;
55
56     private function __construct() {
57         // Potentially long-running daemons or maintenance scripts
58         // should not use an in-process cache as it becomes out of
59         // date.
60         $this->_inlineCache = (php_sapi_name() != 'cli');
61     }
62
63     /**
64      * Singleton constructor
65      *
66      * Use this to get the singleton instance of Cache.
67      *
68      * @return Cache cache object
69      */
70     static function instance()
71     {
72         if (is_null(self::$_inst)) {
73             self::$_inst = new Cache();
74         }
75
76         return self::$_inst;
77     }
78
79     /**
80      * Create a cache key from input text
81      *
82      * Builds a cache key from input text. Helps to namespace
83      * the cache area (if shared with other applications or sites)
84      * and prevent conflicts.
85      *
86      * @param string $extra the real part of the key
87      *
88      * @return string full key
89      */
90     static function key($extra)
91     {
92         $base_key = common_config('cache', 'base');
93
94         if (empty($base_key)) {
95             $base_key = self::keyize(common_config('site', 'name'));
96         }
97
98         return 'gnusocial:' . $base_key . ':' . $extra;
99     }
100
101     /**
102      * Create a cache key for data dependent on code
103      *
104      * For cache elements that are dependent on changes in code, this creates
105      * a more-or-less fingerprint of the current running code and adds it to
106      * the cache key. In the case of an upgrade of core, or addition or
107      * removal of plugins, a new unique fingerprint is generated and used.
108      * 
109      * There can still be problems with a) differences in versions of the 
110      * plugins and b) people running code between official versions. This is
111      * usually a problem only for experienced users like developers, who know
112      * how to clear their cache.
113      *
114      * For sites that run code between versions (like the status.net cloud),
115      * there's an additional build number configuration setting.
116      * 
117      * @param string $extra the real part of the key
118      *
119      * @return string full key
120      */
121     
122     static function codeKey($extra)
123     {
124         static $prefix = null;
125         
126         if (empty($prefix)) {
127             
128             $names   = array();
129             
130             foreach (GNUsocial::getActivePlugins() as $plugin=>$attrs) {
131                 $names[] = $plugin;
132             }
133             
134             asort($names);
135             
136             // Unique enough.
137         
138             $uniq = crc32(implode(',', $names));
139
140             $build = common_config('site', 'build');
141
142             $prefix = GNUSOCIAL_VERSION.':'.$build.':'.$uniq;
143         }
144         
145         return Cache::key($prefix.':'.$extra);
146     }
147     
148     /**
149      * Make a string suitable for use as a key
150      *
151      * Useful for turning primary keys of tables into cache keys.
152      *
153      * @param string $str string to turn into a key
154      *
155      * @return string keyized string
156      */
157     static function keyize($str)
158     {
159         $str = strtolower($str);
160         $str = preg_replace('/\s/', '_', $str);
161         return $str;
162     }
163
164     /**
165      * Get a value associated with a key
166      *
167      * The value should have been set previously.
168      *
169      * @param string $key Lookup key
170      *
171      * @return string retrieved value or null if unfound
172      */
173     function get($key)
174     {
175         $value = false;
176
177         common_perf_counter('Cache::get', $key);
178         if (Event::handle('StartCacheGet', array(&$key, &$value))) {
179             if ($this->_inlineCache && array_key_exists($key, $this->_items)) {
180                 $value = unserialize($this->_items[$key]);
181             }
182             Event::handle('EndCacheGet', array($key, &$value));
183         }
184
185         return $value;
186     }
187
188     /**
189      * Set the value associated with a key
190      *
191      * @param string  $key    The key to use for lookups
192      * @param string  $value  The value to store
193      * @param integer $flag   Flags to use, may include Cache::COMPRESSED
194      * @param integer $expiry Expiry value, mostly ignored
195      *
196      * @return boolean success flag
197      */
198     function set($key, $value, $flag=null, $expiry=null)
199     {
200         $success = false;
201
202         common_perf_counter('Cache::set', $key);
203         if (Event::handle('StartCacheSet', array(&$key, &$value, &$flag,
204                                                  &$expiry, &$success))) {
205
206             if ($this->_inlineCache) {
207                 $this->_items[$key] = serialize($value);
208             }
209
210             $success = true;
211
212             Event::handle('EndCacheSet', array($key, $value, $flag,
213                                                $expiry));
214         }
215
216         return $success;
217     }
218
219     /**
220      * Atomically increment an existing numeric value.
221      * Existing expiration time should remain unchanged, if any.
222      *
223      * @param string  $key    The key to use for lookups
224      * @param int     $step   Amount to increment (default 1)
225      *
226      * @return mixed incremented value, or false if not set.
227      */
228     function increment($key, $step=1)
229     {
230         $value = false;
231         common_perf_counter('Cache::increment', $key);
232         if (Event::handle('StartCacheIncrement', array(&$key, &$step, &$value))) {
233             // Fallback is not guaranteed to be atomic,
234             // and may original expiry value.
235             $value = $this->get($key);
236             if ($value !== false) {
237                 $value += $step;
238                 $ok = $this->set($key, $value);
239                 $got = $this->get($key);
240             }
241             Event::handle('EndCacheIncrement', array($key, $step, $value));
242         }
243         return $value;
244     }
245
246     /**
247      * Delete the value associated with a key
248      *
249      * @param string $key Key to delete
250      *
251      * @return boolean success flag
252      */
253     function delete($key)
254     {
255         $success = false;
256
257         common_perf_counter('Cache::delete', $key);
258         if (Event::handle('StartCacheDelete', array(&$key, &$success))) {
259             if ($this->_inlineCache && array_key_exists($key, $this->_items)) {
260                 unset($this->_items[$key]);
261             }
262             $success = true;
263             Event::handle('EndCacheDelete', array($key));
264         }
265
266         return $success;
267     }
268
269     /**
270      * Close or reconnect any remote connections, such as to give
271      * daemon processes a chance to reconnect on a fresh socket.
272      *
273      * @return boolean success flag
274      */
275     function reconnect()
276     {
277         $success = false;
278
279         if (Event::handle('StartCacheReconnect', array(&$success))) {
280             $success = true;
281             Event::handle('EndCacheReconnect', array());
282         }
283
284         return $success;
285     }
286 }