]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/cache.php
Merge branch '0.9.x' into 1.0.x
[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     var $_items   = array();
47     static $_inst = null;
48
49     const COMPRESSED = 1;
50
51     /**
52      * Singleton constructor
53      *
54      * Use this to get the singleton instance of Cache.
55      *
56      * @return Cache cache object
57      */
58     static function instance()
59     {
60         if (is_null(self::$_inst)) {
61             self::$_inst = new Cache();
62         }
63
64         return self::$_inst;
65     }
66
67     /**
68      * Create a cache key from input text
69      *
70      * Builds a cache key from input text. Helps to namespace
71      * the cache area (if shared with other applications or sites)
72      * and prevent conflicts.
73      *
74      * @param string $extra the real part of the key
75      *
76      * @return string full key
77      */
78     static function key($extra)
79     {
80         $base_key = common_config('cache', 'base');
81
82         if (empty($base_key)) {
83             $base_key = self::keyize(common_config('site', 'name'));
84         }
85
86         return 'statusnet:' . $base_key . ':' . $extra;
87     }
88
89     /**
90      * Create a cache key for data dependent on code
91      *
92      * For cache elements that are dependent on changes in code, this creates
93      * a more-or-less fingerprint of the current running code and adds it to
94      * the cache key. In the case of an upgrade of core, or addition or
95      * removal of plugins, a new unique fingerprint is generated and used.
96      * 
97      * There can still be problems with a) differences in versions of the 
98      * plugins and b) people running code between official versions. This is
99      * usually a problem only for experienced users like developers, who know
100      * how to clear their cache.
101      *
102      * For sites that run code between versions (like the status.net cloud),
103      * there's an additional build number configuration setting.
104      * 
105      * @param string $extra the real part of the key
106      *
107      * @return string full key
108      */
109     
110     static function codeKey($extra)
111     {
112         static $prefix = null;
113         
114         if (empty($prefix)) {
115             
116             $plugins     = StatusNet::getActivePlugins();
117             $names       = array();
118             
119             foreach ($plugins as $plugin) {
120                 $names[] = $plugin[0];
121             }
122             
123             $names = array_unique($names);
124             asort($names);
125             
126             // Unique enough.
127         
128             $uniq = crc32(implode(',', $names));
129
130             $build = common_config('site', 'build');
131
132             $prefix = STATUSNET_VERSION.':'.$build.':'.$uniq;
133         }
134         
135         return Cache::key($prefix.':'.$extra);
136     }
137     
138     /**
139      * Make a string suitable for use as a key
140      *
141      * Useful for turning primary keys of tables into cache keys.
142      *
143      * @param string $str string to turn into a key
144      *
145      * @return string keyized string
146      */
147     static function keyize($str)
148     {
149         $str = strtolower($str);
150         $str = preg_replace('/\s/', '_', $str);
151         return $str;
152     }
153
154     /**
155      * Get a value associated with a key
156      *
157      * The value should have been set previously.
158      *
159      * @param string $key Lookup key
160      *
161      * @return string retrieved value or null if unfound
162      */
163     function get($key)
164     {
165         $value = false;
166
167         common_perf_counter('Cache::get', $key);
168         if (Event::handle('StartCacheGet', array(&$key, &$value))) {
169             if (array_key_exists($key, $this->_items)) {
170                 $value = unserialize($this->_items[$key]);
171             }
172             Event::handle('EndCacheGet', array($key, &$value));
173         }
174
175         return $value;
176     }
177
178     /**
179      * Set the value associated with a key
180      *
181      * @param string  $key    The key to use for lookups
182      * @param string  $value  The value to store
183      * @param integer $flag   Flags to use, may include Cache::COMPRESSED
184      * @param integer $expiry Expiry value, mostly ignored
185      *
186      * @return boolean success flag
187      */
188     function set($key, $value, $flag=null, $expiry=null)
189     {
190         $success = false;
191
192         common_perf_counter('Cache::set', $key);
193         if (Event::handle('StartCacheSet', array(&$key, &$value, &$flag,
194                                                  &$expiry, &$success))) {
195
196             $this->_items[$key] = serialize($value);
197
198             $success = true;
199
200             Event::handle('EndCacheSet', array($key, $value, $flag,
201                                                $expiry));
202         }
203
204         return $success;
205     }
206
207     /**
208      * Atomically increment an existing numeric value.
209      * Existing expiration time should remain unchanged, if any.
210      *
211      * @param string  $key    The key to use for lookups
212      * @param int     $step   Amount to increment (default 1)
213      *
214      * @return mixed incremented value, or false if not set.
215      */
216     function increment($key, $step=1)
217     {
218         $value = false;
219         common_perf_counter('Cache::increment', $key);
220         if (Event::handle('StartCacheIncrement', array(&$key, &$step, &$value))) {
221             // Fallback is not guaranteed to be atomic,
222             // and may original expiry value.
223             $value = $this->get($key);
224             if ($value !== false) {
225                 $value += $step;
226                 $ok = $this->set($key, $value);
227                 $got = $this->get($key);
228             }
229             Event::handle('EndCacheIncrement', array($key, $step, $value));
230         }
231         return $value;
232     }
233
234     /**
235      * Delete the value associated with a key
236      *
237      * @param string $key Key to delete
238      *
239      * @return boolean success flag
240      */
241     function delete($key)
242     {
243         $success = false;
244
245         common_perf_counter('Cache::delete', $key);
246         if (Event::handle('StartCacheDelete', array(&$key, &$success))) {
247             if (array_key_exists($key, $this->_items)) {
248                 unset($this->_items[$key]);
249             }
250             $success = true;
251             Event::handle('EndCacheDelete', array($key));
252         }
253
254         return $success;
255     }
256
257     /**
258      * Close or reconnect any remote connections, such as to give
259      * daemon processes a chance to reconnect on a fresh socket.
260      *
261      * @return boolean success flag
262      */
263     function reconnect()
264     {
265         $success = false;
266
267         if (Event::handle('StartCacheReconnect', array(&$success))) {
268             $success = true;
269             Event::handle('EndCacheReconnect', array());
270         }
271
272         return $success;
273     }
274 }