<?php
// 应用公共文件

/**
 * @param $url
 * @return array
 */
function curl_get($url){

    $headerArray = array("Content-type:application/json;", "Accept:application/json;");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output = json_decode($output, true);


}

/**
 * @param $url
 * @param array $data
 * @param $headerArray
 * @return array
 */
function curl_post($url , $data=array(),$headerArray){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output = json_decode($output, true);;

}

/**
 * 判断是否为合法的身份证号码
 * @param $IDcard
 * @return boolean
 */
function isCreditNo($vStr){

    $vCity = array(
        '11','12','13','14','15','21','22',
        '23','31','32','33','34','35','36',
        '37','41','42','43','44','45','46',
        '50','51','52','53','54','61','62',
        '63','64','65','71','81','82','91'
    );
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
    if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
    $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);
    if ($vLength == 18) {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }
    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
    if ($vLength == 18) {
        $vSum = 0;
        for ($i = 17 ; $i >= 0 ; $i--) {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
        }
        if($vSum % 11 != 1) return false;
    }
    return true;
}

//获取毫秒时间戳
function msectime(){
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

/**
 * 生成随机字符串
 *
 * @return string
 */
function getRandomStr($length=16)
{
    $str = '';
    $str_pol = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyl';
    $max = strlen($str_pol) - 1;
    for ($i = 0; $i < $length; $i++) {
        $str .= $str_pol[mt_rand(0, $max)];
    }
    return $str;
}


//见证手机号是否合法
function isPhoneNo($phone){
    if(preg_match("/^1[34578]\d{9}$/", $phone)){
        return true;
    } else {
        return false;
    }
}

//图片上传
function uploadImgs($up_dir,$base64_img,$imgName="") {
    $up_root_dir = getcwd().$up_dir; //获取绝对路径

    if(!file_exists($up_root_dir)){
         mkdir($up_root_dir,0777);
    }
    if(!$base64_img){
        return ['code'=>400,'msg'=>'图片数据未传递!'];
    }
    if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
        $type = $result[2];
        if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
            if(!$imgName){
                $img_name = date('YmdHis');
            }
            $new_file = $up_root_dir.$img_name.".".$type;
            if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                if(isHTTPS()){
                    $http = "https://";
                } else {
                    $http = "http://";
                }
                return ['code'=>200,'msg'=>$http.$_SERVER['SERVER_NAME'].$up_dir.$img_name.'.'.$type,'path'=>$up_dir.$img_name.'.'.$type];
            }else{
                return ['code'=>400,'msg'=>'图片上传错误!'];
            }
        }else{
            //文件类型错误
            return ['code'=>400,'msg'=>'图片上传类型错误!'];
        }

    }else{
        //文件错误
        return ['code'=>400,'msg'=>'文件错误!'];
    }
}


//文件下载
function downloadFile($file,$file_name) {
    ob_clean();
    if(!file_exists($file)){
        echo "文件不存在";
        return;
    }

    $fp=fopen($file,"r");

    //取得文件大小
    $file_Size=filesize($file);


    header("Content-type:application/octet-stream");
    header("Accept-Ranges:bytes");
    header("Accept-Length:".$file_Size);
    if(!$file_name){
        $fileArr = explode('/',$file);
        $file_name = end($fileArr);
    }
    header("Content-Disposition: attachment; filename=".$file_name);

    $buffer=1024;
    $buffer_count=0;

    while(!feof($fp)&&$file_Size-$buffer_count>0){
        $data=fread($fp,$buffer);
        $buffer_count+=$buffer;
        echo $data;

    }

    fclose($fp);
}

//生成短信验证码
function createPhoneCode($length) {
    return substr(str_shuffle("012345678901234567890123456789"), 0, $length);;
}

//生成订单编号
function createOrderNum(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}


function isHTTPS()
{
    if (defined('HTTPS') && HTTPS) return true;
    if (!isset($_SERVER)) return FALSE;
    if (!isset($_SERVER['HTTPS'])) return FALSE;
    if ($_SERVER['HTTPS'] === 1) {  //Apache
        return TRUE;
    } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
        return TRUE;
    } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
        return TRUE;
    }
    return FALSE;
}








