<?php
/**
 * QQ空间服务类
 * 提供QQ空间各种操作API
 */

// 如果 get_curl_qzone 函数不存在，定义它
if (!function_exists('get_curl_qzone')) {
    function get_curl_qzone($url, $post = 0, $referer = 1, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $httpheader = [
            "Accept: application/json",
            "Accept-Encoding: gzip,deflate,sdch",
            "Accept-Language: zh-CN,zh;q=0.8",
            "Connection: close"
        ];

        if ($post && substr($post, 0, 1) == '{') {
            $httpheader[] = "Content-Type: application/json";
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);

        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }

        if ($header) {
            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://h5.qzone.qq.com/mqzone/index');
            } 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.4.1; zh-cn) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.5 Mobile Safari/533.1');
        }

        if ($nobaody) {
            curl_setopt($ch, CURLOPT_NOBODY, 1);
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }
}

class QzoneService {

    /**
     * 说说秒赞
     */
    public static function like_h5($uin, $skey, $pskey, $qzonetoken, $gtk, $touin, $appid, $unikey, $curkey) {
        $post = 'opuin=' . $touin . '&unikey=' . $unikey . '&curkey=' . $curkey . '&appid=' . $appid . '&opr_type=like&format=purejson';
        $url = 'https://h5.qzone.qq.com/proxy/domain/w.qzone.qq.com/cgi-bin/likes/internal_dolike_app?qzonetoken=' . $qzonetoken . '&g_tk=' . $gtk;
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $json = get_curl_qzone($url, $post, 1, $cookie);
        if ($json) {
            $arr = json_decode($json, true);
            if (isset($arr['ret']) && $arr['ret'] == 0) {
                return '赞 ' . $touin . ' 的说说成功';
            } elseif ($arr['ret'] == -3000) {
                return '赞' . $touin . '的说说失败！原因:SKEY已失效';
            } elseif (isset($arr['msg'])) {
                return '赞 ' . $touin . ' 的说说失败！原因:' . $arr['msg'];
            } else {
                return '赞 ' . $touin . ' 的说说失败！原因:' . $json;
            }
        } else {
            return '获取赞' . $touin . '的说说结果失败！';
        }
    }

    /**
     * 说说秒评
     */
    public static function comment_h5($uin, $skey, $pskey, $content, $touin, $ssid, $from, $richval = null) {
        $gtk = self::qzoneGetGTK($pskey);
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $post = 'topicId=' . $touin . '_' . $ssid . '__' . $from . '&feedsType=100&inCharset=utf-8&outCharset=utf-8&plat=qzone&source=ic&hostUin=' . $touin . '&isSignIn=&platformid=52&uin=' . $uin . '&format=json&ref=feeds&content=' . urlencode($content);
        if ($richval) {
            $post .= '&richval=' . $richval . '&richtype=1';
        } else {
            $post .= '&richval=&richtype=0';
        }
        $post .= '&private=0&paramstr=1&qzreferrer=http%3A%2F%2Fuser.qzone.qq.com%2F' . $uin;
        $url = 'https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_re_feeds?g_tk=' . $gtk;
        $ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36';
        $json = get_curl_qzone($url, $post, 'https://user.qzone.qq.com/' . $uin, $cookie, 0, $ua);

        $arr = json_decode($json, true);

        if (!is_array($arr)) {
            return '评论 ' . $touin . ' 的说说失败！原因:接口返回数据异常';
        }

        if (isset($arr['code']) && $arr['code'] == 0) {
            return '评论 ' . $touin . ' 的说说成功';
        } elseif (isset($arr['code']) && $arr['code'] == -3000) {
            return '评论 ' . $touin . ' 的说说失败！原因:SID已失效，请更新SID';
        } elseif (isset($arr['code']) && $arr['code'] == -3001) {
            return '评论 ' . $touin . ' 的说说失败！原因:需要验证码';
        } elseif (isset($arr['message'])) {
            if (strpos($arr['message'], '评论不符合安全规范') !== false) {
                return '评论 ' . $touin . ' 的说说失败！原因:频繁，可尝试修改评论内容';
            }
            // 空间开启评论审核时，接口会返回“评论成功...审核后显示”
            if (strpos($arr['message'], '评论成功') !== false || strpos($arr['message'], '审核') !== false) {
                return '评论 ' . $touin . ' 的说说成功（待审核）';
            }
            return '评论 ' . $touin . ' 的说说失败！原因:' . $arr['message'];
        } else {
            return '获取评论' . $touin . '的说说结果失败！';
        }
    }

