<?
/*
 * SUMOshop Index v2.21
 * Copyright 2020 SUMOshop http://www.sumoshop.dk
 * All rights reserved
 */
 #if (!in_array($_SERVER["REMOTE_ADDR"], array("188.228.19.128", "95.166.178.192", "90.184.142.106", "85.83.123.238"))) exit;

// Check misuse of index.php
if (isset($_SERVER["REQUEST_URI"]) && strpos($_SERVER["REQUEST_URI"], "index.php")!==FALSE) {
	header("location: /");
	exit;
}

// Reject Bing madness
if (isset($_SERVER["HTTP_USER_AGENT"]) && (strpos($_SERVER["HTTP_USER_AGENT"], "bingbot")!==FALSE || strpos($_SERVER["HTTP_USER_AGENT"], "Pricecloud")!==FALSE || strpos($_SERVER["HTTP_USER_AGENT"], "SemrushBot") || strpos($_SERVER["HTTP_USER_AGENT"], "rogerbot")!==FALSE || strpos($_SERVER["HTTP_USER_AGENT"], "XoviBot")!==FALSE) && isset($_SERVER["QUERY_STRING"]) && (strpos($_SERVER["QUERY_STRING"], "%5B%5D") || strpos($_SERVER["QUERY_STRING"], "[]"))) {
	header("HTTP/1.0 403 Forbidden");
	print "Forbidden";
	exit;
}

// Setup timer
$timer=array_sum(explode(" ", microtime()));

// Requires
session_cache_limiter("");
if (file_exists("../includes/config/std.inc.php")) {
	require_once("../includes/config/std.inc.php");
} else {
	require_once("../include/config/std.inc.php");	
}
if ($config->get("cachepage/enabled")) require_once("cachepage.inc.php");
require_once("error/exceptionerrorhandler.php");
require_once("error/errorhandler.php");
require_once("pathrequestmapper.php");
require_once("httpcontext.php");
require_once("template.php");
require_once("authentication/httploaduser.php");
require_once("authentication/sessionloaduser.php");
require_once("config/components.inc.php");

error_reporting(E_ALL | E_STRICT);
Error_ExceptionErrorHandler::Initialize();

