<?php

namespace core_next;

class Ajax
{
    static function init()
    {
        add_action('wp_ajax_' . Config::$theme_name, array(static::class, 'ajax'));
        add_action('wp_ajax_nopriv_' . Config::$theme_name, array(static::class, 'ajax'));

        add_action('wp_enqueue_scripts', function () {
            wp_enqueue_script('gh-query', 'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js', [], '1.0', ['in_footer' => true]);
        });
    }

    static function ajax()
    {
        $fun_name = $_POST['fun'];
        if (!isset($fun_name)) {
            $fun_name = $_GET['fun'];
            if (!isset($fun_name)) {
                $fun_name = 'error';
            }
        }
        call_user_func(array(static::class, $fun_name));
    }

    static private function setAjaxDataAndDie($code, $msg = '', $data = null)
    {
        $_data['code'] = $code;
        $_data['msg'] = $msg;
        if ($data != null) {
            $_data['data'] = $data;
        }
        wp_die(json_encode($_data, JSON_UNESCAPED_UNICODE));
    }

    static private function validationParameters($arr)
    {
        $parameter = [];
        foreach ($arr as $item) {
            if ($item[1] == 1) {
                if (!isset($_POST[$item[0]])) {
                    self::setAjaxDataAndDie(500, '参数错误');
                }
                $parameter[$item[0]] = $_POST[$item[0]];
            } else {
                if (!isset($_GET[$item[0]])) {
                    self::setAjaxDataAndDie(500, '参数错误');
                }
                $parameter[$_GET[0]] = $_GET[$item[0]];
            }
        }

        return $parameter;
    }

    static private function needLogin($user_type = 'user')
    {
        if (!is_user_logged_in()) {
            self::setAjaxDataAndDie(500, '无权限访问');
        }
        if ($user_type == 'admin') {
            if (!WordPress::isAdmin()) {
                self::setAjaxDataAndDie(500, '权限不足');
            }
        }
    }

    static private function needNotLogin()
    {
        if (WordPress::isLogin()) {
            self::setAjaxDataAndDie(500, '您已经登录');
        }
    }

    static function saveSet()
    {
        self::needLogin('admin');
        $arr = [['data', 1]];
        $arr = self::validationParameters($arr);
        $re = Options::saveSet($arr['data']);
        $code = 500;
        if ($re) {
            $code = 200;
        }
        self::setAjaxDataAndDie($code);
    }

    static function getPostList()
    {
        $arr = [['paged', 1], ['cat_id', 1]];
        $arr = self::validationParameters($arr);
        $list = WordPress::getPostList($arr['paged'], $arr['cat_id']);
        $list = Theme::handleRandomThumbnail($list);
        $html = '';
        foreach ($list as $item) {
            $html .= Template::getTemplateHtmlByDOMDocument('post-item', $item);
        }
        self::setAjaxDataAndDie(200, 'success', $html);
    }


    static function getComment()
    {
        $arr = [['paged', 1], ['post_id', 1]];
        $arr = self::validationParameters($arr);
        if (WordPress::isLogin()) {
            $current_user = wp_get_current_user();
            $mail = $current_user->user_email;
        } else {
            if (isset($_POST['mail'])) {
                $mail = $arr['mail'];
            } else {
                $mail = '';
            }
        }
        self::setAjaxDataAndDie(200, 'success', WordPress::getCommentsList($arr['post_id'], $arr['paged'], 10, $mail));
    }

