<?php
use think\Db;
use think\Addon;
use think\AjaxPage;
use think\facade\Hook;

function http(){

	 if(api('ishttps')){
         return  "https://";
	 }
	 return  "http://";
}
function updateConfig(){
         if(cache("update")){
			return false; 
		 }	
		 $array=array();
		 $list=Db::name('config')->select(); 
		 foreach($list as $k=>$v){
			  if($v["type"]&&$v["type"]=="picture"){ 
			      $cover_id=$v["value"];
		          $v["value"]=get_cover_path($cover_id);  
		    
		      } 
			   $array[$v["name"]]=$v["value"];
		 }
		 $api =serialize($array);
		 cache("api",$api);	
		 cache("update",true);		 
	     return $api;
}
//统一的短信发送接口
function sendSms($mobile=''){	

   hook('send',["mobile"=>$mobile]);
   		
}	

function initData(){   
		 $array=array();
		 $list=Db::name('config')->select(); 
		 foreach($list as $k=>$v){
			  if($v["type"]&&$v["type"]=="picture"){ 
			      $cover_id=$v["value"];
		          $v["value"]=get_cover_path($cover_id);  
		    
		      } 
			   $array[$v["name"]]=$v["value"];
		 }
		 $api =serialize($array);
		 cache("api",$api);		 
	     return $api;
}


function isConfig(){
	 if(!cache("api")){
		return false;
	 }	
	 return true;
}
 function api($name=''){
	 if(!isConfig()){
		$config=initData();
	 }else{
		$config=cache("api");
	 }		 
	   $info=array();
	   $info=unserialize($config);
	   $info[$name]=isset($info[$name])?$info[$name]:'';
	   if($info&&$info[$name]){
		  return $info[$name]; 
	   }
       return  '';
	
}

function get_cover_real($cover_id, $field = null){
    if(empty($cover_id)){
        return false;
    }
    $picture = Db::name('attachment')->where(array('id'=>$cover_id))->find();
    if($field == 'path'){
        if(!empty($picture['url'])){
            $picture['path'] = $picture['url'];
        }else{
            $picture['path'] =$picture['path'];
        }
    }
    return empty($field) ?$picture :$picture[$field];
}  
function is_checked($id ,$ids){
    $arr=explode(",",$ids);
    if(in_array($id,$arr)){
	  return "checked"; 
    }
}
//$output_array = json_decode($output,true);
function curlPost($url,$data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    curl_close($ch);
    return $tmpInfo;
}
	
