<?PHP


if($_SESSION['UserData']['level'] != 10){

	die(header('Location:'._RootUrl));
}


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

$sitemap_nr = '';


$this->callSqlClass(array('redirect_link'), $this);
$this->callClass(array('File'));

$this->redirect_link->Select();
$sitemap_nr = round($this->redirect_link->Numrows/50000);

$rows = $this->redirect_link->Query("SELECT count(1) AS counted FROM redirect_link", true);
$max_redirects = $rows[0]['counted'];

$this->redirect_link->Select("WHERE is_indexed = 0 ");
if($max_redirects == $this->redirect_link->Numrows){

	$this->File->GetAllFiles(_RootFolder, '.xml', '', 'both', false);
	foreach($this->File->Files as $v){

		unlink(_RootFolder.'/'.$v['file']);
	}
	if(is_file(_RootFolder.'/robots.txt'))
		unlink(_RootFolder.'/robots.txt');
}
while($row = $this->redirect_link->Assoc()){

	$this->redirect_link->Update(array('is_indexed' => 1), "WHERE id = ".$row['id']);

	$sitemap_content .= '<url>'."\n".
	'<loc><![CDATA['._RootUrl.'/'.$row['redirect_url'].']]></loc>'."\n".
	'<lastmod>'.date('Y-m-d').'</lastmod>'."\n".
	'<changefreq>monthly</changefreq>'."\n".
	'<priority>0.8</priority>'."\n".
	'</url>'."\n";
}

$sitemap_footer = '</urlset>';

if(!is_file(_RootFolder.'/robots.txt')){

	file_put_contents(_RootFolder.'/robots.txt', "User-agent: *\nAllow: /\n\nUser-agent: Googlebot\nAllow: /\n\nUser-agent: Googlebot-Image\nAllow: /\n\nUser-agent: Googlebot-Mobile\nAllow: /");
}

if($this->redirect_link->Numrows > 0){

	$sitemap_file = $sitemap_nr > 0 ? 'sitemap'.$sitemap_nr.'.xml' : 'sitemap.xml';

	if(!is_file(_RootFolder.'/'.$sitemap_file))
		file_put_contents(_RootFolder.'/'.$sitemap_file, $sitemap_header.$sitemap_content.$sitemap_footer);
	else
		file_put_contents(_RootFolder.'/'.$sitemap_file, str_replace('</urlset>', '', file_get_contents(_RootFolder.'/'.$sitemap_file)).$sitemap_content.$sitemap_footer);


	if(!preg_match('/'.$sitemap_file.'/', file_get_contents(_RootFolder.'/robots.txt')))
		file_put_contents(_RootFolder.'/robots.txt', file_get_contents(_RootFolder.'/robots.txt')."\n\n".''._RootUrl.'/'.$sitemap_file.'');
}

?>