<?php
/**
 * 插件 / 扩展包安装工具
 * 支持 ZIP（含 plugin.json 与 plugin.php）与 JSON（内联 HTML 片段）
 * 所有包先做结构、版本、语法与危险调用检测，通过后才会安装启用。
 */

function plugin_slugify($name)
{
    $slug = strtolower(trim((string) $name));
    $slug = preg_replace('/[^a-z0-9\-_]/', '-', $slug);
    $slug = trim($slug, '-');
    return $slug !== '' ? substr($slug, 0, 40) : 'plugin-' . substr(bin2hex(random_bytes(4)), 0, 8);
}

function plugin_dir($slug)
{
    return APP_ROOT . '/storage/plugins/' . $slug;
}

function plugin_supported_hooks()
{
    return ['layout_footer', 'home_top', 'home_quote', 'home_bottom', 'home_popup', 'content_filter', 'plugin_settings', 'plugin_action'];
}

function plugin_register_row($slug, $name, $version, $desc, $status = 0)
{
    $exists = DB::val('SELECT COUNT(*) FROM ' . DB::table('plugins') . ' WHERE slug = ?', [$slug]);
    if ($exists) {
        DB::run('UPDATE ' . DB::table('plugins') . ' SET name = ?, version = ?, description = ?, status = ? WHERE slug = ?',
            [$name, $version, $desc, (int) $status, $slug]);
        return;
    }
    DB::insert('plugins', [
        'slug'        => $slug,
        'name'        => $name,
        'version'     => $version,
        'description' => $desc,
        'status'      => (int) $status,
        'created_at'  => now(),
    ]);
}

function plugin_manifest_normalize(array $raw, $fallbackSlug = '')
{
    $slug = plugin_slugify($raw['slug'] ?? $fallbackSlug ?? ($raw['name'] ?? ''));
    $name = trim((string) ($raw['name'] ?? ''));
    if ($name === '') {
        $name = $slug;
    }
    if (mb_strlen($name, 'UTF-8') > 60) {
        throw new Exception('插件名称最多 60 个字符');
    }
    $version = trim((string) ($raw['version'] ?? '1.0'));
    if ($version === '' || strlen($version) > 20) {
        throw new Exception('插件版本号格式不正确');
    }
    $desc = trim((string) ($raw['description'] ?? ''));
    if (mb_strlen($desc, 'UTF-8') > 200) {
        throw new Exception('插件简介最多 200 个字符');
    }
    $hook = preg_replace('/[^a-z_]/', '', strtolower((string) ($raw['hook'] ?? 'home_bottom')));
    if (!in_array($hook, plugin_supported_hooks(), true)) {
        throw new Exception('插件钩子不在允许范围内：' . $hook);
    }
    $phpMin = trim((string) ($raw['php_min'] ?? '7.4'));
    $phpMax = trim((string) ($raw['php_max'] ?? ''));
    $appMin = trim((string) ($raw['app_min'] ?? ''));
    $appMax = trim((string) ($raw['app_max'] ?? ''));
    foreach ([$phpMin, $phpMax, $appMin, $appMax] as $ver) {
        if ($ver !== '' && !preg_match('/^\d+(\.\d+){0,3}$/', $ver)) {
            throw new Exception('兼容版本号必须是数字点号格式');
        }
    }
    if (!package_version_matches(PHP_VERSION, $phpMin, $phpMax)) {
        throw new Exception('插件要求 PHP ' . $phpMin . ($phpMax !== '' ? ' ~ ' . $phpMax : '') . '，当前 PHP ' . PHP_VERSION . ' 不兼容');
    }
    if (!package_version_matches(APP_VERSION, $appMin, $appMax)) {
        throw new Exception('插件要求站点版本 ' . ($appMin !== '' ? $appMin : '不限') . ($appMax !== '' ? ' ~ ' . $appMax : '') . '，当前版本 ' . APP_VERSION . ' 不兼容');
    }
    return [
        'slug' => $slug,
        'name' => $name,
        'version' => $version,
        'description' => $desc,
        'hook' => $hook,
        'php_min' => $phpMin,
        'php_max' => $phpMax,
        'app_min' => $appMin,
        'app_max' => $appMax,
    ];
}

