<?php

namespace core_next;

class Tools
{
    static function viewsConvert($num)
    {
        if ($num >= 100000) {
            $num = round($num / 10000) . 'W+';
        } else if ($num >= 10000) {
            $num = round($num / 10000, 1) . 'W+';
        } else if ($num >= 1000) {
            $num = round($num / 1000, 1) . 'K+';
        }
        return $num;
    }

    static function sessionHasLike($post_id)
    {

        $data = [];
        if (!isset($_COOKIE['cp_like'])) {
            $data[] = $post_id;
            setcookie('cp_like', json_encode($data), time() + 3600 * 24 * 30, '/');
            return true;
        } else {
            $json = json_decode(stripslashes($_COOKIE['cp_like']), true);
            if (is_array($json)) {
                if (!in_array($post_id, $json)) {
                    $json[] = $post_id;
                    setcookie('cp_like', json_encode($json), time() + 3600 * 24 * 30, '/');
                    return true;
                } else {
                    return false;
                }
            } else {
                $data[] = $post_id;
                setcookie('cp_like', json_encode($data), time() + 3600 * 24 * 30, '/');
                return true;
            }
        }
    }

    static function getIpAddress()
    {
        //ip是否来自共享互联网
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip_address = $_SERVER['HTTP_CLIENT_IP'];
        } //ip是否来自代理
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } //ip是否来自远程地址
        else {
            $ip_address = $_SERVER['REMOTE_ADDR'];
        }
        return $ip_address;
    }

    static function getShareUrl($type, $title, $summary)
    {
        $description = get_bloginfo('description');
        $url = urlencode(get_the_permalink());
        if ($type == 'qq') {
            return 'https://connect.qq.com/widget/shareqq/index.html?url=' . $url . '&title=' . urlencode($title) . '&source=' . urlencode(get_bloginfo('name')) . '&desc=' . urlencode($description) . '&pics=&summary=' . urlencode($summary);
        } else if ($type == 'weibo') {
            return 'https://service.weibo.com/share/share.php?url=' . $url . '&title=' . urlencode($summary) . '&pic=&appkey=&searchPic=true';
        } else if ($type = 'qzone') {
            return 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' . $url . '&title=' . urlencode($title) . '&pics=&summary=' . urlencode($summary);
        } else {
            return '';
        }
    }


    static function generateCaptchaBase64($code)
    {
        $image = imagecreatetruecolor(100, 30);//imagecreatetruecolor函数建一个真彩色图像
//生成彩色像素
        $bgcolor = imagecolorallocate($image, 255, 255, 255);//白色背景     imagecolorallocate函数为一幅图像分配颜色
        $textcolor = imagecolorallocate($image, 0, 0, 255);//蓝色文本
//填充函数，xy确定坐标，color颜色执行区域填充颜色
        imagefill($image, 0, 0, $bgcolor);
        $captch_code = "";//初始空值
//该循环,循环取数
        /* for ($i = 0; $i < 4; $i++) {
             $fontsize = 8;
             $x = ($i * 25) + rand(5, 10);
             $y = rand(5, 10);//位置随机
             $data = strtoupper('abcdefghijkmnpqrstuvwxyz3456789');
             $fontcontent = substr($data, rand(0, strlen($data) - 1), 1);//strlen仅仅是一个计数器的工作  含数字和字母的验证码
             //可以理解为数组长度0到30
             $fontcolor = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));//随机的rgb()值可以自己定

             imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); //水平地画一行字符串

             $captch_code .= $fontcontent;
         }*/
        for ($i = 0; $i < strlen($code); $i++) {
            $fontcontent = $code[$i];
            $x = ($i * 25) + rand(5, 10);
            $y = rand(5, 10);//位置随机
            $fontsize = 8;
            $fontcolor = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));//随机的rgb()值可以自己定
            imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
        }

        //该循环,循环画背景干扰的点
        for ($m = 0; $m <= 600; $m++) {
            $x2 = rand(1, 99);
            $y2 = rand(1, 99);
            $pointcolor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imagesetpixel($image, $x2, $y2, $pointcolor);// 水平地画一串像素点
        }

        //该循环,循环画干扰直线
        for ($i = 0; $i <= 10; $i++) {
            $x1 = rand(0, 99);
            $y1 = rand(0, 99);
            $x2 = rand(0, 99);
            $y2 = rand(0, 99);
            $linecolor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imageline($image, $x1, $y1, $x2, $y2, $linecolor);//画一条线段

        }
        ob_start();
        imagepng($image);
        $contents = ob_get_contents();
        ob_end_clean();
        $base64 = base64_encode($contents);
        // 释放画布资源
        imagedestroy($image);
        return $base64;
    }

    static function generateRandomString($length, $type = 'all')
    {
        if ($type === 'all') {
            $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        } else {
            $chars = '0123456789';
        }
        $charsLength = strlen($chars);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $chars[rand(0, $charsLength - 1)];
        }
        return $randomString;
    }

    static function getMailHTML($title, $content)
    {
        $data['title'] = $title;
        $data['content'] = $content;
        $data['site_name'] = get_bloginfo('name');
        $data['site_url'] = get_bloginfo('siteurl');
        return Template::getTemplateHtml('mail', $data);
    }

    static function sendMail($mail, $mail_title, $content_title, $content)
    {
        $headers = array('Content-Type: text/html; charset=UTF-8');
        $html = Tools::getMailHTML($content_title, $content);
        return wp_mail($mail, $mail_title, $html, $headers);
    }

    static function validatePassword($password)
    {
        return preg_match('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/', $password);
    }

    static function validationMailCode($par_name, $count_down)
    {
        session_start();
        if (isset($_SESSION[$par_name])) {
            // 获取当前时间戳
            $current_time = time();
            // 计算时间戳之间的差异
            $time_diff = $current_time - $_SESSION[$par_name];
            // 检查时间差是否超过
            $need_time = $count_down - $time_diff;
            if ($time_diff < $count_down) {
                return $need_time;
            } else {
                return 0;
            }
        }
        return 0;
    }

    static function hasSpecialCharacters($text)
    {
        $pattern = '/[~`!#$%\^&*+=\-\[\]\\\'";,/{}|\\":<>\?]/';
        return preg_match($pattern, $text) === 1;
    }

    static function delDir($dir)
    {
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            if (is_dir("$dir/$file")) {
                $del_re = self::delDir("$dir/$file");
            } else {
                $del_re = unlink("$dir/$file");
            }
        }

        return rmdir($dir);
    }

    static function convertToChineseNumber($number)
    {
        $chineseNumber = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二');
        return $chineseNumber[$number];
    }

    static function substr($str, $start, $length, $charset = "utf-8", $suffix = true)
    {
        //中英文混合截取
        switch ($charset) {
            case 'utf-8':
                $char_len = 3;
                break;
            case 'UTF8':
                $char_len = 3;
                break;
            default:
                $char_len = 2;
        }
        // 小于指定长度，直接返回
        if (strlen($str) <= ($length * $char_len)) {
            return $str;
        }
        if (function_exists("mb_substr")) {
            $slice = mb_substr($str, $start, $length, $charset);
        } else if (function_exists('iconv_substr')) {
            $slice = iconv_substr($str, $start, $length, $charset);
        } else {
            $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("", array_slice($match[0], $start, $length));
        }
        if ($suffix) {
            return $slice;
        }
        return $slice;
    }

    static function getWeekdayName()
    {
        //$weekdays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        $weekdays = array('星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
        $currentWeekday = date('w'); // 返回值为0-6，0代表周日，1代表周一，以此类推
        return $weekdays[$currentWeekday];
    }

    /**
     * buildUrl
     * 拼接url
     * @param string $baseURL 基于的url
     * @param array $keysArr 参数列表数组
     * @return string           返回拼接的url
     */
    static function buildUrl($baseURL, $keysArr)
    {
        $combined = $baseURL . "?";
        $valueArr = array();

        foreach ($keysArr as $key => $val) {
            $valueArr[] = "$key=$val";
        }

        $keyStr = implode("&", $valueArr);
        $combined .= ($keyStr);

        return $combined;
    }

    /** 获取真实IP
     * @return mixed|string
     */
    static function getRealIP()
    {
        $ip = false;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = false;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!preg_match("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }

        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    static function isUrl($url)
    {
        if (!empty($url)) {
            // 使用filter_var()函数和FILTER_VALIDATE_URL过滤器验证URL
            return filter_var($url, FILTER_VALIDATE_URL);
        }
        return false;
    }



}