    static function comment()
    {
        global $core_next_set;
        if (get_option('comment_registration') && !WordPress::isLogin()) {
            self::setAjaxDataAndDie(500, '请登录后评论');
        }
        if (WordPress::isLogin()) {
            $arr = [['post_id', 1], ['parent', 1], ['content', 1], ['is_win11', 1]];
        } else {
            if ($core_next_set['open_user_website_url']) {
                $arr = [['post_id', 1], ['parent', 1], ['content', 1], ['user_name', 1], ['user_mail', 1], ['user_url', 1], ['is_win11', 1]];
            } else {
                $arr = [['post_id', 1], ['parent', 1], ['content', 1], ['user_name', 1], ['user_mail', 1], ['is_win11', 1]];
            }
        }
        $arr = self::validationParameters($arr);
        $ua = $_SERVER['HTTP_USER_AGENT'];
        if ($arr['is_win11'] == 'true') {
            $ua = str_replace('Windows NT 10.0', 'Windows 11', $ua);
        }

        $login_approve = 1;
        $not_login_approve = 1;
        if ($core_next_set['comment_approve']) {
            if ($core_next_set['comment_approve_type'] === 'all') {
                $login_approve = 0;
                $not_login_approve = 0;
            } elseif ($core_next_set['comment_approve_type'] === 'not_login') {
                $not_login_approve = 0;
            }
        }
        $user_mail = '';
        if (WordPress::isLogin()) {
            $current_user = wp_get_current_user(); // 获取当前用户
            $my_comment = array(
                'comment_post_ID' => $arr['post_id'],  // 文章ID
                'comment_author' => $current_user->display_name, // 当前用户的显示名称
                'comment_author_email' => $current_user->user_email, // 当前用户的电子邮件地址
                'comment_author_url' => $current_user->user_url, // 当前用户的网站URL
                'comment_content' => $arr['content'], // 评论内容
                'comment_date' => current_time('mysql'), // 评论发表的时间
                'comment_parent' => $arr['parent'],
                'comment_agent' => $ua,
                'user_id' => $current_user->ID,
                'comment_approved' => $login_approve,
                'comment_author_IP' => Tools::getRealIP()
            );
            $user_mail = $current_user->user_email;
        } else {
            $comment_author_url = '';
            if ($core_next_set['open_user_website_url']) {
                $comment_author_url = $arr['user_url'];
            }
            $my_comment = array(
                'comment_post_ID' => $arr['post_id'],  // 文章ID
                'comment_author' => $arr['user_name'], // 当前用户的显示名称
                'comment_author_email' => $arr['user_mail'], // 当前用户的电子邮件地址
                'comment_content' => $arr['content'], // 评论内容
                'comment_date' => current_time('mysql'), // 评论发表的时间
                'comment_parent' => $arr['parent'],
                'comment_agent' => $ua,
                'comment_approved' => $not_login_approve,
                'comment_author_url' => $comment_author_url
            );
            $user_mail = $arr['user_mail'];
        }
        if ($core_next_set['comment_approve']) {
            //关键词匹配
            if (WordPress::commentKeyWordApprove($arr['content'])) {
                $my_comment['comment_approved'] = 0;
            }
            if (WordPress::commentKeyWordBan($arr['content'])) {
                self::setAjaxDataAndDie(500, '此内容禁止评论');
            }
        }
        $re = wp_insert_comment($my_comment);
        $approve_text = '';
        if ($my_comment['comment_approved'] == 0) {
            $approve_text = '，审核成功后会显示';
        }
        setcookie('core_comment_mail', $user_mail, time() + 3600 * 24 * 7, '/');
        if ($re !== false) {
            $ip = Tools::getRealIP();
            if ($ip !== false) {
                $ip_info = Theme::getIPLocationInfo($core_next_set['comment_location_type'], $ip);
                if ($ip_info !== false) {
                    add_comment_meta($re, 'core_ip_place', $ip_info);
                }
            }
            self::setAjaxDataAndDie(200, '评论成功' . $approve_text);
        } else {
            self::setAjaxDataAndDie(500, '评论失败');
        }
    }

    static function addLike()
    {
        $arr = [['post_id', 1]];
        $arr = self::validationParameters($arr);
        $post_id = $arr['post_id'];
        $re = Tools::sessionHasLike($post_id);
        if ($re === true) {
            $like = (int)get_post_meta($post_id, 'cp_like', true) + 1;
            update_post_meta($post_id, 'cp_like', $like);
            self::setAjaxDataAndDie(200, 'success', $like);
        } else {
            self::setAjaxDataAndDie(500, 'liked');
        }
    }

    static function getPosterHTML()
    {
        global $core_next_set;
        $arr = [['post_id', 1]];
        $arr = self::validationParameters($arr);
        $post_id = $arr['post_id'];
        $post_data = WordPress::getPostMetaData(get_post($post_id));
        $data['poster_img'] = null;
        if (!empty($post_data['thumbnail'])) {
            $file = file_get_contents($post_data['thumbnail']);
            if ($file !== false) {
                $data['poster_img'] = base64_encode($file);
            }
        }
        $data['title'] = $post_data['title'];
        $data['author_name'] = $post_data['author_name'];
        $data['post_excerpt'] = $post_data['post_excerpt'];
        $data['site_logo'] = base64_encode(file_get_contents($core_next_set['logo']));
        $html = Template::getTemplateHtml('poster-html', $data);
        self::setAjaxDataAndDie(200, '', $html);
    }

    static function getCaptchaBase64()
    {

        $code = Tools::generateRandomString(4);
        $base64 = Tools::generateCaptchaBase64($code);
        session_start();
        $_SESSION["captcha"] = $code;
        self::setAjaxDataAndDie(200, 'success', $base64);
    }

    static function login()
    {
        self::needNotLogin();
        self::validationCaptcha();
        $arr = [['user_login', 1], ['user_password', 1], ['remember', 1], ['code', 1]];
        $arr = self::validationParameters($arr);
        $user = wp_signon($arr, true);
        if (is_wp_error($user)) {
            self::setAjaxDataAndDie(500, '账号密码错误');
        } else {
            wp_set_current_user($user->ID);
            wp_set_auth_cookie($user->ID, true);
            self::setAjaxDataAndDie(200, '登录成功');
        }
    }

