1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since CakePHP(tm) v 2.5.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15:
16: /**
17: * Memcached storage engine for cache. Memcached has some limitations in the amount of
18: * control you have over expire times far in the future. See MemcachedEngine::write() for
19: * more information.
20: *
21: * Main advantage of this Memcached engine over the memcached engine is
22: * support of binary protocol, and igbibnary serialization
23: * (if memcached extension compiled with --enable-igbinary)
24: * Compressed keys can also be incremented/decremented
25: *
26: * This cache engine requires at least ext/memcached version 2.0
27: *
28: * @package Cake.Cache.Engine
29: */
30: class MemcachedEngine extends CacheEngine {
31:
32: /**
33: * memcached wrapper.
34: *
35: * @var Memcache
36: */
37: protected $_Memcached = null;
38:
39: /**
40: * Settings
41: *
42: * - servers = string or array of memcached servers, default => 127.0.0.1. If an
43: * array MemcacheEngine will use them as a pool.
44: * - compress = boolean, default => false
45: * - persistent = string The name of the persistent connection. All configurations using
46: * the same persistent value will share a single underlying connection.
47: * - serialize = string, default => php. The serializer engine used to serialize data.
48: * Available engines are php, igbinary and json. Beside php, the memcached extension
49: * must be compiled with the appropriate serializer support.
50: * - options - Additional options for the memcached client. Should be an array of option => value.
51: * Use the Memcached::OPT_* constants as keys.
52: *
53: * @var array
54: */
55: public $settings = array();
56:
57: /**
58: * List of available serializer engines
59: *
60: * Memcached must be compiled with json and igbinary support to use these engines
61: *
62: * @var array
63: */
64: protected $_serializers = array(
65: 'igbinary' => Memcached::SERIALIZER_IGBINARY,
66: 'json' => Memcached::SERIALIZER_JSON,
67: 'php' => Memcached::SERIALIZER_PHP
68: );
69:
70: /**
71: * Initialize the Cache Engine
72: *
73: * Called automatically by the cache frontend
74: * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
75: *
76: * @param array $settings array of setting for the engine
77: * @return bool True if the engine has been successfully initialized, false if not
78: * @throws CacheException when you try use authentication without Memcached compiled with SASL support
79: */
80: public function init($settings = array()) {
81: if (!class_exists('Memcached')) {
82: return false;
83: }
84: if (!isset($settings['prefix'])) {
85: $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
86: }
87:
88: if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) {
89: $this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK;
90: }
91:
92: $settings += array(
93: 'engine' => 'Memcached',
94: 'servers' => array('127.0.0.1'),
95: 'compress' => false,
96: 'persistent' => false,
97: 'login' => null,
98: 'password' => null,
99: 'serialize' => 'php',
100: 'options' => array()
101: );
102: parent::init($settings);
103:
104: if (!is_array($this->settings['servers'])) {
105: $this->settings['servers'] = array($this->settings['servers']);
106: }
107:
108: if (isset($this->_Memcached)) {
109: return true;
110: }
111:
112: if (!$this->settings['persistent']) {
113: $this->_Memcached = new Memcached();
114: } else {
115: $this->_Memcached = new Memcached((string)$this->settings['persistent']);
116: }
117: $this->_setOptions();
118:
119: if (count($this->_Memcached->getServerList())) {
120: return true;
121: }
122:
123: $servers = array();
124: foreach ($this->settings['servers'] as $server) {
125: $servers[] = $this->_parseServerString($server);
126: }
127:
128: if (!$this->_Memcached->addServers($servers)) {
129: return false;
130: }
131:
132: if ($this->settings['login'] !== null && $this->settings['password'] !== null) {
133: if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
134: throw new CacheException(
135: __d('cake_dev', 'Memcached extension is not build with SASL support')
136: );
137: }
138: $this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
139: $this->_Memcached->setSaslAuthData($this->settings['login'], $this->settings['password']);
140: }
141: if (is_array($this->settings['options'])) {
142: foreach ($this->settings['options'] as $opt => $value) {
143: $this->_Memcached->setOption($opt, $value);
144: }
145: }
146:
147: return true;
148: }
149:
150: /**
151: * Settings the memcached instance
152: *
153: * @throws CacheException when the Memcached extension is not built with the desired serializer engine
154: * @return void
155: */
156: protected function _setOptions() {
157: $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
158:
159: $serializer = strtolower($this->settings['serialize']);
160: if (!isset($this->_serializers[$serializer])) {
161: throw new CacheException(
162: __d('cake_dev', '%s is not a valid serializer engine for Memcached', $serializer)
163: );
164: }
165:
166: if ($serializer !== 'php' && !constant('Memcached::HAVE_' . strtoupper($serializer))) {
167: throw new CacheException(
168: __d('cake_dev', 'Memcached extension is not compiled with %s support', $serializer)
169: );
170: }
171:
172: $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]);
173:
174: // Check for Amazon ElastiCache instance
175: if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) {
176: $this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
177: }
178:
179: $this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->settings['compress']);
180: }
181:
182: /**
183: * Parses the server address into the host/port. Handles both IPv6 and IPv4
184: * addresses and Unix sockets
185: *
186: * @param string $server The server address string.
187: * @return array Array containing host, port
188: */
189: protected function _parseServerString($server) {
190: $socketTransport = 'unix://';
191: if (strpos($server, $socketTransport) === 0) {
192: return array(substr($server, strlen($socketTransport)), 0);
193: }
194: if (substr($server, 0, 1) === '[') {
195: $position = strpos($server, ']:');
196: if ($position !== false) {
197: $position++;
198: }
199: } else {
200: $position = strpos($server, ':');
201: }
202: $port = 11211;
203: $host = $server;
204: if ($position !== false) {
205: $host = substr($server, 0, $position);
206: $port = substr($server, $position + 1);
207: }
208: return array($host, (int)$port);
209: }
210:
211: /**
212: * Write data for key into cache. When using memcached as your cache engine
213: * remember that the Memcached PECL extension does not support cache expiry times greater
214: * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
215: *
216: * @param string $key Identifier for the data
217: * @param mixed $value Data to be cached
218: * @param int $duration How long to cache the data, in seconds
219: * @return bool True if the data was successfully cached, false on failure
220: * @see http://php.net/manual/en/memcache.set.php
221: */
222: public function write($key, $value, $duration) {
223: if ($duration > 30 * DAY) {
224: $duration = 0;
225: }
226:
227: return $this->_Memcached->set($key, $value, $duration);
228: }
229:
230: /**
231: * Read a key from the cache
232: *
233: * @param string $key Identifier for the data
234: * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
235: */
236: public function read($key) {
237: return $this->_Memcached->get($key);
238: }
239:
240: /**
241: * Increments the value of an integer cached key
242: *
243: * @param string $key Identifier for the data
244: * @param int $offset How much to increment
245: * @return New incremented value, false otherwise
246: * @throws CacheException when you try to increment with compress = true
247: */
248: public function increment($key, $offset = 1) {
249: return $this->_Memcached->increment($key, $offset);
250: }
251:
252: /**
253: * Decrements the value of an integer cached key
254: *
255: * @param string $key Identifier for the data
256: * @param int $offset How much to subtract
257: * @return New decremented value, false otherwise
258: * @throws CacheException when you try to decrement with compress = true
259: */
260: public function decrement($key, $offset = 1) {
261: return $this->_Memcached->decrement($key, $offset);
262: }
263:
264: /**
265: * Delete a key from the cache
266: *
267: * @param string $key Identifier for the data
268: * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
269: */
270: public function delete($key) {
271: return $this->_Memcached->delete($key);
272: }
273:
274: /**
275: * Delete all keys from the cache
276: *
277: * @param bool $check If true no deletes will occur and instead CakePHP will rely
278: * on key TTL values.
279: * @return bool True if the cache was successfully cleared, false otherwise. Will
280: * also return false if you are using a binary protocol.
281: */
282: public function clear($check) {
283: if ($check) {
284: return true;
285: }
286:
287: $keys = $this->_Memcached->getAllKeys();
288: if ($keys === false) {
289: return false;
290: }
291:
292: foreach ($keys as $key) {
293: if (strpos($key, $this->settings['prefix']) === 0) {
294: $this->_Memcached->delete($key);
295: }
296: }
297:
298: return true;
299: }
300:
301: /**
302: * Returns the `group value` for each of the configured groups
303: * If the group initial value was not found, then it initializes
304: * the group accordingly.
305: *
306: * @return array
307: */
308: public function groups() {
309: if (empty($this->_compiledGroupNames)) {
310: foreach ($this->settings['groups'] as $group) {
311: $this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
312: }
313: }
314:
315: $groups = $this->_Memcached->getMulti($this->_compiledGroupNames);
316: if (count($groups) !== count($this->settings['groups'])) {
317: foreach ($this->_compiledGroupNames as $group) {
318: if (!isset($groups[$group])) {
319: $this->_Memcached->set($group, 1, 0);
320: $groups[$group] = 1;
321: }
322: }
323: ksort($groups);
324: }
325:
326: $result = array();
327: $groups = array_values($groups);
328: foreach ($this->settings['groups'] as $i => $group) {
329: $result[] = $group . $groups[$i];
330: }
331:
332: return $result;
333: }
334:
335: /**
336: * Increments the group value to simulate deletion of all keys under a group
337: * old values will remain in storage until they expire.
338: *
339: * @param string $group The group to clear.
340: * @return bool success
341: */
342: public function clearGroup($group) {
343: return (bool)$this->_Memcached->increment($this->settings['prefix'] . $group);
344: }
345:
346: /**
347: * Write data for key into cache if it doesn't exist already. When using memcached as your cache engine
348: * remember that the Memcached pecl extension does not support cache expiry times greater
349: * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
350: * If it already exists, it fails and returns false.
351: *
352: * @param string $key Identifier for the data.
353: * @param mixed $value Data to be cached.
354: * @param int $duration How long to cache the data, in seconds.
355: * @return bool True if the data was successfully cached, false on failure.
356: * @link http://php.net/manual/en/memcached.add.php
357: */
358: public function add($key, $value, $duration) {
359: if ($duration > 30 * DAY) {
360: $duration = 0;
361: }
362:
363: return $this->_Memcached->add($key, $value, $duration);
364: }
365: }
366: