<?php

ignore_user_abort(true);

function get_microtime_index()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

if ($_SERVER['REMOTE_ADDR'] == '109.63.237.55' || $_SERVER['REMOTE_ADDR'] == '46.39.231.98')
	ini_set('display_errors', 1);

$time_start = get_microtime_index();

if (preg_match('@^\/sitemap(_\d+)*?.xml$@', $_SERVER['REQUEST_URI'], $a_match))
{
	$sitemap_folder_path = 'sitemap_http';
	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on" || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
		$sitemap_folder_path = 'sitemap_https';

	header('Content-type: application/xml; charset=utf-8');
	echo file_get_contents('http://'.$_SERVER['HTTP_HOST'].'/'.$sitemap_folder_path.$_SERVER['REQUEST_URI']);
	exit;
}

// Для внутреннего ссылочного ранжирования (предпросмотр)
$a_seo_link_url_param = explode('/', $_SERVER['REQUEST_URI'], 3);
if ($a_seo_link_url_param[1] == 'seo_link_preview')
	$_SERVER['REQUEST_URI'] = '/'.$a_seo_link_url_param[2];

if (strstr($_SERVER['REQUEST_URI'], '?utm_source') || strstr($_SERVER['REQUEST_URI'], '?fbclid') || strstr($_SERVER['REQUEST_URI'], '?yclid') || strstr($_SERVER['REQUEST_URI'], '?frommarket') || strstr($_SERVER['REQUEST_URI'], '?gtm_debug'))
	$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));

// Подключаем необходимые классы
require('./_cms/autoexec.php');

//c_debug::print_r_pre($_REQUEST, false);
if (!empty($_REQUEST))
{
	foreach ($_REQUEST as $request_key => $request_val)
	{
		$is_sql_query = (stristr($request_val, "'") || stristr($request_val, '"') 
							|| stristr($request_val, 'or ') || stristr($request_val, '|| ') 
							|| stristr($request_val, 'select ') || stristr($request_val, 'from ') 
							|| stristr($request_val, 'join ') || stristr($request_val, 'where ') 
							|| stristr($request_val, 'insert ') || stristr($request_val, 'update ') || stristr($request_val, 'delete '));
		
		if (!(stristr($request_val, '--') && $is_sql_query) && !stristr($request_val, 'information_schema') && !stristr($request_val, 'flexible2_'))
			continue;
		
		$log_text = 'IP - '.$_SERVER['REMOTE_ADDR']."<br>\n"
					.'URL - '.$_SERVER['REQUEST_URI']."<br>\n"
					.'HTTP_REFERER - '.(!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '')."<br>\n"
					.'REQUEST_METHOD - '.$_SERVER['REQUEST_METHOD']."<br>\n"
					.'REQUEST_PARAM - '.$request_key.'='.$request_val."<br>\n\n";
		//$log_file_name = CONFIG_PATH_LOGS.'/request/log_'.date('YmdHi').'.txt';
		//$fp_log = fopen($log_file_name, 'a');
		//fwrite($fp_log, $log_text);
		//fclose($fp_log);
		
		// Отпрвляем e-mail
		\c_mail_use::mail_send_action(array(
			'email_recipient'	=> 'info@promoting.ru',
			'email_subject'		=> 'Попытка sql-инъекции на домене '.$_SERVER['HTTP_HOST'],
			'email_template'	=> 'hacking_attempt_email.htm',
			'email_data'		=> array('DOMAIN' => $_SERVER['HTTP_HOST'], 'LOG_TEXT' => $log_text)
		));
		
		header("HTTP/1.0 403 Forbidden");
		exit;
	}
}

require_once(CONFIG_PATH_PLUGIN_DATA_EXT.'/seo/seo_redirect.php');
data_seo_redirect();

// Объявляем необходимые массивы и переменные
$GLOBALS['passed'] = $a_page_module_result = $a_replace = array();
$GLOBALS['path_module'] = FALSE;

