<?php
use app\admin\model\Attachment;
use app\admin\model\AccessToken;
// 应用公共文件
function fetchJson($data=[],$msg='获取成功',$code=0){
    return Json([
        'code'=>$code,
        'data'=>$data,
        'msg'=>$msg
    ]);
}
function p($arr=[]){
    print_r("<pre>");
    print_r($arr);
}
function get_file_url($id=null){
    $file=Attachment::where(['id'=>$id])->find();
    $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
    if($file){
        if($file->driver=='local'){
            return $root_url.$file->path;
        }else{
            return $file->url;
        }
        
    }else{
        return 0;
    }
}
function filter_money($money,$accuracy=2)
{
    $str_ret = 0;
    if (empty($money) === false) {
        $str_ret = sprintf("%.".$accuracy."f", substr(sprintf("%.".($accuracy+1)."f", floatval($money)), 0, -1));
    }

    return floatval($str_ret);
}
function timetodate($c){
    if($c < 86400){
       $time = explode(' ',gmstrftime('%H %M %S',$c));
       $duration="";
       if($time[0]>0){
          $duration .=$time[0].'小时';
       }
       $duration .=$time[1].'分'.$time[2].'秒';
    }else{
        $time = explode(' ',gmstrftime('%j %H %M %S',$c));
        $duration = ($time[0]-1).'天'.$time[1].'小时'.$time[2].'分'.$time[3].'秒';
    }
    return $duration;
}
function generateQrCode($txt='123',$filename="1",$dir='phpqrcode',$prefix = null){
        /* 若目录不存在则创建之 */
    $path = app()->getRootPath().'public/'.$dir;

    if (!is_dir($path)) {
        mkdir(iconv("UTF-8", "GBK", $path),0777,true);
    }
    require app()->getRootPath().'extend/phpqrcode/phpqrcode.php';

    $QRcode = new \QRcode ();
    /* 二维码内容 */
    /* 纠错级别：L、M、Q、H */
    $level = 'L';
    /* // 点的大小：1到10,用于手机端4就可以了 */
    $size = 4;
    /* // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false */
    $QR_path = $path . '/' . $filename . ".png";
    /* // QRcode::png($text,$filename,$level,$size,$padding,$saveandprint); */
    $QRcode->png($txt, $QR_path, 'L', '4', '2', true);
    $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
    return $root_url=request()->domain().str_replace('index.php', '',request()->baseFile()).$dir. '/' . $filename . ".png?time=".time();
}
function str_replace_match($str=''){
    $preg= "/\d/is";
    //过滤
    preg_match_all("/\D/is",$str,$arr);
    $temp=implode('',$arr[0]);
    return $temp;
}
function get_file_urls($ids=null){
    $ids=explode(',',$ids);
    $file_list=[];
    foreach($ids as $id){
        $file_list[]=Attachment::where('id',$id)->field('path,driver,url')->find();
    }
    $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
    $file_arr=[];
    foreach($file_list as &$value){
        if($value['driver']=='local'){
            $file_arr[]=$root_url.$value['path'];
        }else{
            $file_arr[]=$value['url'];
        }
    }
    if($file_arr){ 
        return $file_arr;
    }else{
        return [];
    }
}
function create_access_token($type=1){
    $access_token=strtoupper(sha1(time().rand(1000,9999)));
    while(AccessToken::where(['access_token'=>$access_token])->count()){
        create_access_token($type);
    }
    $form=new AccessToken();
    $form->access_token=$access_token;
    $form->type=$type;
    $form->ip=request()->ip();
    $form->save();
    return $form->access_token;
}
function get_access_token_type($access_token=''){
    $type=AccessToken::where(['access_token'=>$access_token])->value('type');
    return empty($type)?-1:$type;
}
function QyVersions($version1='',$version2=''){
    $version1=explode('.',$version1);
    $version2=explode('.',$version2);
    $version1Num=count($version1);
    $version1number=0;
    foreach ($version1 as $vk1=>$var1){
        if(!is_numeric($var1))return -1;
        $power=$version1Num-$vk1-1;
        $version1number+=pow(10,$power)*$var1*1;
    }
    $version2Num=count($version2);
    $version2number=0;
    foreach ($version2 as $vk2=>$var2){
        if(!is_numeric($var2))return -1;
        $power=$version2Num-$vk2-1;
        $version2number+=pow(10,$power)*$var2;
    }
    if($version1number<$version2number){
        return 1;
    }
    if($version1number==$version2number){
        return 2;
    }
    if($version1number>$version2number){
        return 3;
    }
    return 0;
}
function QyVersionsInc($version=''){
    $version=explode('.',$version);
    $versionNum=count($version);
    $versionnumber=0;
    foreach ($version as $vk=>&$var){
        if(!is_numeric($var))return -1;
        $power=$versionNum-$vk-1;
        if($power<=0){
            $version[$vk]+=1;
        }
    }
    return implode('.',$version);
}
function QyVersionsNum($version=''){
    $version=explode('.',$version);
    $versionNum=count($version);
    $versionnumber=0;
    foreach ($version as $vk=>&$var){
        if(!is_numeric($var))return 0;
        $power=$versionNum-$vk-1;
        $versionnumber+=pow(10,$power)*$var;
    }
    return $versionnumber;
}
//版本号排序
function sortVersion($versions, $sort_rule = true){
    foreach ($versions as $key => $value) {
        $firstArr = explode('.', $value);
        $firstArrCount = count($firstArr);
        for ($i = 0; $i < $firstArrCount; $i++) {
            $firstArr[$i] = str_pad($firstArr[$i], 2, 0, STR_PAD_LEFT);
        }
        $versions[$key] = implode('.', $firstArr);
    }
    if ($sort_rule) {
        sort($versions);
    } else {
        rsort($versions);
    }

    foreach ($versions as $key => $value) {
        $firstArr = explode('.', $value);
        $firstArrCount = count($firstArr);
        for ($i = 0; $i < $firstArrCount; $i++) {
            $firstArr[$i] = intval($firstArr[$i]);
        }
        $versions[$key] = implode('.', $firstArr);
    }
    return $versions;
}
//引用算法
function generateTree($array=[],$pid='pid',$children='children'){
    //第一步 构造数据
    $items = array();
    foreach($array as $value){
        $items[$value['id']] = $value;
    }
    //第二部 遍历数据 生成树状结构
    $tree = array();
    foreach($items as $key => $value){
        if(isset($items[$value[$pid]])){
            $items[$value[$pid]][$children][] = &$items[$key];
        }else{
            $tree[] = &$items[$key];
        }
    }
    return $tree;
}
function filterEmoji($str)
{
  $str = preg_replace_callback(
    '/./u',
    function (array $match) {
      return strlen($match[0]) >= 4 ? '' : $match[0];
    },
    $str);

  return $str;
}
//对emoji表情转反义
function emoji_decode($str){
    $str = preg_replace_callback(
    '/./u',
    function (array $match) {
      return strlen($match[0]) >= 4 ? '' : $match[0];
    },
    $str);

  return $str;
}


//获取七天日期
//day
function getServenDay($getday="",$com=true,$servenDay=7)
{
     if($getday=='hotel'){
        $getday='';
    }  
    empty($getday) ? $time=time() : $time=strtotime($getday);

    $weekarray=array("日","一","二","三","四","五","六");
    $day=[];
    if($com){ //未来7天            
        for($i=0;$i<$servenDay;$i++){
            $t = $time+24*60*60*$i;
            $d=date('d',$t).'/'.$weekarray[date("w",$t)];            
            $day[]=array('time'=>date('Y-m-d',$t),'date'=>$d,'timenum'=>$t);
        }
        return $day;
    }else{ //过去7天
        for($i=$servenDay;$i>0;$i--){
            $t = $time-24*60*60*$i;
            $d=date('d',$t).'/'.$weekarray[date("w",$t)];            
            $day[]=array('time'=>date('Y-m-d',$t),'date'=>$d,'timenum'=>$t);
        }
        return $day;
    }
}

//获取上下二天
function getDay($attr)
{
    $dayinfo=[];
    $day=empty($attr['day']) ? null : $attr['day'];    
    switch ($day) {
        case 'oldserven':
             $time=empty($attr['time']) ? null : $attr['time']; 
             $dayinfo=getServenDay($time,false);             
            break;
        case 'goserven':
            $time=empty($attr['time']) ? null : date('Y-m-d',strtotime($attr['time'])+24*60*60); 
            $dayinfo=getServenDay($time);
            break;
        default:
            $dayinfo=getServenDay($day);      
            break;
    }    

    return $dayinfo;
}
//去重
function assoc_unique($arr, $key) {
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
    if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
        unset($arr[$k]);
    } else {
        $tmp_arr[] = $v[$key];
    }
}
    sort($arr); //sort函数对数组进行排序
    return $arr;
}
/**

 * CURL请求

 * @param $url 请求url地址

 * @param $method 请求方法 get post

 * @param null $postfields post数据数组

 * @param array $headers 请求header信息

 * @param bool|false $debug 调试开启 默认false

 * @return mixed

 */

function httpRequest($url, $method = "GET", $postfields = null, $headers = array(), $debug = false)

{

    $method = strtoupper($method);

    $ci = curl_init();

    /* Curl settings */

    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);//版本

    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");//在HTTP请求中包含一个"User-Agent: "头的字符串。

    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 120); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */

    curl_setopt($ci, CURLOPT_TIMEOUT, 120); /* 设置cURL允许执行的最长秒数 */

    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);//将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。

    switch ($method) {

        case "POST":

            curl_setopt($ci, CURLOPT_POST, true);//启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。

            if (!empty($postfields)) {

                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;

                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);

            }

            break;

        default:

            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */

            break;

    }

    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;

    curl_setopt($ci, CURLOPT_URL, $url);//需要获取的URL地址，也可以在curl_init()函数中设置

    if ($ssl) {

        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts

        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在

    }

    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/

    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);

    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/

    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($ci, CURLINFO_HEADER_OUT, true);

    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */

    $response = curl_exec($ci);

    $requestinfo = curl_getinfo($ci);

    curl_close($ci);

    return $response;

}
/**
 * 方图转圆形
 * @param string $original_path 图片地址
 * @param string $destFolder 保存的图片路径
 * @return string
 */