    /**
     * 发布说说
     * @param string $uin QQ号
     * @param string $skey skey
     * @param string $pskey pskey
     * @param string $content 说说内容
     * @param string $richval 图片参数
     * @param string $listParam 可见好友列表（白名单模式）
     * @param array $denyUins 不可见好友列表（黑名单模式）
     */
    public static function shuos($uin, $skey, $pskey, $content, $richval = 0, $listParam = false, $denyUins = []) {
        try {
            $cookie = self::buildCookie($uin, $skey, $pskey);
            $gtk = self::qzoneGetGTK($pskey);
            $url = 'https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=' . $gtk;

            $post = 'syn_tweet_verson=1&paramstr=1&pic_template=';

            if ($richval) {
                $post .= "&richtype=1&richval=" . urlencode($richval) . "&special_url=&subrichtype=1";
            } else {
                $post .= "&richtype=&richval=&special_url=";
            }

            // 设置可见权限
            if ($listParam) {
                // 白名单模式：仅指定好友可见
                $post .= "&ugc_right=128&allow_uins=" . urlencode($listParam);
            } elseif (!empty($denyUins)) {
                // 黑名单模式：排除指定好友（所有人可见，但排除黑名单）
                // ugc_right=1 所有人可见，deny_uins 排除好友
                $post .= "&ugc_right=1&deny_uins=" . urlencode(implode(',', (array)$denyUins));
            } else {
                // 默认：所有人可见
                $post .= "&ugc_right=1";
            }

            $post .= "&subrichtype=&con=" . urlencode($content)
                . "&feedversion=1&ver=1&to_tweet=0&to_sign=0&hostuin=" . $uin
                . "&code_version=1&format=json&qzreferrer=http%3A%2F%2Fuser.qzone.qq.com%2F" . $uin . "%2F311";

            $json = get_curl_qzone($url, $post, 'https://user.qzone.qq.com/' . $uin . '/311', $cookie);
            $arr = json_decode($json, true);

            if (!isset($arr['code'])) {
                return ['code' => -1, 'msg' => '获取发布说说结果失败'];
            }

            switch ($arr['code']) {
                case 0:
                    return [
                        'code' => 0,
                        'msg' => $uin . ' 发布说说成功',
                        'tid' => $arr['tid'] ?? $arr['t1_tid'] ?? ''
                    ];
                case -3000:
                    return ['code' => -3000, 'msg' => $uin . ' 发布说说失败！原因:SID已失效'];
                case -3001:
                    return ['code' => -3001, 'msg' => $uin . ' 发布说说失败！原因:需要验证码'];
                default:
                    return ['code' => $arr['code'], 'msg' => $uin . ' 发布说说失败！原因:' . ($arr['message'] ?? '未知错误')];
            }
        } catch (Exception $e) {
            return ['code' => -1, 'msg' => '发布说说异常: ' . $e->getMessage()];
        }
    }

