<?PHP

if(preg_match('/(dotbot)/i', $_SERVER['HTTP_USER_AGENT'])) {
	header("http/1.0 403 Forbidden");
	exit;
}

require_once('api/Config.php');

$config = new Config;

require_once(__DIR__ . '/api/includes/redirects.php');

if(file_exists(__DIR__ . '/../redirects.php')) {
	require_once(__DIR__ . '/../redirects.php');
}

$url = trim(str_replace("[]", '%5B%5D', $_SERVER['REQUEST_URI']), '?');
$url = trim(str_replace("%22%3E", '', $url), '?');
$url = trim(str_replace("%3C%3E", '%5B%5D', $url), '?');


$enable403 = $config->enable_403;
// echo __FILE__ . "\n" . $ip . "\n";

$domain = $config->current_domain;


if(!empty($enable403)
	&& ($_SERVER['HTTP_HOST'] == $domain || $_SERVER['HTTP_HOST'] == 'www.' . $domain)
	&& !preg_match($config->bots_pattern, $_SERVER['HTTP_USER_AGENT']) 
	&& empty($_SERVER['HTTP_REFERER'])
	&& !$config->useUTM()
	){
	$config->page502();
}

if($url != $_SERVER['REQUEST_URI']) {
	header("Location: " . $url, true, 301);exit;
}

require_once(__DIR__ . "/script_preload.php");
require_once('api/Simpla.php');

$simpla = new Simpla;


$ip = $simpla->request->getIp();

if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
    $ipLong = sprintf('%u', ip2long($ip));
    $start  = sprintf('%u', ip2long('47.79.0.0'));
    $end    = sprintf('%u', ip2long('47.79.255.255'));

    if ($ipLong >= $start && $ipLong <= $end) {
        http_response_code(403);
        exit('Forbidden');
    }
}

if(preg_match('/sitemap_(.*?).xml/i', $simpla->request->get('url'), $matches)) {
	
	$include = __DIR__ . '/view/sitemaps/' . $matches[1] . '.php';
	
	if(file_exists($include)) {
		
		$sitemap_field = "sitemap_{$matches[1]}_lastmod";
		
		header("Content-type: text/xml; charset=UTF-8");
		
		function url($url, $lastmod = null) {
			print "\t<url>"."\n";
			print "\t\t<loc>$url</loc>"."\n";
			if($lastmod) {
				$lastmod = date('c', strtotime($lastmod));
				print "\t\t<lastmod>$lastmod</lastmod>"."\n";
			}
			print "\t</url>"."\n";
		}
		function esc($s)
		{
			return(htmlspecialchars($s, ENT_QUOTES, 'UTF-8'));	
		}
		
		include($include);
		exit;
	}	
}

if(!empty($_GET['module']) && $_GET['module'] == 'MainView' && !empty($_GET['url'])
	&& $_GET['url'] != 'dobavit-anketu'
	&& $_GET['url'] != 'top-10-anket'
	&& $_GET['url'] != 'top-10-agents'
) {
	
	$temp_items = explode('-', $_GET['url']);
	// echo "<!-- " . print_r($temp_items,1) . " -->";exit;
	$block_page = false;
	if(count($temp_items) > 1) {
		$new_url = array();
		$bl = array();
		$ts_result = $simpla->cache->get_from_cache('tags_urls');
		
		if(!empty($ts_result) && !empty($ts_result[1])) {
			$ts = &$ts_result[1];
			
			
			foreach($temp_items as $u) {
				$bid = !empty($ts[$u]) ? $ts[$u] : 0;
				
				
				if(empty($bl[$bid])) {
					$bl[$bid] = 0;
				}
				$bl[$bid]++;
				if($bl[$bid] > 1) {
					$block_page = true;
					continue;
				}
				$new_url[] = $u;
			}
		}
		
		$new_url = implode('-', $new_url);
		
		if($_GET['url'] != $new_url) {
			header("Location: /" . $new_url, true, 301);exit;
		}
	}	
	
	if(($block_page || count($temp_items) > 3) && (empty($_SERVER['HTTP_USER_AGENT']) || preg_match('/bot/i', $_SERVER['HTTP_USER_AGENT']))) {
		header("Location: /", true, 301);exit;
		
		?><!doctype html>
<html lang="ru-RU" class="no-js">
<head>
	<title>Все проститутки в <?=$simpla->settings->tpl_city_p?> - <?=$simpla->settings->company_name?></title>
	<meta name="description" content="Лучшие проститутки индивидуалки <?=$simpla->settings->tpl_city_r?> на одном сайте" />
	<meta name="robots" content="noindex,nofollow" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
</head>
<body>
	<a href="/">Главная</a>
</body>
</html>
		
		<?php 
		exit;
	}
}

// if(empty($_SESSION))
	// session_start();

if(!empty($_GET['url']) && $_GET['url'] == '>'){
	header('Location: /', true, 301);exit;
}
error_reporting(E_ALL); 
 
// Засекаем время
$time_start = microtime(true);

require_once('view/IndexView.php');

try{
	if(function_exists('print_time')) print_time();
	$view = new IndexView();
	
	if(!empty($_GET['clear_log'])) $view->clear_log();
	$view->log('start');

	if(($res = $view->fetch()) !== false)
	{
		
		if(function_exists('print_time')) print_time();
		header("Content-type: text/html; charset=UTF-8");	
		print $res;

		// Сохраняем последнюю просмотренную страницу в переменной $_SESSION['last_visited_page']
		if(empty($_SESSION['last_visited_page']) || empty($_SESSION['current_page']) || $_SERVER['REQUEST_URI'] !== $_SESSION['current_page'])
		{
			if(!empty($_SESSION['current_page']) && (empty($_SESSION['last_visited_page']) || (!empty($_SESSION['current_page']) && $_SESSION['last_visited_page'] !== $_SESSION['current_page'])))
				$_SESSION['last_visited_page'] = $_SESSION['current_page'];
			$_SESSION['current_page'] = $_SERVER['REQUEST_URI'];
		}		
	}
	else 
	{ 
		// Иначе страница об ошибке
		header("http/1.0 404 not found");
		
		// Подменим переменную GET, чтобы вывести страницу 404
		$_GET['page_url'] = '404';
		$_GET['module'] = 'PageView';
		
		print $view->fetch();   
	}
}catch(Exception $e){
	set_log($e);
	
	if($view->config->no_index) {
		print_r($e->getMessage());
	} else {
		header("http/1.0 502 bad gateway");
		echo " Ошибка на сайте ";
	}
}
if(function_exists('print_time')) print_time();
if(function_exists('print_time')) print_time('', 1);

$view->log('end');
if(!empty($_GET['clear_log'])){
	echo "<!-- " . @file_get_contents(__DIR__ . '/cache/glob_info.txt') . " -->";
	
}
// Отладочная информация
if(!empty($_GET['dddd']))
{
	print "<!--\r\n";
	$time_end = microtime(true);
	$exec_time = $time_end-$time_start;
  
  	if(function_exists('memory_get_peak_usage'))
		print "memory peak usage: ".memory_get_peak_usage()." bytes\r\n";  
	print "page generation time: ".$exec_time." seconds\r\n";  
	print "-->";
}