<?php
header("Content-type: text/xml; charset=UTF-8");

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

/**
 * 数组按字段排序
 */
function arraySort($array, $keys, $sort = SORT_DESC)
{
    $keysValue = [];
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$keys];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}

/**
 * 是否 HTTPS
 */
function isSsl()
{
    if (
        (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == '1' || strtolower($_SERVER['HTTPS']) == 'on')) ||
        (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] == 'https') ||
        (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') ||
        (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
    ) {
        return 'https';
    }

    return 'http';
}

/**
 * 不生成 sitemap 的文件
 */
$dele_arr = [
    'index.php',
    'error_log',
    '404.html',
    'google32ccf7ba0081b2e7.html',
    'yandex_58d7ed5a0d4fdb26.html',
    'yandex_0887a289ce8c8805.html'
];

/**
 * 需要递归扫描的目录
 * 以后新增目录，只需要加这里
 */
$include_dirs = [
    'tag',
    //'tag',
    //'news',
];

$filesss = [];

/**
 * -----------------------
 * 扫描根目录（不递归）
 * -----------------------
 */
foreach (glob("./*.html") as $file) {

    $filename = basename($file);

    if (in_array($filename, $dele_arr)) {
        continue;
    }

    $filesss[] = [
        'filename' => $filename,
        'time' => filemtime($file)
    ];
}

/**
 * -----------------------
 * 扫描指定目录（递归）
 * -----------------------
 */
foreach ($include_dirs as $dir) {

    $scanDir = "./" . $dir;

    if (!is_dir($scanDir)) {
        continue;
    }

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(
            $scanDir,
            RecursiveDirectoryIterator::SKIP_DOTS
        )
    );

    foreach ($iterator as $fileinfo) {

        if (!$fileinfo->isFile()) {
            continue;
        }

        if (strtolower($fileinfo->getExtension()) != 'html') {
            continue;
        }

        // 目录中的相对路径
        $relative = str_replace("\\", "/", $iterator->getSubPathName());

        $filename = $dir . "/" . $relative;

        $parts = explode('/', $filename);

        if (array_intersect($parts, $dele_arr)) {
            continue;
        }

        $filesss[] = [
            'filename' => $filename,
            'time' => $fileinfo->getMTime()
        ];
    }
}

/**
 * 时间倒序
 */
$maps = arraySort($filesss, 'time', SORT_DESC);

$mydomain = isSsl() . "://" . $_SERVER['HTTP_HOST'];

foreach ($maps as $item) {

    $url = $item['filename'];

    // 首页 index.html -> /
    if ($url == "index.html") {
        $url = "";
    } else {

        $arr = explode("/", $url);

        foreach ($arr as &$v) {
            $v = rawurlencode($v);
        }

        $url = implode("/", $arr);
    }

    echo "<url>";
    echo "<loc>" . htmlspecialchars($mydomain . "/de/" . $url, ENT_XML1) . "</loc>";
    echo "<lastmod>" . gmdate("Y-m-d\\TH:i:s+00:00", $item['time']) . "</lastmod>";
    echo "</url>";
}

echo "</urlset>";