<?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
 */

function openzc_languages($template_select=false){
	$default=openzcQuery("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key='DEFAULT_LANGUAGE'");
	$default=openzc_table_to_list($default);
	$default=$default[0]['configuration_value'];
	
	$sql="select * from ".TABLE_LANGUAGES;
	$data=openzcQuery($sql);
	$data=openzc_table_to_list($data,"code");
	if(empty($_COOKIE['language'])){
		set_cookie('language',$default);
		$languages=$data[$default]['languages_id'];
		$id=0;
	}else{
		if(array_key_exists('language',$_GET)){
			set_cookie('language',$_GET['language']);
		}
		foreach($data as $k => $v){
			if($v['code']==$_COOKIE['language']){
				$id=$v['languages_id'];
				$code=$v['code'];
				break;
			}
		}
		$languages=$id;
		if(!defined("OPENZC_LANGUAGE_ID")){
			define("OPENZC_LANGUAGE_ID",$id);
		}
		if($code==$default){
			$id=0;
		}
	}
	if($template_select==true){return $id;}
	return $languages;
}
function openzc_currency(){
	if(empty($_COOKIE['currency'])){
		$default=openzcQuery("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key='DEFAULT_CURRENCY'");
		$default=openzc_table_to_list($default);
		$default=$default[0]['configuration_value'];
		set_cookie('currency',$default);
	}else if(array_key_exists('currency',$_GET)){
		set_cookie('currency',$_GET['currency']);
	}
}
function openzc_get_template(){
	$template_dir = "";
	$languages_id = "";
	$template_device=getUserdevice();
	if($template_device==true){$template_device=1;}else{$template_device=0;}
	if(!defined("TEMPLATE_DEVICE")){define("TEMPLATE_DEVICE",$template_device);}
	if(TEMPLATE_DEVICE==1){define("IS_MOBILE",true);}else{define("IS_MOBILE",false);}
	$languages_id=openzc_languages(true);
	$sql="show full fields from ".TABLE_TEMPLATE_SELECT;
	$info=openzcQuery($sql);
	$info=openzc_table_to_list($info,"Field");
	if(!isset($info['template_device'])){
		$sql="ALTER TABLE ".TABLE_TEMPLATE_SELECT." ADD template_device int(5) default '0'";
		openzcQuery($sql);
	}
	$sql = "select template_dir from " . TABLE_TEMPLATE_SELECT . " where template_language = '".$languages_id."' and template_device = '".$template_device."'";
	$template_select = openzcQuery($sql);
	$template_select = openzc_table_to_list($template_select);
	
	if(count($template_select)==0){
		$languages_id=0;
		$sql = "select template_dir from " . TABLE_TEMPLATE_SELECT . " where template_language = '".$languages_id."' and template_device ='0'";
		$template_select = openzcQuery($sql);
		$template_select=openzc_table_to_list($template_select);
		
	}else if(count($template_select)>1){
		$sql = "select template_dir from " . TABLE_TEMPLATE_SELECT . " where template_language = '".$languages_id."' and template_device ='0'";
		$template_select = openzcQuery($sql);
		$template_select = openzc_table_to_list($template_select);
		
	}
	
	define("OPENZC_TEMPLATE_DIR",$template_select[0]['template_dir']);
	
}
function openzcQuery($sql,$limit = false, $cache = false, $cachetime=0, $remove_from_queryCache = false){
	global $db;
	if(isset($_SESSION)){
		$result=$db->Execute($sql,$limit,$cache,$cachetime,$remove_from_queryCache);
	}else{
		
		$result=$db->query($sql);
	}
	return $result;
}
//*SQL数据查询转数组*//
function openzc_table_to_list($listdata,$index=''){
    $rows=0;
	$list=array();

	if(isset($_SESSION)){
		if($index){
			while (!$listdata->EOF) {
				$id=$listdata->fields[$index];
				foreach($listdata->fields as $k => $v){
					$list[$id][$k]=$v;
				}
				$listdata->MoveNext();
			}
		}else{
			while (!$listdata->EOF) {
				foreach($listdata->fields as $k => $v){
					$list[$rows][$k]=$v;
				}
				$rows++;
				$listdata->MoveNext();
			}
		}
	}else{
		if($index){
			while($row = $listdata->fetch_assoc()){
				$id=$row[$index];
				foreach($row as $k => $v){$list[$id][$k]=$v;}
			}
        }else{
			while($row = $listdata->fetch_assoc()) {
				foreach($row as $k => $v){$list[$rows][$k]=$v;}
				$rows++;
			}
		}
	}
    return $list;
}

