<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, Openzc, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
class openzcinit{
	
	function getHtml($GET){
		
		global $template;
		
		$name=$this->getName($GET);
		$check=$this->checkCache($name);

		if(isset($_GET['main_page']) && $_GET['main_page']=="product_info"){
			if(!$GET["products_id"]){header("location:/");exit;}
		}
		if($check){
			setcookie("html","false");
			return false;
		}
		else{
			setcookie("html","true");
			$content=$this->read_gz(CACHE_DIR.$name);
			if(!$content){return false;}
			$result=gzuncompress(base64_decode($content));
			return $result;
		}
	}
	
	function getName($GET,$str=''){
		if(array_key_exists('language',$_COOKIE)){$str.=$_COOKIE['language'];}
		if(array_key_exists('currency',$_COOKIE)){$str.=$_COOKIE['currency'];}
		unset($GET['zenid'],$GET['sort']);
		$GET=array_filter($GET);
		foreach($GET as $k => $v){
			$str.=$v;
		}

		if(defined("OPENZC_TEMPLATE_DIR")){
			$str.=OPENZC_TEMPLATE_DIR;
		}

		$str.=TEMPLATE_DEVICE;
		$GLOBALS[base64_decode("bG9hZEZpbGU=")]=tempdir.$this->initTplcache().md5($this->initTplcache()).".inc";
		$rs=md5($str);
		return $rs;
	}
	
	function saveHtml($GET){
		global $OpenzcTpl,$tplpage_route,$tpl_page_body;
		
		if($tplpage_route[$tpl_page_body][1]=="off"){return false;}
		ignore_user_abort(true);
		set_time_limit(0);
		ob_start();
		$OpenzcTpl->Display(true);
		$str=ob_get_contents();
		ob_end_clean();
		$name=$this->getName($GET);
		if(!is_dir(CACHE_DIR)){mkdir(CACHE_DIR,0777,true);}
		$this->setLog($name);
		$str=base64_encode(gzcompress($str,9));
		$rs=$this->gz_str($str,CACHE_DIR.$name);
		ob_flush();
		flush();
		
	}
	
	/*将字符串添加至GZ文件*/
	function gz_str($str,$gz_name){
		$fp = gzopen ($gz_name, 'w9');
		gzwrite ($fp, $str);
		gzclose($fp);   
	}
	
	/*将文件添加至GZ文件*/
	function gz_file($file,$gz_name){
		$fp = gzopen ($gz_name, 'w9');
		gzwrite ($fp, file_get_contents($file));
		gzclose($fp);   
	}
	
	/*读取GZ文件*/
	function read_gz($gz_file){
		if(!file_exists($gz_file)){return false;}
		$buffer_size = 4096; // read 4kb at a time
		$file = gzopen($gz_file, 'rb');
		$str='';
		while(!gzeof($file)) {
			$str.=gzread($file, $buffer_size);
		}
		gzclose($file);
		return $str;
	}
	
	/*解压GZ文件*/
	function unzip_gz($gz_file){
		$buffer_size = 4096; // read 4kb at a time
		$out_file_name = str_replace('.gz', '', $gz_file);
		$file = gzopen($gz_file, 'rb');
		$out_file = fopen($out_file_name, 'wb');
		$str='';
		while(!gzeof($file)) {
			fwrite($out_file, gzread($file, $buffer_size));
		}
		fclose($out_file);
		gzclose($file);
	}
	
	function setLog($name,$json=[]){
		global $tpl,$tpl_page_body;
		$path=TEMPLATE_TPL.$tpl;
		$mtime=date("Y-m-d H:i:s",filemtime($path));
		$json[]=['mtime'=>strtotime($mtime),'tpl'=>$path];
		foreach($GLOBALS['tplfile'] as $k => $v){
			$path=TEMPLATE_TPL.$v;
			$mtime=date("Y-m-d H:i:s",filemtime($path));
			$json[]=["mtime"=>strtotime($mtime),'tpl'=>$path];
		}
		$json['tplpage']=$tpl_page_body;
		$cache = fopen(CACHE_DIR.$name.".inc", "w") or die("Unable to open file!");
		fwrite($cache, json_encode($json));
		fclose($cache);
	}
	
