<?php
// +----------------------------------------------------------------------
// | 函数助手 [ 天方夜谭快速开发框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014~2019 http://www.eirds.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 天方夜谭 <17404785@qq.com>
// +----------------------------------------------------------------------

/**
 * 获取和设置配置参数
 * @param null $name
 * @param null $value
 * @param null $default
 * @return array|mixed|null
 */
function TFYT($name = null, $value = null, $default = null)
{
    static $_config = array();
    if (empty($name)) {
        return $_config;
    }
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtoupper($name);
            if (is_null($value)) return isset($_config[$name]) ? $_config[$name] : $default;
            $_config[$name] = $value;
            return null;
        }
        $name = explode('.', $name);
        $name[0] = strtoupper($name[0]);
        if (is_null($value)) return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
        $_config[$name[0]][$name[1]] = $value;
        return null;
    }
    if (is_array($name)) {
        $_config = array_merge($_config, array_change_key_case($name, CASE_UPPER));
        return null;
    }
    return null;
}

/**
 * object(stdclass)转数组的函数
 * @param $array
 * @return array
 */
function object_array($array){
    if(is_object($array)){
        $array = (array)$array;
    }
    if(is_array($array)){
        foreach($array as $key=>$value){
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

/**
 * 获取GET方式接收到的值
 * @param null $key
 * @return mixed|string|string[]|null
 */
function GET($key = null)
{
    if(isset($_GET[$key])){
        $str = $_GET[$key];
        //特殊字符的过滤方法
        return safestr($str);
    }else{
        return null;
    }
}

/**
 * 获取POST方式接收到的值
 * @param null $key
 * @return mixed|string|string[]|null
 */
function POST($key = null)
{
    if(isset($_POST[$key])){
        $str = $_POST[$key];
        //特殊字符的过滤方法
        return safestr($str);
    }else{
        return null;
    }
}

/**
 * 过滤危险字符串
 * @param $str
 * @return string
 */
function safestr($str) {
    if (!get_magic_quotes_gpc()) {
        return addslashes($str);
    } else {
        return $str; //过滤危险字符
    }
}

/**
 * md5加密
 * @param $pwd
 * @return string
 */
function md5Pwd($pwd){
    $pwd=md5(md5(md5($pwd).md5('QQ17404785')));
    return $pwd;
}

/**
 * 生成32位随机字符串
 * @param int $length
 * @param string $char
 * @return bool|string
 */
function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'){
    if(!is_int($length) || $length < 0) {
        return false;
    }
    $string = '';
    for($i = $length; $i > 0; $i--) {
        $string .= $char[mt_rand(0, strlen($char) - 1)];
    }
    return $string;
}

/**
 * 获取QQ名称
 * @param int $qq
 * @return bool|string
 */
function qqnick($qq=10001)
{
    return curl_get("http://qqnick.eirds.com/?qq=".$qq);
}

/**
 * GET请求
 * @param $url
 * @return bool|string
 */
function curl_get($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $dom = curl_exec($ch);
    curl_close($ch);
    return $dom;
}

/**
 * GET请求2
 * @param $url
 * @return bool|string
 */
function curl_get_https($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
    $tmpInfo = curl_exec($curl);
    curl_close($curl);
    return $tmpInfo;   //返回json对象
}

/**
 * 百度ip接口
 * @param null $ip
 * @return mixed
 */
function get_region($ip=null)
{
    $ak = '4l6BwmWwdwU4hsaVZnOwpM6MLy0bYmgc';
    $url = file_get_contents("http://api.map.baidu.com/location/ip?ip=$ip&ak=$ak");
    $res1 = json_decode($url,true);
    $data =$res1;
    return $data['content']['address'];
}

/**
 * 返回上午下午
 * @return string
 */
function getStrTime(){
    $no=date("H",time());
    if ($no>0&&$no<=6){
        return "凌晨好";
    }
    if ($no>6&&$no<12){
        return "上午好";
    }
    if ($no>=12&&$no<=18){
        return "下午好";
    }
    if ($no>18&&$no<=24){
        return "晚上好";
    }
    return "您好";
}

/**
 * 时间比大小
 * @param null $time
 * @return bool
 */
function getIsTime($time1 = null,$time2 = null){
    $zero1=$time1;;
    $zero2=$time2;
    if(strtotime($zero1)>strtotime($zero2)){
        return true;
    }else{
        echo false;
    }
}

/**
 * 计算文件大小
 * @param $size
 * @return int|string
 */
function size($size){
    if($size<1024) $size.='B';
    else{
        $size/=1024;
        if($size<1024) $size=round($size,2).'KB';
        else{
            $size/=1024;
            if($size<1024) $size=round($size,2).'MB';
            else{
                $size/=1024;
                if($size<1024) $size=round($size,2).'GB';
            }
        }
    }
    return $size;
}

/**
 * 对应js encodeURIComponent
 * @param $str
 * @return string
 */
function encodeURIComponent($str) {
    $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
    return strtr(rawurlencode($str), $revert);
}

/**
 * 判断数组里是否存在某个值
 * @param $value
 * @param $array
 * @return bool
 */
function deep_in_array($value, $array) {
    foreach($array as $item) {
        if(!is_array($item)) {
            if ($item == $value) {
                return true;
            } else {
                continue;
            }
        }
        if(in_array($value, $item)) {
            return true;
        } else if(deep_in_array($value, $item)) {
            return true;
        }
    }
    return false;
}

/**
 * 写入文本
 * @param $str
 */
function writelog($str=null)
{
    $open=fopen($_SERVER['DOCUMENT_ROOT']."/Monitor/log.txt","w" );
    fwrite($open,$str);
    fclose($open);
}

/**
 * 函数检测1
 * @param $a
 * @param bool $b
 * @return string
 */
function checkfunc($a, $b = false){
    if (function_exists($a)) {
        return '<font color="green">可用</font>';
    } else {
        if ($b == false) {
            return '<font color="black">不支持</font>';
        } else {
            return '<font color="red">不支持</font>';
        }
    }
}

/**
 * 函数检测2
 * @param $a
 * @param bool $b
 * @return string
 */
function checkclass($a, $b = false){
    if (class_exists($a)) {
        return '<font color="green">可用</font>';
    } else {
        if ($b == false) {
            return '<font color="black">不支持</font>';
        } else {
            return '<font color="red">不支持</font>';
        }
    }
}

/**
 * 计算VIP
 * @param $vip
 * @param $end
 * @return int
 */
function get_isvip($vip='0', $end='')
{
    if ($vip) {
        if (strtotime($end) > time()) {
            return 1;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

/**
 * 获取已经过了多久
 * PHP时间转换
 * 刚刚、几分钟前、几小时前
 * 今天昨天前天几天前
 * @param  string $targetTime 时间戳
 * @return string
 */
function get_last_time($targetTime)
{
    $targetTime = strtotime($targetTime);
    // 今天最大时间
    $todayLast   = strtotime(date('Y-m-d 23:59:59'));
    $agoTimeTrue = time() - $targetTime;
    $agoTime     = $todayLast - $targetTime;
    $agoDay      = floor($agoTime / 86400);

    if ($agoTimeTrue < 60) {
        $result = '刚刚';
    } elseif ($agoTimeTrue < 3600) {
        $result = (ceil($agoTimeTrue / 60)) . '分钟前';
    } elseif ($agoTimeTrue < 3600 * 12) {
        $result = (ceil($agoTimeTrue / 3600)) . '小时前';
    } elseif ($agoDay == 0) {
        $result = '今天 ' . date('H:i', $targetTime);
    } elseif ($agoDay == 1) {
        $result = '昨天 ' . date('H:i', $targetTime);
    } elseif ($agoDay == 2) {
        $result = '前天 ' . date('H:i', $targetTime);
    } elseif ($agoDay > 2 && $agoDay < 16) {
        $result = $agoDay . '天前 ' . date('H:i', $targetTime);
    } else {
        $format = date('Y') != date('Y', $targetTime) ? "Y-m-d H:i" : "m-d H:i";
        $result = date($format, $targetTime);
    }
    return $result;
}

/**
 * 判断手机/电脑端
 * @return bool|null
 */
function wp_is_mobile()
{
    static $is_mobile = null;
    if (isset($is_mobile)) {
        return $is_mobile;
    }
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }
    return $is_mobile;
}

/**
 * 字符串加密
 * @param $string
 * @param string $operation
 * @param string $key
 * @param int $expiry
 * @return false|string
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

    $ckey_length = 4;
    // 随机密钥长度 取值 0-32;
    // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
    // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
    // 当此值为 0 时，则不产生随机密钥

    $key = md5($key ? $key : 'default_key'); //这里可以填写默认key值
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.str_replace('=', '', base64_encode($result));
    }

}

function duo_curl($urls) {
    $ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36';
    $queue = curl_multi_init();
    $map = [];
    foreach ($urls as $url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url."&backurl=".urlencode("http://".$_SERVER['HTTP_HOST']."/"));
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOSIGNAL, true);
        curl_multi_add_handle($queue, $ch);
        $map[(string)$ch] = $url;
    }
    $responses = [];
    do {
        while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) ;
        if ($code != CURLM_OK) {
            break;
        }
        while ($done = curl_multi_info_read($queue)) {
            $info = curl_getinfo($done['handle']);
            $error = curl_error($done['handle']);
            $results = curl_multi_getcontent($done['handle']);//返回内容
            $responses[$map[(string)$done['handle']]] = compact('info', 'error', 'results');
            curl_multi_remove_handle($queue, $done['handle']);
            curl_close($done['handle']);
        }
        if ($active > 0) {
            curl_multi_select($queue, 0.5);
        }
    } while ($active);
    curl_multi_close($queue);
    return $responses;
}

function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $head = 0, $ua = 0, $nobaody = 0) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $header[] = "Accept:application/json";
    $header[] = "Accept-Encoding:gzip,deflate,sdch";
    $header[] = "Accept-Language:zh-CN,zh;q=0.8";
    $header[] = "Connection:keep-alive";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    if ($head) {
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
    }
    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if ($referer) {
        if ($referer == 1) {
            curl_setopt($ch, CURLOPT_REFERER, "https://m.qzone.com/");
        } else {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
    }
    if ($ua) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0');
    }
    if ($nobaody) {
        curl_setopt($ch, CURLOPT_NOBODY, 1);
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    $ret = mb_convert_encoding($ret, "UTF-8", "UTF-8");
    return $ret;
}

/**
 * 随机内容
 * @param $con
 * @return mixed|string
 */
function get_con($con){
    if($con=='[爱情]'){
        $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/aiqing.txt');
        shuffle($row);
        return $row[1];
    }elseif($con=='[伤感]'){
        $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/shanggan.txt');
        shuffle($row);
        return $row[1];
    }elseif($con=='[经典]'){
        $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/jingdian.txt');
        shuffle($row);
        return $row[1];
    }elseif($con=='[人生格言]'){
        $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/rensheng.txt');
        shuffle($row);
        return $row[1];
    }elseif($con=='[笑话]'){
        $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/xiaohua.txt');
        shuffle($row);
        return $row[1];
    }elseif ($con=='[舔狗日记]'){
        $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/tg.txt');
        shuffle($row);
        return "舔狗日记：" . date("Y年m月d日") . " 晴" . $row[1];
    }elseif ($con=='[随机]'){
        $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/content.txt');
        shuffle($row);
        return $row[1];
    }else{
        return $con;
    }
}

/**
 * 随即图片
 * @param $pic
 * @return mixed|string
 */
function get_pic($pic){
    if(empty($pic)){
        $pic = '';
    }else{
        if(!preg_match("/^http(s)?:\\/\\/.+/",$pic)){
            $row=file($_SERVER['DOCUMENT_ROOT'].'/Includes/data/pic.txt');
            shuffle($row);
            $pic=$row[0];
        }
    }
    $pic=trim($pic);
    return $pic;
}