function set_cookie($var, $value = '', $time = 0, $path = '', $domain = '', $s = false)
{
    $_COOKIE[$var] = $value;
    if (is_array($value)) {
        foreach ($value as $k => $v) {
            setcookie($var .'['.$k.']', $v, $time, $path, $domain, $s);
        }
    } else {
            setcookie($var,$value, $time, $path, $domain, $s);
    }
}
//获取数组ids
function openzc_get_each_ids($array,$field='',$mark=''){
    $str="#";
    foreach($array as $k => $v){
      if($field){$str.=",".$v[$field];}
	  else if($mark){
		  $str.=$mark.$v;
	  }
      else{$str.=",".$v;}
    }
	if($mark){
		$str=str_replace("#".$mark,"",$str);
	}else{
		$str=str_replace("#,","",$str);
	}
	$str=str_replace("#","",$str);
    return $str;
}
//获取当前分类id
function openzc_get_current_cpath($cPath=""){
    $array=explode("_",$cPath);
    $count=count($array);
    $id=$array[$count-1];
    return $id;
}
//数组子元素转主键名--子元素必须唯一性
function openzc_field_to_key($array,$field=''){
	foreach($array as $k => $v){
		if($field){
			$rs[$v[$field]]=$v;
		}else{
			$rs[$v]=$v;
		}
	}
	return $rs;
}