    static function validationCaptcha()
    {
        $arr = [['code', 1]];
        $arr = self::validationParameters($arr);
        session_start();
        if (strtolower($_SESSION["captcha"]) !== strtolower($arr['code'])) {
            $data[] = $_SESSION["captcha"];
            $data[] = $arr['code'];
            self::setAjaxDataAndDie(500, '验证码错误', $data);
        }
    }

    static function testSendMail()
    {
        self::needLogin();
        $arr = [['mail_user', 1], ['mail_password', 1], ['mail_host', 1], ['mail_port', 1],
            ['mail_encrypt', 1], ['mail_from_name', 1], ['mail_test_mail', 1]];
        $arr = self::validationParameters($arr);
        add_action('phpmailer_init', function ($phpmailer) use ($arr) {
            $phpmailer->isSMTP();
            $phpmailer->Host = $arr['mail_host'];
            $phpmailer->SMTPAuth = true;
            $phpmailer->Port = $arr['mail_port'];
            $phpmailer->Username = $arr['mail_user'];
            $phpmailer->Password = $arr['mail_password'];
            $phpmailer->SMTPSecure = $arr['mail_encrypt'] == 'ssl' ? 'ssl' : false;
            $phpmailer->From = $arr['mail_user'];
            $phpmailer->FromName = $arr['mail_from_name'];
        });

        $re = Tools::sendMail($arr['mail_test_mail'], $arr['mail_from_name'] . '测试邮件', '测试邮件', '看到这一封邮件，说明邮件服务器配置成功');

        if ($re) {
            self::setAjaxDataAndDie(200);
        } else {
            self::setAjaxDataAndDie(500);
        }
    }

    static function getLostPassMailCode()
    {
        $arr = [['mail', 1]];
        $arr = self::validationParameters($arr);
        $email_exists = email_exists($arr['mail']);
        if (!$email_exists) {
            self::setAjaxDataAndDie(500, '邮箱不存在');
        }
        $re_time = Tools::validationMailCode('lost_pass_mail_code_time', 60);
        if ($re_time > 0) {
            self::setAjaxDataAndDie(501, '请过' . $re_time . '秒后再发送', $re_time);
        }
        $code = Tools::generateRandomString(4);
        global $core_next_set;
        $re = Tools::sendMail($arr['mail'], sprintf('【%s】重置密码验证码', $core_next_set['mail_from_name']), '重置密码验证码', '您正在进行网站重置密码操作，您的验证码是<span style="color:red">' . $code . '</span><br>如果这不是您的操作请忽略。');
        if ($re) {
            session_start();
            $_SESSION['lost_pass_mail_code_time'] = time();
            $_SESSION['lost_pass_mail_code'] = $code;
            $_SESSION['lost_pass_mail'] = $arr['mail'];
            self::setAjaxDataAndDie(200, '发送邮件成功，10分钟内有效');
        } else {
            self::setAjaxDataAndDie(500, '发送邮件失败，请重新尝试。或者联系管理员');
        }
    }

    static function resetPassword()
    {
        $arr = [['mail', 1], ['mail_code', 1], ['password', 1]];
        $arr = self::validationParameters($arr);
        //验证码邮箱
        $email_exists = email_exists($arr['mail']);
        if (!$email_exists) {
            self::setAjaxDataAndDie(500, '邮箱不存在');
        }
        //验证code
        $re_time = Tools::validationMailCode('lost_pass_mail_code_time', 600);
        if ($re_time == 0) {
            self::setAjaxDataAndDie(500, '验证码已失效，请重新获取');
        }
        session_start();
        $code = $_SESSION['lost_pass_mail_code'];
        if ($arr['mail_code'] !== $code || $_SESSION['lost_pass_mail'] !== $arr['mail']) {
            self::setAjaxDataAndDie(500, '邮箱验证码错误');
        }
        //验证密码
        $re = Tools::validatePassword($arr['password']);
        if (!$re) {
            self::setAjaxDataAndDie(500, '密码不符合规则');
        }
        //重置密码
        $user = get_user_by('email', $arr['mail']);
        $new_password = $arr['password'];
        wp_set_password($new_password, $user->ID);
        $user_new = get_user_by('email', $arr['mail']);
        if (wp_check_password($new_password, $user_new->user_pass, $user->ID)) {
            $_SESSION['lost_pass_mail_code'] = '';
            $_SESSION['lost_pass_mail'] = '';
            self::setAjaxDataAndDie(200, '修改成功，请重新登录');
        } else {
            self::setAjaxDataAndDie(500, '修改失败');
        }
    }

