#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
xwplug_check.py —— 校园站插件包 · 提交前自检

用法：
    python xwplug_check.py myplug            # 检查目录
    python xwplug_check.py myplug --zip      # 检查 + 打包成 myplug-1.0.0.zip
    python xwplug_check.py 某包.zip           # 检查一个已有的 zip

它做的事情和线上审核的自动扫描基本一致，提前跑一遍能省掉大部分打回。
结果分三档（和审核一致）：
    PASS  全部通过
    WARN  可以提交，但有些地方建议改
    DENY  一定会被打回，必须改

只依赖 Python 3 标准库，不需要装任何东西。

注意：本脚本的硬红线与线上扫描器保持一致，但线上还会额外跑一遍 php -l
全量语法检查和外联声明比对。看到 PASS 不等于最终通过，最终以开发者中心
里的扫描报告为准。若打回原因写的是平台侧环境异常（例如影子站不可用），
不需要改包，等平台修复后按新版本号重传即可。
"""

import sys
import os
import re
import json
import zipfile
import tempfile
import shutil
from pathlib import Path

# ---------------- 规范常量（改这里没有意义，是平台约定） ----------------
PLUGID_RE = re.compile(r'^[a-z][a-z0-9_]{2,31}$')
VERSION_RE = re.compile(r'^[0-9A-Za-z][0-9A-Za-z._-]{0,30}$')
MAX_ZIP_BYTES = 5 * 1024 * 1024

REQUIRED_FILES = ['manifest.json', 'conf.json', 'install.php', 'unstall.php', 'icon.png']
HOOK_FILE = 'hook/index_route_case_end.php'

# 硬红线：正则命中 = DENY
DENY_PATTERNS = [
    (r'\b(exec|shell_exec|system|passthru|proc_open|popen|pcntl_exec)\s*\(', '命令执行'),
    (r'\beval\s*\(', 'eval 动态执行'),
    (r'create_function\s*\(', 'create_function'),
    (r'\bassert\s*\(', 'assert 执行'),
    (r"preg_replace\s*\(.*/e['\"\s]", 'preg_replace /e 修饰符'),
    (r'\.user\.ini', '.user.ini'),
    (r'\bchattr\b', 'chattr'),
    (r'\bcrontab\b', 'crontab'),
    (r'/etc/(shadow|passwd|sudoers)', '系统账号文件'),
    (r'authorized_keys', 'SSH 公钥'),
    (r'\bsymlink\s*\(', '软链接'),
    (r'openssl_(csr|pkey)_new', '生成密钥/证书'),
    (r'<\?php\s+(echo|print)\s+\$_(GET|REQUEST)', '直接回显请求参数（XSS）'),
    (r'\b(include|require)(_once)?\s*\(?\s*\$_(GET|POST|REQUEST|COOKIE|SERVER)\s*\[', '请求参数拼 include 路径（任意文件包含）'),
]

# 建议项：命中 = WARN
WARN_PATTERNS = [
    (r'file_put_contents\s*\(\s*[\'"]?(/|\.\.)', '往插件目录以外写文件'),
    (r'(include|require)(_once)?\s*\(?\s*\$', 'include 用了变量路径'),
    (r'\$\$[A-Za-z_]', '可变变量'),
    (r'\bbase64_decode\s*\(', 'base64 解码（常见混淆手段）'),
    (r'\bgzinflate\s*\(|\bstr_rot13\s*\(', '压缩/旋转解码（常见混淆手段）'),
]

JUNK_NAMES = {'.DS_Store', 'Thumbs.db', 'desktop.ini', '__MACOSX', '.git', '.idea', '.vscode', 'node_modules'}

C_OK, C_WARN, C_ERR, C_DIM, C_OFF = '\033[32m', '\033[33m', '\033[31m', '\033[90m', '\033[0m'
if os.name == 'nt' and not os.environ.get('WT_SESSION'):
    try:  # 老版 cmd 不开 VT 时退化为无色，避免乱码
        import ctypes
        k = ctypes.windll.kernel32
        k.SetConsoleMode(k.GetStdHandle(-11), 7)
    except Exception:
        C_OK = C_WARN = C_ERR = C_DIM = C_OFF = ''


class Report:
    def __init__(self):
        self.deny, self.warn, self.ok = [], [], []

    def good(self, m):
        self.ok.append(m)
        print('%s  ok  %s%s' % (C_OK, C_OFF, m))

    def w(self, m):
        self.warn.append(m)
        print('%s warn %s%s' % (C_WARN, C_OFF, m))

    def bad(self, m):
        self.deny.append(m)
        print('%s deny %s%s' % (C_ERR, C_OFF, m))


def read_text(p):
    try:
        return p.read_text(encoding='utf-8', errors='replace')
    except Exception:
        return ''


def locate_pkg(root: Path):
    """返回 (包目录, 顶层是否唯一)。允许直接传包目录，也允许传外面套了一层的父目录。"""
    if (root / 'manifest.json').exists():
        return root, True
    subs = [d for d in root.iterdir() if d.is_dir() and not d.name.startswith('.')]
    subs = [d for d in subs if d.name not in ('__MACOSX',)]
    if len(subs) == 1 and (subs[0] / 'manifest.json').exists():
        return subs[0], True
    return root, len(subs) == 1


def check(pkg: Path, rep: Report):
    # ---- manifest ----
    mf_path = pkg / 'manifest.json'
    if not mf_path.exists():
        rep.bad('没有 manifest.json（包根目录必须有）')
        return None
    try:
        mf = json.loads(read_text(mf_path))
        if not isinstance(mf, dict):
            raise ValueError
    except Exception:
        rep.bad('manifest.json 不是合法 JSON（常见原因：末尾多逗号、用了中文引号）')
        return None
    rep.good('manifest.json 可以解析')

    missing = [k for k in ('plugid', 'name', 'version', 'author') if not str(mf.get(k, '')).strip()]
    if missing:
        rep.bad('manifest.json 缺少字段：' + ', '.join(missing))
    if not isinstance(mf.get('permissions'), dict):
        rep.bad('manifest.json 缺少 permissions 对象（即使不用权限也要写 {}）')

    plugid = str(mf.get('plugid', '')).strip()
    version = str(mf.get('version', '')).strip()

    if plugid:
        if not PLUGID_RE.match(plugid):
            rep.bad('plugid "%s" 不合法：小写字母开头，3~32 位，只能是字母数字下划线' % plugid)
        elif plugid == 'myplug':
            rep.bad('plugid 还是模板默认值 myplug，请改成你自己的名字')
        else:
            rep.good('plugid = %s' % plugid)

    if version and not VERSION_RE.match(version):
        rep.bad('version "%s" 不合法（例：1.0.0）' % version)
    elif version == '1.0.0' and str(mf.get('changelog', '')).startswith('1.0.0: 首发'):
        rep.w('version 和 changelog 还是模板默认值，确认一下是否有意为之')

    # ---- 目录名 = plugid ----
    if plugid and pkg.name != plugid:
        rep.bad('文件夹名（%s）和 manifest 里的 plugid（%s）不一致，安装会失败' % (pkg.name, plugid))
    elif plugid:
        rep.good('文件夹名与 plugid 一致')

    # ---- 署名 ----
    author = str(mf.get('author', '')).strip()
    if '请改成' in author or '你的' in author:
        rep.bad('author 还是占位文字，请填你的署名')
    brief = str(mf.get('brief', '')).strip()
    if len(brief) < 8:
        rep.w('brief 太短或没填，商店列表会显示不好看（建议 15~40 字）')
    if not str(mf.get('changelog', '')).strip():
        rep.w('没写 changelog，用户看不到更新说明')

    # ---- 必需文件 ----
    for f in REQUIRED_FILES:
        if not (pkg / f).exists():
            rep.bad('缺少必需文件：%s' % f)
    if not (pkg / HOOK_FILE).exists():
        rep.bad('缺少 %s，插件页面会 404' % HOOK_FILE)

    # ---- conf.json ----
    cf_path = pkg / 'conf.json'
    if cf_path.exists():
        try:
            cf = json.loads(read_text(cf_path))
            if int(cf.get('installed', 0)) != 0 or int(cf.get('enable', 0)) != 0:
                rep.bad('conf.json 里 installed / enable 必须是 0（这是站点安装后的状态位，不能提前置 1）')
            else:
                rep.good('conf.json 状态位正确')
        except Exception:
            rep.bad('conf.json 不是合法 JSON')

    # ---- 路由一致性 ----
    hook = pkg / HOOK_FILE
    if hook.exists():
        h = read_text(hook)
        cases = re.findall(r"case\s+['\"]([^'\"]+)['\"]", h)
        if not cases:
            rep.bad('hook 文件里没有 case 语句，页面无法访问')
        else:
            slug = cases[0]
            if plugid and slug == 'myplug':
                rep.bad('hook 里的访问地址还是模板默认值 myplug，请改成你的插件名')
            elif plugid and slug != plugid:
                rep.w('访问地址前缀（%s）和 plugid（%s）不同。可以，但要确保没和别的插件撞名' % (slug, plugid))
            # 校验 hook 里 include 的目标文件真的存在
            incs = re.findall(r"plugin/([A-Za-z0-9_]+)/([A-Za-z0-9_./-]+\.php)", h)
            if not incs:
                rep.bad('hook 里没有 include 任何文件，页面会白屏')
            for d, rel in incs:
                if d == 'myplug':
                    rep.bad('hook 里的插件目录名还是 myplug，请替换')
                if not (pkg / rel).exists():
                    rep.bad('hook 指向 %s，但包里没有这个文件' % rel)
            if incs and not rep.deny:
                rep.good('路由登记正确：/%s.htm → %s' % (slug, incs[0][1]))

    # ---- 模板占位是否清理干净 ----
    leftovers = []
    for p in pkg.rglob('*'):
        if not p.is_file() or p.suffix.lower() not in ('.php', '.htm', '.html', '.js', '.json'):
            continue
        if 'myplug' in read_text(p):
            leftovers.append(p.relative_to(pkg).as_posix())
    if leftovers:
        rep.bad('以下文件里还留着模板默认名 myplug，需要全部替换：' + ', '.join(leftovers[:5]))

    # ---- icon ----
    icon = pkg / 'icon.png'
    if icon.exists():
        try:
            with open(icon, 'rb') as fh:
                head = fh.read(24)
            if head[:8] != b'\x89PNG\r\n\x1a\n':
                rep.w('icon.png 不是 PNG 格式')
            else:
                w = int.from_bytes(head[16:20], 'big')
                hh = int.from_bytes(head[20:24], 'big')
                if (w, hh) != (128, 128):
                    rep.w('icon.png 是 %dx%d，建议 128x128（非正方形在列表里会被裁切）' % (w, hh))
                else:
                    rep.good('icon.png 正常')
        except Exception:
            rep.w('icon.png 读不出来，确认没损坏')

    # ---- 逐文件扫描 ----
    declared_net = []
    perm = mf.get('permissions') if isinstance(mf.get('permissions'), dict) else {}
    if isinstance(perm.get('network'), list):
        declared_net = [str(x).strip().lower() for x in perm['network'] if str(x).strip()]

    found_domains = {}
    total = 0
    file_count = 0
    for p in pkg.rglob('*'):
        if not p.is_file():
            continue
        rel = p.relative_to(pkg).as_posix()
        if any(part in JUNK_NAMES for part in p.parts):
            rep.w('包里有多余的系统文件：%s（删掉再打包）' % rel)
            continue
        file_count += 1
        total += p.stat().st_size

        if p.suffix.lower() not in ('.php', '.htm', '.html', '.js', '.json', '.css', '.md', '.txt'):
            continue
        # 只有会被执行的代码才查红线与外链；说明文档不算（服务器扫描器也只扫 php/htm/js）
        is_code = p.suffix.lower() in ('.php', '.htm', '.html', '.js')
        data = p.read_bytes()
        if data[:3] == b'\xef\xbb\xbf':
            rep.bad('%s 带了 BOM 头，会导致页面顶部多出空白/乱码，请存成「UTF-8 无 BOM」' % rel)
        txt = data.decode('utf-8', errors='replace')

        if not is_code:
            continue  # 说明文档不参与红线/外链判定

        for pat, label in DENY_PATTERNS:
            mo = re.search(pat, txt)
            if mo:
                line = txt[:mo.start()].count('\n') + 1
                rep.bad('%s 第 %d 行用了%s，会被直接拦' % (rel, line, label))

        for pat, label in WARN_PATTERNS:
            mo = re.search(pat, txt)
            if mo:
                line = txt[:mo.start()].count('\n') + 1
                rep.w('%s 第 %d 行：%s（人工会重点看）' % (rel, line, label))

        for mo in re.finditer(r'https?://([a-zA-Z0-9._-]+)', txt):
            d = mo.group(1).lower()
            if d in ('www.w3.org', 'localhost', '127.0.0.1'):
                continue
            found_domains.setdefault(d, rel)

    # ---- 外链声明比对 ----
    for d, rel in sorted(found_domains.items()):
        if not declared_net:
            rep.bad('代码里访问了 %s（%s），但 manifest 的 permissions.network 是空的' % (d, rel))
        elif d not in declared_net:
            rep.w('代码里访问了 %s（%s），manifest 里没声明' % (d, rel))
    if declared_net and not found_domains:
        rep.w('manifest 声明了外链 %s，但代码里没用到，可以删掉' % ', '.join(declared_net))

    # ---- 体积 ----
    for p in pkg.rglob('*'):
        if p.is_file() and p.suffix.lower() in ('.mp4', '.zip', '.psd', '.ai', '.exe'):
            rep.w('包里有大体积文件：%s（单包上限 5MB）' % p.relative_to(pkg).as_posix())
    if total > MAX_ZIP_BYTES:
        rep.bad('包体积 %.1f MB 超过 5MB 上限（图片请压缩后再放进来）' % (total / 1048576.0))
    else:
        rep.good('包体积 %.2f MB，共 %d 个文件' % (total / 1048576.0, file_count))

    return mf


def make_zip(pkg: Path, mf: dict):
    plugid = str(mf.get('plugid', pkg.name)).strip()
    version = str(mf.get('version', '1.0')).strip()
    out = pkg.parent / ('%s-%s.zip' % (plugid, version))
    if out.exists():
        out.unlink()
    with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as z:
        for p in sorted(pkg.rglob('*')):
            if not p.is_file():
                continue
            if any(part in JUNK_NAMES for part in p.parts):
                continue
            # zip 内路径 = plugid/...
            z.write(p, plugid + '/' + p.relative_to(pkg).as_posix())
    print('\n%s打包完成：%s%s' % (C_OK, out, C_OFF))
    print('大小：%.2f MB' % (out.stat().st_size / 1048576.0))
    return out


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return 2

    target = Path(sys.argv[1]).resolve()
    want_zip = '--zip' in sys.argv[2:]
    workdir = None

    if not target.exists():
        print('%s找不到：%s%s' % (C_ERR, target, C_OFF))
        return 1

    if target.is_file() and target.suffix.lower() == '.zip':
        workdir = Path(tempfile.mkdtemp(prefix='xwplug_'))
        try:
            with zipfile.ZipFile(target) as z:
                for name in z.namelist():
                    if name.startswith('/') or '..' in name.split('/'):
                        print('%s包里含非法路径：%s%s' % (C_ERR, name, C_OFF))
                        return 1
                z.extractall(workdir)
            pkg, _ = locate_pkg(workdir)
        except zipfile.BadZipFile:
            print('%s不是有效的 zip 文件%s' % (C_ERR, C_OFF))
            return 1
    else:
        pkg, unique = locate_pkg(target)
        if not unique:
            print('%s包里只能有一个顶层目录（现在有多个）%s' % (C_ERR, C_OFF))
            return 1

    print('%s检查：%s%s\n' % (C_DIM, pkg.name, C_OFF))
    rep = Report()
    mf = check(pkg, rep)

    print()
    if rep.deny:
        print('%s结果：DENY —— %d 个必须改的问题%s' % (C_ERR, len(rep.deny), C_OFF))
        for m in rep.deny:
            print('  - ' + m)
        code = 1
    elif rep.warn:
        print('%s结果：WARN —— 可以提交，但有 %d 条建议%s' % (C_WARN, len(rep.warn), C_OFF))
        for m in rep.warn:
            print('  - ' + m)
        code = 2
    else:
        print('%s结果：PASS —— 可以提交%s' % (C_OK, C_OFF))
        code = 0

    if want_zip and code != 1 and mf:
        make_zip(pkg, mf)

    if workdir:
        shutil.rmtree(workdir, ignore_errors=True)
    return code


if __name__ == '__main__':
    sys.exit(main())