function curlGet($url=''){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//禁止调用时就输出获取到的数据
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
function sendMessage($uid){
	$str='注册会员成功! 感谢您的注册, 我们将尽最大的努力为您提供优质快捷的服务,如果您对我们有任何意见，请联系'.api('PHONE');
	$reg_time=config('database.reg_time');
	$map['reg_time']=$reg_time;
	  $info =Db::name('user')->where($map)->find();
	    $data ['uid'] =$uid; 
		$data ['group'] =2;   
		$data ['create_time'] = time ();
		$data ['sid'] = $info['id'];
		$data ['content'] = $str;
		Db::name( 'envelope' )->insert( $data );			
}


function encode($str,$key='by'){	    		
        $str=base64_decode($str);		      
        return sha1(md5($str."|".$key));             
   }
function addScore($uid){
    	$start = strtotime(date('Y-m-d').'00:00:00');
        $end = strtotime(date('Y-m-d').'23:59:59');	
		$map[] = ['create_time',[">",$start],["<",$end] ,"AND"];
		$map[] = ['uid','=' ,$uid];
		$map[] = ['type','=' ,1];
		if(db('score_log')->where($map)->find()){
			return ;
		}
		unset($map);
	      $map['id']=$uid;
	      $user=db('user')->where($map)->find();
		  $num=0;
		  $num=api('add_score');	
		 $total=$user['score']+$num;
		 db('user')->where('id',$uid)->setField("score",$total);
		 $save2["uid"]=$uid;
		$save2["type"]=1;//登录赠送
		$save2["score"]=$num;//充值金额
		$save2["create_time"]=time();
	    $save2["content"]="登录赠送积分";
	    $save2["total"]=$total;//充值后剩余金额
	    db("score_log")->insert($save2);						   		
}
   
/**
 * 获取模型数据
 * @param int $id   传入id
 * @param string $field   输出字段
 * @return string 配置值
 */
function get_types($id,$field){
	      $map['id']=$id;
          $info =db('types')->where($map)->find();
           if($info){
		    return $info[$field];
	      }
          return  '';
}		
function  parseScoreType($id,$field){
	       $map['id']=$id;
          $info =db('score_type')->where($map)->find();
          if($info){
		    return $info[$field];
	      }
          return  '';
}

function ucenter_md5($str, $key = 'ThinkUCenter'){
	return  md5(sha1($str) . $key);
}
/**
 * 商品图片列表
 * @param int $id   传入的商品id
 * @return array
 */
function get_pictures($id){
	$map["id"]=$id;
    $info =Db::name('goods')->where("id='$id'")->find();
    $covers=explode(",",$info['covers']);
	array_push($covers,$info["cover_id"]);
	unset($map);
	$map["goods_id"]=$id;
	$list=Db::name('sku')->where("id='$id'")->select();
	foreach ($list as $k => $v ) {
				 array_push($covers,$v["cover_id"]);
	}
    foreach ($covers as $k => $v ) {
				if($v){
					$array[]=$v;
				};
	}
	return $array;
}
/**
 * 时间戳转换普通时间显示
 * @param int $time   传入的时间戳
 * @return string 
 */
function time_format($time){
	  return $time?date('Y-m-d H:i:s',$time):''; 
}
/**
 * 地址解析函数，链接url带http返回原值，否则使用url函数解析
 * @param string $url   传入字符串
 * @return string
 */
function get_url($url){
	if(strpos($url,"http")!==false){
		return $url;
	}
    else{
	   return url($url);
    }
}
 function addUserLog($title,$uid) {
        $data ['uid'] =$uid;  
		$data ['create_time'] = time ();
		$data ['update_time'] = time ();
		$data ['title'] = $title;
		Db::name ( 'UserLog' )->insert( $data );
}
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}
function get_goods_title($id){
    $info =Db::name('goods')->where("id='$id'")->find();
    return $info['title'];
}
function get_attr_title($id){
          $info =Db::name('Attributes')->where("id='$id'")->find();
          return $info['title'];
}
function getforeach($cate,$name = 'child',$pid = 0){
		$arr = array( );
		foreach ( $cate as $key => $v ) {
		//判断，如果$v['pid'] == $pid的则压入数组Child
		if ($v['pid'] == $pid) {
		//递归执行
		       $v[$name] = getforeach($cate,$name,$v['id']);
		        $arr[] = $v;
		      }
		}
		return $arr;
	}