    static function getRegUserCode()
    {
        $arr = [['mail', 1]];
        $arr = self::validationParameters($arr);
        //白名单验证
        global $core_next_set;
        if ($core_next_set['mail_white_list_open']) {
            if (!Theme::verifyMailWhitelist($arr['mail'])) {
                self::setAjaxDataAndDie(500, '当前邮箱不支持，请更换常用邮箱');
            }
        }
        $email_exists = email_exists($arr['mail']);
        if ($email_exists) {
            self::setAjaxDataAndDie(500, '邮箱已存在，请直接登录');
        }
        $re_time = Tools::validationMailCode('reg_mail_code_time', 60);
        if ($re_time > 0) {
            self::setAjaxDataAndDie(501, '请过' . $re_time . '秒后再发送', $re_time);
        }
        $code = Tools::generateRandomString(4);
        global $core_next_set;
        $re = Tools::sendMail($arr['mail'], sprintf('【%s】注册用户验证码', $core_next_set['mail_from_name']), '注册用户验证码', '您正在注册本站用户操作，您的验证码是<span style="color:red">' . $code . '</span><br>如果这不是您的操作请忽略。');
        if ($re) {
            session_start();
            $_SESSION['reg_mail_code_time'] = time();
            $_SESSION['reg_mail_code'] = $code;
            $_SESSION['reg_mail'] = $arr['mail'];
            self::setAjaxDataAndDie(200, '发送邮件成功，10分钟内有效');
        } else {
            self::setAjaxDataAndDie(500, '发送邮件失败，请重新尝试。或者联系管理员');
        }
    }

    static function regUser()
    {
        global $core_next_set;
        $arr = [['mail', 1], ['mail_code', 1], ['password', 1]];
        $arr = self::validationParameters($arr);
        if (!get_option('users_can_register')) {
            self::setAjaxDataAndDie(500, '本站已关闭注册');
        }

        $email_exists = email_exists($arr['mail']);
        if ($email_exists) {
            self::setAjaxDataAndDie(500, '邮箱已存在，请直接登录');
        }
        if (!$core_next_set['close_reg_mail_verify']) {
            $re_time = Tools::validationMailCode('reg_mail_code_time', 600);
            if ($re_time == 0) {
                self::setAjaxDataAndDie(500, '验证码已失效，请重新获取');
            }
        }

        $re = Tools::validatePassword($arr['password']);
        if (!$re) {
            self::setAjaxDataAndDie(500, '密码不符合规则');
        }

        if (!$core_next_set['close_reg_mail_verify']) {
            //验证码验证码
            session_start();
            $code = $_SESSION['reg_mail_code'];
            if ($arr['mail_code'] !== $code || $_SESSION['reg_mail'] !== $arr['mail']) {
                self::setAjaxDataAndDie(500, '邮箱验证码错误');
            }
        }
        //开始注册
        $username = time();
        $user_id = wp_create_user($username, $arr['password'], $arr['mail']);
        if ($user_id) {
            $user = new \WP_User($user_id);
            $user->set_role('subscriber');
            $user->display_name = substr($username, -8);
            wp_update_user($user);
            $_SESSION['reg_mail_code'] = '';
            $_SESSION['reg_mail'] = '';
            self::setAjaxDataAndDie(200, '注册用户成功，请登录');
        } else {
            self::setAjaxDataAndDie(500, '注册用户失败');
        }
    }

    static function editorPowerHtml()
    {
        self::needLogin('admin');
        self::setAjaxDataAndDie(200, '', base64_encode(Template::getTemplateHtml('editor-power', [])));
    }

    static function getPwdShowContent()
    {
        $arr = [['pwd', 1], ['post_id', 1], ['index', 1]];
        $arr = self::validationParameters($arr);
        $post = get_post($arr['post_id']);
        $content = $post->post_content;
        $shortcode_data = WordPress::parseShortcode('pwdshow', $content, $arr['index']);
        $par = shortcode_atts([
            'pwd' => ''
        ], $shortcode_data['attrs']);
        if ($par['pwd'] == '') {
            self::setAjaxDataAndDie(500, '密码设置不正确，请联系管理员修改');
        } else if ($par['pwd'] == $arr['pwd']) {
            $html = do_shortcode($shortcode_data['content']);
            self::setAjaxDataAndDie(200, 'success', $html);
        } else {
            self::setAjaxDataAndDie(500, '密码错误，请重新尝试');
        }
    }

