<?php
// 引入后台路径
require_once $_SERVER['DOCUMENT_ROOT'] . '/data/admin.php';
/*
 * Name: 泛程序系统
 * 禁止用于违法、违规行业，仅供本地学习参考使用，禁止联网采集！
 */
header('Content-type: text/html; charset=utf-8');

@ini_set('memory_limit', '256M');
@ini_set('session.cache_expire', 180);
@ini_set('session.use_trans_sid', 0);
@ini_set('session.use_cookies', 1);
@ini_set('session.auto_start', 0);

require_once 'config.php';
require_once __DIR__ . '/data/no_layer.php';
require_once __DIR__ . '/data/spider_log_async.php';

include $tj . '/t.php';   // 蜘蛛日志：默认 defer 登记
include 'fangke.php';
include 'waf.php';

$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
if ($uri === '' || $uri === false || $uri === null) {
    $uri = '/';
}
if (function_exists('rishouServeBrandHomeAsset') && rishouServeBrandHomeAsset($uri)) {
    exit;
}

include './baidu_set.php';

if (function_exists('rishouRequestIsBrandHome') && rishouRequestIsBrandHome($uri)
    && function_exists('rishouServeBrandHomePage') && rishouServeBrandHomePage()) {
    exit;
}

// 历史首页：斗篷之后，仅裸域和 www 首页、且该根域有 data/hist_home/{根域}.html 才退出。
// 其它二级首页走日收模版。extractRootDomain 会剥 www，不能单用它判断。没有文件的域走原模板。
if ($uri === '/' || preg_match('#^/(index\.(php|html|htm|asp))$#i', (string) $uri)) {
    $histHost = strtolower(trim((string) ($_SERVER['HTTP_HOST'] ?? '')));
    $histHost = preg_replace('/:\d+$/', '', $histHost);
    $histHost = rtrim($histHost, '.');
    $histRoot = extractRootDomain($histHost);
    if ($histHost !== '' && ($histHost === $histRoot || $histHost === 'www.' . $histRoot) && preg_match('/^[a-z0-9.-]+$/', $histRoot)) {
        $histFile = __DIR__ . '/data/hist_home/' . $histRoot . '.html';
        if (is_file($histFile)) {
            $histHtml = file_get_contents($histFile);
            if (is_string($histHtml) && $histHtml !== '') {
                echo $histHtml;
                if (function_exists('fastcgi_finish_request')) {
                    @fastcgi_finish_request();
                }
                alan_spider_log_flush_jobs();
                exit;
            }
        }
    }
}

$ext = pathinfo($uri, PATHINFO_EXTENSION);
if ($ext && preg_match('/^(jpg|jpeg|png|gif|webp|svg|ico|bmp)$/i', $ext)) {
    $types = [
        'jpg' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
        'webp' => 'image/webp',
        'svg' => 'image/svg+xml',
        'ico' => 'image/x-icon',
        'bmp' => 'image/bmp',
    ];
    $ctype = $types[strtolower($ext)] ?? 'application/octet-stream';

    $parts = explode('/', ltrim($uri, '/'));
    $count = count($parts);
    for ($i = 0; $i < $count; $i++) {
        $candidate = '/' . implode('/', array_slice($parts, $i));
        $p = $_SERVER['DOCUMENT_ROOT'] . $candidate;
        if (is_file($p)) {
            header('Content-Type: ' . $ctype);
            header('Content-Length: ' . filesize($p));
            readfile($p);
            exit;
        }
    }
    header('HTTP/1.1 404 Not Found');
    exit;
}

if ($google == 1) {
    $mubanDir = 'ggtemplates';
} else {
    $mubanDir = 'templates';
}

if ($indexnow == 1) {
    require_once 'indexnow.php';
}

$dataDir = 'data';

if (function_exists('rishouHyeeaModIdInner') && rishouHyeeaModIdInner($uri)) {
    $templatePath = $mubanDir . '/show';
} elseif ($uri === '/' || preg_match('#^/(index\.(php|html|htm|asp))$#i', $uri)) {
    $templatePath = $mubanDir . '/index';
} elseif (preg_match('#\.[^/]+$#', $uri)) {
    $templatePath = $mubanDir . '/show';
} elseif (preg_match('#/$#', $uri) || !strpos(basename($uri), '.')) {
    $templatePath = $mubanDir . '/list';
} else {
    $templatePath = $mubanDir . '/index';
}

// ---- SEO / 网络营销推广 栏目：按一级路径前缀切到独立模板组 ----
// 站点主体是软件下载站，GPT 语料却是 SEO 教程文章；把这类内容收进专属栏目，
// 避免「标题承诺应用下载、正文是 SEO 教程」的语义错配。
// 目录不存在或为空时自动回落到通用模板，所以未部署 seo-* 模板时本段是惰性的。
$seoSectionPrefixes = ['seo', 'tuiguang', 'yingxiao', 'marketing'];
$firstSegment = strtolower(explode('/', trim((string) $uri, '/'))[0] ?? '');
if ($firstSegment !== '' && in_array($firstSegment, $seoSectionPrefixes, true)) {
    if ($templatePath === $mubanDir . '/show') {
        $seoDir = $mubanDir . '/seo-show';
    } elseif ($templatePath === $mubanDir . '/list') {
        $seoDir = $mubanDir . '/seo-list';
    } else {
        $seoDir = null;
    }
    if ($seoDir !== null && is_dir($seoDir) && glob($seoDir . '/*.html')) {
        $templatePath = $seoDir;
    }
}

$muban = process($templatePath, $dataDir);

// 防查看：可配置 KB + 镜像加厚（见 data/no_layer.php / pz.php）
if ($no == 1) {
    $noLayer = alan_get_no_layer_for_request();
    if ($noLayer !== '') {
        $muban = $noLayer . $muban;
    }
}

if ($onlinks == 1) {
    ob_start();
    include 'links.php';
    $linksContent = ob_get_clean();
    $muban = $muban . $linksContent;
}

// SEO 页响应头：配合 meta no-transform / noarchive（增强声明，删不掉历史快照）
if (!headers_sent()) {
    header('Cache-Control: no-transform');
    // 仅声明 noarchive，不使用 noindex，避免误伤收录
    header('X-Robots-Tag: noarchive');
}

echo $muban;

// 尽快结束响应后再写蜘蛛日志（FPM）
if (function_exists('fastcgi_finish_request')) {
    @fastcgi_finish_request();
}
alan_spider_log_flush_jobs();