function roundImg($original_path = '', $destFolder = './')
{
    //获取参数
    $types = array(1 => "gif", 2 => "jpeg", 3 => "png");//图片类型
    list($width1, $height1, $type1) = getimagesize($original_path);

    $createBgImg1 = "imagecreatefrom" . $types[$type1];
    $viceImage = $createBgImg1($original_path);//1:读取文件对象
    
    $w = imagesx($viceImage);//读取副图文件的宽高
    $h = imagesy($viceImage);

    if (!file_exists($destFolder)) {
        mkdir($destFolder, 0777, true);
    }

    $dest_path = $destFolder;
    $src = imagecreatefromstring(file_get_contents($original_path));
    $newpic = imagecreatetruecolor($w, $h);
    imagealphablending($newpic, false);
    $transparent = imagecolorallocatealpha($newpic, 255, 255, 255, 127);
    $r = $w / 2;
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $c = imagecolorat($src, $x, $y);
            $_x = $x - $w / 2;
            $_y = $y - $h / 2;
            if ((($_x * $_x) + ($_y * $_y)) < ($r * $r)) {
                imagesetpixel($newpic, $x, $y, $c);
            } else {
                imagesetpixel($newpic, $x, $y, $transparent);
            }
        }
    }

    imagesavealpha($newpic, true);
    imagepng($newpic, $dest_path);
    imagedestroy($newpic);
    imagedestroy($src);
    imagedestroy($viceImage);
    return $dest_path;
}

/**
 * 将图片四直角处理成圆角
 *
 * @param $src_img 目标图片
 * @param $width 宽
 * @param $height 高
 * @param int $radius 圆角半径
 * @return resource
 */
function radiusImg($src_img, $width,$height, $radius = 17) {
    $w  = &$width;
    $h  = &$height;
    $img = imagecreatetruecolor($w, $h);//创建底图
    //这一句一定要有
    imagesavealpha($img, true);//设置是否保存透明图像资源
    
    //拾取一个完全透明的颜色,最后一个参数127为全透明
    $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
    imagefill($img, 0, 0, $bg);
    
    $r = $radius; //圆角半径
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgbColor = imagecolorat($src_img, $x, $y);
            if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                //不在四角的范围内,直接画
                imagesetpixel($img, $x, $y, $rgbColor);
            } else {
                //在四角的范围内选择画
                //上左
                $y_x = $r; //圆心X坐标
                $y_y = $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
                //上右
                $y_x = $w - $r; //圆心X坐标
                $y_y = $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
                //下左
                $y_x = $r; //圆心X坐标
                $y_y = $h - $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
                //下右
                $y_x = $w - $r; //圆心X坐标
                $y_y = $h - $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
    }
    
    return $img;
}
function fromXml($xml) {   
    if(!$xml) {
      return false;
    }
    //将XML转为array
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);        
}
/*
  加密函数
 */
function qy_encode($text="",$key="qy"){
    $key_b=md5(time());
    $rand_key=$key_b.$key;
    $rand_key=md5($rand_key);
    $textlen=strlen($text);
    $reslutstr="";
    for($i=0;$i<$textlen;$i++){
        $reslutstr.=$text{$i}^$rand_key{$i%32};
    }
    $reslutstr=trim($key_b.base64_encode($reslutstr),"==");
    $reslutstr=substr(md5($reslutstr), 0,8).$reslutstr;
    return $reslutstr;
}
/*
  解密函数
 */
function qy_decode($text="",$key="qy"){
    if(strlen($text)<14)return false;
    $verity_str=substr($text, 0,8);
    $text=substr($text, 8);
    if($verity_str!=substr(md5($text),0,8)){
        //完整性验证失败
        return false;
    }   
    $key_b=substr($text,0,32);
    $rand_key=$key_b.$key;
    $rand_key=md5($rand_key);
    $text=base64_decode(substr($text, 32));
    $textlen=strlen($text);
    $reslutstr="";
    for($i=0;$i<$textlen;$i++){
        $reslutstr.=$text{$i}^$rand_key{$i%32};
    }
    return $reslutstr;
}
function create_code($len=8){
    if($len<=0){
        return '';
    }
    $str='A,B,C,D,E,F,G,H,I,J,K,L,N,M,O,P,Q,R,S,T,U,V,W,X,Y,Z,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,1,2,3,4,5,6,7,8,9,0';
    $string_array=explode(',', $str);
    $arr=array_rand($string_array,$len);
    foreach ($arr as &$value){
        $value=$string_array[$value];
    }
    return implode('', $arr);
}