<?php
@ini_set('display_errors', 0);
@error_reporting(0);

// 1. 啟動最外層輸出緩衝，攔截 mainfile.php 可能產生的任何雜訊
ob_start();

if (file_exists("mainfile.php")) {
    include_once "mainfile.php";
} else {
    ob_end_clean();
    die("Error: mainfile.php not found.");
}

global $xoopsDB;

$site_domain = "https://shadowsum.com";
$secret_key  = "shadowsum_worship_secret_2026";

$sql = "SELECT id FROM " . $xoopsDB->prefix("song_lyrics") . " ORDER BY id DESC";
$result = $xoopsDB->query($sql);

$urls = array();
if ($result) {
    while ($row = $xoopsDB->fetchArray($result)) {
        $real_id   = intval($row['id']);
        if ($real_id > 0) {
            $crypto_id = substr(md5($real_id . $secret_key), 0, 8);
            $urls[]    = $site_domain . "/modules/song/ppts.php?id=" . $crypto_id;
        }
    }
}

// 2. 徹底清空緩衝區內所有多餘的空白、換行或警告訊息
while (ob_get_level() > 0) {
    ob_end_clean();
}

// 3. 發送標準 XML 標頭並禁止快取
header("Content-Type: application/xml; charset=utf-8");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

$xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://sitemaps.org">' . "\n";

$xml .= "  <url>\n";
$xml .= "    <loc>" . $site_domain . "/index.php</loc>\n";
$xml .= "    <changefreq>daily</changefreq>\n";
$xml .= "    <priority>1.0</priority>\n";
$xml .= "  </url>\n";

$xml .= "  <url>\n";
$xml .= "    <loc>" . $site_domain . "/modules/song/index.php</loc>\n";
$xml .= "    <changefreq>daily</changefreq>\n";
$xml .= "    <priority>0.9</priority>\n";
$xml .= "  </url>\n";

foreach ($urls as $song_url) {
    $clean_url = htmlspecialchars($song_url, ENT_XML1, 'UTF-8');
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . $clean_url . "</loc>\n";
    $xml .= "    <changefreq>weekly</changefreq>\n";
    $xml .= "    <priority>0.8</priority>\n";
    $xml .= "  </url>\n";
}

$xml .= '</urlset>';

// 過濾掉任何可能導致 XML 解析崩潰的非法控制字元
echo preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml);
exit;
?>
