<?php
/* ============================================================
 * 网站地图 XML（动态生成）
 * ============================================================ */
header('Content-Type: application/xml; charset=utf-8');

$root = __DIR__;
$db   = new SQLite3($root . '/data/d777ce190a82629e6fc10b69cfacc6be.db');
$db->busyTimeout(5000);

$site   = $db->querySingle("SELECT * FROM ay_site WHERE acode='cn'", true);
$domain = ($site && $site['domain']) ? $site['domain'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '127.0.0.6');
$base   = 'http://' . $domain;

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// 首页
echo "  <url>\n";
echo "    <loc>$base/</loc>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>1.0</priority>\n";
echo "  </url>\n";

// 栏目
$sorts = array();
$r = $db->query("SELECT * FROM ay_content_sort WHERE status='1' ORDER BY sorting, id");
while ($row = $r->fetchArray(SQLITE3_ASSOC)) {
    $sorts[$row['id']] = $row;
    $url = $base . '/' . $row['filename'] . '/';
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>0.8</priority>\n";
    echo "  </url>\n";
}

// 文章
$r = $db->query("SELECT id, scode, title, date FROM ay_content WHERE status='1' ORDER BY date DESC");
while ($row = $r->fetchArray(SQLITE3_ASSOC)) {
    $sort = isset($sorts[$row['scode']]) ? $sorts[$row['scode']] : null;
    if (!$sort) continue;
    $url = $base . '/' . $sort['filename'] . '/' . $row['id'] . '.html';
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
    echo "    <lastmod>" . date('Y-m-d', strtotime($row['date'])) . "</lastmod>\n";
    echo "    <changefreq>monthly</changefreq>\n";
    echo "    <priority>0.6</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>' . "\n";
