<?php
// +----------------------------------------------------------------------
// | Yershop 开源网店系统
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.yershop.com All rights reserved.
// +----------------------------------------------------------------------
use think\Db;
use think\AjaxPage;

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 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 str($katakana){
    $i_end = 1; //打断位数长度，分清楚英文和中文
    $check_sucess = array();
    for($i_start=0; $i_start < strlen($katakana); $i_start=$i_start+1){       
        $str_cut = substr($katakana,$i_start,$i_end);
        $check_sucess[$i_start] = $str_cut;
        echo '$str_cut='.$str_cut.'<br>';
    }
    return $check_sucess;
}
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 sendSms($mobile=''){	

    $map["mobile"]=safe_replace($mobile);	
	$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
	$length=api('sms_code_length')?api('sms_code_length'):4;
	$mobile_code =random($length,1);//获取验证码		
    $u=api('HUYIUSERNAME');
	$p=api('HUYIPASSWORD');
	$post_data = "account={$u}&password={$p}&mobile=".$mobile."&content=".rawurlencode("您的验证码是：".$mobile_code."。请不要把验证码泄露给其他人。");
	//密码可以使用明文密码或使用32位MD5加密
	$gets = xml_to_array(httpPost($post_data, $target));
	if($gets&&$gets['SubmitResult']['code']==2){		
		$_SESSION['mobile'] = $mobile;
		$_SESSION['mobile_code'] = $mobile_code;
		
		//发送成功加入记录
		 $data["content"]=$mobile_code;//验证码
	     $data["mobile"]=$mobile;//验证码
	     $data["create_time"]=time();//验证码
	     db("sms")->insert($data);	
		 
		$res["msg"]=$gets['SubmitResult']['msg'];
		$res["code"]=1;	
		header('Content-Type:application/json; charset=utf-8');
	    print_r( json_encode($res,JSON_UNESCAPED_UNICODE));
		exit();
	}else{
		$res["msg"]=$gets?$gets['SubmitResult']['msg']:'未连接网络';
		$res["code"]=0;	
		header('Content-Type:application/json; charset=utf-8');
	    print_r( json_encode($res,JSON_UNESCAPED_UNICODE));
		exit();
    }
   		
}	
function httpPost($curlPost,$url){
	    $url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
}
function random($length = 6 , $numeric = 0) {
	
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}
 function xml_to_array($xml){
		$arr=array();
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
   }

  function parseMobile($mobile) {
	  if(!isset($mobile)||$mobile==0){
		 return "";  
	  }else{
         $str = substr($mobile, 0, 3).'****'.substr($mobile, 7);
	     return $str;
	  }
    }
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 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;
	}
//$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 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;
    }
/**
 * 权限判断当前id是否在数组里
 * @param int $id   传入id
 * @param array $ids 传入数组
 * @return bool
 */
function is_checked($id ,$ids){
    $arr=explode(",",$ids);
    if(in_array($id,$arr)){
	  return "checked"; 
    }
}
/**
 * 商品图片列表
 * @param int $id   传入的商品id
 * @return array
 */
function get_pictures($id){
	$map["id"]=$id;
    $info =Db::name('goods')->where($map)->find();
    $covers=explode(",",$info['covers']);
	array_push($covers,$info["cover_id"]);
	unset($map);
	$map["goods_id"]=$id;
	$array=array();
	$list=Db::name('sku')->where($map)->select();
	foreach ($list as $k => $v ) {
				 array_push($covers,$v["cover_id"]);
	}
    foreach ($covers as $k => $v ) {
				if($v){
					$array[]=$v;
				};
	}
	krsort($array);
	return $array?$array:"";
}

 function encode($str,$key='by'){	    		
        $str=base64_decode($str);		      
        return sha1(md5($str."|".$key));             
   }
/**
 * 时间戳转换普通时间显示
 * @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 if(strpos($url,"https")!==false){
		return $url;
	}
    else{
	   return url($url);
    }
}
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 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);						   		
}

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();
       if($info){
			  
			    return $info['title']; 
		  }
          return '';
}
function get_attr_title($id){
          $info =Db::name('Attributes')->where("id='$id'")->find();
		  if($info){
			  
			    return $info['title']; 
		  }
          return '';
}
function get_specs_title($id){
          $info =Db::name('specs')->where("id='$id'")->find();
          if($info){
			    return $info['title']; 
		  }
          return '';
}
/**
 * 获取模型数据
 * @param int $id   传入id
 * @param string $field   输出字段
 * @return string 配置值
 */
