/**
 * 判断文件或文件夹是否可写
 * @param string $file 文件或目录
 * @return    bool
 */
function is_really_writable($file)
{
    if (DIRECTORY_SEPARATOR === '/') {
        return is_writable($file);
    }
    if (is_dir($file)) {
        $file = rtrim($file, '/') . '/' . md5(mt_rand());
        if (($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        @chmod($file, 0755);
        @unlink($file);
        return true;
    } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
        return false;
    }
    fclose($fp);
    return true;
}

/**
 * 返回打印数组结构
 * @param string $var 数组
 * @param string $indent 缩进字符
 * @return string
 */
function var_export_short($var, $indent = "")
{
    switch (gettype($var)) {
        case "string":
            return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
        case "array":
            $indexed = array_keys($var) === range(0, count($var) - 1);
            $r = [];
            foreach ($var as $key => $value) {
                $r[] = "$indent    "
                    . ($indexed ? "" : var_export_short($key) . " => ")
                    . var_export_short($value, "$indent    ");
            }
            return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
        case "boolean":
            return $var ? "TRUE" : "FALSE";
        default:
            return var_export($var, true);
    }
}
/**
*图片裁剪
*/
function image_resize($src_file, $dst_file, $new_width, $new_height)
{
    $new_width = intval($new_width);
    $new_height = intval($new_width);
    if ($new_width < 1 || $new_height < 1) {
        echo "params width or height error !";
        exit();
    }
    if (!file_exists($src_file)) {
        echo $src_file .
            " is not exists !";
        exit();
    }
    // 图像类型
    $type = exif_imagetype($src_file);
    $support_type = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
    if (!in_array($type, $support_type, true)) {
        echo "this type of image does not support! only support jpg , gif or png";
        exit();
    }
    //Load image
    switch ($type) {
        case IMAGETYPE_JPEG:
            $src_img = imagecreatefromjpeg($src_file);
            break;
        case IMAGETYPE_PNG:
            $src_img = imagecreatefrompng($src_file);
            break;
        case IMAGETYPE_GIF:
            $src_img = imagecreatefromgif($src_file);
            break;
        default:
            echo "Load image error!";
            exit();
    }
    $w = imagesx($src_img);
    $h = imagesy($src_img);
    $ratio_w = 1.0 * $new_width / $w;
    $ratio_h = 1.0 * $new_height / $h;
    $ratio = 1.0;
    // 生成的图像的高宽比原来的都小,或都大 ,原则是 取大比例放大,取大比例缩小(缩小的比例就比较小了)
    if (($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
        if ($ratio_w < $ratio_h) {
            $ratio = $ratio_h;
            // 情况一,宽度的比例比高度方向的小,按照高度的比例标准来裁剪或放大
        } else {
            $ratio = $ratio_w;
        }
        // 定义一个中间的临时图像,该图像的宽高比 正好满足目标要求
        $inter_w = (int)($new_width / $ratio);
        $inter_h = (int)($new_height / $ratio);
        $inter_img = imagecreatetruecolor($inter_w, $inter_h);
//            var_dump($inter_img);
        imagecopy($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h);
        // 生成一个以最大边长度为大小的是目标图像$ratio比例的临时图像
        // 定义一个新的图像
        ini_set('memory_limit', '8M'); //更改PHP的内存限制
        $new_img = imagecreatetruecolor($new_width, $new_height);
        //var_dump($new_img);exit();
        imagecopyresampled($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height, $inter_w, $inter_h - 7);
        switch ($type) {
            case IMAGETYPE_JPEG:
                // 存储图像
                imagejpeg($new_img, $dst_file, 100);
                break;
            case IMAGETYPE_PNG:
                imagepng($new_img, $dst_file, 100);
                break;
            case IMAGETYPE_GIF:
                imagegif($new_img, $dst_file, 100);
                break;
            default:
                break;
        }
    } else {
        // end if 1
        // 2 目标图像 的一个边大于原图,一个边小于原图 ,先放大平普图像,然后裁剪
        // =if( ($ratio_w < 1 && $ratio_h > 1) || ($ratio_w >1 && $ratio_h <1) )
        $ratio = $ratio_h > $ratio_w ? $ratio_h : $ratio_w;
        //取比例大的那个值
        // 定义一个中间的大图像,该图像的高或宽和目标图像相等,然后对原图放大
        $inter_w = (int)($w * $ratio);
        $inter_h = (int)($h * $ratio);
        $inter_img = imagecreatetruecolor($inter_w, $inter_h);
        //将原图缩放比例后裁剪
        imagecopyresampled($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h, $w, $h);
        // 定义一个新的图像
        $new_img = imagecreatetruecolor($new_width, $new_height);
        imagecopy($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height);
        switch ($type) {
            case IMAGETYPE_JPEG:
                // 存储图像
                imagejpeg($new_img, $dst_file, 100);
                break;
            case IMAGETYPE_PNG:
                imagepng($new_img, $dst_file, 100);
                break;
            case IMAGETYPE_GIF:
                imagegif($new_img, $dst_file, 100);
                break;
            default:
                break;
        }
    }
}
/*
下载保存指定地址的图片
*/
function downloadimg($url, $path, $savename, $cookie = '')
{
    $path_info = str_ireplace('../', '', $path);
    if (!file_exists($path . '/' . $savename)) {
        checkDir($path . '/' . $savename);
        @mkdir($path, 0777);
        $get_file = get_curl($url, $cookie);
        // dump( $get_file);
        $fp = fopen($path . '/' . $savename, "w");
        fwrite($fp, $get_file['info']);
        fclose($fp);
    }
    return $path_info ? $path_info . '/' . $savename : $path . '/' . $savename;
}

/*
 * 上传base64位图片
*/
function imgsave_auth($base64_image_content)
{
    //保存base64字符串为图片
    if ($base64_image_content) {
        //base64_image 要截取base64,前的部分
        preg_match('/(?<=base64,)[\S|\s]+/', $base64_image_content, $base64_image);
        $list = explode(';', $base64_image_content);
        // logs('base64_image',$base64_image);
        if (stristr($list[0], 'png')) {
            $img_str = '.png';
        } elseif (stristr($list[0], 'jpg')) {
            $img_str = '.jpg';
        } elseif (stristr($list[0], 'jpeg')) {
            $img_str = '.jpeg';
        } elseif (stristr($list[0], 'gif')) {
            $img_str = '.gif';
        } elseif (stristr($list[0], 'mp4')) {
            $img_str = '.mp4';
        } else {
            $img_str = '.png';
            // $data['status']=0;
            // $data['info']= '图片格式错误';
            // return $data;
        }
        //  匹配出图片的格式
        $date = date('Ymd', time());
        $time = time();
        $round = rand_string(4, 1);
        $imgpath = 'photos/file/app/' . $date . '/' . $time . $round . $img_str;
        $imgurl = 'photos/file/app/' . $date . '/' . $time . $round . $img_str;
        checkDir($imgpath);
        $res = file_put_contents($imgpath, base64_decode($base64_image[0]));
        if ($res) {
            $data['status'] = 1;
            $data['imgurl'] = $imgurl;
            return $data;
        } else {
            $data['status'] = 0;
            $data['info'] = '保存失败,请刷新后重试';
            return $data;
        }
    }
}
/*
 * 时间格式
 */
function formatDate($sTime)
{
    //sTime=源时间,cTime=当前时间,dTime=时间差
    $cTime = time();
    $dTime = $cTime - $sTime;
    $dDay = intval(date("Ymd", $cTime)) - intval(date("Ymd", $sTime));
    $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
    if ($dTime < 60) {
        $dTime = $dTime . "秒前";
    } elseif ($dTime < 3600) {
        $dTime = intval($dTime / 60) . "分钟前";
    } elseif ($dTime >= 3600 && $dDay == 0) {
        $dTime = "今天" . date("H:i", $sTime);
    } elseif ($dYear == 0) {
        $dTime = date("m-d H:i", $sTime);
    } else {
        $dTime = date("Y-m-d H:i", $sTime);
    }
    return $dTime;
}

/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function  friend_date( $time )
{
    if  (! $time ){
        return false;
    }
    $d  = time() -  intval ( $time );
    $ld  =  $time  -  mktime (0, 0, 0, 0, 0,  date ( 'Y' ));  //得出年
    $md  =  $time  -  mktime (0, 0, 0,  date ( 'm' ), 0,  date ( 'Y' ));  //得出月
    $byd  =  $time  -  mktime (0, 0, 0,  date ( 'm' ),  date ( 'd' ) - 2,  date ( 'Y' ));  //前天
    $yd  =  $time  -  mktime (0, 0, 0,  date ( 'm' ),  date ( 'd' ) - 1,  date ( 'Y' ));  //昨天
    $dd  =  $time  -  mktime (0, 0, 0,  date ( 'm' ),  date ( 'd' ),  date ( 'Y' ));  //今天
    $td  =  $time  -  mktime (0, 0, 0,  date ( 'm' ),  date ( 'd' ) + 1,  date ( 'Y' ));  //明天
    $atd  =  $time  -  mktime (0, 0, 0,  date ( 'm' ),  date ( 'd' ) + 2,  date ( 'Y' ));  //后天
    if  ( $d  == 0) {
        $fdate  =  '刚刚' ;
    }  else  {
        switch  ( $d ) {
            case  $d  <  $td :
                $fdate  =  '后天'  .  date ( 'H:i' ,  $time );
                break ;
            case  $d  < 0:
                $fdate  =  '明天'  .  date ( 'H:i' ,  $time );
                break ;
            case  $d  < 60:
                $fdate  =  $d  .  '秒前' ;
                break ;
            case  $d  < 3600:
                $fdate  =  floor ( $d  / 60) .  '分钟前' ;
                break ;
            case  $d  <  $dd :
                $fdate  =  floor ( $d  / 3600) .  '小时前' ;
                break ;
            case  $d  <  $yd :
                $fdate  =  '昨天'  .  date ( 'H:i' ,  $time );
                break ;
            case  $d  <  $byd :
                $fdate  =  '前天'  .  date ( 'H:i' ,  $time );
                break ;
            case  $d  <  $md :
                $fdate  =  date ( 'm月d日 H:i' ,  $time );
                break ;
            case  $d  <  $ld :
                $fdate  =  date ( 'm月d日' ,  $time );
                break ;
            default :
                $fdate  =  date ( 'Y年m月d日' ,  $time );
                break ;
        }
    }
    return  $fdate ;
}

/**
 *  作用:将xml转为array
 */
function xmlToArray($xml)
{
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}

/**
 * 多维数组查询值是否存在
 * @param  string         $value  需要查询的值
 * @param  array          $array  需要查询的数组
 * @return string|boolean         查询到返回包含值的数组,查询不到返回false
 */
function deep_in_array($value, $array)
{
    foreach ($array as $v) {
        if (!is_array($v)) {
            if ($v == $value) {
                return $v;
            }
            continue;
        }
        if (in_array($value, $v)) {
            return $v;
        } else {
            deep_in_array($value, $v);
        }
    }
    return false;
}

/**
 * 简单可逆加密
 * @param  string $txtStream 需要加密的数据
 * @param  string $password  键值
 * @return string       加密结果
 */
function simple_encrypt($txtStream, $password = '')
{
    if ($password === '') {
        $password = config('encrypt_salt'); //BUzheng_123
    }
    //密锁串,不能出现重复字符,内有A-Z,a-z,0-9,=,+,_,
    $lockstream = '1234567890zxcvbnmZXCVBNM=asdfghjklASDFGHJKL+qwertyuiopQWERTYUIOP_';
    //密锁串长度
    $lockLen = strlen($lockstream);
    //随机找一个数字,并从密锁串中找到一个密锁值
    $lockCount = rand(0, $lockLen - 1);
    //截取随机密锁值
    $randomLock = $lockstream[$lockCount];
    //结合随机密锁值生成MD5后的密码
    $password = md5($password . $randomLock);
    //开始对字符串加密
    $txtStream = base64_encode($txtStream);
    $tmpStream = '';
    $i         = 0;
    $j         = 0;
    $k         = 0;
    for ($i = 0; $i < strlen($txtStream); $i++) {
        $k = ($k == strlen($password)) ? 0 : $k;
        $j = (strpos($lockstream, $txtStream[$i]) + $lockCount + ord($password[$k])) % ($lockLen);
        $tmpStream .= $lockstream[$j];
        $k++;
    }
    return $tmpStream . $randomLock;
}

/**
 * 简单可逆解密
 * @param  string $txtStream 需要解密的数据
 * @param  string $password  键值
 * @return string       解密结果
 */
function simple_decrypt($txtStream, $password = '')
{
    if ($password === '') {
        $password = config('encrypt_salt');
    }
    //密锁串,不能出现重复字符,内有A-Z,a-z,0-9,=,+,_,
    $lockstream = '1234567890zxcvbnmZXCVBNM=asdfghjklASDFGHJKL+qwertyuiopQWERTYUIOP_';
    //密锁串长度
    $lockLen = strlen($lockstream);
    //获得字符串长度
    $txtLen = strlen($txtStream);
    //截取随机密锁值
    $randomLock = $txtStream[$txtLen - 1];
    //获得随机密码值的位置
    $lockCount = strpos($lockstream, $randomLock);
    //结合随机密锁值生成MD5后的密码
    $password = md5($password . $randomLock);
    //开始对字符串解密
    $txtStream = substr($txtStream, 0, $txtLen - 1);
    $tmpStream = '';
    $i         = 0;
    $j         = 0;
    $k         = 0;
    for ($i = 0; $i < strlen($txtStream); $i++) {
        $k = ($k == strlen($password)) ? 0 : $k;
        $j = strpos($lockstream, $txtStream[$i]) - $lockCount - ord($password[$k]);
        while ($j < 0) {
            $j = $j + ($lockLen);
        }
        $tmpStream .= $lockstream[$j];
        $k++;
    }
    return base64_decode($tmpStream);
}