<?php

namespace Heanup\Frame;


class Helper
{

    /*
    * 检测链接是否是SSL连接
    * @return bool
    */
    public static function isSSL()
    {
        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;
    }

    /**
     * 随机数生成器
     */
    public static function random()
    {
        return md5(microtime() . rand() . uniqid() . $_SERVER['REMOTE_ADDR']);
    }

    /**
     * 简单验证email
     * @param $email
     * @return bool
     */
    public static function validateEmail($email)
    {
        $email = trim($email);
        if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
            return False;
        }
        return True;
    }

    /**
     * 简单验证是否有效的URL
     * @param $url
     * @return bool
     */
    public static function validateURL($url)
    {
        $url = trim($url);
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
            return False;
        }
        return True;
    }


    /**
     * 转换为友好时间
     * @param int|string $timestamp
     * @return string
     */
    public static function convertToFriendlyTime($timestamp)
    {
        if (!is_numeric($timestamp)) {
            $timestamp = strtotime($timestamp);
        }
        $now = time();
        $interval = abs($now - $timestamp);
        $today = strtotime(date("Ymd"));
        $tomorrow = strtotime(date("Ymd", $now + 86400));
        $thisYear = strtotime(date("Y-01-01 00:00"));
        if ($interval < 60) {
            if ($interval < 10) {
                $interval = 10;
            }
            $string = $interval . "秒前";
        } else if ($interval < 3600) {
            $string = floor($interval / 60) . '分钟前';
        } else if ($today < $timestamp AND $timestamp < $tomorrow) {
            $string = '今天' . date('H:i', $timestamp);
        } else if ($thisYear < $timestamp) {
            $string = date('n月j日', $timestamp);
        } else {
            $string = date('Y-m-d', $timestamp);
        }
        return $string;
    }


    /**
     * 计算字符串长度，汉字按两个字符
     * @param string $str
     * @return int
     */
    public static function strlenUtf8($str)
    {
        $length = strlen(preg_replace('/[u4e00-u9fa5 ]/', '', $str));

        if ($length) {
            if($length < 3){
                return $length;
            }
            return strlen($str) - $length + intval($length / 3) * 2;
        } else {
            return strlen($str);
        }
    }

    /**
     * 获取服务器IP
     * @param bool $toLong 是否返回整形
     * @return string
     */
    public static function getServerIp($toLong = false)
    {
        if (isset($_SERVER['SERVER_ADDR'])) {
            $ip = $_SERVER['SERVER_ADDR'];
        } else {
            $domain = gethostname();
            $ip = gethostbyname($domain);
        }
        if ($toLong) {
            $ip = ip2long($ip);
        }
        return $ip;
    }

    /**
     * 获取客户端Ip
     * @param bool $toLong 是否返回整形
     * @return string|int
     */
    public static function getClientIp($toLong = false)
    {
        $ip = '';
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"]) {
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif (isset($_SERVER["HTTP_CLIENT_IP"]) && $_SERVER["HTTP_CLIENT_IP"]) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        } elseif (isset($_SERVER["REMOTE_ADDR"]) && $_SERVER["REMOTE_ADDR"]) {
            $ip = $_SERVER["REMOTE_ADDR"];
        }
        $pos = strpos($ip, ',');
        if ($pos) {
            $ip = substr($ip, 0, $pos);
        }
        $ip = trim($ip);
        if ($toLong) {
            $ip = ip2long($ip);
        }
        return $ip;
    }

    /**
     * 从 $argv 中解析合并参数, 兼容一下情况:
     *      无前缀, 被解析成索引数组
     *      单前缀(只能是单字母, 后面可以直接跟value, 也可以空格后面跟着value,二者不能混用), 被解析成关联数组
     *      双前缀形式(可以是单字母也可以是多字母,后面必需跟着 '='), 被解析成关联数组
     * 如果不确定, 请自行打印结果查看是否正确
     * @example : php index.php first -s 'second' --third='third'
     * @return array('first', 's' => 'second', 'third' => 'third')
     */
    public static function getArguments()
    {
        $arguments = $_SERVER['argv'];
        for ($i = 0; $i < $_SERVER['argc']; $i++) {
            if (!isset($arguments[$i][0])) {
                continue;
            }

            //判断第一位是否是 '-'
            if (substr($arguments[$i], 0, 1) != '-') {
                continue;
            }

            //判断第二位是否是 '-'
            if (substr($arguments[$i], 1, 1) != '-') {
                if (strlen($arguments[$i]) == 2) {
                    $key = substr($arguments[$i], 1);
                    $value = $arguments[$i + 1];
                    $arguments[$key] = trim($value);
                    unset($arguments[$i]);
                    unset($arguments[$i + 1]);
                } elseif (strlen($arguments[$i]) > 2) {
                    $key = substr($arguments[$i], 1, 1);
                    $value = substr($arguments[$i], 2);
                    $arguments[$key] = trim($value);
                    unset($arguments[$i]);
                }
            } else {
                $value = substr($arguments[$i], 2);
                $value = explode('=', $value, 2);
                $arguments[$value[0]] = trim($value[1]);
                unset($arguments[$i]);
            }
        }
        return $arguments;
    }

    /**
     * 尝试解析字符串,如果解析失败则返回原值
     * @param $string
     * @return string | array
     */
    public static function jsonDecode($string)
    {
        if (!$string) {
            return $string;
        }
        $result = json_decode($string, true);
        if ($result) {
            $string = $result;
        }
        return $string;
    }

    /**
     * 获取数组分片, 从指定列表中获取指定元素之后的若干个切片
     * @param $idList
     * @param $lastId
     * @param $count
     * @return array
     */
    public static function getSlice($idList, $lastId = 0, $count = 20)
    {
        $result = array();
        if (!$idList || ($lastId && !in_array($lastId, $idList))) {
            return $result;
        }
        if ($lastId) {
            $position = array_search($lastId, $idList) + 1;
        } else {
            $position = 0;
        }
        $result = array_slice($idList, $position, $count);
        return $result;
    }

    /**
     * 创建目录
     * @param string $dir
     * @param integer $mode
     */
    public static function mkdir($dir, $mode = 0755)
    {
        if (!is_dir($dir)) {
            $temp = explode('/', $dir);
            $cur_dir = '';
            for ($i = 0; $i < count($temp); $i++) {
                $cur_dir .= $temp[$i] . '/';
                if (!is_dir($cur_dir)) {
                    @mkdir($cur_dir, 0777);
                    @chmod($cur_dir, $mode);
                }
            }
        }
    }

    public static function copydir($strSrcDir, $strDstDir)
    {
        $dir = opendir($strSrcDir);
        if (!$dir) {
            return false;
        }
        if (!is_dir($strDstDir)) {
            if (!mkdir($strDstDir)) {
                return false;
            }
        }
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($strSrcDir . '/' . $file)) {
                    if (!self::copydir($strSrcDir . '/' . $file, $strDstDir . '/' . $file)) {
                        return false;
                    }
                } else {
                    if (!copy($strSrcDir . '/' . $file, $strDstDir . '/' . $file)) {
                        return false;
                    }
                }
            }
        }
        closedir($dir);
        return true;
    }

    /**
     * 获取强密码
     * @param int $length
     * @return string
     */
    public static function getStrongCode($length = 8)
    {
        $length = $length > 8 ? intval($length) : 8;
        $arr = array();
//        $arr[] = self::getRandoms($length - 4);
        $arr[] = strtolower(self::getRandoms($length, 'char'));
//        $arr[] = strtolower(self::getRandoms(1, 'char'));
        $arr[] = mt_rand(0, 9);
//        $special = '!@#$%^*()';
//        $arr[] = $special{mt_rand(0, 11)};
        shuffle($arr);
        return implode('', $arr);
    }

    /**
     * 获取随机数
     *
     * @param int $length
     * @param string $type (可选)
     * @return string
     */
    public static function getRandoms($length = 4, $type = '')
    {
        $returnStr = '';
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        if ($type == 'char') {
            $start = 10;
            $end = 61;
        } elseif ($type == 'num') {
            $start = 0;
            $end = 9;
        } else {
            $start = 0;
            $end = 61;
        }
        for ($i = 0; $i < $length; $i++) {
            $returnStr .= $pattern{mt_rand($start, $end)}; // 生成php随机数
        }
        return $returnStr;
    }


}
