cache.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 = [];
  117. foreach (GNUsocial::getActiveModules() 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', [&$key, &$value])) {
  157. if ($this->_inlineCache && array_key_exists($key, $this->_items)) {
  158. $value = unserialize($this->_items[$key]);
  159. }
  160. }
  161. Event::handle('EndCacheGet', [$key, &$value]);
  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', [&$key, &$value, &$flag, &$expiry, &$success])) {
  179. if ($this->_inlineCache) {
  180. $this->_items[$key] = serialize($value);
  181. }
  182. $success = true;
  183. }
  184. Event::handle('EndCacheSet', [$key, $value, $flag, $expiry]);
  185. return $success;
  186. }
  187. /**
  188. * Atomically increment an existing numeric value.
  189. * Existing expiration time should remain unchanged, if any.
  190. *
  191. * @param string $key The key to use for lookups
  192. * @param int $step Amount to increment (default 1)
  193. *
  194. * @return mixed incremented value, or false if not set.
  195. */
  196. function increment($key, $step=1)
  197. {
  198. $value = false;
  199. common_perf_counter('Cache::increment', $key);
  200. if (Event::handle('StartCacheIncrement', [&$key, &$step, &$value])) {
  201. // Fallback is not guaranteed to be atomic,
  202. // and may original expiry value.
  203. $value = $this->get($key);
  204. if ($value !== false) {
  205. $value += $step;
  206. $ok = $this->set($key, $value);
  207. $got = $this->get($key);
  208. }
  209. }
  210. Event::handle('EndCacheIncrement', [$key, $step, $value]);
  211. return $value;
  212. }
  213. /**
  214. * Delete the value associated with a key
  215. *
  216. * @param string $key Key to delete
  217. *
  218. * @return boolean success flag
  219. */
  220. function delete($key)
  221. {
  222. $success = false;
  223. common_perf_counter('Cache::delete', $key);
  224. if (Event::handle('StartCacheDelete', [&$key, &$success])) {
  225. if ($this->_inlineCache && array_key_exists($key, $this->_items)) {
  226. unset($this->_items[$key]);
  227. }
  228. $success = true;
  229. }
  230. Event::handle('EndCacheDelete', [$key]);
  231. return $success;
  232. }
  233. /**
  234. * Close or reconnect any remote connections, such as to give
  235. * daemon processes a chance to reconnect on a fresh socket.
  236. *
  237. * @return boolean success flag
  238. */
  239. function reconnect()
  240. {
  241. $success = false;
  242. if (Event::handle('StartCacheReconnect', [&$success])) {
  243. $success = true;
  244. }
  245. Event::handle('EndCacheReconnect', []);
  246. return $success;
  247. }
  248. }