<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
// 定义静态资源目录 或 URL

define('G_HTTP', isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? "https://" : "http://");
define('G_HTTP_HOST', isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "");
defined('PUBLIC_PATH') or define('PUBLIC_PATH', dirname("https://" . G_HTTP_HOST . $_SERVER['SCRIPT_NAME']));

/**
 * 验证POS json格式数据
 * @param string $string
 * @return string|bool
 */
function isJson($string)
{
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

function get_token()
{
    //从协议头获取token
    return \think\Request::instance()->header('X-Access-Token');
}

function get_brand()
{
    //从协议头获取token
    return \think\Request::instance()->header('BRAND');
}

function timeToDate($time = 0)
{
    return date("Y-m-d H:i:s", empty($time) ? time() : $time);
}

function randString($len = 4)
{
    $chars = str_repeat('0123456789', $len);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);
    return $str;
}

function getToken()
{
    //从协议头获取token
    return \think\Request::instance()->header('X-Access-Token');
}

function uuid($prefix = '')
{
    $chars = md5(uniqid(mt_rand(), true));
    return $prefix . $chars;
}

function object2array($object)
{
    $array = array();
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    } else {
        $array = $object;
    }
    return $array;
}

function curlSend($url)
{
    try {
        $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_FOLLOWLOCATION, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    } catch (\Exception $e) {
        return false;
    }
}

function curl_post($url, $res)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_SSL_VERIFYPEER => FALSE,
        CURLOPT_SSL_VERIFYHOST => FALSE,
        CURLOPT_TIMEOUT => 300,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($res),
        CURLOPT_HTTPHEADER => array(
            "Content-type: application/json;charset='utf-8'",
        )
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        return $err;
    } else {

        return json_decode($response, true);
    }
}

function token($uuid)
{
    return md5(md5($uuid . time() . rand(10, 19999)));
}

function logFile($content, $title = 'LOG', $filename = 'log_file')
{
    try {
        $titleShow = (strlen($title) > 30) ? substr($title, 0, 27) . '...' : $title;
        $spaceNum = (66 - strlen($titleShow)) / 2;
        $titleShow = '=' . str_repeat(' ', intval($spaceNum)) . $titleShow . str_repeat(' ', ceil($spaceNum)) . '=';

        $time = date('Y-m-d H:i:s');
        $content = var_export($content, true);

        $logContent = <<<EOT
====================================================================
{$titleShow}
====================================================================
time:     {$time}
title:    {$title}
--------------------------------------------------------------------
content:  \n{$content}\n\n\n
EOT;

        $logPath = LOG_PATH;
        $logName = $filename . date('Ymd') . '.log';
        if (!is_dir($logPath)) {
            mkdir($logPath);
        }
        $logFile = fopen($logPath . $logName, "a");
        fwrite($logFile, $logContent);
        fclose($logFile);
    } catch (\Exception $e) {
        // do nothing
    }
}

function getSign($Obj)
{
    foreach ($Obj as $k => $v) {
        $Parameters[$k] = $v;
    }
    //签名步骤一：按字典序排序参数
    ksort($Parameters);
    $String = formatBizQueryParaMap($Parameters, false);
    //签名步骤四：所有字符转为大写
    $result_ = strtoupper($String);
    return $result_;
}

function formatBizQueryParaMap($paraMap, $urlencode)
{
//    var_dump($paraMap);//die;
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v) {
        if ($urlencode) {
            $v = urlencode($v);
        }
        //$buff .= strtolower($k) . "=" . $v . "&";
//        $buff .= $k . "=" . $v . "&";
        $buff .= $k;
    }

    /*if (strlen($buff) > 0)
    {
        $reqPar = substr($buff, 0, strlen($buff)-1);
    }*/
    return $buff;
}

//将uuid数组组合成 ('1','2','3')这种形式的
function arrayToString($uuid)
{
    $uuids = '(';
    foreach ($uuid as $k => $v) {
        $uuids .= "'" . $v . "',";
    }
    $uuids = rtrim($uuids, ",");
    $uuids .= ')';
    return $uuids;
}

/**
 * @author: Airon
 * @time:   2018年5月
 * description 计算百分比
 * @param int $divisor 基数
 * @param int $dividend 总数
 * @return string
 */
function percent($divisor, $dividend)
{
    if ($dividend == 0) {
        return '0%';
    }

    return (round($divisor / $dividend, 2) * 100) . "%";
}
/**
 * 替换字符串中间位置字符为星号
 * @param  [type] $str [description]
 * @return [type] [description]
 */
function replaceToStar($str)
{
    $len = strlen($str) / 2; //a0dca4d0****************ba444758]
    return substr_replace($str, str_repeat('*', $len), floor(($len) / 2), $len);
}


/**
 * @author: ChiaHsiang
 * @time: 2018/8/7
 * @description: 判断日期是否连续，0：同一日；1：日期相邻；其他值为日期相差天数
 * @param $start
 * @param $end
 * @return int|mixed
 */
function timeDiff($start, $end) {
    $earlier = new DateTime($start);
    $later = new DateTime($end);

    $date1 = $earlier->format('Y-m-d');
    $date2 = $later->format('Y-m-d');

    $earlier = new DateTime($date1);
    $later = new DateTime($date2);

    $day_diff = $later->diff($earlier)->days;

    /*if ($day_diff == 0) {
        $date1 = $earlier->format('Y-m-d');
        $date2 = $later->format('Y-m-d');
        dump($date1);dump($date2);exit;
        $d1 = explode('-', $date1);
        $d2 = explode('-', $date2);

        if (end($d1) !== end($d2)) {
            return 1;
        }
    }*/

    return $day_diff;
}

/**
 * @author: ChiaHsiang
 * @time: 2018/8/26
 * @description: 直接返回响应
 * @param $msg
 * @param int $code
 */
function ResponseDirect($msg, $code = 400) {
    throw new think\exception\HttpResponseException(json(array('error' => ['message' => $msg]), $code));
}

function array2JsonStr($array) {

    $arrayRecursive = function (&$array, $function, $apply_to_keys_also = false) {
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
            die('possible deep recursion attack');
        }
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $this->arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }

            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
        $recursive_counter--;
    };

    $arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}

function send_post($url, $post_data) {

    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间（单位:s）
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}


/**
 * 获取客户端IP地址
 * @return string
 */
function get_client_ip() {
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    } else {
        $ip = '0.0.0.0';
    }
    return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches[0] : '';
}