function get_types($id,$field){
	      $map['id']=$id;
          $info =Db::name('types')->where($map)->find();
		  if($info){
		    return $info[$field];
	      }
          return  '';
         
}		
function  parseScoreType($id,$field){
	      $map['id']=$id;
          $info =Db::name('score_type')->where($map)->find();
          if($info){
		    return $info[$field];
	      }
          return  '';
}
function get_user($id,$field){
	      $map['id']=$id;
          $info =Db::name('user')->where($map)->find();
          if($info){
		    return $info[$field];
	      }
          return  '';
}	
// 应用公共文件
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 safe_replace($string) {
    if(is_array($string)){ 
	   $string=implode('，',$string);
       $string=htmlspecialchars(str_shuffle($string));
	} else{
	    $string=htmlspecialchars($string);
	}
	$string = str_replace('%20','',$string);
    $string = str_replace('%27','',$string);
    $string = str_replace('%2527','',$string);
    $string = str_replace('*','',$string);
    $string = str_replace('"','&quot;',$string);
    $string = str_replace("'",'',$string);
    $string = str_replace('"','',$string);
    $string = str_replace(';','',$string);
    $string = str_replace('<','&lt;',$string);
    $string = str_replace('>','&gt;',$string);
    $string = str_replace("{",'',$string);
    $string = str_replace('}','',$string);
	return $string;
}
//分页函数
function getLists($model,$map="",$num="10",$listsort="id desc",$field=""){
        $page=input("page")?input("page"):1;	
        if($map){
			$searchArray =serialize($map);
		    cache("searchArray",$searchArray);	
			cache("model",$model);

		}else if(!$map&&cache("model")==$model&&input("page")){
			$searchArray= cache("searchArray");
			$map=unserialize($searchArray);
			cache("page",input("page"));
		}else{
			$map=""; 
			cache("searchArray",'');	
			cache("page",'');cache("model",'');
		}     		
		 $res["list"]=Db::name($model)->where($map)->field($field)->order($listsort)->paginate($num);
		 $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){
    $goods=Db::name("goods");
	$map['id']=$id;
	$info=$goods->where($map)->field($field)->find();
	if($info){
	  return $info[$field];	
	}
   return '';   
}
function get_category($id,$field){
    $goods=Db::name("category");
	$map['id']=$id;
	$info=$goods->where($map)->field($field)->find();
     if($info){
			    return $info[$field]; 
		  }
          return '';
	

}
function get_cover_path($id){
	if(!$id){
	   $id=1;	
	}
	$map['id']=$id;
    $info = Db::name('attachment')->where($map)->find();
	if($info){
	  $path=$info["path"];
       return site_url().$path;
	}
	return '';
}
function get_path($id){
     $cover_id= get_goods($id,"cover_id");
     return get_cover($cover_id,'path');//商品图片
}
function get_cover($cover_id, $field ='path'){
    if(empty($cover_id)){
        return false;
    }
	$map['id']=$cover_id;
    $info = Db::name('attachment')->where($map)->find();
   
	if($info){
		  return  site_url().$info[$field];
	}
    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 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 get_username($id=null){
    if(!($id && is_numeric($id))){ //获取当前登录用户名
        return session('user_auth.username');
    }else{
	   $map['id']=$id;
	   $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 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){
    $map['status']=1;
	$list=Db::name("Channel")->order($order)->where($map)->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',"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; 
	
}
/**
 * excel导出
 * @param string $expTitle 导出保存的文件名称
 * @param array  $expCellName 单元格格式
 * @param object $expTableData 查询的数据
 */
function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName ="yershop".date('YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        //vendor("PHPExcel.PHPMailerAutoload");
		include(ROOT_PATH.'extend/PHPExcel.php');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
        } 
          // Miscellaneous glyphs, UTF-8   
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
          }             
        }  
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
        $objWriter->save('php://output'); 
        exit;   
    }
function getQrcode($url='',$goods_id=0,$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."_".$goods_id.'.png';
	$filename = ROOT_PATH  .  'public/uploads/'.'QRcode/'.$name;
     QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);  
	
	$logo = 'qrcode/logo.jpg'; 	//准备好的logo图片   
	$QR = $filename; 
    $cover_id=get_goods($goods_id,'cover_id');
	$logo = get_cover_path($cover_id); 	//准备好的logo图片 

$path=ROOT_PATH.$logo;	
$logo=str_replace('//','/',$path);

	//已经生成的原始二维码图  
     $url= ROOT_PATH.'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; 
}	
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; 
}