<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Sitemap extends MY_Controller {
 function __construct()
    {    
        parent::__construct();        
        header('Content-Type: application/xml; charset=utf-8');
        $this->output->set_content_type('text/xml');
        $this->load->helper('file');
    }   

	public function index()
	{
		$this->_get_cache("sitemap.xml");					
					
		$data['sites']  	= $this->Admin->getTable("sites",false,false,false,0,20000);
		$data['pages']  	= $this->Admin->getTable("pages");			
		$file = $this->load->view("sitemap/sitemap",$data,true);
		$this->_set_cache("sitemap.xml",$file);
		echo $file;
	}




	protected function _get_cache($file)
	{
		
		$file_cache = "cache/sitemap/$file";
		if(file_exists($file_cache) && is_readable($file_cache))
		{		
			if (time()-filemtime($file_cache) > 24 * 3600) {
			  // file older than 24 hours
				@unlink($file_cache);
			}		
			if(file_exists($file_cache))
			{
				/*header('Content-Type: application/xml; charset=utf-8');
				echo read_file($file_cache).$this->_set_benchmark();
				exit;*/
				redirect(base_url().$file_cache,301);
				die();
			}
			else
			{
				return false;
			}

		}
		return false;
	}

	protected function _set_cache($file,$xml)
	{	
		if(!file_exists("cache/sitemap/"))
			mkdir("cache/sitemap/",0777,TRUE);
		if(!is_writable("cache/sitemap/"))
		{
			header('Content-Type: text/html; charset=utf-8');
			die("Please set permissions to folder cache/sitemap");
		}
		$file_cache = "cache/sitemap/$file";		
		write_file($file_cache, $xml);		
	}

	protected function _set_benchmark()
	{		
		return "<!-- Cache -->";
	}



}