// Подключаем файлы подготовки данных и обработки шаблонов
if (isset($o_outerface->a_outerface) && is_array($o_outerface->a_outerface))
{
	$a_outerface_mask_integration = $o_outerface->a_outerface_mask_integration;

	//echo '$o_outerface->a_outerface = <pre>'; print_r($o_outerface->a_outerface); echo '</pre>';
	foreach ($o_outerface->a_outerface as $a_outerface_info)
	{
		// Если у аутерфейса указан id сайта
		if ($a_outerface_info['plugin_data_site_id'])
		{
			// Формируем имя файла. Плагин гдето в папке /_site/
			$s_plugin_file_name = CONFIG_PATH_SITE.'/'.c_site::$a_site['ext_folder'].'/ext/data/'.$a_outerface_info['plugin_data_dir'].'/'.$a_outerface_info['plugin_data'];
		}
		else
		{
			// Не указан, значит где-то в папке /_cms/
			$s_plugin_file_name = CONFIG_PATH_PLUGIN_DATA_EXT.'/'.$a_outerface_info['plugin_data_dir'].'/'.$a_outerface_info['plugin_data'];
		}

		// Подключаем необходимые плагины
		if (is_file($s_plugin_file_name))
			require_once($s_plugin_file_name);
		elseif (is_file(CONFIG_PATH_PLUGIN_DATA_EXT.'/'.$a_outerface_info['plugin_data']))
			require_once(CONFIG_PATH_PLUGIN_DATA_EXT.'/'.$a_outerface_info['plugin_data']);
	}
}

// Маски, отсортированные по run_priority
if (isset($o_outerface->a_outerface_mask) && is_array($o_outerface->a_outerface_mask) && is_array($o_outerface->a_outerface_to_page))
{
	// Бежим по маскам, отсортированным по run_priority
	foreach ($o_outerface->a_outerface_mask as $a_outerface_mask_info)
	{
		// Бежим по привякам оутерфейсов к страницам
		foreach ($o_outerface->a_outerface_to_page as $a_outerface_to_page_info)
		{
			if ($a_outerface_to_page_info['outerface_id'] == $a_outerface_mask_info['id_group'])
			{
				// Информация об оутерфейсе
				$a_outerface_info = $o_outerface->a_outerface[$a_outerface_to_page_info['outerface_id']];

				// Отрезаем расширения файла для вызова функции
				$a_outerface_to_page_info['plugin_data'] = substr($a_outerface_info['plugin_data'], 0, -4);
				//$a_outerface_to_page_info['plugin_template'] = substr($a_outerface_info['plugin_template'], 0, -4);

				// Получить список параметров конфигурации
				if (isset($o_outerface->a_outerface_config[$a_outerface_to_page_info['page_module_id']][$o_outerface->a_outerface[$a_outerface_to_page_info['outerface_id']]['id_row']]))
					$a_plugin_param = $o_outerface->a_outerface_config[$a_outerface_to_page_info['page_module_id']][$o_outerface->a_outerface[$a_outerface_to_page_info['outerface_id']]['id_row']];
				else
					$a_plugin_param = '';

				// Получить список таблиц
				if (isset($o_outerface->a_outerface_table[$a_outerface_to_page_info['module_id']]))
					$a_plugin_table = $o_outerface->a_outerface_table[$a_outerface_to_page_info['module_id']];
				else
					$a_plugin_table = '';

				// Запуск плагина подготовки данных
				if (!empty($a_outerface_to_page_info['plugin_data']))
				{
					$a_outerface_to_page_info['plugin_data'] = 'data_'.$a_outerface_to_page_info['plugin_data'];
					
					// Сортировка вывода оутерфейсов по позициям
					if (!isset($a_page_module_result[$a_outerface_to_page_info['block_name']][$a_outerface_to_page_info['outerface_position']]))
						$a_page_module_result[$a_outerface_to_page_info['block_name']][$a_outerface_to_page_info['outerface_position']] = $a_outerface_to_page_info['plugin_data']();
					else
						$a_page_module_result[$a_outerface_to_page_info['block_name']][] = $a_outerface_to_page_info['plugin_data']();

					// Для блока контент запускаем плагин простановки ссылок
					//if ($a_outerface_to_page_info['block_name'] == 'content')
					//	require(CONFIG_PATH_PLUGIN_DATA_EXT.'/seo/seo_link_info.php');
				}
                
				unset($a_plugin_param);
				unset($a_plugin_table);
			}
		}
	}
}

