<?php
/**
 * QQ机器人类
 * 
 * @author anqiu xiao
 * @version 1.0
 * @date	2010.09.27
 */
class qqrobot
{
	//E:/APMServ5.2.6/www/htdocs/ecshop/api/qqrobot
	private $_rootPath = '';
	
	//缓存文件
	private $_cacheFile = 'qqmsg';
	
	public function __construct()
	{
		$this->_rootPath = str_replace('\\', '/', dirname(__FILE__));
	}
	
	/**
	 * 添加一条新的QQ消息到缓存
	 * 
	 * @param string		$qq			接收消息的QQ号码
	 * @param string		$content	消息内容
	 * @return bool
	 */
	public function addMsg($qq, $content)
	{
		if(empty($qq) || empty($content)){
			return ;
		}
		$msgs = $this->read_static_cache();
		if(false === $msgs){
			$msgs = array();
		}
		$msgs[] = array(
						'qq'		=>	$qq,
						'content'	=>	$content,
						);
		$this->write_static_cache($msgs);
	}
	
	/**
	 * 获取所有的待发送消息
	 * 
	 * @return array
	 */
	public function getFirstMsg()
	{
		$msgs = $this->read_static_cache();
		$msg  = array();
		if(false !== $msgs){
			if(empty($msgs)){
				$msg = array();
			}else{
				$msg = array_shift($msgs);
				$this->write_static_cache($msgs);
			}
		}
		return $msg;
	}
	
	/**
	 * 读结果缓存文件
	 *
	 * @return  array
	 */
	public function read_static_cache()
	{
		static $result = array();
		$cache_file_path = $this->_rootPath . '/' . $this->_cacheFile . '.php';
		if (file_exists($cache_file_path))
		{
			include_once($cache_file_path);
			$result = $data;
			return $result;
		}
		else
		{
			return false;
		}
	}

	/**
	 * 写结果缓存文件
	 *
	 * @params  string  $caches
	 *
	 * @return void
	 */
	public function write_static_cache($caches)
	{
		$cache_file_path = $this->_rootPath . '/' . $this->_cacheFile . '.php';
		$content = "<?php\r\n";
		$content .= "\$data = " . var_export($caches, true) . ";\r\n";
		$content .= "?>";
		file_put_contents($cache_file_path, $content, LOCK_EX);
	}
}//END CLASS