// Dispatch
try {
	$context=new HttpContext();
	$GLOBALS["__locale"]=$context->locale;

	if ($config->get("url/replacelocale") && is_object($context->locale)) {
		$replaces=$config->get("url/replacelocale");
		if (isset($replaces[$context->locale->getLanguage()])) $config->set("url/replace", $replaces[$context->locale->getLanguage()]);
	}

	// Set language etc. by url
	if ($config->get("url/language")) {
		$found=FALSE;
		foreach ($config->get("url/language") as $url=>$vars) {
			if (substr($_SERVER["RELATIVE_REQUEST_URI"], 0, strlen($url)+1)==$url."/" || $_SERVER["RELATIVE_REQUEST_URI"]==$url) {
				$_SERVER["RELATIVE_REQUEST_URI"]=substr($_SERVER["RELATIVE_REQUEST_URI"], strlen($url)+1);
				if (is_string($vars)) $vars=array($vars);
				if ($vars[0]!=$context->getLanguage()) {
					$context->setLanguage($vars[0], (isset($vars[1]) ? $vars[1]:FALSE), (isset($vars[2]) ? $vars[2]:FALSE));
					if ($config->get("url/replacelocale")) {
						$replaces=$config->get("url/replacelocale");
						if (isset($replaces[$vars[0]])) $config->set("url/replace", $replaces[$vars[0]]);
					}

				}
				$found=TRUE;
			}
		}

		// Forward url by country
		if (!$found && $context->getLanguageUrl()) {
			$replaces=$config->get("url/replace");
			if (substr($_SERVER["RELATIVE_REQUEST_URI"], 0, 10)!="backadmin/" && substr($_SERVER["RELATIVE_REQUEST_URI"], 0, 4)!="api/" && substr($_SERVER["RELATIVE_REQUEST_URI"], 0, 9)!="sumorest/" && substr($_SERVER["RELATIVE_REQUEST_URI"], 0, 7)!="remote/" && substr($_SERVER["RELATIVE_REQUEST_URI"], 0, 9)!="loginauth" && substr($_SERVER["RELATIVE_REQUEST_URI"], 0, 7)!="country" && !(isset($replaces["country"]) && substr($_SERVER["RELATIVE_REQUEST_URI"], 0, strlen($replaces["country"]))==$replaces["country"])) {
				$to=$context->getEnv("URL_BASE").$context->getLanguageUrl().($_SERVER["RELATIVE_REQUEST_URI"] ? "/".$_SERVER["RELATIVE_REQUEST_URI"]:"").($context->getEnv("REDIRECT_QUERY_STRING") ? "?".$context->getEnv("REDIRECT_QUERY_STRING"):($context->getEnv("QUERY_STRING") ? "?".$context->getEnv("QUERY_STRING"):""));
				header("Location: ".$to);
				echo "<html><script type=\"text/javascript\">window.location.href=\"".htmlentities(addslashes($to))."\";</script><body><a href=\"".htmlentities($to)."\">".htmlentities($to)."</a></body></html>";
				exit;
			}
		}
	}

	// Check redirects
	if (is_array($config->get("redirects/fixed"))) {
		foreach ($config->get("redirects/fixed") as $from=>$to) {
			if ($from==$context->getEnv("RELATIVE_REQUEST_URI")) {
				header("Location: ".$to);
				echo "<html><script type=\"text/javascript\">window.location.href=\"".htmlentities(addslashes($to))."\";</script><body><a href=\"".htmlentities($to)."\">".htmlentities($to)."</a></body></html>";
				exit;
			}
		}
	}
	if ($config->get("url/replace") && $config->get("url/redirect")) {
		$replaces=$config->get("url/replace");
		$url=$context->getEnv("RELATIVE_REQUEST_URI");
		if (strpos($url, "/")) $url=substr($url, 0, strpos($url, "/"));
		if ($url && !empty($replaces[$url]) && $replaces[$url]!=$url) {
			$to=$context->getEnv("URL_BASE").$replaces[$url].substr($context->getEnv("RELATIVE_REQUEST_URI"), strlen($url)).($context->getEnv("REDIRECT_QUERY_STRING") && $context->getEnv("REDIRECT_QUERY_STRING")!=$context->getEnv("QUERY_STRING") ? "?".$context->getEnv("REDIRECT_QUERY_STRING"):"").($context->getEnv("QUERY_STRING") ? "?".$context->getEnv("QUERY_STRING"):"");
			header("Location: ".$to, TRUE, 301);
			echo "<html><script type=\"text/javascript\">window.location.href=\"".htmlentities(addslashes($to))."\";</script><body><a href=\"".htmlentities($to)."\">".htmlentities($to)."</a></body></html>";
			exit;
		}
	}
	if (file_exists(stream_resolve_include_path("config/user.inc.php"))) include "config/user.inc.php";

	// Get dispatch
	$dispatcher=new PathRequestMapper($context);
	$dispatcher->default="Front";
	$dispatcher->classPrefix="action/public/";
	if ($config->get("landingpages/enabled") && $_SERVER["RELATIVE_REQUEST_URI"]) {
		$gatewayLandingpages=Components::GetService("DataSource/Landingpage");
		$landingpage=$gatewayLandingpages->fetchByURL($_SERVER["RELATIVE_REQUEST_URI"]);
		if (is_object($landingpage)) {
			$dispatcher->action="Landingpage";
			$_SERVER["URL_REWRITE_MATCHES"]=array($_SERVER["RELATIVE_REQUEST_URI"]."/".$landingpage->getPid(), $landingpage->getPid());
		}
	}
	$rewrites=array(
		"~^it.gif([^\\?\\#]*)~"=>"imagetrack",
		"~^it.png([^\\?\\#]*)~"=>"imagetrack",
	);
	foreach (array("article", "ask", "block", "blog", "brand", "campaign", "cartrestore", "cartsort", "catalog", "category", "commodity", "competition", "completionoffer", "countryproduced", "country", "currency", "draw", "feature", "formverify", "form", "gallery", "image", "itemnotify", "keyword", "news", "notify", "landingpage", "language", "lookbook", "look", "magazine", "newsmail", "ordercancel", "orderfile", "orderimages", "orderprint", "orderreturnlabel", "order", "page", "person", "pressfile", "pressgroup", "pricegroup", "pricematch", "request", "reviewer", "screenshot", "season", "section", "selectiontocart", "selectiondelete", "selectioncopy", "selectionpdf", "selectiontype", "selectionlistempty", "selectionlistshare", "selectionlist", "selection", "selleraccount", "series", "share", "splittest", "subscriptionchange", "subscriptionpayment", "subscription", "tell", "ticketedit", "ticketfile", "ticket", "userreviewer", "user", "venue", "vimeo", "wiki", "wishlist", "year", "youtube", "sumorest", "restapi") as $command) {
		$rewrites["~^".$command."/([^\\?\\#]*)~"]=$command;
	}
	if (is_array($config->get("url/replace"))) {
		foreach ($config->get("url/replace") as $from=>$to) {
			$rewrites["~^".$to."/([^\\?\\#]*)~"]=$from;
			$rewrites["~^".$to."$~"]=$from;
		}
	}
	if (is_array($config->get("url/rewrites"))) {
		foreach ($config->get("url/rewrites") as $from=>$to) {
			$rewrites["~^".$from."([^\\?\\#]*)~"]=$to;
		}
	}
	$route=$context->getEnv("RELATIVE_REQUEST_URI");
	if ($dispatcher->action!="Landingpage") {
		foreach ($rewrites as $pattern=>$rewrite) {
			if (preg_match($pattern, $route, $matches)) {
				$_SERVER["RELATIVE_REQUEST_URI"]=$rewrite;
				$_SERVER["URL_REWRITE_MATCHES"]=$matches;
				break;
			}
		}
	}

	// Set canonical
	if ($config->get("canonical")) {
		$route=$_SERVER["RELATIVE_REQUEST_URI"].(isset($_SERVER["URL_REWRITE_MATCHES"][1]) ? "/".$_SERVER["URL_REWRITE_MATCHES"][1]:"");
		if ($route=="/" || $route=="") $route="front";
		$route.=($context->getEnv("QUERY_STRING") ? "?".$context->getEnv("QUERY_STRING"):"");
		foreach ($config->get("canonical") as $pattern=>$canonicalhref) {
			if (@preg_match($pattern, $route, $matches)) {
				$GLOBALS["canonical"]=":".str_replace("#1", (isset($matches[1]) ? $matches[1]:""), $canonicalhref);
				break;
			}
		}
	}

	// Get landingpage
	if ($config->get("landingpages/enabled") && !$context->get("ajax")) {
		$gatewayLandingpages=Components::GetService("DataSource/Landingpage");
		$landingpage=$gatewayLandingpages->fetchByAction($_SERVER["RELATIVE_REQUEST_URI"]);
		if (is_object($landingpage)) {
			$dispatcher->action="Landingpage";
			$_SERVER["OLD_REWRITE_MATCHES"]=(isset($_SERVER["URL_REWRITE_MATCHES"]) ? $_SERVER["URL_REWRITE_MATCHES"]:"");
			$_SERVER["URL_REWRITE_MATCHES"]=array($_SERVER["RELATIVE_REQUEST_URI"]."/".$landingpage->getPid(), $landingpage->getPid());
		}
	}

	// Check filters and do dispatch
	$filters=array(
		new Authentication_HTTPLoadUser(Components::GetService("DataSource/User")),
		new Authentication_SessionLoadUser(Components::GetService("DataSource/User")),
	);
	$dispatch=TRUE;
	foreach ($filters as $filter) {
		$dispatch=$dispatch && $filter->execute($context);
	}
	if ($dispatch) $context->response->setContent($dispatcher->execute());

	// Update visits
	if (($config->get("visit/enabled") || $context->get("search")) && !$config->get("site/salemode")) {
		$gatewayVisits=Components::GetService("DataSource/Visit");
		$gatewayVisits->register($context);
	}

	// Return response
	if (isset($cache_page) && $cache_page) {
		$response=$context->response->out(TRUE);
	} else {
		$context->response->out();
	}
} catch (Exception $ex) {
	error_logger($ex, TRUE);
	exit;
}

// Clean up
Error_ExceptionErrorHandler::Uninitialize();
if (isset($cache_page) && $cache_page && isset($response) && $response) {
	$sql="REPLACE INTO cache_page (`url`, `page`, `headers`) VALUES ('".mysql_escape_string($url)."', '".mysql_escape_string($response["page"])."', '".mysql_escape_string(serialize($response["headers"]))."')";
	mysql_unbuffered_query($sql, $GLOBALS["__cache"]);
}
Components::GetService("DataBase/Connection")->close();

// Timer
if (!empty($_GET["timer"])) print "Timer: ".str_replace(".", ",", round(1000*(array_sum(explode(" ", microtime())) - $timer)))." ms.<br />\n";
?>