    /**
     * 转发说说
     */
    public static function pczhuanfa($uin, $skey, $pskey, $content, $touin, $ssid) {
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $gtk = self::qzoneGetGTK($pskey);
        $url = 'https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_forward_v6?g_tk=' . $gtk;
        $post = 'tid=' . $ssid . '&t1_source=1&t1_uin=' . $touin . '&signin=0&con=' . urlencode($content) . '&with_cmt=0&fwdToWeibo=0&forward_source=2&code_version=1&format=json&out_charset=UTF-8&hostuin=' . $uin . '&qzreferrer=https%3A%2F%2Fuser.qzone.qq.com%2F' . $uin . '%2Finfocenter';
        $json = get_curl_qzone($url, $post, 'https://user.qzone.qq.com/' . $uin . '/infocenter', $cookie);
        if ($json) {
            $arr = json_decode($json, true);
            if (isset($arr['code']) && $arr['code'] == 0) {
                return '转发 ' . $touin . ' 说说成功';
            } elseif ($arr['code'] == -3000) {
                return '转发 ' . $touin . ' 说说失败！原因:' . $arr['message'];
            } elseif (isset($arr['code'])) {
                return '转发 ' . $touin . ' 说说失败！原因:' . $arr['message'];
            } else {
                return '转发 ' . $touin . ' 说说失败！原因' . $json;
            }
        } else {
            return '获取转发 ' . $touin . ' 说说结果失败';
        }
    }

    /**
     * 空间签到
     */
    public static function cpqiandao($uin, $skey, $pskey, $qzonetoken, $gtk, $content) {
        try {
            $cookie = self::buildCookie($uin, $skey, $pskey);

            // 构建签到图片HTML
            $html = self::buildSignHtml($content);

            // 生成签到图片
            $richval = self::generateSignImage($gtk, $html, $cookie);
            if ($richval === false) {
                return ['code' => 301, 'msg' => '生成签到图片失败！'];
            }

            // 发布签到说说
            $url = 'https://h5.qzone.qq.com/webapp/json/publishDiyMood/publishmood?g_tk=' . $gtk . '&qzonetoken=' . $qzonetoken;

            $post = http_build_query([
                'uin' => $uin,
                'content' => $richval ? '' : $content,
                'issynctoweibo' => '0',
                'isWinPhone' => '2',
                'richtype' => $richval ? '1' : '0',
                'richval' => $richval,
                'sourceName' => '',
                'frames' => '10',
                'source.subtype' => '33',
                'extend_info.checkinfall' => '{"uuid":"' . time() . '123"}',
                'right_info.ugc_right' => '1',
                'stored_extend_info.is_diy' => '1',
                'stored_extend_info.event_tags' => '',
                'stored_extend_info.pic_jump_type' => '0',
                'stored_extend_info.signin_group_id' => '1',
                'stored_extend_info.signin_seal_id' => '285',
                'stored_extend_info.signin_op' => '1',
                'format' => 'json',
                'inCharset' => 'utf-8',
                'outCharset' => 'utf-8'
            ]);

            $json = get_curl_qzone($url, $post, 'https://h5.qzone.qq.com/checkinv2/editor?type=daily', $cookie);
            $arr = json_decode($json, true);

            if (isset($arr['ret']) && $arr['ret'] == 0) {
                return [
                    'code' => 200,
                    'msg' => $uin . ' 签到成功',
                    'tid' => $arr['data']['tid'] ?? ''
                ];
            }

            if (isset($arr['ret'])) {
                switch ($arr['ret']) {
                    case -3000:
                        return ['code' => 301, 'msg' => $uin . ' 签到失败！原因:SID已失效'];
                    case -3001:
                        return ['code' => 301, 'msg' => $uin . ' 签到失败！原因:需要验证码'];
                    default:
                        return ['code' => 301, 'msg' => $uin . ' 签到失败！原因:' . ($arr['msg'] ?? '未知错误')];
                }
            }

            return ['code' => 301, 'msg' => $uin . ' 签到失败！原因:' . $json];
        } catch (Exception $e) {
            return ['code' => 301, 'msg' => '签到异常: ' . $e->getMessage()];
        }
    }

