<?php

/**
* Include file, initiates adodb and smarty libraries.
* Set smarty path-and-environment variables.
* Set language and modules settings.
*
* @package DatingPro
* @subpackage User Mode
**/

ini_set("display_errors", "0");
ini_set("memory_limit", "256M");
//error_reporting (E_ALL^E_NOTICE^E_DEPRECATED);
error_reporting (E_ALL);

if (!isset($_SESSION)) {
	session_start();
}

/////// link for install
if(!$config["server"] && !$config["dbname"] && !$config["dbhost"] && !$config["dbuname"]){
	$path = substr(__FILE__,0, -10);
	if (file_exists("./install/index.php"))
	echo "<script>location.href='./install/index.php'</script>";
	exit;
}

/// sistem settings
if (substr(php_uname(), 0, 7) == "Windows") {
	$config["system"] = "win";
} else {
	$config["system"] = "unix";
}

$dir = $config["site_path"];
if (strlen($dir)==0) {
	$dir = ".";
	$dir = dirname(__FILE__);
}

///// for download temp files
$config["file_temp_path"] = $config["site_path"]."/templates_c";

switch ($config["system"]) {
	case "unix":
		ini_set("include_path", ".:".$dir.":".$dir."/include:".$dir."/adodb:".$dir."/smarty");
		break;
	case "win":
		ini_set("include_path", ".;".$dir.";".$dir."/include;".$dir."/adodb;".$dir."/smarty");
		break;
}

include_once $config["site_path"]."/include/class.loader.php";
include_once $config["site_path"]."/include/functions_xml.php";

include_once "adodb/tohtml.inc.php";
include_once "adodb/adodb.inc.php";

function PN_DBMsgError($db='',$prg='',$line=0,$message='Error accesing to the database') {
	$lcmessage = $message . "<br>" .
	"Program: " . $prg . " - " . "Line N.: " . $line . "<br>" .
	"Database: " . $db->database . "<br> ";

	if ($db->ErrorNo()<>0) {
		$lcmessage .= "Error (" . $db->ErrorNo() . ") : " . $db->ErrorMsg() . "<br>";
	}
	//echo "Can't connect to database. Please <a href='./install/index.php'>install</a> product.";
	die($lcmessage);
}

$dbconn = &ADONewConnection($config['dbtype']);
GLOBAL $ADODB_FETCH_MODE;


$connectString = $config['dbtype'].":".$config['dbuname'].":".$config['dbpass']."@".$config['dbhost']."/".$config['dbname'];
$dbh = $dbconn->Connect($config['dbhost'],($config['dbuname']),($config['dbpass']),$config['dbname']);

$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

if ($dbh === false) {
	error_log ("connect string: $connectString");
	error_log ("error: " . $dbconn->ErrorMsg());
	// show error and die
	PN_DBMsgError($dbconn, __FILE__ , __LINE__, "Error connecting to db".$config['dbname']);
}

//utf-8
$dbconn->Execute("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");

//    Smarty
include_once "smarty/Smarty.class.php";

if ((isset($smarty) && !is_object($smarty)) || !isset($smarty))
$smarty = new Smarty;
$smarty->force_compile = false;
$smarty->template_dir = $dir."/templates/";
$smarty->compile_dir = $dir."/templates_c";
$smarty->plugins_dir = $dir."/smarty/plugins";
if(!$smarty)  die("Smarty error");