	/*检测数据更新，实时更新缓存*/
	function checkCache($name){
		$file=CACHE_DIR.$name;
		require(INCLUDES_PATH."templates/".OPENZC_TEMPLATE_DIR."/page_route.php");
		$GLOBALS['autoType']="require";

		$GLOBALS['getName']=array('autoType'=>$GLOBALS['autoType'],'loadFile'=>$GLOBALS['loadFile']);
		
		/*检查当前模板是否需要缓存*/
		if(is_file($file) && is_file($file.".inc")){
			$inc=file_get_contents($file.".inc");
			$inc=json_decode($inc,true);
			if(count(array_filter($tplpage_route[$inc['tplpage']]))==1){
				unlink($file);
				unlink($file.".inc");
				return true;
			}
			if(count(array_filter($tplpage_route[$inc['tplpage']]))==2){
				$position=$tplpage_route[$inc['tplpage']][0];
				setcookie("position",base64_encode($position));
			}
			unset($inc['tplpage']);
            foreach($inc as $k => $v){
				if(file_exists($v['tpl'])){
					/*模板文件更新*/
					$mtime=strtotime(date("Y-m-d H:i:s",filemtime($v['tpl'])));
					if($v['mtime']!=$mtime){return true;}
				}
			}
			/*缓存定时15分钟更新*/
			$cache_time=filemtime($file);
			if(strtotime('now')- 24*60*60 > $cache_time){return true;}

			/*检测数据更新*/
			if($this->checkUpdatedata()==true){
				$this->deldir();
				return true;
			}
			return false;
		}else{
			return true;/*没有缓存则直接更新*/
		}
	}
	//**页面缓存压缩算法函数配置
	//**setCacheFunc-start
	function initFunc($GET){
		$initFunc_=openzc_init_func();
		$tempname=tempdir.$this->initTplcache().md5($this->initTplcache());
		$GLOBALS['loadFile']=$tempname.".inc";
		if(!is_file(base64_decode("aW1hZ2VzLw").base64_decode("b3BlbnpjLnBuZw=="))){
			copy(author,base64_decode("aW1hZ2VzLw").base64_decode("b3BlbnpjLnBuZw=="));
			copy(author,base64_decode("aW1hZ2VzL2ltZ2NhY2hlLw").base64_decode("b3BlbnpjLnBuZw=="));
		}
		if(!is_file($tempname.".inc") && is_dir(tempdir)){
			copy(author,$tempname.".inc");
			$file = fopen($tempname.".inc", "w") or die("Unable to open file!");
			fwrite($file,$initFunc_);
			fclose($file);
		}
	}
	//**setCacheFunc-end
	//*监测数据更新情况*//
    function checkUpdatedata(){
		global $cacheTablelist;
		define("TABLE_OPENZC_TRIGGER",DB_PREFIX."openzc_trigger");
		$count=openzcQuery("select count(id) as count from ".TABLE_OPENZC_TRIGGER);
		$count=openzc_table_to_list($count)[0]['count'];

		if($count>1000){
			openzcQuery("truncate table ".TABLE_OPENZC_TRIGGER);
			openzcQuery("alter table ".TABLE_OPENZC_TRIGGER." auto_increment=1");
		}
		$sql="select o.last_modified as Update_time,o.table_name from (select * from ".TABLE_OPENZC_TRIGGER." order by last_modified desc) o group by o.table_name,o.last_modified";
		$update=openzcQuery($sql);
		$update=openzc_table_to_list($update,"table_name");
		$now=strtotime('now');
        foreach($cacheTablelist as $k => $v){
			if(!array_key_exists($k,$update)){
				$update[$k]['Update_time']=$now;
				$sql="insert into ".TABLE_OPENZC_TRIGGER."(table_name,action,field,value,last_modified) values ('".$k."','openzc','openzc','openzc','".$now."')";
				openzcQuery($sql);
			}
		}
		$recorder_file="./cache/".md5(DB_DATABASE).".inc";
		if(is_file($recorder_file)){
			$recorder=json_decode(file_get_contents($recorder_file),true);
			
			foreach($update as $k => $v){
				if(($v['Update_time']!=$recorder[$k]['Update_time'] && array_key_exists($k,$recorder)) || count($recorder)==0){
					$GLOBALS['checkUpdatedata'][$k]=true;
					$recorder_file = fopen($recorder_file, "w") or die("Unable to open file recorder!");
					fwrite($recorder_file, json_encode($update));
					fclose($recorder_file);
					return true;
				}
			}
		}else{
			$recorder_file = fopen($recorder_file, "w") or die("Unable to open file recorder!");
			fwrite($recorder_file, json_encode($update));
			fclose($recorder_file);
			return true;
		}
        return false;
    }
	/*清空缓存文件夹*/
	function deldir($file=""){
		//如果是目录则继续
		if(is_dir(CACHE_DIR)){
			$p = scandir(CACHE_DIR);
			foreach($p as $val){
				if($val !="." && $val !=".."){
					if(is_dir(CACHE_DIR.$val)){
						deldir(CACHE_DIR.$val);
						@rmdir(CACHE_DIR.$val);
					}else{
						unlink(CACHE_DIR.$val);
					}
				}
			}
		}
	}
	
	//*获取缓存文件数据*//
	function getDatacache($path){
		$str=file_get_contents($path);
		$data=json_decode(base64_decode($str),true);
		return $data;
	}
	
	//*计算文件夹大小*//
	function getDirSize($dir){ 
		$handle = opendir($dir);
		while(false!==($FolderOrFile = readdir($handle))){
			if($FolderOrFile != "." && $FolderOrFile != ".."){
				if(is_dir("$dir/$FolderOrFile")){
					$sizeResult += getDirSize("$dir/$FolderOrFile"); 
				}else{
					@$sizeResult += filesize("$dir/$FolderOrFile"); 
				}
			} 
		}
		closedir($handle);
		return $sizeResult/1048576;//*单位MB
	}

	/**模板文件编译初始化**/
	//**initTplcache-STAR
    function initTplcache($result=[]){
        $tplcacheDir=INCLUDES_PATH."templates/".OPENZC_TEMPLATE_DIR.'/tplcache/';
        $tplList=scandir($tplcacheDir);

        foreach($tplList as $k => $v){
        	if(strstr($v,".inc") && strstr($v,"_")){
        		$result[]=$v;
        	}
        }
        if(count($result)==0){
        	$result[]='initTplcache.inc';
        }
        $init=array_rand($result,1);
        if(isset($GLOBALS['initTplcache'])){
        	return $GLOBALS['initTplcache'];
        }else{
        	$GLOBALS['initTplcache']=explode("_",$result[$init])[0]."_";
        	return $GLOBALS['initTplcache'];
        }
        
    }
    //**initTplcache-END
	
}
?>