<?php
    // generates sitemap for eKerner sites.
    // httpd.conf must set for this file: ForceType application/x-httpd-php
    // ekerner@ekerner.com.au

$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);

header('Content-type: application/xml');

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

recurse(
  $docRoot,
  strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/'))). '://', 
  $_SERVER['HTTP_HOST'], 
  array('/ajax', '/bin', '/widgets', '/error', '/stats')
);

function recurse($path, $proto, $host, $filters) 
{
  foreach (glob($path . '/*') as $pathName)
  {
    if (filterPath($pathName, $filters))
      continue;
    if (is_file($pathName)) {
      if (preg_match('@/[^\.]+(.(ht|x|w)ml)?$@', $pathName))
        writeSitemapEntry($pathName, $proto, $host);
    }
    else
      recurse($pathName, $proto, $host, $filters);
  }
}

// returns true if pathName occurs in filters and therefore path to be filtered out ...
function filterPath($pathName, $filters) {
  foreach($filters as $filter)
    if (preg_match('@' . $filter . '$@', $pathName))
      return true;
  return false;
}

function writeSitemapEntry($filePath, $proto, $host)
{
  global $docRoot;
  $lastMod  = date('Y-m-d', filemtime($filePath));
  $fileURI  = preg_replace('@/index$@', '/', str_replace($docRoot, '', $filePath));
  $changes  = 'monthly';
  $priority = 11 - (substr_count($fileURI, '/') * 2);
  if     (preg_match('@/index$@' , $filePath)) {
    $changes  = 'weekly';
    $priority += 1;
  }
  elseif (preg_match('@(/(sitemap|privacy|terms)|\.(ht|x|w)ml)$@', $filePath)) {
    $changes  = 'yearly';
    $priority  = 1;
  }
  if (!$priority) {
    $changes  = 'yearly';
    $priority = 1;
  }
  echo '
    <url>
      <loc>' . $proto . $host . $fileURI . '</loc>
      <lastmod>' . $lastMod . '</lastmod>
      <changefreq>' . $changes . '</changefreq>
      <priority>' . ($priority / 10) . '</priority>
    </url>
  ';
}

echo "  </urlset>\n";

?>
