<?php
// Version
define('VERSION', '3.0.3.7');
ini_set("display_errors", ON);
error_reporting(E_ALL);

// Configuration
if (is_file('config.php')) {
	require_once('config.php');
}

// Install
if (!defined('DIR_APPLICATION')) {
	header('Location: install/index.php');
	exit;
}
//header("HTTP/1.0 404 Not Found");
//exit();
require_once(DIR_SYSTEM . 'startup.php');

$registry = new Registry();
// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);
// Config
$config = new Config();
$registry->set('config', $config);
// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

$registry->set('db', $db);

// Settings
$query = $db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '0' OR store_id = '" . (int)$config->get('config_store_id') . "' ORDER BY store_id ASC");

foreach ($query->rows as $setting) {
	$config->set($setting['key'], $setting['value']);
}

$blackIp = array();
$table = DB_PREFIX . "customer_ban_ip";
$iquery = $db->query("SHOW TABLES LIKE '". $table."'");
if(!empty($iquery->rows)) {
    $ipquery = $db->query("SELECT * FROM " . DB_PREFIX . "customer_ban_ip");
	foreach ($ipquery->rows as $val) {
		$blackIp[] = $val['ip'];
	}
}else{
	$db->query("CREATE TABLE ". $table ." (
		`customer_ban_ip_id` int(11) NOT NULL AUTO_INCREMENT,
		`ip` varchar(40) NOT NULL,
		PRIMARY KEY (`customer_ban_ip_id`),
		KEY `ip` (`ip`)
	  ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;");
}


function getPreferredLanguage() {  
    $langs = array();  
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {  
        // break up string into pieces (languages and q factors)  
        preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)s*(;s*qs*=s*(1|0.[0-9]+))?/i',  
                $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);  
        if (count($lang_parse[1])) {  
            // create a list like "en" => 0.8  
            $langs = array_combine($lang_parse[1], $lang_parse[4]);  
            // set default to 1 for any without q factor  
            foreach ($langs as $lang => $val) {  
                if ($val === '') $langs[$lang] = 1;  
            }  
            // sort list based on value  
            arsort($langs, SORT_NUMERIC);  
        }  
    }  
    //extract most important (first)  
    foreach ($langs as $lang => $val) { break; }  
    //if complex language simplify it  
    if (stristr($lang,"-")) {$tmp = explode("-",$lang); $lang = $tmp[0]; }  
    return $lang;  
} 
$the_host = $_SERVER['HTTP_HOST']; //获取主域名
$request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; //获取后缀
$website = HTTPS_SERVER;
preg_match("/^(https:\/\/)?([^\/]+)/i", $website, $matches);
$host = $matches[2];
// 从主机名中取得后面两段 
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches); 
if(stripos($the_host, $matches[0]) === false)  
{   
	$website = str_replace($matches[0].'/', $matches[0], $website);
	header('HTTP/1.1 301 Moved Permanently');
	header('Location: '.$website.$request_uri);
}
//IP白名单
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
    $ip_address = $_SERVER['REMOTE_ADDR'];
}
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4);
$lang_ex = getPreferredLanguage();
if (preg_match("/zh-c/i", $lang) || preg_match("/zh-c/i", $lang_ex) )   
{
	if ($config->get('config_whitelist') && strpos($_SERVER['REQUEST_URI'], "api") === false && strpos($_SERVER['REQUEST_URI'], "review") === false){
		if (strpos($config->get('config_whitelist'),'|')){
			$whiteList = explode('|',$config->get('config_whitelist'));
		}else{
			$whiteList = $config->get('config_whitelist');
		}
		if (is_array($whiteList)){
			if (!in_array($ip_address,$whiteList))
			{
				//不是白名单拒绝访问
				header("HTTP/1.0 404 Not Found");
				exit();
			}
		}else if ($ip_address != $whiteList){
			//不是白名单拒绝访问
			header("HTTP/1.0 404 Not Found");
			exit();
		}
	}

	if(!empty($blackIp) && strpos($_SERVER['REQUEST_URI'], "api") === false && strpos($_SERVER['REQUEST_URI'], "review") === false){
		if (in_array($ip_address, $blackIp))
		{
			header("HTTP/1.0 404 Not Found");
			exit();
		}
	}
}

if ($config->get('config_login_password'))
{

	if(strpos($_SERVER['REQUEST_URI'], "api") !== false || strpos($_SERVER['REQUEST_URI'], "review") !== false){
		
	}else{
		//访问需要密码
		@$login = $_COOKIE['login'];
		/*
		密码在这里修改，请把123456改成你想要的密码 ，其他东西请勿动！
		*/
		$mima = $config->get('config_login_password'); 

		$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); //只取前4位，这样只判断最优先的语言。如果取前5位，可能出现en,zh的情况，影响判断。   
		if (preg_match("/zh-c/i", $lang))   
		 {
			if($login==""){
					if(@$_POST['passwords']!=""){
				
							$password=$_POST['passwords'];
							if($mima==$password){
								setcookie("login","ok", time()+3600*24);
						    @$login = $_COOKIE['login'];
						  }else{
							setcookie("login");
						    echo "password error";exit();
						  }
				
				  }else{		 
									 
					  echo '<form id="form1" name="form1" method="post" action="">
				  please input the password
				  <label>
				    <input type="text" name="passwords" id="textfield" />
				  </label>
				  <label>
				    <input type="submit" name="button" id="button" value="submit" />
				  </label>
				</form>';
				exit();
				 }
			
			} 
	}
	
}
}else if (preg_match("/zh/i", $lang))  {}

// Startup


start('catalog');