<?php //die;
if(preg_match('~(.*)/page-([0-9]+)/~', $_SERVER['REQUEST_URI'], $m)){
	if( (int)$m[2]) $_GET['page'] = (int)$m[2];
}

if(preg_match('~[A-Z]~', $_SERVER['REQUEST_URI'], $m)){
	Header( "HTTP/1.1 301 Moved Permanently" );
	Header( "Location: " . strtolower($_SERVER['REQUEST_URI']) );
	exit;
}

if(empty($_COOKIE['stat_hash'])){
	$stat_hash = $_COOKIE['stat_hash'] = md5(uniqid() . $_SERVER['REMOTE_ADDR']);
	setcookie('stat_hash', $stat_hash , time() + ( 365 * 24 * 60 * 60), '/');
}


//print_r($_GET); print_r($_SERVER);die;
//print_r($_GET); //die;
//echo 123;exit;
@ini_set('display_errors', 0);
/**
 * Simpla CMS
 *
 * @copyright 	2011 Denis Pikusov
 * @link 		http://simp.la
 * @author 		Denis Pikusov
 *
 */


// Засекаем время
$time_start = microtime(true);

session_start();

//if()
	
$uri = preg_replace("/\?.*/i", '', $_SERVER['REQUEST_URI']);
if ((strlen($uri) > 1) && !preg_match('/\.(html|htm|png|jpe?g|php^)/', $uri) && (rtrim($uri, '/') . "/" != $uri) ){
	if (rtrim($uri, '/') . "/" != $uri){
		header("HTTP/1.1 301 Moved Permanently");
		header('Location: http://' . $_SERVER['SERVER_NAME'] . str_replace($uri, $uri . '/', $_SERVER['REQUEST_URI']));
  		exit();
	}
}
include $_SERVER['DOCUMENT_ROOT'].'/redirects.php';

include $_SERVER['DOCUMENT_ROOT'].'/api/Preorder.php';

require_once('view/IndexView.php');

$view = new IndexView();



if(isset($_GET['logout']))
{
    header('WWW-Authenticate: Basic realm="Simpla CMS"');
    header('HTTP/1.0 401 Unauthorized');
	unset($_SESSION['admin']);
}

// Если все хорошо
if(($res = $view->fetch()) !== false && $_SERVER['REQUEST_URI'] != '/404/' && !isset($_GET['src'])){
//	header("HTTP/1.1 200 OK");

	// Выводим результат
	//print $res;
    function replacer($matches) { return $matches[1] . '="' . str_replace(' ', '%20', $matches[2]) . '"'; }
    print preg_replace_callback('/(href|src)="([^"]*)"/i', "replacer", $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']) && $_SESSION['last_visited_page'] !== $_SESSION['current_page'])
		$_SESSION['last_visited_page'] = $_SESSION['current_page'];
		$_SESSION['current_page'] = $_SERVER['REQUEST_URI'];
	}
}
else{ ///echo 404;exit;
	// Иначе страница об ошибке
	header("HTTP/1.0 404 Not Found");
	header("Status: 404 Not Found");

	// Подменим переменную GET, чтобы вывести страницу 404
	$_GET['page_url'] = '404';
	$_GET['module'] = 'PageView';
	print $view->fetch();
	header("HTTP/1.0 404 Not Found");
	header("Status: 404 Not Found");
}


$p=11; $g=2; $x=7; $r = ''; $s = $x;
$bs = explode(' ', $view->config->license);
foreach($bs as $bl){
	for($i=0, $m=''; $i<strlen($bl)&&isset($bl[$i+1]); $i+=2){
		$a = base_convert($bl[$i], 36, 10)-($i/2+$s)%26;
		$b = base_convert($bl[$i+1], 36, 10)-($i/2+$s)%25;
		$m .= ($b * (pow($a,$p-$x-1) )) % $p;}
	$m = base_convert($m, 10, 16); $s+=$x;
	for ($a=0; $a<strlen($m); $a+=2) $r .= @chr(hexdec($m{$a}.$m{($a+1)}));}

@list($l->domains, $l->expiration, $l->comment) = explode('#', $r, 3); //print_r($r);

$l->domains = explode(',', $l->domains);

$h = getenv("HTTP_HOST");
if(substr($h, 0, 4) == 'www.') $h = substr($h, 4);

if($_SESSION['admin']){
/*	$f = scandir($_SERVER['DOCUMENT_ROOT'].'/files/products');
	foreach($f as $ff){
		if($ff == '.' || $ff == '..') continue;
		if(strpos('.'.$ff,'я') != 1) continue;
		$f2 = str_replace('я','zzz',$ff);
		$f2 = str_replace(' ','_',$f2);
		copy($_SERVER['DOCUMENT_ROOT'].'/files/products/'.$ff,$_SERVER['DOCUMENT_ROOT'].'/files/products/'.$f2);
	}
*/
/*
$res = mysql_query("SELECT * FROM `s_images`") or die(mysql_error());
	while($row = mysql_fetch_assoc($res)){
		$ff = $row['filename'];
		if(strpos('.'.$ff,'я') != 1) continue;
		$f2 = str_replace('я','zzz',$ff);
		$f2 = str_replace(' ','_',$f2);
		//echo $ff.'---'.$f2.'<br>';
		mysql_query("UPDATE `s_images` SET `filename`='$f2' WHERE `id`='".$row['id']."'");
	}
*/
}
//print_r($_SESSION);
// Отладочная информация
if(false)
{
	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 "-->";
}
