/usr/share/php/Horde/Memcache.php is in php-horde-memcache 2.1.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | <?php
/**
* Copyright 2007-2016 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Jan Schneider <jan@horde.org>
* @author Michael Slusarz <slusarz@horde.org>
* @author Didi Rieder <adrieder@sbox.tugraz.at>
* @category Horde
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Memcache
*/
/**
* This class provides an API or Horde code to interact with a centrally
* configured memcache installation.
*
* memcached website: http://www.danga.com/memcached/
*
* @author Jan Schneider <jan@horde.org>
* @author Michael Slusarz <slusarz@horde.org>
* @author Didi Rieder <adrieder@sbox.tugraz.at>
* @category Horde
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Memcache
*/
class Horde_Memcache implements Serializable
{
/**
* The number of bits reserved by PHP's memcache layer for internal flag
* use.
*/
const FLAGS_RESERVED = 16;
/**
* Locking timeout.
*/
const LOCK_TIMEOUT = 30;
/**
* Suffix added to key to create the lock entry.
*/
const LOCK_SUFFIX = '_l';
/**
* The max storage size of the memcache server. This should be slightly
* smaller than the actual value due to overhead. By default, the max
* slab size of memcached (as of 1.1.2) is 1 MB.
*/
const MAX_SIZE = 1000000;
/**
* Serializable version.
*/
const VERSION = 1;
/**
* Locked keys.
*
* @var array
*/
protected $_locks = array();
/**
* Logger instance.
*
* @var Horde_Log_Logger
*/
protected $_logger;
/**
* Memcache object.
*
* @var Memcache
*/
protected $_memcache;
/**
* A list of items known not to exist.
*
* @var array
*/
protected $_noexist = array();
/**
* Memcache defaults.
*
* @var array
*/
protected $_params = array(
'compression' => false,
'hostspec' => array('localhost'),
'large_items' => true,
'persistent' => false,
'port' => array(11211),
'prefix' => 'horde'
);
/**
* The list of active servers.
*
* @var array
*/
protected $_servers = array();
/**
* Constructor.
*
* @param array $params Configuration parameters:
* - compression: (boolean) Compress data inside memcache?
* DEFAULT: false
* - c_threshold: (integer) The minimum value length before attempting
* to compress.
* DEFAULT: none
* - hostspec: (array) The memcached host(s) to connect to.
* DEFAULT: 'localhost'
* - large_items: (boolean) Allow storing large data items (larger than
* Horde_Memcache::MAX_SIZE)? Currently not supported with
* memcached extension.
* DEFAULT: true
* - persistent: (boolean) Use persistent DB connections?
* DEFAULT: false
* - prefix: (string) The prefix to use for the memcache keys.
* DEFAULT: 'horde'
* - port: (array) The port(s) memcache is listening on. Leave empty
* if using UNIX sockets.
* DEFAULT: 11211
* - weight: (array) The weight(s) to use for each memcached host.
* DEFAULT: none (equal weight to all servers)
*
* @throws Horde_Memcache_Exception
*/
public function __construct(array $params = array())
{
$this->_params = array_merge($this->_params, $params);
$this->_init();
}
/**
* Do initialization.
*
* @throws Horde_Memcache_Exception
*/
public function _init()
{
if (class_exists('Memcached')) {
if (empty($this->_params['persistent'])) {
$this->_memcache = new Memcached();
} else {
$this->_memcache = new Memcached('horde_memcache');
}
$this->_params['large_items'] = false;
$this->_memcache->setOptions(array(
Memcached::OPT_COMPRESSION => $this->_params['compression'],
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_HASH => Memcached::HASH_MD5,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
Memcached::OPT_PREFIX_KEY => $this->_params['prefix'],
));
} else {
// Force consistent hashing
ini_set('memcache.hash_strategy', 'consistent');
$this->_memcache = new Memcache();
}
for ($i = 0, $n = count($this->_params['hostspec']); $i < $n; ++$i) {
if ($this->_memcache instanceof Memcached) {
$res = $this->_memcache->addServer(
$this->_params['hostspec'][$i],
empty($this->_params['port'][$i]) ? 0 : $this->_params['port'][$i],
!empty($this->_params['weight'][$i]) ? $this->_params['weight'][$i] : 0
);
} else {
$res = $this->_memcache->addServer(
$this->_params['hostspec'][$i],
empty($this->_params['port'][$i]) ? 0 : $this->_params['port'][$i],
!empty($this->_params['persistent']),
!empty($this->_params['weight'][$i]) ? $this->_params['weight'][$i] : 1,
1,
15,
true,
array($this, 'failover')
);
}
if ($res) {
$this->_servers[] = $this->_params['hostspec'][$i] . (!empty($this->_params['port'][$i]) ? ':' . $this->_params['port'][$i] : '');
}
}
/* Check if any of the connections worked. */
if (empty($this->_servers)) {
throw new Horde_Memcache_Exception('Could not connect to any defined memcache servers.');
}
if ($this->_memcache instanceof Memcache &&
!empty($this->_params['c_threshold'])) {
$this->_memcache->setCompressThreshold($this->_params['c_threshold']);
}
if (isset($this->_params['logger'])) {
$this->_logger = $this->_params['logger'];
$this->_logger->log('Connected to the following memcache servers:' . implode($this->_servers, ', '), 'DEBUG');
}
}
/**
* Shutdown function.
*/
public function shutdown()
{
foreach (array_keys($this->_locks) as $key) {
$this->unlock($key);
}
}
/**
* Delete a key.
*
* @see Memcache::delete()
*
* @param string $key The key.
* @param integer $timeout Expiration time in seconds.
*
* @return boolean True on success.
*/
public function delete($key, $timeout = 0)
{
return isset($this->_noexist[$key])
? false
: $this->_memcache->delete($this->_key($key), $timeout);
}
/**
* Get data associated with a key.
*
* @see Memcache::get()
*
* @param mixed $keys The key or an array of keys.
*
* @return mixed The string/array on success (return type is the type of
* $keys), false on failure.
*/
public function get($keys)
{
$flags = null;
$key_map = $missing_parts = $os = $out_array = array();
$ret_array = true;
if (!is_array($keys)) {
$keys = array($keys);
$ret_array = false;
}
$search_keys = $keys;
foreach ($search_keys as $v) {
$key_map[$v] = $this->_key($v);
}
if ($this->_memcache instanceof Memcached) {
$res = $this->_memcache->getMulti(array_values($key_map));
} else {
$res = $this->_memcache->get(array_values($key_map), $flags);
}
if ($res === false) {
return false;
}
/* Check to see if we have any oversize items we need to get. */
if (!empty($this->_params['large_items'])) {
foreach ($key_map as $key => $val) {
$part_count = isset($flags[$val])
? ($flags[$val] >> self::FLAGS_RESERVED) - 1
: -1;
switch ($part_count) {
case -1:
/* Ignore. */
unset($res[$val]);
break;
case 0:
/* Not an oversize part. */
break;
default:
$os[$key] = $this->_getOSKeyArray($key, $part_count);
foreach ($os[$key] as $val2) {
$missing_parts[] = $key_map[$val2] = $this->_key($val2);
}
break;
}
}
if (!empty($missing_parts)) {
if (($res2 = $this->_memcache->get($missing_parts)) === false) {
return false;
}
/* $res should now contain the same results as if we had
* run a single get request with all keys above. */
$res = array_merge($res, $res2);
}
}
foreach ($key_map as $k => $v) {
if (!isset($res[$v])) {
$this->_noexist[$k] = true;
}
}
foreach ($keys as $k) {
$out_array[$k] = false;
if (isset($res[$key_map[$k]])) {
$data = $res[$key_map[$k]];
if (isset($os[$k])) {
foreach ($os[$k] as $v) {
if (isset($res[$key_map[$v]])) {
$data .= $res[$key_map[$v]];
} else {
$this->delete($k);
continue 2;
}
}
}
$out_array[$k] = @unserialize($data);
} elseif (isset($os[$k]) && !isset($res[$key_map[$k]])) {
$this->delete($k);
}
}
return $ret_array
? $out_array
: reset($out_array);
}
/**
* Set the value of a key.
*
* @see Memcache::set()
*
* @param string $key The key.
* @param string $var The data to store.
* @param integer $timeout Expiration time in seconds.
*
* @return boolean True on success.
*/
public function set($key, $var, $expire = 0)
{
return $this->_set($key, @serialize($var), $expire);
}
/**
* Set the value of a key.
*
* @param string $key The key.
* @param string $var The data to store (serialized).
* @param integer $timeout Expiration time in seconds.
* @param integer $lent String length of $len.
*
* @return boolean True on success.
*/
protected function _set($key, $var, $expire = 0, $len = null)
{
if (is_null($len)) {
$len = strlen($var);
}
if (empty($this->_params['large_items']) && ($len > self::MAX_SIZE)) {
return false;
}
for ($i = 0; ($i * self::MAX_SIZE) < $len; ++$i) {
$curr_key = $i ? ($key . '_s' . $i) : $key;
$res = $this->_memcache instanceof Memcached
? $this->_memcache->set($curr_key, $var, $expire)
: $this->_memcache->set(
$this->_key($curr_key),
substr($var, $i * self::MAX_SIZE, self::MAX_SIZE),
$this->_getFlags($i ? 0 : ceil($len / self::MAX_SIZE)),
$expire
);
if ($res === false) {
$this->delete($key);
break;
}
unset($this->_noexist[$curr_key]);
}
return $res;
}
/**
* Replace the value of a key.
*
* @see Memcache::replace()
*
* @param string $key The key.
* @param string $var The data to store.
* @param integer $timeout Expiration time in seconds.
*
* @return boolean True on success, false if key doesn't exist.
*/
public function replace($key, $var, $expire = 0)
{
$var = @serialize($var);
$len = strlen($var);
if ($len > self::MAX_SIZE) {
if (!empty($this->_params['large_items']) &&
$this->_memcache->get($this->_key($key))) {
return $this->_set($key, $var, $expire, $len);
}
return false;
}
return $this->_memcache instanceof Memcached
? $this->_memcache->replace($key, $var, $expire)
: $this->_memcache->replace(
$this->_key($key), $var, $this->_getFlags(1), $expire
);
}
/**
* Obtain lock on a key.
*
* @param string $key The key to lock.
*/
public function lock($key)
{
$i = 0;
while ($this->_lockAdd($key) === false) {
usleep(min(pow(2, $i++) * 10000, 100000));
}
/* Register a shutdown handler function here to catch cases where PHP
* suffers a fatal error. Must be done via shutdown function, since
* a destructor will not be called in this case.
* Only trigger on error, since we must assume that the code that
* locked will also handle unlocks (which may occur in the destruct
* phase, e.g. session handling).
* @todo: $this is not usable in closures until PHP 5.4+ */
if (empty($this->_locks)) {
$self = $this;
register_shutdown_function(function() use ($self) {
$e = error_get_last();
if ($e['type'] & E_ERROR) {
/* Try to do cleanup at very end of shutdown methods. */
register_shutdown_function(array($self, 'shutdown'));
}
});
}
$this->_locks[$key] = true;
}
/**
* Small wrapper around Memcache[d]#add().
*
* @param string $key The key to lock.
*/
protected function _lockAdd($key)
{
if ($this->_memcache instanceof Memcached) {
$this->_memcache->add(
$this->_key($key . self::LOCK_SUFFIX), 1, self::LOCK_TIMEOUT
);
} else {
$this->_memcache->add(
$this->_key($key . self::LOCK_SUFFIX), 1, 0, self::LOCK_TIMEOUT
);
}
}
/**
* Release lock on a key.
*
* @param string $key The key to lock.
*/
public function unlock($key)
{
$this->_memcache->delete($this->_key($key . self::LOCK_SUFFIX), 0);
unset($this->_locks[$key]);
}
/**
* Mark all entries on a memcache installation as expired.
*/
public function flush()
{
$this->_memcache->flush();
}
/**
* Get the statistics output from the current memcache pool.
*
* @return array The output from Memcache::getExtendedStats() using the
* current configuration values.
*/
public function stats()
{
return $this->_memcache instanceof Memcached
? $this->_memcache->getStats()
: $this->_memcache->getExtendedStats();
}
/**
* Failover method.
*
* @see Memcache::addServer()
*
* @param string $host Hostname.
* @param integer $port Port.
*
* @throws Horde_Memcache_Exception
*/
public function failover($host, $port)
{
$pos = array_search($host . ':' . $port, $this->_servers);
if ($pos !== false) {
unset($this->_servers[$pos]);
if (!count($this->_servers)) {
throw new Horde_Memcache_Exception('Could not connect to any defined memcache servers.');
}
}
}
/**
* Obtains the md5 sum for a key.
*
* @param string $key The key.
*
* @return string The corresponding memcache key.
*/
protected function _key($key)
{
return $this->_memcache instanceof Memcached
? $key
: hash('md5', $this->_params['prefix'] . $key);
}
/**
* Returns the key listing of all key IDs for an oversized item.
*
* @return array The array of key IDs.
*/
protected function _getOSKeyArray($key, $length)
{
$ret = array();
for ($i = 0; $i < $length; ++$i) {
$ret[] = $key . '_s' . ($i + 1);
}
return $ret;
}
/**
* Get flags for memcache call.
*
* @param integer $count
*
* @return integer
*/
protected function _getFlags($count)
{
$flags = empty($this->_params['compression'])
? 0
: MEMCACHE_COMPRESSED;
return ($flags | $count << self::FLAGS_RESERVED);
}
/* Serializable methods. */
/**
* Serialize.
*
* @return string Serialized representation of this object.
*/
public function serialize()
{
return serialize(array(
self::VERSION,
$this->_params
));
}
/**
* Unserialize.
*
* @param string $data Serialized data.
*
* @throws Exception
* @throws Horde_Memcache_Exception
*/
public function unserialize($data)
{
$data = @unserialize($data);
if (!is_array($data) ||
!isset($data[0]) ||
($data[0] != self::VERSION)) {
throw new Exception('Cache version change');
}
$this->_params = $data[1];
$this->_init();
}
}
|