<?php

if (!function_exists('micro_time')) {
    /**
     * 获取当前时间的微秒时间戳
     * @return string
     */
    function micro_time()
    {
        list($usec, $sec) = explode(" ", microtime());
        $time = ($sec . substr($usec, 2, 3));
        return $time;
    }
}

#是否微信浏览器
function isWeChatBrowser()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } else {
        return false;
    }
}

#获取随机字符串
function getChars($lenth = 16)
{
    $string = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789';
    $key = '';
    for ($i = 0; $i < $lenth; $i++) {
        $key .= substr($string, mt_rand(0, 51), 1);
    }
    return $key;
}


function imageGetBase64($url)
{
    $imgs = [
        'image/jpeg' => 'jpeg',
        'image/jpg' => 'jpg',
        'image/gif' => 'gif',
        'image/png' => 'png',
        'text/html' => 'html',
        'text/plain' => 'txt',
        'image/pjpeg' => 'jpg',
        'image/x-png' => 'png',
        'image/x-icon' => 'ico'
    ];
    if (!stristr($url, 'http')) {
        throw new \Exception("url不正确", 2101);
    }
    $dir = pathinfo($url);
    $host = $dir['dirname'];
    $refer = $host . '/';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_REFERER, $refer); //伪造来源地址
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回变量内容还是直接输出字符串,0输出,1返回内容
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);//在启用CURLOPT_RETURNTRANSFER的时候，返回原生的（Raw）输出
    curl_setopt($ch, CURLOPT_HEADER, 0); //是否输出HEADER头信息 0否1是
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); //超时时间
    $data = curl_exec($ch);
    //$httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    //$httpContentType = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
    $info = curl_getinfo($ch);
    curl_close($ch);
    $httpCode = intval($info['http_code']);
    $httpContentType = $info['content_type'];
    $httpSizeDownload = intval($info['size_download']);

    if ($httpCode != '200') {
        throw new \Exception("url返回内容不正确", 2102);
    }
    if (!isset($imgs[$httpContentType])) {
        throw new \Exception("url资源类型未知", 2103);
    }
    if ($httpSizeDownload < 1) {
        throw new \Exception("内容大小不正确", 2104);
    }
    $base_64 = base64_encode($data);
    $data = "data:{$httpContentType};base64,{$base_64}";
    unset($info, $base_64);
    return $data;
}

function encryptString(string $string, string $key)
{
    $key = md5($key);
    $x = 0;
    $len = strlen($string);
    $l = strlen($key);
    $char = null;
    $str = null;
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord($string{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}

// #解密
function decryptString(string $string, string $key)
{
    $key = md5($key);
    $x = 0;
    $string = base64_decode($string);
    $len = strlen($string);
    $l = strlen($key);
    $char = null;
    $str = null;
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($string, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($string, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($string, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return $str;
}


/**
 * @param  array  $array
 * @return xml
 */
function array2xml(array $array)
{
    $xml = "<xml>";
    foreach ($array as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}

/**
 * 将xml转为array
 * @param  string  $xml
 * @return array
 */
function xml2array($xml)
{
    //将XML转为array
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}


function https_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

function getUTF8Sting(string $string)
{
    //reject overly long 2 byte sequences, as well as characters above U+10000 and replace with ?
    $string = preg_replace(
        '/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]' .
        '|[\x00-\x7F][\x80-\xBF]+' .
        '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*' .
        '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})' .
        '|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
        '?',
        $string
    );

    //reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
    $string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]' .
        '|\xED[\xA0-\xBF][\x80-\xBF]/S', '?', $string);

    return $string;
}


function uuid()
{
    return \Ramsey\Uuid\Uuid::uuid4()->toString();
    return md5(uniqid(mt_rand(100000000, 999999999)));
}

/**
 * 版本检测
 * @param  string  $client_version  客户端版本
 * @param  string  $low_version  最低兼容版本
 * @param  string  $latest_version  最新版本
 * @throws \App\Exceptions\VersionException
 */
function version(string $client_version, string $low_version, string $latest_version)
{
    if (strcmp($client_version, $low_version) < 0) {
        // 不兼容
        throw new \App\Exceptions\VersionException("不兼容", 208);
    }
    if (strcmp($client_version, $latest_version) < 0) {
        // 有更新
    }
}

/**
 * 调试打印
 * @param  \Illuminate\Http\Request  $request
 * @param $var
 * @return array
 */
function debugdump(\Illuminate\Http\Request $request, $var)
{
    if (98047 == $request->get('debug')) {
        foreach (array_slice(func_get_args(), 1) as $v) {
            dump($v);
        }

        if (2 < func_num_args()) {
            return func_get_args();
        }

        return $var;
    }
}