    /**
     * 构建签到HTML
     */
    private static function buildSignHtml($content) {
        $month = date("F");
        $date = date("Y.m.d");
        return '<!DOCTYPE html><html style="background:transparent;"><head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="http://qzonestyle.gtimg.cn/touch/proj-qzone-app/checkin-pc/index.css"></head><body style="background:transparent;"><div class="checkIn-days" style="background: transparent;"><div class="template-area screenshot dark style-ten"><div class="pic-area j-pic-area"><div class="upload-pic j-upload-pic"><img src="https://qresource.cdn-go.cn/qzone-checkin/069cf0a6/kongjianqiandao/0612-800X580.jpg"></div><div class="operate-area j-operate-area" style="background-image: url(&quot;data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7&quot;);"></div><div class="camera-wrap"><i class="icon icon-camera"></i></div></div><div class="date-area"><div class="month">' . $month . ' /</div><div class="date-detail">' . $date . '</div></div><div class="word-area j-word-area"><div class="word-main"><p class="word j-word">' . $content . '</p></div><div class="word-side j-edit-btn"><button class="btn-refresh"><i class="icon-refresh"></i></button></div></div></div></div></body></html>';
    }

    /**
     * 生成签到图片
     */
    private static function generateSignImage($gtk, $html, $cookie) {
        $post = json_encode([
            'html' => $html,
            'viewport' => ['width' => 820, 'height' => 820],
            'type' => 'png',
            'cache' => true
        ]);

        $url = 'https://h5.qzone.qq.com/services/picGenerator?cmd=stringToUrl&g_tk=' . $gtk;
        $json = get_curl_qzone($url, $post, 'https://h5.qzone.qq.com/checkinv2/editor?type=daily', $cookie);
        $arr = json_decode($json, true);

        if (!isset($arr['code']) || $arr['code'] != 0) {
            return false;
        }

        return 'aurl=' . urlencode($arr['picUrl']['sOriUrl'])
            . '&s_width=400&s_height=300'
            . '&murl=' . urlencode($arr['picUrl']['sOriUrl'])
            . '&m_width=600&m_length=450'
            . '&burl=' . urlencode($arr['picUrl']['sOriUrl'])
            . '&b_width=800&b_length=600'
            . '&pic_type=10&templateId=1&who=2';
    }

    /**
     * 删除说说
     */
    public static function delete_shuo_h5($uin, $skey, $pskey, $gtk, $qzonetoken, $ssid) {
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $gtk = self::qzoneGetGTK($pskey);
        $url = 'https://mobile.qzone.qq.com/operation/operation_add?qzonetoken=' . $qzonetoken . '&g_tk=' . $gtk;
        $data = 'opr_type=delugc&res_type=311&res_id=' . $ssid . '&real_del=0&res_uin=' . $uin . '&format=json';
        $json = get_curl_qzone($url, $data, 'https://h5.qzone.qq.com/', $cookie);
        if ($json) {
            $arr = json_decode($json, true);
            if (isset($arr['code']) && $arr['code'] == 0) {
                return ['code' => 200, 'msg' => '删除说说' . $ssid . '成功'];
            } elseif ($arr['code'] == -3000) {
                return ['code' => 301, 'msg' => '删除说说' . $ssid . '失败！原因:SKEY已失效'];
            } else {
                return ['code' => 302, 'msg' => '删除说说' . $ssid . '失败！原因:' . json_encode($arr, JSON_UNESCAPED_UNICODE)];
            }
        } else {
            return ['code' => 302, 'msg' => $uin . '获取删除结果失败'];
        }
    }

    /**
     * 获取留言列表
     */
    public static function getliuyan($uin, $skey, $pskey) {
        $gtk = self::qzoneGetGTK($pskey);
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0';
        $url = 'https://user.qzone.qq.com/proxy/domain/m.qzone.qq.com/cgi-bin/new/get_msgb?uin=' . $uin . '&hostUin=' . $uin . '&start=0&s=0.860240' . time() . '&format=json&num=10&inCharset=utf-8&outCharset=utf-8&g_tk=' . $gtk;
        $json = get_curl_qzone($url, 0, 'https://user.qzone.qq.com/', $cookie, 0, $ua);
        $arr = json_decode($json, true);
        if (isset($arr['code']) && $arr['code'] == 0) {
            return ['code' => 200, 'msg' => '获取留言列表成功！', 'data' => $arr['data']['commentList']];
        } elseif ($arr['code'] == -4001) {
            return ['code' => 301, 'msg' => 'SKEY已失效！'];
        } else {
            return ['code' => 302, 'msg' => '获取留言列表失败！'];
        }
    }