$o_outerface->__destruct();
unset($o_outerface);

// Вывод ошибки 404 - Страница не найдена
//if ((isset(c_page::$a_page['path_module']) && c_page::$a_page['path_module'] && !$GLOBALS['path_module']))
if (!$GLOBALS['path_module'])
{
	if (!headers_sent())
        header("HTTP/1.0 404 Not Found");
	require('404.php');
	exit;
}

// Загружаем основной шаблон страницы
if (!empty($seo_link_preview_flag))
	$content_template = file_get_contents(CONFIG_PATH_TPL.c_page::$a_page['tpl_path'].'/seo_link_preview.htm');
else
	$content_template = file_get_contents(CONFIG_PATH_TPL.c_page::$a_page['tpl_path'].'/'.c_page::$a_page['tpl_file']);

if (!headers_sent())
	header('Content-type: text/html; charset=utf-8');

// Проставляем title
if (!empty($GLOBALS['seo_headers']['title']))
	$a_page_module_result['head_title'][] = $GLOBALS['seo_headers']['title'];
else
	$a_page_module_result['head_title'][] = c_page::$a_page['name'];

// Вывод заголовков
if (!empty($GLOBALS['seo_headers']['header_expires']))
{
	if (!headers_sent())
		header($GLOBALS['seo_headers']['header_expires']);
}
if (!empty($GLOBALS['seo_headers']['header_cachecontrol']))
{
	if (!headers_sent())
		header($GLOBALS['seo_headers']['header_cachecontrol']);
}
if (!empty($GLOBALS['seo_headers']['header_pragma']))
{
	if (!headers_sent())
		header($GLOBALS['seo_headers']['header_pragma']);
}
if (!empty($GLOBALS['seo_headers']['header_lastmodified']))
{
	$GLOBALS['seo_headers']['header_lastmodified'] = "Last-Modified: ".gmdate("D, d M Y H:i:s", time())." GMT";
	// Изменяем день недели, тк он неправильный!
	// При формировании $GLOBALS['seo_headers']['header_lastmodified'] брался текущий день недели!
	$a_lastmodified = explode(': ',$GLOBALS['seo_headers']['header_lastmodified'], 2);
	$a_lastmodified_date = explode(', ', $a_lastmodified[1], 2);
	$lastmodified = date('D', strtotime($a_lastmodified_date[1])).', '.$a_lastmodified_date[1];
	//$GLOBALS['seo_headers']['header_lastmodified'] = $a_lastmodified[0].': '.$lastmodified;
	if (!headers_sent())
		header($GLOBALS['seo_headers']['header_lastmodified']);
	if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
	{
		if (strtotime($lastmodified) <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
		{
			if (!headers_sent())
				header("HTTP/1.0 304 Not Modified");
			exit;
		}
	}
}
// Отсортировать контент на местах по полю position
if (count($a_page_module_result))
{
	foreach ($a_page_module_result as $template_place => $a_place)
	{
		ksort($a_place);
		foreach ($a_place as $position => $content)
		{
			if (isset($a_replace[$template_place]))
				$a_replace[$template_place] .= $content;
			else
				$a_replace[$template_place] = $content;
		}
	}
}
unset($a_page_module_result);
unset($a_place);

// Выполнить подстановку контента по местам
if (count($a_replace) > 0)
{
	foreach ($a_replace as $template_place => $content)
		$content_template = str_replace('[['.$template_place.']]', $content, $content_template);
	foreach ($a_replace as $template_place => $content)
		$content_template = str_replace('[['.$template_place.']]', $content, $content_template);
}
unset($a_replace);

// удаляем  все /> закрывашки, потому как они нахрен не нужны и в спецификации HTML считаются НЕ верными и нужны лишь в XHTML!
$content_template = str_replace('/>', '>', $content_template);

//Удаляем все пустые строки, не нужные блоки шаблона и т.п.
echo preg_replace(array("'\[\[.*?\]\]'", "/[\s]+$/m"), '', $content_template);

$time_end = get_microtime_index();
$time = $time_end - $time_start;

// echo 'Время генерации страницы '.number_format($time, 5, '.', ' ');
?>