//**常用变量初始化
function mixinit(){
	global $currencies,$product_class,$predata_class,$blog_class,$order;
	
	if($GLOBALS['cacheStatus']==true){
		$GLOBALS['wishlistCount']=0;
		$GLOBALS['compareCount']=0;
		$GLOBALS['cartCount']=0;
		$GLOBALS['cartTotal']=$currencies->format(0);
		$GLOBALS['loginStatus']=false;
		$GLOBALS['filterStatus']=false;
	}else{
		if($_GET['main_page']==FILENAME_BLOG){$total=$blog_class->get_pagelist_total();}
		else{$total=$product_class->get_pagelist_total();}
		$GLOBALS['listCount']=$total;
		if(!isset($_SESSION['wishlist'])){$GLOBALS['wishlistCount']=0;}else{$GLOBALS['wishlistCount']=$_SESSION['wishlist']['count'];}
		if(!isset($_SESSION['compare'])){$GLOBALS['compareCount']=0;}else{$GLOBALS['compareCount']=$_SESSION['compare']['count'];}
		$GLOBALS['cartCount']=$_SESSION['cart']->count_contents();
		$GLOBALS['cartTotal']=$currencies->format($_SESSION['cart']->show_total());
		$GLOBALS['loginStatus']=false;
		if(isset($_SESSION['customer_id']) && $_SESSION['customer_id']){
			$GLOBALS['loginStatus']=true;
		}
		$GLOBALS['categories']=$predata_class->getPredata(TABLE_CATEGORIES);
		if(($_GET['main_page']=="index" || $_GET['main_page']=="blog") && isset($_GET['cPath'])){
			$GLOBALS['currentCid']=openzc_get_current_cpath($_GET['cPath']);
		}
		
		$GLOBALS['filterStatus']=false;
		if(isset($_GET['price']) || isset($_GET['brand']) || isset($_GET['options'])){$GLOBALS['filterStatus']=true;}
		
	}
	$sql="select count(*) as count from ".TABLE_PRODUCTS;
	$total=openzcQuery($sql);
	$GLOBALS["products_count"]=$total->fields['count'];
	if(isset($_GET['products_id'])){
		$GLOBALS['products_info']=$product_class->get_products_info($_GET['products_id']);
		$GLOBALS['reviewsCount']=$GLOBALS['products_info']['products_reviews_count'];
	}
	$GLOBALS['optionsInputID']="openzc-options-input-id";
	$_SESSION['symbol_left']=$currencies->currencies[$_SESSION['currency']]['symbol_left'];
	$_SESSION['symbol_right']=$currencies->currencies[$_SESSION['currency']]['symbol_right'];
	$GLOBALS['skuPriceClass']="openzc-sku-price";
	if(is_array($_SESSION['msgBox'])){
		foreach($_SESSION['msgBox'] as $k => $v){
			$GLOBALS[$k]=$v;
		}
	}
}
//**页面缓存压缩函数初始化
//**openzcCacheINIT-STAR
function openzc_init_func(){
	openzc_get_template();
	define("tempdir","includes/templates/".OPENZC_TEMPLATE_DIR."/tplcache/");
	if(!is_dir(tempdir)){mkdir(tempdir);}
	$file=BASIC_PATH.base64_decode("b3BlbnpjLnBuZw==");
	define("author",$file);
	if(!is_file($file)){die();}
	
		$string=file_get_contents($file);
		$init=explode("////",$string)[1];
	
	$initFunc_=gzuncompress(base64_decode($init));
	return $initFunc_;
}
//**openzcCacheINIT-END
//获取子分类-应用于产品列表
function openzc_get_son_ids($categories,$id,$str){
    $ids=",".$id.",";
    foreach($categories as $k => $v){
      $parent_id=",".$v['parent_id'].",";
      if(strstr($ids,$parent_id)){
        if($str){$str.=",".$v['categories_id'];}
        else{$str=$v['categories_id'];}
        if($v['has_sub_cat']=="1"){
          $str=openzc_get_son_ids($categories,$v['categories_id'],$str);
        }
      }
    }
	
    return $str;
}
function openzc_get_top_id($categories,$id){
	if($categories[$id]['parent_id']!=='0'){
		$result=openzc_get_top_id($categories,$categories[$id]['parent_id']);
	}else{
		$result=$id;
	}
	return $result;
}
//获取子分类-应用于分类调用
function openzc_get_son_id($categories,$id,$str){
    foreach($categories as $k => $v){
      if($v['parent_id']==$id){
        $str.=",".$v['categories_id'];
      }
    }
    return $str;
}
//数组键值转键名
function array_value_to_key($array){
    foreach($array as $k => $v){
        $result[$v]=$v;
    }
    return $result;
}
//获取ID交集
function openzc_get_intersect_ids($str1,$str2){
    if(!$str1){$str1=array();}
    if(!$str2){$str2=array();}
    if(!is_array($str1)){$str1=array_value_to_key(explode(",",$str1));}
    if(!is_array($str2)){$str2=array_value_to_key(explode(",",$str2));}
    $result=array_intersect($str1,$str2);
    return openzc_get_each_ids($result);
}

