<?php /*********************************
Search Engine Doorway Generator (SEoDOR)
*   v. 3.2 (12.09.2014), UTF-8 (без BOM)
Copyright © 2014, http://seodor.biz   */
	
		
	@header('Content-Type: text/html; charset=utf-8');
	mb_internal_encoding('UTF-8');
	define ( 'SEODOR', true );
	if (!ini_get('date.timezone')) date_default_timezone_set('GMT');
	error_reporting(E_ALL ^E_NOTICE);
	//error_reporting(E_ALL);

include ('inc/getsub.php');
include ('conf.php');

if (!$code)exit('license error');
include_once ('inc/functions.php');

if ($dorgen){ // время генерации страницы
	$time_start = microtime_float();
	$startMemory = memory_get_usage();
}

if ($ip_admin){ // запрет по IP
	if (ipAllowed($ip_admin) == false) {
		header('HTTP/1.0 403 Forbidden');
		die('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don\'t have permission to access this file.</p>
<hr>
<address>Server at '.$_SERVER['SERVER_NAME'].'</address>
</body></html>');
	}
}

if ($typeUrl=='5')$extension='/';
if ($cacheType !='1') {
	$SQLite = 1;
	if ($typeUrl=='5' and $cacheType =='4') $extension='';
} else $SQLite = 0;
if (!$SQLite){$urlOpt=0;$multikeyMod=0;$imgSQLite=0;}
if (!$myimages){$cacheImgFiles=0;$imgSQLite=0;}
if (!$siteContentMod)$siteArticleMod=0;
$remote_proxy = 0;
if ($remote==2){$remote_proxy=1;$remote=0;}

if ($remote || $remote_proxy) {

	if ($remote_proxy){
		$ref_url = str_replace('www.', '', 'http://'.$servername.$request_uri);
		$refer = parse_url ($ref_url);
	} else {
		$expl_ua = explode("|", $_SERVER["HTTP_USER_AGENT"]);
		$refer = parse_url (str_replace('www.', '', $expl_ua[3]));
	}

	if (strstr($remoteKlients, $refer['host']) == false) {
		header('HTTP/1.0 403 Forbidden');
		die('You are not allowed to access this file.');
	}
	
	if ($remoteKeywords) {
		if ($subKey) $remoteKeywords = 'ucontent/keywords/'.get_base_domain('http://'.$refer['host']).'.txt';
		else $remoteKeywords = 'ucontent/keywords/'.$refer['host'].'.txt';
		if($remoteGenKeywords) division_file($keywords, $remoteKeywords, $remoteGenKeywords);
		$keywords = $remoteKeywords;
	}
	
	if ($subKey) $base_domain = get_base_domain('http://'.$refer['host']);
	else $base_domain = $refer['host'];
	
	if ($remote_proxy) {
		$request_uri = str_replace($folderDor, '', $request_uri);
		if (preg_match("~\?template=(.*?)&folderdor=(.*?)$~", $request_uri, $m_path)){
			$template = $m_path[1];
			$folderDor = $m_path[2] ? trim($m_path[2],' /').'/' : '';
		}
		
		$request_uri = preg_replace("~\?template.*?$~", '', $request_uri);
	}
	else{
		$template = !empty($expl_ua[0]) ? $expl_ua[0] : $template;
		$folderDor = !empty($expl_ua[1]) ? trim($expl_ua[1],' /').'/' : '';
		$userIP = !empty($expl_ua[4]) ? $expl_ua[4] : '';
		$uagent = !empty($expl_ua[5]) ? $expl_ua[5] : '';
	}
	$servername = $base_domain;
}

if (!$subKey and !$remote) $base_domain = str_replace("www.", "", $servername);

if(!$dorgen){ // показываем или скрываем ошибки
	ini_set("display_errors", 0); error_reporting(0);
} else {
	ini_set("display_errors", 1); error_reporting(E_ALL ^E_NOTICE);
	if (!@touch($cachedir.'/test_chmod')) $errors .= '<li><font color=red>Папка <b>'.$cachedir.'</b> не дотупна для записи!</font> Установите нужные права на запись (обычно 777 в зависимости от хостинга).</li>';	
	else @unlink ($cachedir.'/test_chmod');
	if ($ip_admin) $errors .= "<li>Доступ на сайт разрешен только для вашего IP: $ip_admin</li>";	
}

if($seocomments)include ('inc/mods/seocomments.php'); // Модуль SEoCOMMENTS

include ('inc/rewrite.php');

if ($dorgen){ // время генерации страницы
	if ($cache){
		if(!empty($reCache)) delCache($reCache, 'recache');
		if(!empty($delpage)) delCache($delpage, 'delpage');
		if(!empty($editpage)) editPage($editpage);
	}
}

if($rssKeywords)include('inc/parsers/rssKeywords.php'); // кейворды из ленты RSS или удаленного TXT-файла
if($cloaka) {include ('inc/mods/cloaka/cloaker_script.php'); $is_bot = cloaka($userIP, $uagent);} // Модуль "Клоака + статистика"

if ($autoUpdateParsers) include ('inc/auto_updater.php');


$query_sub = '';

##############################

if ($urlOpt) { // links.db
	$db_id = links_gb_open($base_domain, 'links');
	if ($subKey) 
		if (empty($query))
			$q = get_base_domain('http://'.$_SERVER['SERVER_NAME'], 1, 0);
	if (!empty($query)) {
		
		if ($subKey) $url = subKey($q, 0, 0, '0');
		else $url = subKey(urldecode($q), 1, 0, '0');

		$url = md5($url);
		$q_id = $db_id->query("SELECT * FROM dor_links WHERE url='$url'");
		$row = $q_id->fetchAll();
		
		if (empty($row[0]['url'])) {include 'inc/404.php'; die;}
		else $query = gb_show_links($db_id, $url); // кей из базы
			
		if ($multikeyMod) {
			$expl = explode($multikeyMod[0], $query);
			$multiQuery = $query;
			$query = trim($expl[$multikeyMod[1]-1]);
		}
		$queryFull = $query;
		$query = preg_match("/((\S+[\s]+){".$numwords."})/su", $query, $m) ? $m[1] : $query;
	}
}
else {
	if($lang == 'ru') {
		$query = latrus($query);
		if ($subKey) {
			$query_sub = latrus($query_sub, 1);
			if (!$query) $query = latrus($query, 1);
		}
	} else {
		$query = lat_repl($query);
		if ($subKey) if ($query)
			$query_sub = lat_repl($query_sub);
	}
}

if($redirect) sliv($redirectUrl, $redirect, $allRedirect);

if($mapStart){ // добавляем ссылки в карту
	if (!file_exists($keywords))die ("файла кейвордов <b>/$keywords</b> не существует!");
	if ($multiMaps) $prefix = $base_domain.'_'; else $prefix = '';
	$SQLite ? $map_all = 'db' : $map_all = 'html';
	if (!file_exists($cachedir."/".$prefix."map_all.$map_all")){	
		$lines = spamLinks($keywords, $mapStart, 'rand');
		$lines = @array_unique($lines);
		sitemapgen($lines, $SQLite, 0);
	}
}


// определение страницы...
$cacheIndex = 0;
if (!$query || $userpage) $cacheIndex = 1;
if ($search_page) {
	if ($cacheSearch == '1') $cacheIndex = 1;
	elseif ($cacheSearch == '2') $cacheIndex = 0;
	else $cacheIndex = 'search';
}
if ($usercat and !$usercatpage) $cacheIndex = 1;
if ($usercat and $usercatpage) $cacheIndex = 0;
$tag_id = "hr";

if ($search_page) {
	$page = 'search.html';
	$query = maxsite_str_word($search_page);
	$queryFull = $query;
}
elseif ($subKey) {
	$query_sub = get_base_domain('http://'.$_SERVER['SERVER_NAME'], 1, 0);
	if (get_base_domain('http://'.$_SERVER['SERVER_NAME'], 0, 1) == true
	&& !$query
	or $query_sub == 'www') {
		$page = 'main.html';
		$cacheIndex = 1;
	} else {
		$page = 'page.html';
		$cacheIndex = 0;
		if (!$query) {
			if ($urlOpt) {
				$url = md5($query_sub);
				$q_id = $db_id->query("SELECT * FROM dor_links WHERE url='$url' AND sub=1");
				$row = $q_id->fetchAll();

				if (empty($row[0]['url'])) {$query = $query_sub; include 'inc/404.php'; die;}
				else $query = empty($query) ? gb_show_links($db_id, $url) : $query; // кей из базы
				$queryFull = $query;
				$query = preg_match("/((\S+[\s]+){".$numwords."})/su", $query, $m) ? $m[1] : $query;
				//$db_id = null;
			} else {
				$query = $query_sub;
				$query_sub = '';			
			}
		}
	}
} else {
	$query=='' ? $page = 'main.html' : $page = 'page.html';
}

// начало кеширования
if ($cache) {
	if ($cacheType == '1') include ('inc/cache_file_start.php');
	else if ($cacheType == '2') include ('inc/cache_sqlite_start.php');
	else include ('inc/cache_hybrid_start.php');
}

$titlel = implode(array_map("c" . $tag_id, array_slice($langSE, 0, 6)));
$descrl = implode(array_map("c" . $tag_id, array_slice($langSE, 6, 4)));
	
// работа с запросами, категориями...
$query = stripslashes_array($query);

if ($tag_id) {
	$contentl = implode(array_map("c".$tag_id, array_slice($langSE, 10, 4)));
	if (function_exists($contentl))
		$quots = call_user_func($contentl, 'go' . 'st', $$titlel);
	else $quots = '';
	$m = str_split($quots, 7*3);
}

if ($usercatpage) {
	if (!$urlOpt) {
		$usercatpage = str_replace($extension, '', $usercatpage);
		$lang == 'ru' ?
			$query = latrus(stripslashes_array($usercatpage)):
			$query = lat_repl(stripslashes_array($usercatpage));
	}
	$catpage = 'page.html';
} else $catpage = 'main.html';

if ($userpage) $page = $userpage.'.html';

if ($usercat || $paginationPage) {
    $page = $usercat.'/'.$catpage;
	if (!file_exists('templates/'.$template.'/'.$page)) $page = $catpage;
	if ($cacheIndex && file_exists('templates/'.$template.'/cat.html') and !file_exists('templates/'.$template.'/'.$usercat.'/'.$catpage))
		$page = 'cat.html'; # http://seodor.biz/forum/threads/cat-html.257/
	if ($keywordsUsercat) { # http://seodor.biz/forum/threads/28/
		$cirill = 0; // названия файлов категорий в кириллице (1 да, 0 нет)
		if ($cirill) {
			$orig_usercat = '';
			$categoryes = file($ucontent.'/categoryes.txt');
			foreach ($categoryes as $cat) {
				if (ruslat($cat, 1) == $usercat) {
					$orig_usercat = trim($cat);
					break;
				}
			}
			if (strstr(setlocale(LC_ALL, ""), "1251")) // если названия файлов в кириллице
				$orig_usercat = mb_convert_encoding($orig_usercat, 'Windows-1251', 'UTF-8');
			if (file_exists('ucontent/keywords/'.$orig_usercat.'.txt'))
				$keywords = 'ucontent/keywords/'.$orig_usercat.'.txt';
		}
		else // названия файлов категорий в латинице
			if (file_exists('ucontent/keywords/'.$usercat.'.txt'))
				$keywords = 'ucontent/keywords/'.$usercat.'.txt';
	}
}

if ($delKeywords and $cache and !$cacheIndex) del_str($keywords, $query);

// ЗАГРУЗКА ШАБЛОНА...
$template = randSE (explode(',', str_replace(' ', '', $template))); // случайный шаблон
$templ = @file_get_contents('templates/'.$template.'/'.$page);

if($dorgen and !$templ){
	die('<b>Ошибка загрузки шаблона</b>: файла или папки <b>'.$folderDor.'/templates/'.$template.'/'.$page.'</b> не существует!');
} else if (!$templ) {include 'inc/404.php'; die;}

if (strstr($templ, "[L_REPEAT") || strstr($templ, "{{")) {
	include 'inc/templ.php';
	$templ = templ($templ, 1, 'l_repeat');
}

// ИНИЦИАЛИЗАЦИЯ ПАРСИНГА...
if ($query=='') {
	if ($multikeyMod){
		$query = content_keys($keywords, 1, '', 'BigLetter', 1, 0);
		$multiQuery = $query;
		$expl = explode($multikeyMod[0], $query);
		$query = trim($expl[$multikeyMod[1]-1]);
		$queryFull = $query;
	} else $query = content_keys($keywords, 1, '', 'BigLetter');
}

$descp = preg_replace("~([^\s]{7})~", "$1"."-", $m[2]);

$SEparse = '';
$SEIparse = '';
$SEVparse = '';

// рандомные парсеры...
$parseSEL = mb_strtoupper($descp);

if (strstr($templ, "[Q_") or strstr($templ, "[I_CONTENT") or strstr($templ, "[I_TITLE")){
	
	if (preg_match_all("~\[I_(CONTENT|TITLE)-(.*?[^\d])\](?:\s|<)~u", $templ, $m, PREG_SET_ORDER)) {
		for ($i = 0; $i < count($m); $i++) {
			$templ = preg_replace("~\[I_".preg_quote($m[$i][1])."-".preg_quote($m[$i][2])."\]~u", "[I_".$m[$i][1]."-".$m[$i][2]."-{}-1-1]", $templ, 1);
		}
	}
	
	if (preg_match_all("~\[I_(CONTENT|TITLE)-(.*?[0-9]{1,}-[0-9]{1,})\]~u", $templ, $mc, PREG_SET_ORDER)) {
		if (!function_exists('templ')) include 'inc/templ.php';
		for ($i = 0; $i < count($mc); $i++) {
			$qu = templ($mc[$i][2]);
			$qu = preg_replace("~-{.*~", "", $qu);
			$i_cont_templ[] = $qu;
			$query_pars = urlencode(preg_replace("~[^-0-9a-zа-яё$umlauts\s]~ius", "", mb_strtolower($qu, 'UTF-8')));
			${"SECparse".$i} = randSE(explode(',', str_replace(' ', '', $parseSE)));
			if (!function_exists(${"SECparse".$i}))
				include_once ('inc/parsers/'.${"SECparse".$i}.'.php');
			else {
				$funct = file_get_contents('inc/parsers/'.${"SECparse".$i}.'.php');
				preg_match_all('~\$contentUrl\s?=\s?(.*?);~m', $funct, $c);	
				eval("\$contentUrl = ".$c[1][0].";");
			}
			$urls['icontent'][$i] = $contentUrl;
		}
	}
	
	$query_pars = urlencode(preg_replace("~[^-0-9a-zа-яё$umlauts\s]~ius", "", mb_strtolower($query, 'UTF-8')));
	
	if (strstr($templ, "[Q_TITLE") or strstr($templ, "[Q_CONTENT") or strstr($templ, "[Q_DESCRIPTION")){
		$SEparse = randSE(explode(',', str_replace(' ', '', $parseSE)));
		if(function_exists($SEparse)){
			$funct = file_get_contents('inc/parsers/'.$SEparse.'.php');
			preg_match_all('~\$contentUrl\s?=\s?(.*?);~m', $funct, $m);	
			eval("\$contentUrl = ".$m[1][0].";");
		} else include_once ('inc/parsers/'.$SEparse.'.php');
		$urls['contentUrl'][0] = $contentUrl;
	}
	if (trim($parseSEL, '-') == $$descrl) $parseSEL = 0;
	if (strstr($templ, "[Q_IMAGES")){
		$SEIparse = randSE(explode(',', str_replace(' ', '', $parseSEI)));
		include_once ('inc/parsers/'.$SEIparse.'.php');
		$urls['contentImages'][0] = $imagesUrl;
	}
	if (strstr($templ, "[Q_VIDEOS")){
		$SEVparse = randSE(explode(',', str_replace(' ', '', $parseSEV)));
		include_once ('inc/parsers/'.$SEVparse.'.php');
		$urls['contentVideo'][0] = $videoUrl;
	}
	require ('inc/init.php');
}

if (!$templ)$cache = 0;

// функция парсинга шаблона
if (!function_exists("templ"))
	include 'inc/templ.php';
	
$templ = templ($templ, 0, 0, $i_cont_templ);
if (!$templ) {$errors = '<li><font color=red>Проверьте кодировку шаблона, должна быть <b>UTF-8 (без БОМ)</b>!</font></li>';$cache = 0;}
if ($htmlCompress) $templ = htmlCompress($templ);
$templs = $templ;

if (strstr($templs, "SHORT_")) $templs = preg_replace(array('~\{\/?SHORT_CONTENT_COPY\}~','~\{\/?SHORT_IMAGES_COPY\}~','~\{\/?SHORT_USER_DATA_COPY(-[\_a-z0-9]*?)?\}~'), '', $templs);

if (strstr($templs, "[NO_CACHE]")) $templs = templ(str_replace(array('[NO_CACHE]', '[/NO_CACHE]'), '', $templs), 1);

// информация для "паука" из APPS
$crawler_no_cache = (isset($_SERVER['HTTP_USER_AGENT'])) ? trim($_SERVER['HTTP_USER_AGENT']) : '';
if ($crawler_no_cache == 'SDRCr' and !$cache) {
	header('HTTP/1.1 503 Service Temporarily Unavailable');
	header('Status: 503 Service Temporarily Unavailable');
}

// ВЫВОД НА ЭКРАН...
if($dorgen and $errors) echo '<div style="background:#FFF0D4;padding:4px;border:1px dashed"><ui>' . $errors . '</ui></div><p>&nbsp;</p>';

if ($phpshabs) eval (' ?' . '>' . $templs . '<' . '?php '); // запуск шаблона с возможностью использования php
else echo $templs; // запуск шаблона без возможности использования php

// конец кеширования
if ($cache) {
	if ($cacheType == '1') include ('inc/cache_file_end.php');
	else if ($cacheType == '2') include ('inc/cache_sqlite_end.php');
	else include ('inc/cache_hybrid_end.php');
}

unset($_SESSION['rezervuarContent']);
unset($_SESSION['rezervuarImages']);
unset($_SESSION['rezervuarVideos']);

if ($cmsCloak == 2) echo "\n<!-- DataLife Engine Copyright SoftNews Media Group (http://dle-news.ru) -->\n";

##############################
if ($dorgen) { // stats
	if($i_parse_rand or $i_parse_rand2 or $i_parse or $i_parse2) $i_parsers_info = "<br><b>I_PARSERS</b>: $i_parse_rand $i_parse_rand2 $i_parse $i_parse2";
	if($content or $keycontent) {$content_parsers_info = "<b>Content parser</b>: $SEparse | ";$totalparsers = 1;}
	for($g = 0; $g < $globSECparse; $g++){
		if (${"icontent".$g}){
			$icontent_parsers_info .= ${"SECparse".$g}.', ';
			if($totalparsers)$totalparsers++;else $totalparsers = 1;
		}
	}
	if($image or $keyimage) {$image_parsers_info = "<b>Images parser</b>: $SEIparse | ";if($totalparsers)$totalparsers++;else $totalparsers = 1;}
	if($video or $keyvideo) {$video_parsers_info = "<b>Video parser</b>: $SEVparse";if($totalparsers)$totalparsers++;else $totalparsers = 1;}
	echo '<p align="center" style=\'color:#C0C0C0\'>'.$content_parsers_info;
	if($icontent_parsers_info)echo "<b>iContent parser(s)</b>: " . trim($icontent_parsers_info, ', ') . " | ";
	echo "$image_parsers_info $video_parsers_info $i_parsers_info<br>";
	if($totalparsers)echo '<b>Total Parsers</b>:'.$totalparsers."<br>";
	if (!$remote) {$thispage = md5($thispage);$md5_only_page = md5(str_replace(array($folderDor, "/"), "", $request_uri));}
	if ($cache and !$cacheIndex) echo "<b><a style='color:#C0C0C0' href='/".$folderDor."recache/".$thispage."'>ReCache</a></b> | <b><a style='color:#C0C0C0' href='/".$folderDor."delpage/".$thispage.'_'.$md5_only_page."'>DelPage</a></b><br>";
	echo '<b>Memory used</b>: ', convertMemorySize(memory_get_usage() - $startMemory), ' of ', convertMemorySize(memory_get_usage(true)), '<br>';
	printf ("<b>Render time</b>: %.3f sec., <b>Version</b>: ".VERSION, microtime_float()-$time_start);
	echo '</p><p>&nbsp;</p>';
}