]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/cache.php
Merge ActivitySpam plugin
[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 'statusnet:' . $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             $plugins     = StatusNet::getActivePlugins();
129             $names       = array();
130             
131             foreach ($plugins as $plugin) {
132                 $names[] = $plugin[0];
133             }
134             
135             $names = array_unique($names);
136             asort($names);
137             
138             // Unique enough.
139         
140             $uniq = crc32(implode(',', $names));
141
142             $build = common_config('site', 'build');
143
144             $prefix = STATUSNET_VERSION.':'.$build.':'.$uniq;
145         }
146         
147         return Cache::key($prefix.':'.$extra);
148     }
149     
150     /**
151      * Make a string suitable for use as a key
152      *
153      * Useful for turning primary keys of tables into cache keys.
154      *
155      * @param string $str string to turn into a key
156      *
157      * @return string keyized string
158      */
159     static function keyize($str)
160     {
161         $str = strtolower($str);
162         $str = preg_replace('/\s/', '_', $str);
163         return $str;
164     }
165
166     /**
167      * Get a value associated with a key
168      *
169      * The value should have been set previously.
170      *
171      * @param string $key Lookup key
172      *
173      * @return string retrieved value or null if unfound
174      */
175     function get($key)
176     {
177         $value = false;
178
179         common_perf_counter('Cache::get', $key);
180         if (Event::handle('StartCacheGet', array(&$key, &$value))) {
181             if ($this->_inlineCache && array_key_exists($key, $this->_items)) {
182                 $value = unserialize($this->_items[$key]);
183             }
184             Event::handle('EndCacheGet', array($key, &$value));
185         }
186
187         return $value;
188     }
189
190     /**
191      * Set the value associated with a key
192      *
193      * @param string  $key    The key to use for lookups
194      * @param string  $value  The value to store
195      * @param integer $flag   Flags to use, may include Cache::COMPRESSED
196      * @param integer $expiry Expiry value, mostly ignored
197      *
198      * @return boolean success flag
199      */
200     function set($key, $value, $flag=null, $expiry=null)
201     {
202         $success = false;
203
204         common_perf_counter('Cache::set', $key);
205         if (Event::handle('StartCacheSet', array(&$key, &$value, &$flag,
206                                                  &$expiry, &$success))) {
207
208             if ($this->_inlineCache) {
209                 $this->_items[$key] = serialize($value);
210             }
211
212             $success = true;
213
214             Event::handle('EndCacheSet', array($key, $value, $flag,
215                                                $expiry));
216         }
217
218         return $success;
219     }
220
221     /**
222      * Atomically increment an existing numeric value.
223      * Existing expiration time should remain unchanged, if any.
224      *
225      * @param string  $key    The key to use for lookups
226      * @param int     $step   Amount to increment (default 1)
227      *
228      * @return mixed incremented value, or false if not set.
229      */
230     function increment($key, $step=1)
231     {
232         $value = false;
233         common_perf_counter('Cache::increment', $key);
234         if (Event::handle('StartCacheIncrement', array(&$key, &$step, &$value))) {
235             // Fallback is not guaranteed to be atomic,
236             // and may original expiry value.
237             $value = $this->get($key);
238             if ($value !== false) {
239                 $value += $step;
240                 $ok = $this->set($key, $value);
241                 $got = $this->get($key);
242             }
243             Event::handle('EndCacheIncrement', array($key, $step, $value));
244         }
245         return $value;
246     }
247
248     /**
249      * Delete the value associated with a key
250      *
251      * @param string $key Key to delete
252      *
253      * @return boolean success flag
254      */
255     function delete($key)
256     {
257         $success = false;
258
259         common_perf_counter('Cache::delete', $key);
260         if (Event::handle('StartCacheDelete', array(&$key, &$success))) {
261             if ($this->_inlineCache && array_key_exists($key, $this->_items)) {
262                 unset($this->_items[$key]);
263             }
264             $success = true;
265             Event::handle('EndCacheDelete', array($key));
266         }
267
268         return $success;
269     }
270
271     /**
272      * Close or reconnect any remote connections, such as to give
273      * daemon processes a chance to reconnect on a fresh socket.
274      *
275      * @return boolean success flag
276      */
277     function reconnect()
278     {
279         $success = false;
280
281         if (Event::handle('StartCacheReconnect', array(&$success))) {
282             $success = true;
283             Event::handle('EndCacheReconnect', array());
284         }
285
286         return $success;
287     }
288 }