    /**
     * 删除留言
     */
    public static function deleteliuyan($uin, $skey, $pskey, $idList, $uinList) {
        $gtk = self::qzoneGetGTK($pskey);
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $url = "https://h5.qzone.qq.com/proxy/domain/m.qzone.qq.com/cgi-bin/new/del_msgb?g_tk=" . $gtk;
        $post = "qzreferrer=https%3A%2F%2Fctc.qzs.qq.com%2Fqzone%2Fmsgboard%2Fmsgbcanvas.html%23page%3D1&hostUin=" . $uin . "&idList=" . urlencode($idList) . "&uinList=" . urlencode($uinList) . "&format=json&iNotice=1&inCharset=utf-8&outCharset=utf-8&ref=qzone&json=1&g_tk=" . $gtk;
        $json = get_curl_qzone($url, $post, 'https://ctc.qzs.qq.com/qzone/msgboard/msgbcanvas.html', $cookie);
        $arr = json_decode($json, true);
        if (isset($arr['code']) && $arr['code'] == 0) {
            return ['code' => 200, 'msg' => $arr['message']];
        } elseif ($arr['code'] == -3000) {
            return ['code' => 301, 'msg' => 'SKEY已失效！'];
        } else {
            return ['code' => 302, 'msg' => '删除留言失败！' . $arr['message']];
        }
    }

    /**
     * 获取我的说说列表
     */
    public static function getMyNews($uin, $skey, $pskey, $qzonetoken, $gtk) {
        try {
            $cookie = self::buildCookie($uin, $skey, $pskey);
            $url = 'https://mobile.qzone.qq.com/list?qzonetoken=' . $qzonetoken . '&g_tk=' . $gtk . '&res_attach=&format=json&list_type=shuoshuo&action=0&res_uin=' . $uin . '&count=20';

            $json = get_curl_qzone($url, 0, 1, $cookie);
            $arr = json_decode($json, true);

            if (isset($arr['code']) && $arr['code'] == 0) {
                if (isset($arr['data']['vFeeds'])) {
                    return ['code' => 200, 'msg' => '获取说说列表成功！', 'data' => $arr['data']['vFeeds']];
                } else {
                    return ['code' => 200, 'msg' => '获取说说列表成功！', 'data' => []];
                }
            } elseif (isset($arr['code']) && $arr['code'] == -3000) {
                return ['code' => -3000, 'msg' => '获取最新说说失败！原因:SKEY已失效'];
            } else {
                $message = $arr['message'] ?? $arr['msg'] ?? '未知错误';
                return ['code' => -1, 'msg' => '获取最新说说失败！原因:' . $message];
            }
        } catch (Exception $e) {
            return ['code' => -1, 'msg' => '获取说说列表失败: ' . $e->getMessage()];
        }
    }