    static function updateUserInfo()
    {
        self::needLogin();
        global $core_next_set;
        $arr = [['display_name', 1], ['user_description', 1]];
        if ($core_next_set['open_user_website_url']) {
            $arr = [['display_name', 1], ['user_description', 1], ['user_url', 1]];
        }
        $arr = self::validationParameters($arr);
        if (Tools::hasSpecialCharacters($arr['display_name']) || Tools::hasSpecialCharacters($arr['user_description'])) {
            self::setAjaxDataAndDie(500, '内容包含特殊字符');
        }
        $user_url = '';
        if ($core_next_set['open_user_website_url']) {
            if (Tools::isUrl($arr['user_url'])) {
                $user_url = $arr['user_url'];
            }
        }
        $user_id = get_current_user_id();
        $user_data = array(
            'ID' => $user_id,
            'display_name' => $arr['display_name'],
            'description' => $arr['user_description'],
            'user_url' => $user_url
        );
        if (wp_update_user($user_data)) {
            self::setAjaxDataAndDie(200, 'success');
        } else {
            self::setAjaxDataAndDie(500, 'error');
        }
    }

    static function getResetPasswordMailCode()
    {
        self::needLogin();
        $user_data = get_userdata(get_current_user_id());
        $user_email = $user_data->user_email;
        $re_time = Tools::validationMailCode('get_reset_mail_code_time', 60);
        if ($re_time > 0) {
            self::setAjaxDataAndDie(501, '请过' . $re_time . '秒后再发送', $re_time);
        }
        $code = Tools::generateRandomString(4);
        global $core_next_set;
        $re = Tools::sendMail($user_email, sprintf('【%s】重置密码验证码', $core_next_set['mail_from_name']), '重置密码验证码', '您正在进行网站重置密码操作，您的验证码是<span style="color:red">' . $code . '</span><br>如果这不是您的操作请忽略。');
        if ($re) {
            session_start();
            $_SESSION['get_reset_mail_code_time'] = time();
            $_SESSION['get_reset_mail_code'] = $code;
            self::setAjaxDataAndDie(200, '发送邮件成功，10分钟内有效');
        } else {
            self::setAjaxDataAndDie(500, '发送邮件失败，请重新尝试。或者联系管理员');
        }
    }

    static function resetPasswordLogind()
    {
        self::needLogin();
        $arr = [['password', 1], ['code', 1]];
        $arr = self::validationParameters($arr);

        //验证code
        session_start();
        $get_mail_time = $_SESSION['get_reset_mail_code_time'];
        $now_time = time();
        if ($now_time - $get_mail_time > 600) {
            $data['get_mail_time'] = $get_mail_time;
            $data['now_time'] = $now_time;
            $data['time'] = $now_time - $get_mail_time;
            self::setAjaxDataAndDie(500, '验证码已失效，请重新获取', $data);
        }
        if (!Tools::validatePassword($arr['password'])) {
            self::setAjaxDataAndDie(500, '密码不符合规则');
        }

        session_start();
        $code = $_SESSION['get_reset_mail_code'];
        if ($code !== $arr['code']) {
            self::setAjaxDataAndDie(500, '邮箱验证码错误');
        }
        $_SESSION['get_reset_mail_code'] = '';
        $user_id = get_current_user_id();
        wp_set_password($arr['password'], $user_id);
        self::setAjaxDataAndDie(200, 'success');
    }

    static function checkUpdate()
    {
        self::needLogin('admin');
        global $core_next_expand_set;
        $core_next_expand_set = Options::getExpandOptions();
        $now_time = time();
        $info = [];
        $must_get = false;
        if (isset($_POST['must_get'])) {
            $must_get = true;
        }

        if ($now_time - $core_next_expand_set['last_check_time'] > 3600 || $must_get === true) {
            $info = Theme::getServeThemeInfo();
            if ($info === false) {
                self::setAjaxDataAndDie(500, 'error');
            }
            $info['can_update'] = false;
            if ($info['version'] > Config::$theme_version) {
                $core_next_expand_set['need_update'] = true;
                $info['can_update'] = true;
            } else {
                $core_next_expand_set['need_update'] = false;
            }
            $core_next_expand_set['last_check_time'] = time();
            Options::saveExpandSet($core_next_expand_set);
        }
        self::setAjaxDataAndDie(200, 'success', $info);
    }

