<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class Cache_Memcache extends Memcache implements Cache_Interface
{
	public $host_id=null;
	
	protected function __clone()
	{
	}

	public function __construct()
	{
		$this->host_id=config::get('core.host_id');
		$this->_cache_compress = (config::get('core.memcached_compress')) ? MEMCACHE_COMPRESSED : 0;
		$this->connect(config::get('core.memcached_host'), config::get('core.memcached_port'));
	}
	
	public function set($key, $data, $ttl=3600)
	{
		if (!config::get('core.cache')) return;
		if ($ttl==-1) $ttl=0; //в мемкэше 0 соответсвует бессрочному хранению
		if ($ttl) $ttl=time()+$ttl;
		return parent::set($this->_getKey($key), $data, $this->_cache_compress, $ttl);
	}
	
	//добавляет новый ключ, если таковой не существует
	public function add($key, $data, $ttl=3600)
	{
		if (!config::get('core.cache')) return;
		if ($ttl==-1) $ttl=0; //в мемкэше 0 соответсвует бессрочному хранению
		if ($ttl) $ttl=time()+$ttl;
		return parent::add($this->_getKey($key), $data, $this->_cache_compress, $ttl);
	}
	
	public function remove($key)
	{
		$this->delete($this->_getKey($key));
	}
	
	public function clean()
	{
		$this->flush();
	}
	
	public function get($key)
	{
		if (!config::get('core.cache')) return;
		$keys=$this->_getKey($key);
		$result=parent::get($keys);
		if (is_array($key) && $result) {
			foreach ($keys as $id=>$hkey) {
				if (isset($result[$hkey])) {
					$result[$key[$id]]=$result[$hkey];
					unset($result[$hkey]);
				}
			}
		}
		return $result;
	}
	
	protected function _getKey($key)
	{
		if (empty($this->host_id)) return $key;
		else
		{	
			if (!is_array($key)) return $this->host_id.'_'.$key;
			foreach ($key as $k=>$v) {
				$key[$k]=$this->host_id.'_'.$v;
			}
			return $key;
		}
	}
}