function plugin_validate_php_tree($root, $label = '插件')
{
    foreach (package_scan_files($root, ['max_files' => 500, 'max_total' => 40 * 1024 * 1024, 'max_single' => 10 * 1024 * 1024]) as $f) {
        $ext = strtolower(pathinfo($f['rel'], PATHINFO_EXTENSION));
        $allowed = ['php', 'json', 'css', 'js', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'woff2', 'woff', 'ttf', 'otf', 'md', 'txt'];
        if (!in_array($ext, $allowed, true)) {
            throw new Exception($label . ' 包含不允许的文件类型：' . $f['rel']);
        }
        if (package_path_blocked($f['rel'])) {
            throw new Exception($label . ' 包含受保护路径：' . $f['rel']);
        }
        if ($ext === 'php') {
            $lint = package_php_lint($f['full']);
            if ($lint !== '') {
                throw new Exception($f['rel'] . ' ' . $lint);
            }
            $errors = package_plugin_code_errors((string) file_get_contents($f['full']), $f['rel']);
            if ($errors) {
                throw new Exception(implode('；', $errors));
            }
        }
    }
}

function plugin_hook_calls($code)
{
    $hooks = [];
    if (preg_match_all('/plugin_register\s*\(\s*[\'"]([a-zA-Z0-9_]+)[\'"]/i', (string) $code, $m)) {
        $hooks = array_values(array_unique(array_map('strtolower', $m[1])));
    }
    return $hooks;
}

function plugin_install_copy($srcDir, $slug)
{
    $target = plugin_dir($slug);
    if (strpos($target, APP_ROOT . '/storage/plugins/') !== 0) {
        throw new Exception('插件目录不合法');
    }
    if (!is_dir(dirname($target))) {
        @mkdir(dirname($target), 0775, true);
    }
    $backup = '';
    if (is_dir($target)) {
        $backup = package_tmp_make('plugin_backup');
        if (!@rename($target, $backup)) {
            throw new Exception('无法备份旧插件目录');
        }
    }
    try {
        if (!@mkdir($target, 0775, true) && !is_dir($target)) {
            throw new Exception('无法创建插件目录');
        }
        foreach (array_diff(scandir($srcDir), ['.', '..']) as $item) {
            $src = $srcDir . '/' . $item;
            $dst = $target . '/' . $item;
            if (is_dir($src)) {
                plugin_copy_dir($src, $dst);
            } elseif (!@copy($src, $dst)) {
                throw new Exception('复制插件文件失败');
            }
        }
    } catch (Exception $e) {
        plugin_remove_files($target);
        if ($backup !== '' && is_dir($backup)) {
            @rename($backup, $target);
        }
        throw $e;
    }
    if ($backup !== '') {
        package_remove_dir($backup);
    }
}

/** 对字符串代码做语法检查（用于 JSON 生成的 plugin.php） */
function package_php_lint_code($code)
{
    try {
        token_get_all((string) $code, TOKEN_PARSE);
    } catch (ParseError $e) {
        return 'PHP 语法错误：' . $e->getMessage();
    } catch (Throwable $e) {
        return 'PHP 语法错误：' . $e->getMessage();
    }
    return '';
}