    /**
     * 上传图片到QQ空间
     */
    public static function uploadimg_pc($uin, $skey, $pskey, $image_url, $return_url = false) {
        try {
            // 使用带 UA/Referer 的请求拉图，避免外链防盗链导致读取失败（如 yun.nmtxqq.cn 等）
            $opts = [
                'http' => [
                    'method' => 'GET',
                    'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\r\nReferer: https://user.qzone.qq.com/\r\n",
                    'timeout' => 15,
                    'ignore_errors' => true,
                ],
                'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
            ];
            $ctx = stream_context_create($opts);
            $image = @file_get_contents($image_url, false, $ctx);
            if ($image === false || empty($image)) {
                // 返回 false 便于调用方判断，避免误把数组当 richval 传给评论接口导致“链接不是有效链接”
                return false;
            }

            // 构建请求
            $cookie = self::buildCookie($uin, $skey, $pskey);
            $gtk = self::qzoneGetGTK($pskey);
            $url = 'https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=' . $gtk;

            $post = http_build_query([
                'filename' => 'filename',
                'uin' => $uin,
                'skey' => $skey,
                'p_uin' => $uin,
                'p_skey' => $pskey,
                'qzonetoken' => '',
                'uploadtype' => '1',
                'albumtype' => '7',
                'exttype' => '0',
                'refer' => 'shuoshuo',
                'output_type' => 'json',
                'charset' => 'utf-8',
                'output_charset' => 'utf-8',
                'upload_hd' => '1',
                'hd_width' => '2048',
                'hd_height' => '10000',
                'hd_quality' => '96',
                'backUrls' => '',
                'url' => '',
                'base64' => '1',
                'picfile' => base64_encode($image),
                'qzreferrer' => 'https://user.qzone.qq.com/' . $uin
            ]);

            // 发起请求
            $data = get_curl_qzone($url, $post, 'https://user.qzone.qq.com/' . $uin, $cookie);

            // 解析响应
            if (!preg_match('/_Callback\((.*)\);/', $data, $arr)) {
                error_log("Qzone图片上传失败：响应格式错误，原始响应: " . substr($data, 0, 500));
                return false;
            }
            $result = json_decode($arr[1], true);
            if (!isset($result['ret']) || $result['ret'] != 0) {
                $errMsg = $result['msg'] ?? ($result['message'] ?? '未知错误');
                error_log("Qzone图片上传失败：ret={$result['ret']}, msg={$errMsg}, 原始响应: " . substr($data, 0, 500));
                return false;
            }

            return self::formatImageResult($result, $return_url, $uin);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 格式化图片上传结果
     */
    private static function formatImageResult($result, $return_url, $uin = '') {
        if (!isset($result['data']['url'], $result['data']['albumid'], $result['data']['lloc'], $result['data']['sloc'])) {
            return false;
        }

        if ($return_url) {
            return $result['data']['url'];
        }
        return $uin . ',' . $result['data']['albumid'] . ',' . $result['data']['lloc'] . ',' . $result['data']['sloc'] . ',' . $result['data']['type'] . ',' . $result['data']['height'] . ',' . $result['data']['width'] . ',,,';
    }

    /**
     * 获取最新说说列表
     */
    public static function getnew($uin, $skey, $pskey, $gtk, $qzonetoken, $do = 0) {
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $url = 'https://h5.qzone.qq.com/webapp/json/mqzone_feeds/getActiveFeeds?qzonetoken=' . $qzonetoken . '&g_tk=' . $gtk;
        $post = 'res_type=0&res_attach=&refresh_type=2&format=json&attach_info=';
        $json = get_curl_qzone($url, $post, 1, $cookie);
        $arr = json_decode($json, true);
        if (isset($arr['code']) && $arr['code'] == 0) {
            if (isset($arr['data']['vFeeds']))
                return $arr['data']['vFeeds'];
            else
                return $arr['data']['feeds']['vFeeds'] ?? [];
        } else {
            return false;
        }
    }

    /**
     * 获取说说列表(格式化)
     */
    public static function getQzoneList($uin, $skey, $pskey, $gtk, $qzonetoken) {
        $shuos = self::getnew($uin, $skey, $pskey, $gtk, $qzonetoken);
        $arryj = [];

        if (!is_array($shuos)) {
            return [];
        }

        foreach ($shuos as $shuo) {
            $like = isset($shuo['like']['isliked']) ? $shuo['like']['isliked'] : 0;
            $is_comment = false;
            if (isset($shuo['comment']['comments'])) {
                $is_comment = self::is_comment($uin, $shuo['comment']['comments']);
            }
            $fid = $shuo['id']['cellid'] ?? '';
            if (strlen($fid) >= 24) {
                $arryj[] = [
                    "touin" => $shuo['userinfo']['user']['uin'],
                    "appid" => $shuo['comm']['appid'],
                    "typeid" => $shuo['comm']['feedstype'],
                    "fid" => $fid,
                    "ssid" => $fid,
                    "abstime" => $shuo['comm']['time'],
                    "uinkey" => $shuo['comm']['orglikekey'],
                    "curkey" => $shuo['comm']['curlikekey'],
                    "from" => $shuo['userinfo']['user']['from'],
                    "is_like" => $like != 0,
                    "is_comment" => $is_comment,
                ];
            }
        }
        return $arryj;
    }

    /**
     * 检查是否已评论
     */
    private static function is_comment($uin, $arrs) {
        if ($arrs) {
            foreach ($arrs as $arr) {
                if ($arr['user']['uin'] == $uin) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }

    /**
     * 检测Cookie状态
     */
    public static function check_status($uin, $skey, $pskey) {
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $gtk = self::qzoneGetGTK($pskey);
        $url = 'https://h5.qzone.qq.com/proxy/domain/r.qzone.qq.com/cgi-bin/user/qzone_cgi_msg_getcnt2?uin=' . $uin . '&bm=0800950000008001&v=1&g_tk=' . $gtk . '&g=0.291287' . time();
        $data = get_curl_qzone($url, 0, 'https://cnc.qzs.qq.com/qzone/v6/setting/profile/profile.html', $cookie);
        if (empty($data)) {
            usleep(150000);
            $data = get_curl_qzone($url, 0, 'https://cnc.qzs.qq.com/qzone/v6/setting/profile/profile.html', $cookie);
            if (empty($data)) {
                return false;
            }
        }

        if (preg_match('/\_Callback\((.*?)\);/is', $data, $json)) {
            $arr = json_decode($json[1], true);
            if (isset($arr['error'])) {
                if ($arr['error'] == 4004) {
                    return false;
                } else {
                    return true;
                }
            }
        }

        if (strpos($data, '4004') !== false || strpos($data, '未登录') !== false || strpos($data, 'cookie') !== false) {
            return false;
        }

        return true;
    }

    /**
     * 计算GTK
     */
    public static function qzoneGetGTK($skey) {
        $len = strlen($skey);
        $hash = 5381;
        for ($i = 0; $i < $len; $i++) {
            $hash += ($hash << 5 & 2147483647) + ord($skey[$i]) & 2147483647;
            $hash &= 2147483647;
        }
        return $hash & 2147483647;
    }

    /**
     * 构建Cookie
     */
    public static function buildCookie($uin, $skey, $pskey) {
        return 'pt2gguin=o0' . $uin . '; uin=o0' . $uin . '; skey=' . $skey . '; p_skey=' . $pskey . '; p_uin=o0' . $uin;
    }

    /**
     * 获取QzoneToken
     */
    public static function qzoneGetQzonetoken($uin, $skey, $pskey, $url = 'https://h5.qzone.qq.com/mqzone/index') {
        $cookie = self::buildCookie($uin, $skey, $pskey);
        $ua = 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.5 Mobile Safari/533.1';
        $json = get_curl_qzone($url, 0, 0, $cookie, 0, $ua);
        preg_match('/\(function\(\){ try{.*return (.*?);} catch\(e\)/i', $json, $match);
        if ($data = $match[1] ?? null) {
            $word = array('([]+[][(![]+[])[!+[]+!![]+!![]]+([]+{})[+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]][([]+{})[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]]+(![]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(!![]+[])[+[]]+([]+{})[+!![]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+([][[]]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]+!![]+!![]]+(![]+[])[!+[]+!![]]+([]+{})[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(+{}+[])[+!![]]+(!![]+[])[+[]]+([][[]]+[])[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]])())' => 'https', '([][[]]+[])' => 'undefined', '([]+{})' => '[object Object]', '(+{}+[])' => 'NaN', '(![]+[])' => 'false', '(!![]+[])' => 'true');
            $words = array();
            $i = 0;
            foreach ($word as $k => $v) {
                $words[$i] = $v;
                $data = str_replace($k, '$words[' . $i . ']', $data);
                $i++;
            }
            $data = str_replace(array('!+[]', '+!![]', '+[]'), array('+1', '+1', '+0'), $data);
            $data = str_replace(array('+(', '+$'), array('.(', '.$'), $data);
            if (!$data) {
                return '';
            }
            $data = trim($data, '"');
            return $data;
        } else {
            return '';
        }
    }
}