function get_specs_title($id){
          $info =Db::name('specs')->where("id='$id'")->find();
          return $info?$info['title']:'';
}		
function getOrderCount($num=null){
	if(!is_null($num)){
		$map[]=['status','=',$num];
	}else{
		$map[]=['status','>=',0];
	}
	 $map[]=['uid','=',is_login()]; 	
     $count =db('order')->where($map)->count();
	 if(!$count){
		$count=0; 
	 }
	 
     return $count;
}	
function getAccountCount($num=null){
	if(!is_null($num)){
		$map[]=['type','=',$num];
	}else{
		$map[]=['type','>=',0];
	}
	 $map[]=['uid','=',is_login()]; 	
     $count =db('accountLog')->where($map)->count();
	 if(!$count){
		$count=0; 
	 }
	 
     return $count;
}	
// 应用公共文件
function session_uid(){
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

// 应用公共文件
function is_login(){
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

//分页函数
function getLists($model,$map="",$num="10",$listsort="id desc",$field=""){ 
		 $res["list"]=Db::name($model)->where($map)->field($field)->order($listsort)->
		 paginate($num,false,['query' => request()->param()]);;
		 $res["data"]=Db::name($model)->where($map)->field($field)->order($listsort)->limit($num)->select();
		 $res["page"]= $res["list"]->render();
		 $res["total"]=Db::name($model)->where($map)->field($field)->count();
		 $res["count"]= ceil($res["total"]/$num);
		 return $res;
	}
//查询函数	
function lists($model,$map="",$num="10",$listsort="id desc",$field=""){ 
       
		 $data=Db::name($model)->where($map)->field($field)->order($listsort)->limit($num)->select();
		
		 return $data;
	}
	
function U($url){ 
		  return url($url);
	}	
function site_url(){
	$INSTALL_PATH = str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME']));
    if($INSTALL_PATH==="/"){
          $INSTALL_PATH="";		
    }else{
        $INSTALL_PATH= '/'. trim($INSTALL_PATH,'/');
    }
     return  http().$_SERVER['HTTP_HOST'].$INSTALL_PATH;
}
function root_url(){
	$INSTALL_PATH = str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME']));
    if($INSTALL_PATH==="/"){
          $INSTALL_PATH="";		
    }else{
        $INSTALL_PATH= '/'. trim($INSTALL_PATH,'/');
    }
     return  http().$_SERVER['HTTP_HOST'];
}
function getAjaxLists($model,$map="",$num="10",$listsort="id desc",$field="",$page=""){ 
            $res["list"]=Db::name($model)->where($map)->field($field)->order($listsort)->page($page,$num)->select();
		    $res["data"]=Db::name($model)->where($map)->field($field)->order($listsort)->paginate($num);
		    $res["page"]= $res["data"]->render();
		   // 产生分页信息，AJAX的连接在此处生成
		  return $res;
}

function get_goods($id,$field){
	$map['id']=$id;
	$info=Db::name("goods")->where($map)->field($field)->find();
	if($info){
		return $info[$field];  
      } 
	  return '';
	}
function get_logo($uid){
	$cover_id=get_user($uid,"cover_id");
	if($cover_id){
		
		return get_cover_path($cover_id);
	}
	  return get_cover_path(1);
	}  	
 function get_user($id,$field){
	$map['id']=$id;
	$info=Db::name("user")->where($map)->field($field)->find();
	if($info){
		return $info[$field];  
      } 
	  return '';
	}   
function get_shop($id,$field){
	if($id){
		$map['id']=$id;
	    $info=Db::name("shop")->where($map)->field($field)->find();
         if($info){
		    return $info[$field];
	      }
          return  '';
	} 
	if(!$id){
	  return "商城自营";
	}
}
function get_category($id,$field){
	$map['id']=$id;
	$info=Db::name("category")->where($map)->field($field)->find();
    if($info){
		return $info[$field];  
      } 
	  return '';
	
}
function get_cover_path($id){
    $info = Db::name('attachment')->where(array('id'=>$id))->find();
	$path=$info?$info["path"]:'';
    return $path?site_url().$path:"";
}
function get_cover($cover_id, $field = 'path'){
    if(empty($cover_id)){
        return false;
    }
	$map['id']=$cover_id;
    $picture = Db::name('attachment')->where($map)->find();
    if($picture&&$picture['path']){
            return site_url().$picture['path'];    		
    }
    return '';
}  

function get_cover_id(){
	return ;
}
function get_goods_cover($id){
    $cover_id=get_goods($id,'cover_id');
    return get_cover($cover_id,"path");  
}
function msubstr_sn($str,  $length) {
    $charset="utf-8";$start=0;$suffix=true;
	;if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}
   
function get_username($uid=null){
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        return session('user_auth.username');
    }else{
	   $map['id']=$uid;
	   $info=Db::name("User")->where($map)->find();
       if($info){
		   
		    return $info['username']; 
	   }
	   return ''; 
	}
}


/**
* 字符串截取函数
* @param string $str 传入的字符串
* @param  int $len   截取长度
* @return string     
*/
function substr_cn($str, $len=29) {  
        $str=htmlspecialchars($str);
        $start=0;
        $tmpstr = "";  
        $strlen = $start + $len;  
        for($i = 0; $i < $strlen; $i++){  
            if(ord(substr($str, $i, 1)) > 127){  
                $tmpstr.=substr($str, $i, 3);  
                $i+=2;  
            }else  
                $tmpstr.= substr($str, $i, 1);  
        }  
        return htmlspecialchars($tmpstr)."..";  
 }


	function getParent($id = 0){
	    
	      $data= Db::name("category")->field("id,pid")->select();
		
		$arr = array( ); 
		$temp = array();
		   foreach ( $data as $key => $v ) {
		   //判断，如果$v['pid'] == $pid的则压入数组Child
		       if ($v['id'] == $id&&$v['pid']!=0) {
					//递归执行
					  $temp[] = $v['pid']; 
                      $temp = array_merge($temp,getParent($v['pid'],$data));				
		       }
		   }
	
		return $temp;
	}
	function getChild($id){
	    $data= Db::name("category")->field("id,pid")->select();
		
		$arr = array( ); 
		$temp = array();
		   foreach ( $data as $key => $v ) {
		   //判断，如果$v['pid'] == $pid的则压入数组Child
		       if ($v['pid'] == $id) {
					//递归执行
					  $temp[] = $v['id']; 
                      $temp = array_merge($temp,getChild($v['id'],$data));				
		       }
		   }
	
		return $temp;
    }
	function getChilds($id){
	    $data= Db::name("User")->field("id,pid")->select();
		
		$arr = array( ); 
		$temp = array();
		   foreach ( $data as $key => $v ) {
		   //判断，如果$v['pid'] == $pid的则压入数组Child
		       if ($v['pid'] == $id) {
					//递归执行
					  $temp[] = $v['id']; 
                      $temp = array_merge($temp,getChilds($v['id'],$data));				
		       }
		   }
	
		return $temp;
    }
	function setChild($id){
	    $data= Db::name("cate")->field("id,pid")->select();
		
		$arr = array( ); 
		$temp = array();
		   foreach ( $data as $key => $v ) {
		   //判断，如果$v['pid'] == $pid的则压入数组Child
		       if ($v['pid'] == $id) {
					//递归执行
					  $temp[] = $v['id']; 
                      $temp = array_merge($temp,getChild($v['id'],$data));				
		       }
		   }
	
		return $temp;
    }
	/**
 * 标签库解析广告位标签
 * @param int $place   传入广告的位置
 * @return string
 */
function  parseAd($place){
	$map['place']=$place;
	$list=Db::name("ad")->where($map)->select();
    return $list;  
}
/**
 * 标签库解析推荐位标签
 * @param id $position   传入推荐位
 * @return string
 */	
function  parsePos($pos){
   
	$map['position']=$pos;
	$list=Db::name("document")->where($map)->select();
    return $list;  
}
/**
 * 标签库解析知道分类下位置标签
 * @param id $id   传入分类的id
 * @return string
 */
function  parseCate($id,$order,$limit){
	$Category=new \app\index\model\Category;
	$ids=$Category->getChildId($id);	
    $map[]=['category_id',"in",$ids];
	$list=Db::name("document")->where($map)->order($order)->limit($limit)->select();
    return $list;  
}
/**
 * 标签库解析知道分类下位置标签
 * @param string $ids   传入分类的id
 * @return string
 */
function  parseMix($ids,$order,$limit){
    $map['category_id']=array("in",$ids);
	$list=Db::name("document")->where($map)->order($order)->limit($limit)->select();
    return $list;  
}
/**
 * 标签库解析知道幻灯片位置标签
 * @param string $ids   传入分类的id
 * @return string
 */
function  parseSlide($place,$order,$limit){
    $map['place']=$place;
	$list=Db::name("slide")->where($map)->order($order)->limit($limit)->select();
    return $list;  
}
/**
 * 标签库解析文章位置标签
 * @param string $ids   传入分类的id
 * @return string
 */
function  parseRead($model_id,$order,$limit){
    $map['model_id']=$model_id;
	$list=Db::name("document")->where($map)->order($order)->limit($limit)->select();
    return $list;  
}
/**
 * 标签库解析友情链接标签
 * @param string $ids   传入分类的id
 * @return string
 */
function  parseLink($order,$limit){
   
	$list=Db::name("friendlink")->order($order)->limit($limit)->select();
    return $list;  
}
/**
 * 标签库解析导航位置标签
 * @param string $ids   传入分类的id
 * @return string
 */
function  parseChannel($order,$limit){
   
	$list=Db::name("Channel")->order($order)->limit($limit)->select();
    return $list;  
}
/**
 * 解析指定分类下分类标签
 * @param id $id   传入分类的id
 * @return string
 */
function  parseHot($id){
	$Category=new \app\index\model\Category;
	$ids=$Category->getChildrenId($id);	
	$map['id']=array("in",$ids);
	$list=Db::name("category")->where($map)->limit(9)->select();
	$html="";
	 foreach ($list as $key=>$val) {
		 if($id!=$val['id']){
		 $url=url('Goods/lists?id='.$val['id']);
		 $html .="<span><a href=".$url." title=".$val["title"].">".$val["title"]."</a></span>";//标识号
                 
		   }
		 }
    return $html; 
	
}
function qrcode($url='',$cover_id="",$uid=0){
   


//define('INSTALL_PATH',$INSTALL_PATH);//安装目录
//define('ROOT_PATH',$INSTALL_PATH);//安装目录
	include(ROOT_PATH.'extend/phpqrcode/phpqrcode.php'); 
	
	$value = $url;					//二维码内容
	
	$errorCorrectionLevel = 'L';	//容错级别 
	$matrixPointSize = 5;			//生成图片大小  
	
	//生成二维码图片
	$name=$uid."_".microtime().'.png';
	$filename = ROOT_PATH  .  'public/uploads/'.'QRcode/'.$name;
     QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);  
	
	$logo = 'qrcode/logo.jpg'; 	//准备好的logo图片   
	$QR = $filename; 

	$logo = get_cover_path($cover_id); 	//准备好的logo图片   
				//已经生成的原始二维码图  
     $url= site_url().'/public/uploads/QRcode/'.$name;
	 $QR = $url;
	if (file_exists($logo)) {   
		$QR = imagecreatefromstring(file_get_contents($QR));   		//目标图象连接资源。
		$logo = imagecreatefromstring(file_get_contents($logo));   	//源图象连接资源。
		$QR_width = imagesx($QR);			//二维码图片宽度   
		$QR_height = imagesy($QR);			//二维码图片高度   
		$logo_width = imagesx($logo);		//logo图片宽度   
		$logo_height = imagesy($logo);		//logo图片高度   
		$logo_qr_width = $QR_width / 4;   	//组合之后logo的宽度(占二维码的1/5)
		$scale = $logo_width/$logo_qr_width;   	//logo的宽度缩放比(本身宽度/组合后的宽度)
		$logo_qr_height = $logo_height/$scale;  //组合之后logo的高度
		$from_width = ($QR_width - $logo_qr_width) / 2;   //组合之后logo左上角所在坐标点
		
		//重新组合图片并调整大小
		/*
		 *	imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
		 */
		imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height); 
	} 
	return site_url().'/public/uploads/QRcode/'.$name; 
}