    static function startUpdate()
    {
        if (Config::$is_development) {
            //  self::setAjaxDataAndDie(500, '当前为开发模式');
        }
        $info = Theme::getServeThemeInfo();
        if ($info !== false) {
            if ($info['version'] > Config::$theme_version) {
                //准备更新
                if (isset($info['down_url'])) {
                    $url = $info['down_url'];
                    $dir = dirname(get_template_directory()) . '/core_next_tmp';
                    if (!is_dir($dir)) {
                        mkdir($dir);
                    }
                    $file_name = time() . '.zip';
                    $response = wp_remote_get($url);
                    if (is_wp_error($response)) {
                        self::setAjaxDataAndDie(500, '主题下载失败，请尝试手动安装');
                    } else {
                        $remote_zip = wp_remote_retrieve_body($response);
                        $write_re = file_put_contents($dir . "/{$file_name}", $remote_zip);
                        if ($write_re === false) {
                            self::setAjaxDataAndDie(500, '文件写入失败', $dir);
                        }
                    }
                    //self::setAjaxDataAndDie(500, '已暂停', $dir);
                    $file_path = $dir . '/' . $file_name;
                    if (strtoupper(md5_file($file_path)) != $info['md5']) {
                        Tools::delDir($dir);
                        self::setAjaxDataAndDie(500, '更新失败，文件校验失败，请手动更新');
                    }
                    $zip = new \ZipArchive();
                    if ($zip->open($file_path) === true) {
                        $zip->extractTo(dirname(get_template_directory()));
                        $zip->close();
                        Tools::delDir($dir);
                    } else {
                        Tools::delDir($dir);
                        self::setAjaxDataAndDie(500, '解压失败，可能没有权限');
                    }
                    global $core_next_expand_set;
                    $core_next_expand_set = Options::getExpandOptions();
                    $core_next_expand_set['need_update'] = false;
                    Options::saveExpandSet($core_next_expand_set);
                    self::setAjaxDataAndDie(200, '更新成功，请刷新！');
                } else {
                    self::setAjaxDataAndDie(500, '更新失败，未获取到下载地址');
                }
            }
        }
    }


    static function otherLoginCreateUser()
    {
        $arr = [['mail', 1], ['mail_code', 1]];
        $arr = self::validationParameters($arr);
        session_start();
        if (!isset($_SESSION['core_next_bind_type'])) {
            self::setAjaxDataAndDie(500, '绑定错误，请重新登陆');
        }
        if (!isset($_SESSION['core_next_open_id'])) {
            self::setAjaxDataAndDie(500, '参数错误，请重新登陆');
        }
        if (!isset($_SESSION['other_login_create_code_time']) || !isset($_SESSION['other_login_create_code']) || !isset($_SESSION['other_login_create_mail'])) {
            self::setAjaxDataAndDie(500, '参数错误，请尝试重新获取验证码');
        }

        $bind_type = $_SESSION['core_next_bind_type'];
        $open_id = $_SESSION['core_next_open_id'];
        $last_get_code_time = $_SESSION['other_login_create_code_time'];
        $mail_code = $_SESSION['other_login_create_code'];
        $mail = $_SESSION['other_login_create_mail'];
        //判断验证码和超时
        $time = time();
        $timeout = 60 * 10;
        if ($time - $last_get_code_time > $timeout) {
            self::setAjaxDataAndDie(500, '验证码超时，请重新获取');
        }
        if ($mail !== $arr['mail']) {
            self::setAjaxDataAndDie(500, '邮箱不匹配');
        }
        if ($mail_code !== $arr['mail_code']) {
            self::setAjaxDataAndDie(500, '验证码错误，请重新获取');
        }
        $user = get_user_by('email', $mail);
        if ($user) {
            self::setAjaxDataAndDie(500, '用户已存在，请直接绑定账号');
        }

        if ($bind_type === 'qq') {
            $username = time();
            $user_id = wp_create_user($username, $arr['password'], $arr['mail']);
            if ($user_id) {
                $user = new \WP_User($user_id);
                $user->set_role('subscriber');
                $user->display_name = substr($username, -8);
                wp_update_user($user);
                $_SESSION['other_login_create_code'] = '';
                $_SESSION['other_login_create_code_time'] = 0;
                update_user_meta($user_id, 'corepress_thirdparty_qq', $open_id);
                self::setAjaxDataAndDie(200, '绑定成功，请重新登陆。跳转中，请稍后');
            } else {
                self::setAjaxDataAndDie(500, '注册用户失败');
            }

        } else {
            self::setAjaxDataAndDie(500, '找不到绑定项目');
        }

    }

