<?php
    if( isset($_GET['xml']) ) {
        $display_xml = true;
    } else {
        $display_xml = false;
    }
    $base_url = "https://sirius10.net";
    $base_dir = "/var/www/sirius10";
    $index_html = "/index.html";
    $exclude_list = array(
                  "/blog/wordpress/",
                  "/cgi-bin/",
                  "/sitemap.php"
    );
    $n_exclude = count($exclude_list);
    $mysketch = "/blog/MySketch/index.html";
    $wordpress = "https://sirius10.net/blog/wordpress/index.php/page-1564";

    $list_link = array($index_html);
    $xml = "";

    function add_first() {
        global $wordpress, $display_xml, $xml;

        if( $display_xml ) {
            $xml = $xml . "<url><loc>https://sirius10.net/blog/wordpress/</loc></url>\n";
//            return "";
        }

        $retval = "";
        if( ($blog = file($wordpress)) === false ) {
            return "        <li><a href=\"" .
                   $wordpress . "\">Sirius のブログ</a></li>\n";
        }

        $wp_list = array();
        $skip = true;
        $n_ul = 0;
        $ul_skip = false;
        foreach( $blog as $line ) {
            if( $skip && strpos($line, '<h2 class="entry-title">カテゴリー</h2>') !== false ) {
                $skip = false;
                continue;
            }
            if( $skip ) continue;
            if( strpos($line, "<ul>") !== false ) $n_ul++;
            if( strpos($line, "</ul>") !== false ) $n_ul--;
            if( strpos($line, "</ul>\n") !== false ) {
                $ul_skip = true;
                continue;
            }
            if( $n_ul == 0 ) {
                $retval = $retval . "          </ul>\n";
                break;
            }
            $line = preg_replace('/ class="[^"]*"/', '', $line);
            if( substr($line, -5) == "</a>\n" ) {
                $line = str_replace('<li>', '<li><details open><summary>', $line);
                $line = substr($line, 0, strlen($line) - 1) . "</summary>\n";
            } else if( strpos($line, "</ul></li>") !== false )
                $line = "</ul></details></li>\n";
            $spc = sprintf("%" . ($n_ul * 2 + 8) . "s", "");
            if( strpos($line, "<ul>") !== false && $ul_skip ) {
                $retval = $retval . $spc . substr($line, 4);
                $ul_skip = false;
            } else
                $retval = $retval . $spc . "  " . $line;
            if( $display_xml ) {
                if( strpos($line, "<a href=") !== false ) {
                    $url = substr($line, strpos($line, "<a href=")+9);
                    $url = substr($url, 0, strpos($url, '"'));
                    for( $i = 0; $i < count($wp_list); $i++ ) {
                        if( $url == $wp_list[$i] ) break;
                    }
                    if( $i >= count($wp_list) ) {
                        $xml = $xml . "<url><loc>". $url . "</loc></url>\n";
                        $wp_list[] = $url;
                    }
                }
            }
        }
        return "        <li><details><summary><a href=\"https://sirius10.net/blog/wordpress/\">Sirius のブログ</a></summary>\n" . $retval .
               "        </details></li>\n";
    }

    function add_last() {
        global $display_xml, $xml;

        if( $display_xml ) {
            $xml = $xml . "<url><loc>https://sirius10.net/sitemap.php</loc></url>\n";
            return "";
        }
        return "        <li>サイトマップ</li>\n";
    }

    function get_title($file) {
        $retval = $file;
        if( ($fp = fopen($file, "r")) !== false ) {
            while( ($line = fgets($fp)) !== false ) {
                if( preg_match('/<title>(?P<title>.*) - Sirius<\/title>/', $line, $word) ) {
                    $retval = mb_convert_encoding($word['title'], "utf-8", "Windows-31J");
                    break;
                }
            }
            fclose($fp);
        }
        return $retval;
    }

    function get_category($file) {
        $retval = $file;
        if( ($fp = fopen($file, "r")) !== false ) {
            $cat_f = false;
            while( ($line = fgets($fp)) !== false ) {
                if( $cat_f ) {
                    if( preg_match('/<p>(?P<title>.*)<\/p>/', $line, $word) ) {
                        if( substr($word['title'], 0, 1) == "/" )
                            $title = substr($word['title'], 1);
                        else
                            $title = $word['title'];
                        $retval = mb_convert_encoding($title, "utf-8", "Windows-31J");
                        break;
                    }
                }
                if( strpos($line, "<h2>Category</h2>") !== false )
                    $cat_f = true;
                else
                    $cat_f = false;
            }
            fclose($fp);
        }
        return $retval;
    }

    function check_article($dir) {
        global $base_dir, $base_url, $display_xml, $xml;

        $retval = "";
        if( ($fp = fopen($base_dir . $dir . ".html", "r")) !== false ) {
            while( ($line = fgets($fp)) !== false ) {
                if( strpos($line, "<h2>Categories</h2>") !== false ) break;
                if( preg_match('/<a href=.*ShowDiary_file=(?P<url>[^"]*)">(?P<title>[^<]*)</', $line, $word) ) {
                    $file = "/blog/MySketch/category" . $word['url'] . ".html";
                    if( ! is_file($base_dir .$file) ) continue;
                    $retval = $retval . "                <li><a href=\"" .
                         $base_url . $file . "\">" .
                         mb_convert_encoding($word['title'], "utf-8",
                         "Windows-31J") . " (" .  date("Y-m-dTH:d:s",
                         filemtime($base_dir .$file)) . " 更新)</a></li>\n";
                    if( $display_xml ) {
                        $xml = $xml . "<url><loc>" . $base_url . $file .
                               "</loc><lastmod>" . date(DATE_W3C,
                               filemtime($base_dir . $file)) .
                               "</lastmod></url>\n";
                    }
                }
            }
            fclose($fp);
        }
        return $retval;
    }

    function check_noarticle($dir) {
        global $base_dir, $base_url, $display_xml, $xml;

        $retval = "";
        $page_list = array();
        if( is_dir($base_dir . $dir) ) {
            if( $dp = opendir($base_dir . $dir) ) {
                $retval = $retval . "              <ul>\n";
                while( ($file = readdir($dp)) !== false ) {
                    if( strpos($file, ".i.html") ) continue;
                    if( ! is_file($base_dir . $dir . "/" . $file) ) continue;
                    $page_list[] = $dir . "/" . $file;
                }
                rsort($page_list);
                $n_page = count($page_list);
                for( $i = 0; $i < $n_page; $i++ ) {
                    $title = get_title($base_dir . $page_list[$i]);
                    $retval = $retval . "                <li><a href=\"" .
                              $base_url . $page_list[$i] . "\">" .
                              $title . " (" .  date("Y-m-dTH:d:s",
                              filemtime($base_dir . $page_list[$i])) .
                              " 更新)</a></li>\n";
                    if( $display_xml ) {
                        $xml = $xml . "<url><loc>" . $base_url . $page_list[$i] .
                               "</loc><lastmod>" . date(DATE_W3C,
                               filemtime($base_dir . $page_list[$i])) .
                               "</lastmod></url>\n";
                    }
                }
                $retval = $retval . "              </ul>\n            </details></li>\n";
                closedir($dp);
            }
        }
        return $retval;
    }

    function parse_mysketch($title, $html, $level) {
        global $base_dir, $base_url, $exclude_list, $n_exclude,
               $list_link, $display_xml, $xml;
        $retval = "";
        $cat_dir = "/blog/MySketch/category/";
        $retval = "        <li><details><summary><a href=\"" .
                  $base_url . $html . "\">ブログ (" .
                  date("Y-m-dTH:d:s", filemtime($base_dir . $html)) .
                  " 更新)</a></summary>";
        if( $display_xml ) {
            $xml = $xml . "<url><loc>" . $base_url . $html . "</loc><lastmod>" .
                   date(DATE_W3C, filemtime($base_dir . $html)) .
                   "</lastmod></url>\n";
        }
        if( ($dp = opendir($base_dir . $cat_dir)) === false ) {
            $retval = $retval . "</details></li>\n";
            return $retval;
        }
        $retval = $retval . "\n          <ul>\n";
        while (($file = readdir($dp)) !== false) {
            if( ! is_dir($base_dir . $cat_dir . $file) ) continue;

            $target = $file . ".html";
            if( ! is_file($base_dir . $cat_dir . $target) ) continue;

            $list_link[] = $cat_dir . $target;
            $title = get_category($base_dir . $cat_dir . $target);
            $retval = $retval .
                      "            <li><details open><summary><a href=\"" .
                      $base_url . $cat_dir .
                      $target . "\">" .  $title . " (" .
                      date("Y-m-dTH:d:s", filemtime($base_dir . $cat_dir . $target)) .
                      " 更新)</a></summary>\n              <ul>\n" .
                      check_article($cat_dir . $file) .
                      "              </ul>\n            </details></li>\n";
            if( $display_xml ) {
                $xml = $xml . "<url><loc>" . $base_url . $cat_dir . $target .
                       "</loc><lastmod>" . date(DATE_W3C,
                       filemtime($base_dir . $cat_dir . $target)) .
                       "</lastmod></url>\n";
            }
        }
        closedir($dp);
        $retval = $retval . "            <li><details open><summary>未分類</summary>\n" .
        check_noarticle($cat_dir . "nocategory") .
        "          </ul>\n        </details></li>\n";

        return $retval;
    }

    function fixpath($html) {
        global $base_dir, $list_link, $exclude_list, $n_exclude;

        if( substr($html, 0, 2) == "//" ) $html = substr($html, 1);
        $lastChar = substr($html, -1);

        $target = $html;
        if( $lastChar == '/' ) {
            if( is_file($base_dir . $html . "index.html") ) {
                $target = $html . "index.html";
            } else if( is_file($base_dir . $html . "index.php") ) {
                $target = $html . "index.php";
            }
        }
        $htmlpath = realpath($base_dir . $target);
        if( $htmlpath === false || !is_file($htmlpath) ) return false;
        $target = substr($htmlpath, strlen($base_dir));

        $i = 0;
        for( ; $i < count($list_link); $i++ ) {
            if( $target == $list_link[$i] )
                break;
        }
        if( $i < count($list_link) ) return false;

        $i = 0;
        for( ; $i < $n_exclude; $i++ ) {
            if( strpos($target, $exclude_list[$i]) !== false )
                break;
        }
        if( $i < $n_exclude ) return false;

        return $target;
    }

    function parse_html($title, $html, $level) {
        global $base_dir, $base_url, $exclude_list, $n_exclude,
               $list_link, $mysketch, $display_xml, $xml;

        $retval = "";
        if( $html == $mysketch ) return parse_mysketch($title, $html, $level);
        if( ($fp = fopen($base_dir . $html, "r")) === false ) return "";
        $list_url = array();
        $list_title = array();
        $innerhtml = "";
        $skip = false;
        while( ($line = fgets($fp)) !== false ) {
            if( $skip ) {
                if( strpos($line, "<td bgcolor=") !== false
                    || strpos($line, "</details>") !== false )
                    $skip = false;
                continue;
            }
            if( preg_match('/<[Aa] [^<]*[Hh][Rr][Ee][Ff]="(?P<href>[^"]*)"[^>]*>(?P<title>.*)<\/a>/', $line, $url) ) {
                if( $url['href'] == "" ) continue;
                $new_html = $url['href'];
                if( strpos($url['href'], "http") !== false ) {
                    if( strpos($url['href'], $base_url) !== false )
                        $new_html = substr($url['href'], strlen($base_url)-1);
                    else
                        continue;
                } else {
                    $firstChar = substr($url['href'], 0, 1);
                    if( $firstChar != '/' )
                            $new_html = dirname($html) . "/" . $url['href'];
                }
                if( ($new_html = fixpath($new_html)) === false ) continue;
                $list_url[] = $new_html;
                $list_title[] = mb_convert_encoding($url['title'],
                                                "utf-8", "utf-8,Windows-31J");
                $list_link[] = $new_html;
            } else {
                if( strpos(mb_convert_encoding($line , "utf-8", "utf-8,Windows-31J"), "更新履歴") !== false ) {
                    $skip = true;
                }
            }
        }
        $n = count($list_url);
        for( $i = 0; $i < $n; $i++ ) {
            $innerhtml = $innerhtml . parse_html($list_title[$i] , $list_url[$i], $level + 1);
        }
        if( ! feof($fp) ) {
            echo $html . "ファイルの読み込みでエラーがありました。\n";
        }
        fclose($fp);

        $spc = sprintf("%" . ($level * 4) . "s", "");
        if( $innerhtml != "" ) {
            $retval = $retval . $spc .
                      "<li><details open><summary><a href=\"" . $base_url .
                      $html . "\">" . $title ." (" . "" .
                      date("Y-m-dTH:d:s", filemtime($base_dir . $html)) .
                      " 更新)</a></summary>";
        } else {
            $retval = $retval . $spc . "<li><a href=\"" . $base_url .
                      $html . "\">" .  $title ." (" . "" .
                      date("Y-m-dTH:d:s", filemtime($base_dir . $html)) .
                      " 更新)</a>";
        }
        if( $display_xml ) {
            $xml = $xml . "<url><loc>" . $base_url . $html .
                   "</loc><lastmod>" . date(DATE_W3C,
                   filemtime($base_dir . $html)) .
                   "</lastmod></url>\n";
        }
        if( $innerhtml != "" ) {
            $retval = $retval . "\n" . $spc . "  <ul>\n";
            if( $level == 1 ) $retval = $retval . add_first();
            $retval = $retval . $innerhtml;
            if( $level == 1 ) $retval = $retval . add_last();
            $retval = $retval . $spc . "  </ul>\n" . $spc . "</details></li>\n";
        } else
            $retval = $retval . "</li>\n";

        return $retval;
    }

    if( $display_xml ) {
        header('Content-Type: application/xml');
        parse_html("ホーム", $index_html, 1);
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . 
            '<?xml-stylesheet type="text/xsl" href="https://sirius10.net/css/sitemap.xsl" ?>' . "\n" .
            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' .
            "\n" . $xml . "</urlset>\n";
        $sxe = new SimpleXMLElement($xml);
        echo $sxe->asXML();
    } else {
?>
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
  <title>サイトマップ</title>
  <link rel="stylesheet" href="/css/base.css" type="text/css">
  <link rel="shortcut icon" href="/favicon.ico">
  <style>
    li { margin-top: 0.5em; }
  </style>
  <script src="/js/sites.js" charset="utf-8"></script>
  <script type="application/ld+json">
  [{
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [{
      "@type": "ListItem",
      "position": 1,
      "name": "ホーム",
      "item": "https://sirius10.net/"
    },{
      "@type": "ListItem",
      "position": 2,
      "name": "サイトマップ"
    }]
  },{
    "@context": "https://schema.org",
    "@type": "WebSite",
    "url": "https://sirius10.net/",
    "potentialAction": {
      "@type": "SearchAction",
      "target": "https://sirius10.net/cgi-bin/Search/namazu.cgi?query={query}&amp;max=50&amp;result=normal&amp;sort=score",
      "query-input": "required name=query"
    }
  }]
  </script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-NVLD9FGZ73"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-NVLD9FGZ73');
</script>
</head>
<body>
<div class="header">
  <div class="breadcrumb">
    <ol>
      <li><a href="/">ホーム</a></li>
      <li>サイトマップ</li>
    </ol>
  </div>
  <div class="sitemap"><a href="#" onClick="history.back();return false;">戻る</a></div>
  <div class="search_box">
    <form id="search_form" accept-charset="EUC-JP" method="get" action="/cgi-bin/Search/namazu.cgi">
      <input id="search_text" type="search" name="query" size="35" placeholder="サイト内検索(ブログは除外)" title="サイト内検索" value="" required>
      <input id="search_button" type="submit" name="submit" value="" alt="検索">
      <input type="hidden" name="max" value="50">
      <input type="hidden" name="result" value="normal">
      <input type="hidden" name="sort" value="score">
    </form>
  </div>
</div>
<div class="title">
  <div class="wellcome"><h1>サイトマップ</h1></div>
</div>
<div class="tree">
  <ul>
<?php
        echo parse_html("ホーム", $index_html, 1);
?>
  </ul>
</div>
</body>
</html>
<?php
    }
