<?php
// 统一配置（避免硬编码）
define('DB_HOST', '144.34.236.197');
define('DB_NAME', 'tupian');
define('DB_USER', 'tupian');
define('DB_PASS', '4482DMteXaZGcNLG');

// 全局资源声明（避免未定义警告）
$dbh = null;
$stmt = null;
$memcache = null;

try {
    // 参数过滤（防御XSS/SQL注入）
    $table = isset($_GET['table']) ? preg_replace('/[^a-zA-Z0-9_]/', '', trim($_GET['table'])) : '';
    $name = isset($_GET['name']) ? htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8') : '';

    // 尺寸档(2026-09-21 加): 不传 = 1920, 即原行为(详情页大图用);
    //   详情页的缩略图条传 400(只够 40x54 的框看, 实测 256x384 / 12~25KB)。
    //   ★ 别传它没有的档: 微云 scale 的档位**每张图不一样**, 缺档会退回原图
    //     (实测 size=300 在 8 张抽样里有 1 张退回原图 137KB; size=400 在 8/8 都命中)。
    //   夹紧到 200~1920, 防滥用。
    $size = isset($_GET['size']) ? (int)$_GET['size'] : 1920;
    if ($size < 200) { $size = 200; }
    if ($size > 1920) { $size = 1920; }

    // 白名单校验（严格模式）
    $allowed_tables = ['1xiuren', '1xiurenup1', '1xiurenup2','2xiezhenup2','2xiezhen', '2xiezhenup1', '3jingpin', '3jingpinup1', '3jingpinup2','4simo', '4simoup1', '4simoup2', '5dachidu', '5dachiduup1', '6wanghong', '6wanghongup1', '7fuli', '7fuliup1','7fuliup2', '8asmr', '8cos', '8cosup1', '9shipinv'];
    if (!in_array($table, $allowed_tables, true)) {
        throw new Exception("非法请求");
    }

    // 生成标准缓存键（避免特殊字符）
    $cache_key = substr(preg_replace('/[^a-zA-Z0-9_-]/', '_', "{$table}_{$name}"), 0, 200);

    // 优先初始化memcache持久连接并查询缓存（命中则直接返回，不连DB）
    $memcache = new Memcache;
    if (!$memcache->pconnect('localhost', 11211)) {
        throw new Exception("缓存服务异常");
    }

    // 缓存命中：直接跳转，跳过DB连接
    if ($data = $memcache->get($cache_key)) {
        header("Location: https://picabstract-preview-ftn.weiyun.com".$data['tupian_weiyun']."?pictype=scale&fname=$name&size=$size");
        exit();
    }

    // 缓存未命中：才初始化PDO持久连接查数据库
    $dbh = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME,
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true]
    );

    // 数据库查询（防止SQL注入，只选择需要的列）
    $stmt = $dbh->prepare("SELECT tupian_weiyun FROM `{$table}` WHERE tupian_name = :name");
    $stmt->bindValue(':name', $name, PDO::PARAM_STR);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        $memcache->set($cache_key, $result, 0, 259200);
        header("Location: https://picabstract-preview-ftn.weiyun.com".$result['tupian_weiyun']."?pictype=scale&fname=$name&size=$size");
        exit();
    } else {
        throw new Exception("Data does not exist");
    }

} catch (PDOException $e) {
    error_log("数据库异常: ".$e->getMessage());
    $error = "系统繁忙，请稍后重试";
} catch (Exception $e) {
    $error = $e->getMessage();
}

// 资源释放（持久连接不真正关闭，仅释放引用）
$stmt = null;
$dbh = null;
// memcache持久连接不调用close，由PHP进程生命周期管理

// 错误输出
die(isset($error) ? $error : '未知错误');
?>