    static function otherLoginBindUser()
    {
        $arr = [['mail', 1], ['mail_code', 1]];
        $arr = self::validationParameters($arr);
        session_start();
        if (!isset($_SESSION['core_next_bind_type'])) {
            self::setAjaxDataAndDie(500, '绑定错误，请重新登陆');
        }
        if (!isset($_SESSION['core_next_open_id'])) {
            self::setAjaxDataAndDie(500, '参数错误，请重新登陆');
        }

        if (!isset($_SESSION['other_login_bind_code_time']) || !isset($_SESSION['other_login_bind_code']) || !isset($_SESSION['other_login_bind_mail'])) {
            self::setAjaxDataAndDie(500, '参数错误，请尝试重新获取验证码');
        }

        $bind_type = $_SESSION['core_next_bind_type'];
        $open_id = $_SESSION['core_next_open_id'];
        $last_get_code_time = $_SESSION['other_login_bind_code_time'];
        $mail_code = $_SESSION['other_login_bind_code'];
        $mail = $_SESSION['other_login_bind_mail'];
        //判断验证码和超时
        $time = time();
        $timeout = 60 * 10;
        if ($time - $last_get_code_time > $timeout) {
            self::setAjaxDataAndDie(500, '验证码超时，请重新获取');
        }
        if ($mail !== $arr['mail']) {
            self::setAjaxDataAndDie(500, '邮箱不匹配');
        }
        if ($mail_code !== $arr['mail_code']) {
            self::setAjaxDataAndDie(500, '验证码错误，请重新获取');
        }
        //查询用户是否存在
        $user = get_user_by('email', $mail);
        if ($user === false) {
            self::setAjaxDataAndDie(500, '用户不存在，请注册新用户');
        }

        if ($bind_type === 'qq') {
            //判读是否有open_id
            $bind_open_id = get_user_meta($user->ID, 'corepress_thirdparty_qq', true);
            if ($bind_open_id) {
                self::setAjaxDataAndDie(500, '此账号已经绑定了QQ了，更换绑定请进入个人中心修改');
            }
            //不存在，则绑定
            update_user_meta($user->ID, 'corepress_thirdparty_qq', $open_id);
            self::setAjaxDataAndDie(200, '绑定成功，请重新登陆。跳转中，请稍后');
        } else {
            self::setAjaxDataAndDie(500, '找不到绑定项目');
        }
    }

    static function getOtherLoginMailCode()
    {
        $arr = [['mail', 1], ['type', 1]];
        $arr = self::validationParameters($arr);
        session_start();
        $now_time = time();
        $countdown = 60;
        $site_name = get_bloginfo('name');
        $code = Tools::generateRandomString(4);
        //判断是否在白名单
        global $core_next_set;
        if ($core_next_set['mail_white_list_open']) {
            if (!Theme::verifyMailWhitelist($arr['mail'])) {
                self::setAjaxDataAndDie(500, '当前邮箱不支持，请更换常用邮箱');
            }
        }

        if ($arr['type'] === 'create') {
            //超时判断
            if (isset($_SESSION['other_login_create_code_time']) && $now_time - $_SESSION['other_login_create_code_time'] < $countdown) {
                $_time = $countdown - ($now_time - $_SESSION['other_login_create_code_time']);
                self::setAjaxDataAndDie(500, '超时', $_time);
            } else {
                //判断邮箱是否存在
                $_SESSION['other_login_create_code_time'] = time();
                $_SESSION['other_login_create_code'] = $code;
                $_SESSION['other_login_create_mail'] = $arr['mail'];

                $email_exists = email_exists($arr['mail']);
                if ($email_exists) {
                    self::setAjaxDataAndDie(500, '邮箱已存在，请直接登录或选择绑定已有账号');
                } else {
                    //不存在，开始发邮件
                    $re = Tools::sendMail($arr['mail'], "【{$site_name}】账户注册验证码", '您正在本站进行社交账户注册操作', '您正在进行网站注册操作，您的验证码是<span style="color:red">' . $code . '</span><br>如果这不是您的操作请忽略。');
                    if ($re) {
                        self::setAjaxDataAndDie(200, '发送邮件成功，10分钟内有效');
                    } else {
                        self::setAjaxDataAndDie(500, '发送邮件失败，请联系管理员检查邮箱服务');
                    }
                }
            }
        } else {
            //绑定用户
            if (isset($_SESSION['other_login_bind_code_time']) && $now_time - $_SESSION['other_login_bind_code_time'] < $countdown) {
                $_time = $countdown - ($now_time - $_SESSION['other_login_bind_code_time']);
                self::setAjaxDataAndDie(500, '超时', $_time);
            } else {
                $_SESSION['other_login_bind_code_time'] = time();
                $_SESSION['other_login_bind_code'] = $code;
                $_SESSION['other_login_bind_mail'] = $arr['mail'];

                $user = get_user_by('email', $arr['mail']);
                if ($user === false) {
                    self::setAjaxDataAndDie(500, '邮箱不存在，请尝试创建新账号');
                } else {
                    //存在用户，判断要绑定哪个账户
                    if (!isset($_SESSION['core_next_bind_type'])) {
                        $data['type'] = 'bind_type_error';
                        self::setAjaxDataAndDie(500, '系统错误，请重新尝试第三方登录');
                    }
                    $bind_type = $_SESSION['core_next_bind_type'];
                    if ($bind_type === 'qq') {
                        //判断是否已经绑定了QQ
                        $open_id = get_user_meta($user->ID, 'corepress_thirdparty_qq', true);
                        if ($open_id) {
                            self::setAjaxDataAndDie(500, '此账号已经绑定了QQ了，更换绑定请进入个人中心修改');
                        }
                        //开始发邮件
                        $re = Tools::sendMail($arr['mail'], "【{$site_name}】账户绑定验证码", '您正在本站进行社交账户绑定操作', '您正在进行网站绑定操作，您的验证码是<span style="color:red">' . $code . '</span><br>如果这不是您的操作请忽略。');
                        if ($re) {
                            self::setAjaxDataAndDie(200, '发送邮件成功，10分钟内有效');
                        } else {
                            self::setAjaxDataAndDie(500, '发送邮件失败，请联系管理员检查邮箱服务');
                        }
                    }
                }
            }
        }
    }