function plugin_install_json_package($raw)
{
    $json = json_decode((string) $raw, true);
    if (!is_array($json)) {
        throw new Exception('插件 JSON 格式不正确');
    }
    $manifest = plugin_manifest_normalize($json);
    $html = (string) ($json['html'] ?? '');
    $htmlErrors = package_plugin_html_errors($html);
    if ($htmlErrors) {
        throw new Exception(implode('；', $htmlErrors));
    }
    $code = "<?php\n// " . $manifest['name'] . " · 由扩展包安装\n"
        . "plugin_register('" . $manifest['hook'] . "', function () {\n    echo " . var_export($html, true) . ";\n});\n";
    $lint = package_php_lint_code($code);
    if ($lint !== '') {
        throw new Exception('生成的插件代码检测失败：' . $lint);
    }
    $work = package_tmp_make('plugin_json');
    file_put_contents($work . '/plugin.json', json_encode($manifest + ['html' => $html], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    file_put_contents($work . '/plugin.php', $code);
    plugin_install_copy($work, $manifest['slug']);
    package_remove_dir($work);
    plugin_register_row($manifest['slug'], $manifest['name'], $manifest['version'], $manifest['description'], 1);
    return $manifest;
}

function plugin_install_zip_package($filePath)
{
    $work = package_extract_zip($filePath, ['max_files' => 500, 'max_total' => 40 * 1024 * 1024, 'max_single' => 10 * 1024 * 1024, 'max_ratio' => 120]);
    try {
        $manifests = package_find_manifest($work, 'plugin.json');
        if (count($manifests) === 0) {
            throw new Exception('插件包缺少 plugin.json');
        }
        if (count($manifests) > 1) {
            throw new Exception('插件包内只能有一个 plugin.json');
        }
        $root = dirname($manifests[0]);
        $raw = json_decode((string) file_get_contents($manifests[0]), true);
        if (!is_array($raw)) {
            throw new Exception('plugin.json 不是有效的 JSON');
        }
        $manifest = plugin_manifest_normalize($raw);
        if (!is_file($root . '/plugin.php')) {
            throw new Exception('插件包缺少 plugin.php');
        }
        plugin_validate_php_tree($root, '插件');
        $hooks = plugin_hook_calls((string) file_get_contents($root . '/plugin.php'));
        if (!$hooks) {
            throw new Exception('plugin.php 未调用 plugin_register，无法挂载到站点');
        }
        foreach ($hooks as $hook) {
            if (!in_array($hook, plugin_supported_hooks(), true)) {
                throw new Exception('plugin.php 使用了不支持的钩子：' . $hook);
            }
        }
        plugin_install_copy($root, $manifest['slug']);
        plugin_register_row($manifest['slug'], $manifest['name'], $manifest['version'], $manifest['description'], 1);
        return $manifest;
    } finally {
        package_remove_dir($work);
    }
}

/**
 * 从上传框安装插件，返回 slug；失败抛异常
 */
function plugin_install_from_upload($field)
{
    if (empty($_FILES[$field]['name'])) {
        throw new Exception('请选择插件包（.zip 或 .json）');
    }
    $file = $_FILES[$field];
    if ((int) $file['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('文件上传失败，错误码 ' . $file['error']);
    }
    if ($file['size'] > 20 * 1024 * 1024) {
        throw new Exception('插件包不能超过 20MB');
    }
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['zip', 'json'], true)) {
        throw new Exception('仅支持 .zip 或 .json 插件包');
    }
    if ($ext === 'json') {
        if ($file['size'] > 2 * 1024 * 1024) {
            throw new Exception('JSON 插件不能超过 2MB');
        }
        $manifest = plugin_install_json_package((string) file_get_contents($file['tmp_name']));
    } else {
        $manifest = plugin_install_zip_package($file['tmp_name']);
    }
    $GLOBALS['PLUGIN_INSTALL_REPORT'] = $manifest;
    return $manifest['slug'];
}

function plugin_copy_dir($src, $dst)
{
    if (!is_dir($dst)) {
        @mkdir($dst, 0775, true);
    }
    foreach (array_diff(scandir($src), ['.', '..']) as $item) {
        $s = $src . '/' . $item;
        $d = $dst . '/' . $item;
        if (is_dir($s)) {
            plugin_copy_dir($s, $d);
        } else {
            @copy($s, $d);
        }
    }
}

function plugin_remove_files($dir)
{
    if (!is_dir($dir)) {
        return;
    }
    foreach (array_diff(scandir($dir), ['.', '..']) as $item) {
        $path = $dir . '/' . $item;
        if (is_link($path) || is_file($path)) {
            @unlink($path);
        } elseif (is_dir($path)) {
            plugin_remove_files($path);
        }
    }
    @rmdir($dir);
}

function plugin_cleanup($dir)
{
    package_remove_dir($dir);
}

function plugin_uninstall($slug)
{
    $slug = plugin_slugify($slug);
    plugin_remove_files(plugin_dir($slug));
    DB::delete('plugins', 'slug = ?', [$slug]);
}