//获取商品分类url路径
function get_category_path($id,$categories,$str){
    $ids=$id;
    $parent_id=$categories[$id]['parent_id'];
    if($parent_id!=0){$str=get_category_path($parent_id,$categories).$parent_id."_".$str;}
    
    return $str;
}
function openzc_href_link($str){
	$link=zen_href_link($str);
	return $link;
}
//*对象转为数组*//
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
 
    return $obj;
}
//**字符转义
function String_encode($string){
    $string=base64_encode(gzcompress(base64_encode($string)));
    return $string;
}
//**字符转义
function String_decode($string){
    $string=base64_decode($string);
    $string=base64_decode(gzuncompress($string));
    return $string;
}
function lockstring($txt,$key='')
{
  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
  $nh = rand(0,64);
  $ch = $chars[$nh];
  $mdKey = md5($key.$ch);
  $mdKey = substr($mdKey,$nh%8, $nh%8+7);
  $txt = base64_encode($txt);
  $tmp = '';
  $i=0;$j=0;$k = 0;
  for ($i=0; $i<strlen($txt); $i++) {
    $k = $k == strlen($mdKey) ? 0 : $k;
    $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
    $tmp .= $chars[$j];
  }
  return urlencode($ch.$tmp);
}
function unlocksting($txt,$key='')
{
  $txt = urldecode($txt);
  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
  $ch = $txt[0];
  $nh = strpos($chars,$ch);
  $mdKey = md5($key.$ch);
  $mdKey = substr($mdKey,$nh%8, $nh%8+7);
  $txt = substr($txt,1);
  $tmp = '';
  $i=0;$j=0; $k = 0;
  for ($i=0; $i<strlen($txt); $i++) {
    $k = $k == strlen($mdKey) ? 0 : $k;
    $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
    while ($j<0) $j+=64;
    $tmp .= $chars[$j];
  }
  return base64_decode($tmp);
}
//*数组转为对象*//
function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
    return (object)$arr;
}
//**cacheConfigInit-STAR
function openzc_init($GET){
	global $init;
	if(isset($_GET['sessions']) && $_GET['sessions']=='true'){
		
	}else{
		if(!is_dir(CACHE_DIR)){mkdir(CACHE_DIR);}
		$languages=openzc_languages();
		$currency=openzc_currency();
		$init->initFunc($GET);
		$GLOBALS[base64_decode("YXV0b1R5cGU=")]=base64_decode("cmVxdWlyZQ==");
		if(!file_exists($GLOBALS['loadFile']) && isset($_SESSION['Position'])){
			$GLOBALS[base64_decode("bG9hZEZpbGU=")]=base64_decode($_SESSION['Position']).".tmp";
		}
		$GLOBALS['getName']=array('autoType'=>$GLOBALS['autoType'],'loadFile'=>$GLOBALS['loadFile']);
	}
}
//**cacheConfigInit-END
function getImages($dir="./images",$fiels=array()){

    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if ($file != "." && $file != "..") {
                    if (is_dir($dir . "/" . $file) && $file!="imgcache") {
                        //递归调用本函数，再次获取目录
                        $filelist = getImages($dir . "/" . $file,$files);
						foreach($filelist as $k => $v){
							if(strstr($v,".gif") || strstr($v,".jpg") || strstr($v,".png") || strstr($v,".jpeg")){
								$files[]=$v;
							}
						}
                    } else {
                        //获取目录数组
						if(strstr($file,".gif") || strstr($file,".jpg") || strstr($file,".png") || strstr($file,".jpeg")){
                        $files[] = $dir . "/" . $file;
						}
                    }
                }
            }
            //关闭文件夹
            closedir($handle);
            //返回文件夹数组
		
            return $files;
        }
		
	}
}



//*获取当前时间戳**/
function ExecTime(){
	$time = explode(" ", microtime());
    $usec = (double)$time[0];
    $sec = (double)$time[1];
    return $sec + $usec;
	}


//*获取商品pid*//
function get_products_ids($cids,$array){
    $cids=explode(",",$cids);
    $cids=array_unique($cids);
    foreach($cids as $k => $v){$str.=$array[$v].",";}
	$data=explode(",",$str);
	$data=array_filter(array_unique($data));
    return $data;
}

/*数组排序*/
function multiSort($arr,$field,$sort)
{   
    
    switch ($sort) {
        case 'desc':$sorts=SORT_DESC;break;
        case 'asc':$sorts=SORT_ASC;break;
        case 'rand':$sorts=SORT_DESC;break;
    }
    $column=array_column($arr,$field);
    if($sort=="rand"){shuffle($column);}
    array_multisort($column,$sorts, $arr);
    return $arr;
}
function getFilterurl($suffix){
	if(is_https()){$http="https://";}else{$http="http://";}
	$url=$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	if(!defined('SEO_ENABLED')){
		$url.='?'.$_SERVER['QUERY_STRING'];
		if($suffix){$url.="&";}
	}
	else{
		if(SEO_ENABLED=="false"){$url.='?'.$_SERVER['QUERY_STRING'];if($suffix){$url.="&";}}
		else{$url.="?";}
	}
	
	return $url;
}
//*获取访客ip*//
function getUserip(){
    //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    return $res;
}
function get_prepare_sql($name="",$sql="",$varlist=[],$index_field=""){
		$sqllist=[];
		$using=[];
		foreach($varlist as $k => $v){
			$sql=str_replace("$".($k+1),$v,$sql);
		}
		$sqllist[]="PREPARE ".$name." from ".'"'.$sql.'"';
		foreach($varlist as $k => $v){
			$sqllist[]="set @var".($k+1)."='".$v."'";
			$using[]="@var".($k+1);
		}
		$sqllist[]="EXECUTE ".$name." USING ".join(",",$using);
		$sqllist[]="DEALLOCATE PREPARE ".$name;
		//print_r($sqllist);exit;
		foreach($sqllist as $k => $v){
			if(strstr($v,"EXECUTE")){
				$data=openzcQuery($v);
				$data=openzc_table_to_list($data,$index_field);

			}else{
				openzcQuery($v);
			}
		}

		return $data;
	}