    static function unsetOtherLoginBind()
    {
        $arr = [['type', 1]];
        $arr = self::validationParameters($arr);
        if ($arr['type'] === 'qq') {
            $user_id = get_current_user_id();
            if (delete_user_meta($user_id, 'corepress_thirdparty_qq')) {
                self::setAjaxDataAndDie(200, 'success');
            }
        }
        self::setAjaxDataAndDie(500, 'error');
    }

    static function testLocation()
    {
        self::needLogin();
        $arr = [['type', 1], ['key', 1]];
        $arr = self::validationParameters($arr);

        $info = Theme::getIPLocationInfo($arr['type'], '223.5.5.5', $arr['key']);
        if ($info !== false) {
            self::setAjaxDataAndDie(200, 'success', $info);
        }
        self::setAjaxDataAndDie(500, '获取IP失败');
    }

    static function getUserPost()
    {
        $arr = [['page', 1], ['user', 1]];
        $arr = self::validationParameters($arr);
        $user = get_user_by('login', $arr['user']);
        if ($user === false) {
            self::setAjaxDataAndDie(500, 'error');
        }
        $query = new \WP_Query(array('author' => $user->ID, 'posts_per_page' => 20, 'paged' => $arr['page']));
        $total_posts = $query->found_posts; // 获取总文章数
        $total_pages = $query->max_num_pages; // 计算总页数
        $post_list = [];
        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $post = get_post();
                $post_list[] = WordPress::getUserPostMeta($post);
            }
        }
        wp_reset_postdata();
        $data['list'] = $post_list;
        $data['post_count'] = $total_posts;
        $data['page_count'] = $total_pages;
        self::setAjaxDataAndDie(200, 'success', $data);
    }

    static function getUserComment()
    {
        $arr = [['page', 1], ['user', 1]];
        $arr = self::validationParameters($arr);
        $user = get_user_by('login', $arr['user']);
        if ($user === false) {
            self::setAjaxDataAndDie(500, 'error');
        }

        $comments_args = array(
            'user_id' => $user->ID,
            'status' => 'approve',
            'number' => 20,
            'paged' => $arr['page']
        );
        global $wpdb;
        $user_id = $user->ID;
        $sql = "SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id='$user_id' AND comment_approved = 1";
        $count = $wpdb->get_var($sql);

        $comments_query = new \WP_Comment_Query;
        $comments = $comments_query->query($comments_args);

        $comment_list = [];

        foreach ($comments as $item) {
            $info = WordPress::getUserCommentMeta($item);
            $post = get_post($info['post_id']);
            $info['post_title'] = $post->post_title;
            $info['post_url'] = get_the_permalink($post);
            unset($info['post_id']);
            $comment_list[] = $info;

        }

        $data['list'] = $comment_list;
        $data['comment_count'] = (int)$count;
        self::setAjaxDataAndDie(200, 'success', $data);
    }

    static function checkPostPassword()
    {
        $arr = [['pass', 1], ['post_id', 1]];
        $arr = self::validationParameters($arr);
        $post_object = get_post($arr['post_id']);
        if ($post_object->post_password == $arr['pass']) {
            $expire = apply_filters('post_password_expires', time() + 10 * DAY_IN_SECONDS);
            $referer = wp_get_referer();
            if ($referer) {
                $secure = ('https' === parse_url($referer, PHP_URL_SCHEME));
            } else {
                $secure = false;
            }
            setcookie('wp-postpass_' . COOKIEHASH, wp_hash_password(wp_unslash($arr['pass'])), $expire, COOKIEPATH, COOKIE_DOMAIN, $secure);
            self::setAjaxDataAndDie(200, 'success');
        } else {
            self::setAjaxDataAndDie(500, '密码错误');
        }
    }

    static function uploadAvatar()
    {
        self::needLogin();
        $arr = [['data', 1]];
        $arr = self::validationParameters($arr);
        $user_id = get_current_user_id();
        $user = get_userdata($user_id);
        $mail = $user->user_email;
        $data = explode(',', $arr['data'])[1];
        $re = Theme::createAvatar($data, $mail);
        if ($re !== false) {
            $_data['url'] = $re;
            self::setAjaxDataAndDie(200, 'success', $_data);
        } else {
            self::setAjaxDataAndDie(500, 'error');
        }
    }
}