<?php

include_once './core/sitemap.class.php';
include_once './core/structure.class.php';

class website_sitemap {
	private $base_object;
	private $layout_object;
	
	public function __construct($base_object, $layout_object) {
		$this->base_object = $base_object;
		$this->layout_object = $layout_object;
	}
		
	function run() {
		if (isset($_GET['action']) && $_GET['action'] == 'get_xml') {
			return $this->get_xml_sitemap();
		}
		else {
			return $this->get_sitemap();
		}
	}

	private function get_sitemap() {
		$file = $this->base_object->get_document_dir() . 'files/sitemap.html';
		
		if (file_exists($file)) {
			$text = '';
			$fh = fopen($file, 'r');
			while (!feof($fh)) {
				$text .= fread($fh, 8192);
			}
			fclose($fh);
			
			return $text;
		} else {
			$sitemap_object = new Sitemap($this->base_object);
			
			$sitemap_data = $sitemap_object->get_sitemap();
			
			$this->layout_object->assign('sitemap', $sitemap_data);
			
			return $this->layout_object->_fetch('content_sitemap.tpl');
		}
	}
	
	private function get_xml_sitemap() {
		$file = $this->base_object->get_document_dir() . 'files/sitemap.xml';
		
		if (file_exists($file)) {
			$fh = fopen($file, 'r');
			while (!feof($fh)) {
				echo fread($fh, 8192);
			}
			fclose($fh);
			
			exit();
		} else {
			$sitemap_object = new Sitemap($this->base_object);
			
			$sitemap_data = $sitemap_object->get_sitemap();
			$date = date('Y-m-d');
			
			$this->layout_object->assign('sitemap', $sitemap_data);
			$this->layout_object->assign('date', $date);
			header("Content-type: text/xml");
			echo $this->layout_object->_fetch('sitemap.xml');
                        exit();
		}
	}
}