cache.php 8.3 KB

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