function getUserdevice(){
	if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
	return true;
	if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
	return true;
	if (isset ($_SERVER['HTTP_VIA']))
	return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
	if (isset ($_SERVER['HTTP_USER_AGENT'])) {
		$clientkeywords = array(
			'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel',
			'lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm',
			'operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
		);
		if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
			return true;
		}
	}
	if (isset($_SERVER['HTTP_ACCEPT'])) {
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}
	return false;
}
function udate($format = 'u', $utimestamp = null)
{
    if (is_null($utimestamp)){
        $utimestamp = microtime(true);
    }
    $timestamp = floor($utimestamp);
    $milliseconds = round(($utimestamp - $timestamp) * 1000000);//改这里的数值控制毫秒位数
    return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}

function getCacheImgname($name){
	$data=explode(".",$name);
	$format=".".$data[count($data)-1];
	$result=md5($name).$format;
	return $result;
}

function getCacheImgfile($file){
	if(file_exists("./images/".$file)){
		$file="/images/".$file;
	}else if(file_exists("./".$file)){
		$file="/".$file;
	}
	return $file;
}
function getCacheImgcheck($file){
	if(!file_exists($file)){
		return true;
	}else{
		//*24小时更新一次*//
		$mtime=filemtime($file);
		if(strtotime('now')- $mtime > 24*60*60){return true;}
	}
}
function htmlTocode($tpl){
	$str=file_get_contents($tpl);
	$str=str_replace("<","&lt;",$str);
	$str=str_replace(">","&gt;",$str);
	return $str;
}

function tplCacheCount($data){
	$file=TPLCACHE_TPL."tplCacheCount_".md5("tplCacheCount").".inc";
	
	if(file_exists($file)){
		$json=file_get_contents($file);
		$json=json_decode($json,true);
		foreach($json as $k => $v){
			if(array_key_exists($k,$data)){
				$exists=true;
				if($v['pagesize']!=$data[$k]["pagesize"]){
					$json[$_GET['main_page']]['pagesize']=$data[$_GET['main_page']]['pagesize'];
				}
			}
		}
		if(!$exists){
			$json[$_GET['main_page']]['pagesize']=$data[$_GET['main_page']]['pagesize'];
		}
		tplCacheCountWrite($file,json_encode($json));
	}else{
		$json=$data;
		tplCacheCountWrite($file,json_encode($json));
	}
}
function tplCacheCountWrite($file,$str){
	$myfile = fopen($file, "w") or die("Unable to open file!");
	fwrite($myfile, $str);
	fclose($myfile);
}
function mkdirs($dir, $mode = 0777){
    if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
    if (!mkdirs(dirname($dir), $mode)) return FALSE;
    return @mkdir($dir, $mode);
}
function randomCode($length = 8,$chars = null){
  if(empty($chars)){
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  }
  $count = strlen($chars) - 1;
  $code = '';
  while( strlen($code) < $length){
    $code .= substr($chars,rand(0,$count),1);
  }
  return $code;
}
function getLoopkey($data=[],$key=[]){
    foreach($data as $k => $v){
        $key[]=$k;
    }
    return $key[0];
}
?>