$rs_smarty = $dbconn->Execute("Select value, name from ".SETTINGS_TABLE." where name like 'use_pilot_module_%' or
             name in ('admin_theme_path','index_theme_path','index_theme_css_path','index_theme_images_path',
          'default_lang','path_lang','date_format','use_success_stories',
          'site_top_logotype', 'site_logotype_format', 'site_banner', 'site_banner_format', 'site_logotype_width',
          'site_logotype_height', 'site_banner_width', 'site_banner_height','site_banner_color', 'user_banners_feature', 'voipcall_feature',
          'color_theme', 'site_status', 'site_status_warning','use_facebook_connect', 'facebook_connect_api_key', 'facebook_connect_secret_key',
		  'use_vk_connect', 'vk_api_id',
          'use_recaptcha', 'recaptcha_public_key', 'recaptcha_private_key', 'use_profile_mandatory', 'google_analytics_activate', 'manual_tracker_activate',
		  'use_global_seo', 'use_seo_multilang', 'lang_ident_feature', 'use_default_smiles'
          )");
while(!$rs_smarty->EOF){
	$config[$rs_smarty->fields[1]] = $rs_smarty->fields[0];
	$smarty->assign($rs_smarty->fields[1], $rs_smarty->fields[0]);
	$rs_smarty->MoveNext();
}

$settings = array();
if(isset($config["use_pilot_module_multidomainV1"]) && $config["use_pilot_module_multidomainV1"]){
    $server = "http://".$_SERVER["HTTP_HOST"].$config["site_root"];
    include_once $config["site_path"]."/admin/admin_multidomain.php";
    if(function_exists('loadSettings')){
        $settings = loadSettings($server);
        if($settings){
            $config["index_theme_path"] = $settings['index_theme_path'];
            $config["color_theme"] = $settings['color_theme'];
			$config["server_id"] = $settings["server_id"];
			$config["server"] = $settings["server"];
			$config["domain_site_path"] = $settings["site_path"];
        }
    }
}else{
	$config["server"] = $config["server"].$config["site_root"];
	$config["domain_site_path"] = $config["site_path"];
}

$server_time = array();
$sql_server_time = $dbconn->Execute("SELECT NOW(), UNIX_TIMESTAMP(NOW())");
$server_time['sql_time'] = $sql_server_time->fields[0];
$server_time['sql_unix_time'] = $sql_server_time->fields[1];
$server_time['php_time'] = date("Y-m-d H:i:s", mktime());
$server_time['php_unix_time'] = time();
$smarty->assign('server_time', $server_time);
$smarty->assign('server_time_json', json_encode($server_time));


function loadSystemSettings(){ // for later use to reinit config
	global $rs_smarty, $settings, $dbconn;
	$rs_smarty = $dbconn->Execute("Select value, name from ".SETTINGS_TABLE);
	while(!$rs_smarty->EOF){
		$settings[$rs_smarty->fields[1]] = $rs_smarty->fields[0];
		$rs_smarty->MoveNext();
	}
}
loadSystemSettings();
if(isset($config["use_pilot_module_multidomainV1"]) && $config["use_pilot_module_multidomainV1"]){
	 $settings['index_theme_path'] = $config["index_theme_path"];
     $settings['color_theme'] = $config["color_theme"];
}
$smarty->assign("demo_module", $config["demo_module"]);

$settings['theme_postfix'] = '';
$settings['theme_postfix'] = ($settings['color_theme'] == '' || !isset($settings['color_theme'])) ? $settings['theme_postfix'] = "_default" : "_".$settings['color_theme'];

if ($config['use_global_seo'] == 1) {
    $theme_get = str_replace($_SERVER['REDIRECT_URL']."?theme=", "", $_SERVER['REQUEST_URI']);
} else {
    $theme_get = isset($_GET['theme']) ? $_GET['theme'] : null;
}
if(!$config["demo_module"]){
	unset($_SESSION['theme']);
}
if (isset($theme_get) && in_array($theme_get, array('boyfriends','girlfriends','adult','matrimonial','niche','standard'))) {
	$_SESSION['theme'] = $theme_get;
	$settings["theme_postfix"] = "_".$theme_get;
	$config["color_theme"] = $theme_get;
} elseif (isset($_SESSION['theme'])) {
	$settings["theme_postfix"] = "_".$_SESSION['theme'];
	$config["color_theme"] = $_SESSION['theme'];
}
$strSQL = "SELECT name, value FROM ".COLOR_THEME." WHERE theme='{$config['color_theme']}'";
$rs = $dbconn->Execute($strSQL);
$theme_colors = array();
foreach($rs as $field){
	$theme_colors[$field[0]] = $field[1];
}
$smarty->assign('theme_colors',$theme_colors);

$smarty->assign('settings',$settings);

$smarty->assign("header_tpl","index_top.tpl");
$smarty->assign("footer_tpl","index_bottom.tpl");
$smarty->assign("theme_postfix",$settings["theme_postfix"]);

if (isset($config['use_pilot_module_webmessenger']) && $config['use_pilot_module_webmessenger'] == 1) {
	$rs_smarty = $dbconn->Execute("SELECT value, name FROM ".UP_MESSENGER_SETTINGS_TABLE." WHERE name IN ('presence_id','account_password') ");
	while(!$rs_smarty->EOF){
		$config[$rs_smarty->fields[1]] = $rs_smarty->fields[0];
		$rs_smarty->MoveNext();
	}
	if (!isset($config['presence_id']) || !isset($config['account_password'])) {
		$config['presence_id'] = "";
		$config['account_password'] = "";
	}
}

if (isset($config['use_pilot_module_blog']) && $config['use_pilot_module_blog'] == 1) {
	$config_index["tag_opt"]['blog'] = array(	'table'=>BLOG_PROFILE_TABLE,
				'item_id_field'=>'id',
				'owner_field'=>'id_user',
				'item_name'=>'title',
				'item_link'=>$config["server"].'/blog.php?sel=view_user&id_blog=[item_id]',
				'is_popup'=>false);
}
if (isset($config['use_pilot_module_events']) && $config['use_pilot_module_events'] == 1) {
	$config_index["tag_opt"]['event'] = array(	'table'=>EVENT_DESCR_TABLE,
				'item_id_field'=>'id',
				'owner_field'=>'id_creator',
				'item_name'=>'event_name',
				'item_link'=>$config["server"].'/events.php?sel=event&amp;id_event=[item_id]',
				'is_popup'=>false);
}

if (isset($config['use_pilot_module_club']) && $config['use_pilot_module_club'] == 1) {
	$config_index["tag_opt"]['club'] = array(	'table'=>CLUB_TABLE,
				'item_id_field'=>'id',
				'owner_field'=>'id_creator',
				'item_name'=>'name',
				'item_link'=>$config["server"].'/club.php?sel=club&amp;id_club=[item_id]',
				'is_popup'=>false);
}

if(!$config["admin_theme_path"])  $config["admin_theme_path"] = "/templates/admin";
if(!$config["index_theme_path"])  $config["index_theme_path"] = "/templates/pilot_3_theme";
if (isset($theme_ident)) {
	$config["index_theme_path"] = "/templates/".$theme_ident;
}

if(!$config["index_theme_css_path"])  $config["index_theme_css_path"] = "/css";
if(!$config["index_theme_images_path"]) $config["index_theme_images_path"] = "/images";

if ($config["system"] == "win"){
	$smarty->assign("gentemplates", "file:".$dir.$config["index_theme_path"]);
	$smarty->assign("admingentemplates", "file:".$dir.$config["admin_theme_path"]);
}else{
	$smarty->assign("gentemplates", "file:".$config["site_path"].$config["index_theme_path"]);
	$smarty->assign("admingentemplates", "file:".$config["site_path"].$config["admin_theme_path"]);
}

/// languages
if(!$config["default_lang"])  $config["default_lang"] = "1";
if(!$config["path_lang"]) $config["path_lang"] = "/languages";

$langCodeFromUrl = "";
$paramsSeoReq = "";
$routerFileName = "";

if(isset($useRouting) && $useRouting){
	$router = new Router($dbconn, $config);

	// get kod (ru, en ...) language requested by the site through a router
	
	$langCodeFromUrl = $router->getLangCodeFromUrl();
	// get the file name include in route.php
	$tmp = $router->getFilenameForInclude();

	$routerFileName = $tmp["file"];
	if(isset($tmp["params"])){
		$paramsSeoReq = $tmp["params"];
	}

	if($routerFileName == ""){
		header("HTTP/1.0 404 Not Found");
		$_REQUEST["code"] = "404";
		$routerFileName = "error.php";
	}
}

if(isset($config["use_seo_multilang"]) && $config["use_seo_multilang"] && isset($useRouting) && $useRouting){
	// check the language in the address, take it as a basis
	$sql = "SELECT id FROM ".LANGUAGE_TABLE." WHERE code='".$langCodeFromUrl."' AND visible='1'";
	$rs = $dbconn->Execute($sql);
	if ($rs->fields[0] > 0) {
		$language_code = $rs->fields[0];
		setcookie("language_cd", $language_code, time()+7200, str_replace("www.", "", $config["site_root"])."/");
		$config["default_lang"] = $language_code;
		$lang_code = $language_code;
	}
	else{
		$lang_code = $config["default_lang"];
	}
}
else{
	if(isset($_GET["language_code"]) && intval($_GET["language_code"])>0){
		$language_code = intval($_GET["language_code"]);
		$sql = "SELECT id, charset, lang_file, code FROM ".LANGUAGE_TABLE." WHERE id='".$language_code."' AND visible='1'";
		$rs = $dbconn->Execute($sql);
		if ($rs->fields[0] > 0) {
			setcookie("language_cd", $language_code, time()+7200, str_replace("www.", "", $config["site_root"])."/");
			$lang_code = $language_code;
			$config["default_lang"] = $language_code; 
		} else {
			$lang_code = $config["default_lang"];
		}	
	} elseif (isset($_COOKIE["language_cd"]) && strval($_COOKIE["language_cd"])!="") {
		$rs = $dbconn->Execute("SELECT id FROM ".LANGUAGE_TABLE." WHERE id='".$_COOKIE["language_cd"]."' AND visible='1'");
		if($rs->RecordCount()){
			$lang_code = $_COOKIE["language_cd"];
			$config["default_lang"] = $_COOKIE["language_cd"];
		}else{
			$lang_code = $config["default_lang"];
			setcookie("language_cd", $lang_code, time()+7200, str_replace("www.", "", $config["site_root"])."/");
		}
	} else {
		$lang_code = $config["default_lang"];
	}
}
$smarty -> assign("lang_code",$lang_code);

//// load language interface
$strSQL = "select charset, lang_file, code, dir FROM ".LANGUAGE_TABLE." where id='".intval($lang_code)."'";
$rs = $dbconn->Execute($strSQL);
$charset = $rs->fields[0];
$lang_file = $rs->fields[1];
$lang_code = $rs->fields[2];
$smarty->assign('code', $lang_code);
$config["lang_short_code"] = $lang_code;

$lang_dir = $rs->fields[3];
$theme_style = "";

if(!$langCodeFromUrl && isset($config["use_seo_multilang"]) && $config["use_seo_multilang"]){
	$langCodeFromUrl = $lang_code;
}
if($langCodeFromUrl != ""){
	$smarty->assign("seo_site_root", $config["site_root"]."/".$langCodeFromUrl);
	$config['seo_site_root'] = $config["server"]."/".$langCodeFromUrl;
}
else{
	$smarty->assign("seo_site_root", $config["site_root"]);
	$config['seo_site_root'] =  $config["server"];
}

if(!isset($useRouting) || !$useRouting) {
	if(!isset($config["use_seo_multilang"]) && !$config["use_seo_multilang"]){
		// Turn on the conversion, but is bypassing the router
		// Check the language of the site and do a redirect.

		$query = strtolower($_SERVER["PHP_SELF"]);

		// Admin, news, and the backend does not redirect
		if(
			!stristr($query, "/admin/") && 
			!stristr($query, "/admin/newsletter/") && 
			!stristr($query, "/backend.php") && 
			!stristr($query, "/ajax_backend.php") && 
			!stristr($query, "/combine.php") && 
			!stristr($query, "/news.php") && 
			!stristr($query, "/flash_chat/") && 
			!stristr($query, "/blog.php") && 
			!stristr($query, "/m/") &&
			!stristr($query, "/facebook_connect/") &&
			!stristr($query, "/msanalysis/") &&
			!stristr($query, "/im/") &&
			!stristr($query, "/OpenInviter/") &&
			!stristr($query, "payment_request.php") &&
			!stristr($query, "topcmm_123flashchat") &&
			!stristr($query, "/quick_search.php") && 
			!stristr($query, "webmessenger") &&
			!stristr($query, "chat7") &&
			!stristr($query, "messenger7") &&
			!stristr($query, "webchat") &&
			!stristr($query, "webrecorder") &&
			!stristr($query, "/install/") &&
			!stristr($query, "/update/")
		){
			
			$query = str_replace(strtolower($config["site_root"]), "", $query);
			$query = ltrim($query, '/');
			if($_SERVER["QUERY_STRING"]){
				$query .= "?".$_SERVER["QUERY_STRING"];
			}

			// language from cookies, else - use the default.
			if(isset($_COOKIE["language_cd"]) && intval($_COOKIE["language_cd"])!=""){
				$strSQL = "select code FROM ".LANGUAGE_TABLE." where id='".intval($_COOKIE["language_cd"])."'";
				$rs = $dbconn->Execute($strSQL);
				if ($rs->fields[0] != "") {
					header("Location: ".$config["site_root"]."/".$rs->fields[0]."/".$query);
				}
				else{
					header("Location: ".$config["site_root"]."/".$config["lang_short_code"]."/".$query);
				}
			}
			else{
				header("Location: ".$config["site_root"]."/".$config["lang_short_code"]."/".$query);
			}
			exit;
		}
	}
}


if (isset($config["theme_postfix"]) && $config["theme_postfix"] != '') {
	//$lang_dir = "ltr";
	$theme_style = $config["theme_postfix"];
}

if(file_exists($config["site_path"]."/include/functions_seo.php")){
	include_once $config["site_path"]."/include/functions_seo.php";
}

if(substr($config["path_lang"], -1) != "/" && substr($config["path_lang"], -1) != "\\")  $config["path_lang"] = $config["path_lang"]."/";
if(substr($config["path_lang"], 0, 1) == "/" || substr($config["path_lang"],0,1) == "\\")  $config["path_lang"] = substr($config["path_lang"],1);
if(substr($lang_file,0,1) == "/" || substr($lang_file,0,1) == "\\") $lang_file = substr($lang_file, 1);

if (function_exists('apache_get_modules')) {
     if (in_array('mod_rewrite',apache_get_modules())) {
         $smarty->assign('use_mod_rewrite',1);
     }
}

$lang_file = explode(".",$lang_file);

// если включен роутинг - то PHP_SELF указывает на route.php, что не есть хорошо - не грузятся нужные лэнги.
// поэтому делаем условие
if(isset($useRouting) && $useRouting){
	$path_file = explode("/",$routerFileName);
}
else{
	$path_file = explode("/",strtolower($_SERVER["PHP_SELF"]));
}

$count_path_file = count($path_file);
$path_lang = explode(".",$path_file[$count_path_file-1]);

if((isset($path_file[$count_path_file-2]) && $path_file[$count_path_file-2] == "admin") || (isset($path_file[$count_path_file-3]) && $path_file[$count_path_file-3] == "admin") || (isset($path_file[$count_path_file-4]) && $path_file[$count_path_file-4] == "admin")) {
	GetLangContent($lang_file[0], $config["path_lang"].$lang_file[0]."/admin");
    if(isset($config_index["module"])){
		foreach ($config_index["module"] as $key => $value) {
			if (file_exists($config["site_path"]."/".$config["path_lang"].$lang_file[0]."/".$value.".xml"))
                GetLangContent($value, $config["path_lang"].$lang_file[0]);
		}
    }

} else {
    $path_lang_module = ModuleLang($path_lang[0]);
	if ($path_lang_module) $path_lang[0] = $path_lang_module;
	if(file_exists($config["site_path"]."/".$config["path_lang"].$lang_file[0]."/".$path_lang[0].".xml"))
        GetLangContent($path_lang[0], $config["path_lang"].$lang_file[0]);

    if ($path_lang[0] == 'myprofile' && file_exists($config["site_path"]."/".$config["path_lang"].$lang_file[0]."/horoscope.xml"))
        GetLangContent("horoscope", $config["path_lang"].$lang_file[0]);
        
    if ($path_lang[0] == 'index' && file_exists($config["site_path"]."/".$config["path_lang"].$lang_file[0]."/quick_search.xml"))
        GetLangContent("quick_search", $config["path_lang"].$lang_file[0]);
	
	if ($path_lang[0] == 'myprofile' && file_exists($config["site_path"]."/".$config["path_lang"].$lang_file[0]."/audiovideo.xml"))
        GetLangContent("audiovideo", $config["path_lang"].$lang_file[0]);
	
	if ($path_lang[0] == 'map' && file_exists($config["site_path"]."/".$config["path_lang"].$lang_file[0]."/affiliate.xml"))
        GetLangContent("affiliate", $config["path_lang"].$lang_file[0]);
	
	if ($path_lang[0] == 'viewprofile' && file_exists($config["site_path"]."/".$config["path_lang"].$lang_file[0]."/rss.xml"))
        GetLangContent("rss", $config["path_lang"].$lang_file[0]);
}
GetLangContent("general", $config["path_lang"].$lang_file[0]);
GetLangContent("error", $config["path_lang"].$lang_file[0]);
$config["lang_name"] = $lang_file[0];
include_once $config["site_path"]."/include/class.breadcrumbs.php";

$default_ltr = $lang_dir ? $lang_dir : 'ltr';
$default_left = $lang_dir == 'ltr' ? 'left' : 'right';
$default_right = $lang_dir == 'ltr' ? 'right' : 'left';

$strSQL = "SELECT title, keywords, description FROM ".METATAGS." WHERE page = 'main' AND id_lang = '".$config["default_lang"]."' ";
$rs = $dbconn -> Execute($strSQL);

if($rs->_numOfRows){
	$lang["main_title"] = stripslashes($rs->fields[0]);
	$lang["keywords"] = stripslashes($rs->fields[1]);
	$lang["description"] = stripslashes($rs->fields[2]);
}

$smarty->assign("default_lang", $lang_code);
$smarty->assign("charset", $charset);
$smarty->assign("lang", $lang);
$smarty -> assign("default_ltr", $default_ltr);
$smarty -> assign("default_right", $default_right);
$smarty -> assign("default_left", $default_left);

$rs = $dbconn->Execute("Select id, name, code from ".LANGUAGE_TABLE." where visible='1'");
$i = 0;

// если запрос идет через роутер - то в QUERY_STRING у нас полностью запрашиваемый адрес, а нам нужны только параметры.
// Парсим его на url и параметры.
$routingUrl = "";
if(isset($useRouting) && $useRouting){
	$query = $_SERVER["QUERY_STRING"];
	$query = explode('?', $query);

	if(isset($langCodeFromUrl)){
		$routingUrl = $query[0];
		$routingUrl = str_replace("/".$langCodeFromUrl."/", "", $routingUrl);
	}

	$queries = array();
	foreach($_GET as $key => $value){
		$queries[] = $key."=".$value;
	}
	$queries = implode('&', $queries);
	$query = "";

}
else{
	$query = $_SERVER["QUERY_STRING"];
}

$langSeoLinks = array();
if(isset($config["use_global_seo"]) && $config["use_global_seo"]){
	if($routerFileName != 'quick_search.php'){
		$strSQL = "SELECT file_assoc, lang_code FROM ".SEO_FILES_ASSOC." WHERE (file_name='{$routerFileName}' AND params='{$paramsSeoReq}' AND file_name != 'info.php') OR ( file_name = 'info.php' AND params='{$paramsSeoReq}') ";
	}
	else{
		$strSQL = "SELECT file_assoc, lang_code FROM ".SEO_FILES_ASSOC." WHERE (file_name='{$routerFileName}' AND file_name != 'info.php' AND params='{$paramsSeoReq}') ";
	}
	$res2 = $dbconn->Execute($strSQL);
	if($res2->_numOfRows){
		while(!$res2->EOF){
			$langSeoLinks[$res2->fields[1]] = $res2->fields[0];
			$res2->MoveNext();
		}
	}
}

while(!$rs->EOF){
	$lang_link[$i]["code"] = $rs->fields[2];
	$lang_link[$i]["name"] = ucfirst($rs->fields[1]);
	$lang_link[$i]["id"] = $rs->fields[0];

    $j=0;
	if($query){
		$query_arr = array();
		$new_query_arr = array();
		$query_arr = explode("&",$query);

                
		foreach($query_arr as $k =>$v){
			$s = explode("=",$v);
                       if(trim($s[0] != "language_code")) {
  
                            if ($j>0) {
                                $new_query_item = explode("=",$new_query_arr[$j-1]);
                                if ($new_query_item[0] != trim($s[0]) && trim($s[0])!= '') {
                                    array_push($new_query_arr, $v);
                                    $j++;
                                }
                            } else {
                            array_push($new_query_arr, $v);
                            $j++;
                            }
                        }
		}
		$query = implode("&", $new_query_arr);
	}
	if(strlen($query)>0) $query .= "&";

	// при включенной опции разделения на языки в seo - выбор языка сайта из дропдауна приобретает другой вид
	if($routingUrl && isset($config["use_seo_multilang"]) && $config["use_seo_multilang"]){

		if(isset($langSeoLinks[$rs->fields[2]])){
			$lang_link[$i]["link"] = $config["site_root"]."/".$rs->fields[2]."/".$langSeoLinks[$rs->fields[2]].($queries ? "?".$queries : "");
		}
		else{
			$lang_link[$i]["link"] = $config["site_root"]."/".$rs->fields[2]."/".$routerFileName.($queries ? "?".$queries : "");
		}
	}
	else{
		$lang_link[$i]["link"] = "?".$query."language_code=".$rs->fields[0];
	}
	$rs->MoveNext(); $i++;
}

$smarty->assign("lang_link", $lang_link);

$smarty->assign("site_path", $config["site_path"]);
$smarty->assign("site_root", $config["site_root"]);
$smarty->assign("server", $config["server"]);

$smarty->assign("main","templates/pilot_3_theme/css/basic.css");

if ($lang_code == "ar")
	$smarty->assign("style_left","templates/pilot_3_theme/css/arabic_".$default_left.".css");
else
	$smarty->assign("style_left","templates/pilot_3_theme/css/langstyle_".$default_left.".css");

if ($theme_style == "")
	$theme_style = "_def";

$smarty->assign("admin_style","templates/pilot_3_theme/css/color".$theme_style."_admin.css");

if (isset($config["social"])) {
	$smarty->assign("social", $config["social"]);
} else {
	$smarty->assign("social", 0);
}

if (!isset($config["server_id"]) || $config["server_id"] == "") {
    $config["server_id"] = 1;
}
global $_SERVER;
global $FILE_SELF;
$FILE_SELF = basename($_SERVER["PHP_SELF"]);

$strSQL = "SELECT value, width, height, type FROM ".SPECIAL_LOGOTYPE_TABLE." WHERE (CURDATE() >= date_start) AND (CURDATE() <= date_end)";
$result = $dbconn -> Execute($strSQL);

if($result -> fields[0] != "") {
	$logo_setup['site_top_logotype'] = $result -> fields[0];
	$logo_setup['site_logotype_format'] = $result -> fields[3];
	$logo_setup['site_logotype_width'] = $result -> fields[1];
	$logo_setup['site_logotype_height'] = $result -> fields[2];
} else {
	$logo_setup['site_top_logotype'] = $config['site_top_logotype'];
	$logo_setup['site_logotype_format'] = $config['site_logotype_format'];
	$logo_setup['site_logotype_width'] = $config['site_logotype_width'];
	$logo_setup['site_logotype_height'] = $config['site_logotype_height'];
}

$logo_setup['site_banner'] = $config['site_banner'];
$logo_setup['site_banner_format'] = $config['site_banner_format'];
$logo_setup['site_banner_width'] = $config['site_banner_width'];
$logo_setup['site_banner_height'] = $config['site_banner_height'];

$smarty->assign("logo_setup", $logo_setup);


$strSQL = "SELECT id_servers, server, site_path FROM ".SERVERS_TABLE;
$res = $dbconn -> Execute($strSQL);
$servers = array();
while (!$res -> EOF) {
	$servers[$res -> fields[0]]['server'] = $res -> fields[1];
	$servers[$res -> fields[0]]['site_path'] = $res -> fields[2];
	$res -> MoveNext();
}


if (isset($_POST["agree"]) && $_POST["agree"] == '1') {
	setcookie('agree','1',time()+200000,'/');
	echo "<script>location.href='".seo("index", 1)."'</script>";
}
function ModuleLang($path_lang_module) {
	global $config_index;
    if(isset($config_index["module"]) && count($config_index["module"]) > 0){
		foreach ($config_index["module"] as $key => $module_name) {
			if(isset($config_index[$module_name]))
			foreach ($config_index[$module_name] as $index => $value) {
				if ($path_lang_module == $value) return $module_name;
			}
		}
    }
}

function stripslashes_for_array(&$arr)
{
   foreach($arr as $k=>$v)
   {
       if (is_array($v))
       {
           stripslashes_for_array($v);
           $arr[$k] = $v;
       }
       else
       {
           $arr[$k] = stripslashes($v);
       }
   }
}

function fix_magic_quotes_gpc()
{
   if (get_magic_quotes_gpc())
   {
       stripslashes_for_array($_POST);
       stripslashes_for_array($_GET);
       stripslashes_for_array($_COOKIE);
	   stripslashes_for_array($_REQUEST);
   }
}

function getReq($sField = '', $bEscape = false) {
	$sVal = isset($_REQUEST[$sField]) ? trim($_REQUEST[$sField]) : '';
	if ($bEscape) {
		$sVal = mysql_real_escape_string($sVal);
	}
	return $sVal;
}

fix_magic_quotes_gpc();

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// paysystems
include_once "Payment_Config.php";

define('PAYMENT_DIR', $dir."/include/");
define('SYSTEMS_DIR', $dir."/include/systems/");

include_once "Payment_Data_Kipper.php";
include_once "Payment_Engine.php";
$link = $config['server'].str_replace($config['site_root'],'',$_SERVER['REQUEST_URI']);
if (preg_match("/.*(".str_replace('/', '\/', $config['server']).").*/",$link) && (!preg_match('/.*\/admin\/.*/', $link))) {
	if (isset($_SESSION['back_url'])){
		if ($_SESSION['back_url'][count($_SESSION['back_url'])-1] != $link) {
			if (isset($_SESSION['back_url'][count($_SESSION['back_url'])-2]) && $_SESSION['back_url'][count($_SESSION['back_url'])-2] == $link) {
				unset($_SESSION['back_url'][count($_SESSION['back_url'])-1]);					
			} elseif (!preg_match('/.*('.str_replace('/', '\/', $config['server']).'.{1,4}$|alert\.php.*|[^_]index\.php.*|ajax_class\.php.*|backend\.php.*|ajax_backend\.php.*|location\.php.*|im\/.*|flash_chat\/.*|w_communicator\/.*|webmessenger\/.*|\/uploades\/.*|\/fckeditor\/.*|\/include\/.*|\/install\/.*|\/facebook_connect\/.*|\/templates\/.*|ajax|viewprofile.php$)/', $link)) {
				$_SESSION['back_url'][] = $link;
			} elseif (count($_SESSION['back_url']) == 1 && preg_match('/.*index\.php.*$/', $link)) {
				unset($_SESSION['back_url']);
			}
		} 
	} else {
		if (!preg_match('/.*('.str_replace('/', '\/', $config['server']).'.{1,4}$|alert\.php.*|[^_]index\.php.*|ajax_class\.php.*|backend\.php.*|ajax_backend\.php.*|location\.php.*|im\/.*|flash_chat\/.*|w_communicator\/.*|webmessenger\/.*|\/uploades\/.*|\/fckeditor\/.*|\/include\/.*|\/install\/.*|\/facebook_connect\/.*|\/templates\/.*|ajax|viewprofile.php$)/', $link)) {
			$_SESSION['back_url'][] = $link;
		}
	}
}
if (isset($_SESSION['back_url']) && isset($_SESSION['back_url'][count($_SESSION['back_url'])-2]))
	$smarty->assign('back_to_view', $_SESSION['back_url'][count($_SESSION['back_url'])-2]);
else 
	$smarty->assign('back_to_view', $config['server'].'/'.($config["use_global_seo"] ? $config["lang_short_code"].'/' : '').'index.php');
?>
