<?php
$dir = __DIR__;
$rootDir = dirname(dirname($dir));
$dcDir = $rootDir . '/mysyde';
$intranetDir = $rootDir . '/mysyde/intranet/';
$moduleDir = $rootDir . '/module';
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Verbindung mit Datenbank herstellen
db_connect();

require_once($dcDir . '/admin/admin_functions.inc.php');


//Url rewrite management
try {
    $query_rewrite = "
    SELECT new_url, rewrite_code FROM `main_rewrite_rules` WHERE 
    (TRIM(`old_url`) LIKE ? 
    OR CONCAT(TRIM(`old_url`),'/') LIKE ? 
    OR TRIM(`old_url`) LIKE ? 
    OR CONCAT(TRIM(`old_url`),'/') LIKE ?)
    AND active = 1
    LIMIT 1
";

    $serverRequestUri = filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL);
    $replacedServerRequestUri = str_replace('&', '%26', $serverRequestUri);
    $stmt = @mysqli_prepare($GLOBALS["mysql_con"], $query_rewrite);
    @mysqli_stmt_bind_param($stmt, "ssss", $serverRequestUri, $serverRequestUri, $replacedServerRequestUri, $replacedServerRequestUri);
    @mysqli_stmt_execute($stmt);
    @mysqli_stmt_store_result($stmt);
    $redirectRows = @mysqli_stmt_num_rows($stmt);

    if ($redirectRows > 0) {
        @mysqli_stmt_bind_result($stmt, $newUrl, $rewriteCode);
        while (@mysqli_stmt_fetch($stmt)) {
            switch ($rewriteCode) {
                case "302":
                    $redirect = "302 Found";
                    break;
                case "301":
                default:
                    $redirect = "301 Moved Permanently";
                    break;
            }

            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $new_url = $protocol . $_SERVER['SERVER_NAME'] . $newUrl;
            header("HTTP/1.1 " . $redirect);
            header('Location: ' . $new_url);
            header("Connection: close");
            exit;
        }
    }
} catch (Throwable $t) {

} catch (Exception $e) {

}


//Konstanten
define('COOKIE_DAYS_VALID', 30);
define('CMS_PATH', $dcDir . '/');
define('INTRANET_PATH', $intranetDir . '/');
define('MODULE_PATH', $moduleDir . '/');
define('ROOT_PATH', $rootDir . '/');

// set autoloader
function defaultAutoloader($class_name)
{
    $filePath = sprintf($rootDir . "/mysyde/common/classes/%s.php", $class_name);
    if (file_exists($filePath)) {
        require_once($filePath);
    }
}

//spl_autoload_register('defaultAutoloader');

\DynCom\mysyde\common\classes\Registry::set('translation', new \DynCom\mysyde\common\classes\Translate("de"));
//Umrechnungs-Globals
$GLOBALS["cm_per_in"] = 0.393700787;
$GLOBALS["mm_per_in"] = 3.93700787;
$GLOBALS["in_per_cm"] = 2.545;
$GLOBALS["in_per_mm"] = 25.45;

// Variablen schützen
// $_GET = secure_array($_GET, TRUE);
// $_POST = secure_array($_POST, TRUE);

// Setup auslesen
$setup = setup_get();
$GLOBALS["setup"] = $setup;
$websiteInfo = getSiteInfo(str_replace('www.', '',$_SERVER['SERVER_NAME']));
// Aktuelle Webseite auslesen
$site = (isset($_GET["site"]) && $_GET["site"] <> '') ? site_getbycode($_GET["site"]) : ( !empty($websiteInfo) ? $websiteInfo : site_getbyid($setup["std_main_site_id"]));

$GLOBALS["site"] = $site;
//echo "SITE IS: ";
set_sitecode_get();
$GLOBALS["insert_live_edit_js"] = FALSE;
$GLOBALS["live_edit_mode"] = FALSE;

if ($con_user_id !== null) {
    $_SESSION["login_id"] = $con_user_id;
}
if ($iphone !== null) {
    $_SESSION["is_phone"] = true;
}else {
    $_SESSION["is_phone"] = null;
}

// Session-ID generieren
if ($GLOBALS["site"]["use_session_id"]) {

    ini_set("session.use_cookies", 1);
    ini_set("session.use_only_cookies", 1);
    ini_set("session.use_trans_sid", 1);
    session_name("sid" . $site['code']);

    $visitor_set = 0;

    if (!empty($_COOKIE['sid' . $GLOBALS['site']['code']])) {
        $cookie_preset = TRUE;
    } else {
        $cookie_preset = FALSE;
    }
    if (!(strlen(session_id()) > 0)) {
        if (!empty($_GET['sid']) && check_sid_for_login($_GET['sid'], TRUE)) {
            session_id($_GET['sid']);
            session_start();
        } elseif ($cookie_preset) {
            session_id($_COOKIE['sid' . $GLOBALS['site']['code']]);
            session_start();
        } else {
            session_start();
        }
    }

    if (isset($_SESSION['sidcms']) && $_SESSION['sidcms'] == $_SESSION['sid' . $GLOBALS['site']['code']]) {
        if (session_regenerate_id()) {
            $_SESSION['sid' . $GLOBALS['site']['code']] = session_id();
        }
    }

    if (!empty($_GET['live_edit']) && $_GET['live_edit'] == 1) {
        $GLOBALS["insert_live_edit_js"] = TRUE;
    } elseif (!empty($_GET['sid']) && check_sid_for_login($_GET['sid'], TRUE)) {
        $session_start_sid = $_GET['sid'];
        $startby = 'navlogin';
        $visitor = get_visitor_small($session_start_sid);
    } elseif (!empty($_SESSION['sid' . $GLOBALS['site']['code']])) {
        $visitor = get_visitor_small($_SESSION['sid' . $GLOBALS['site']['code']], 1, 0);
        $visitor_set = 1;
    }
    if (!empty($_COOKIE['sid' . $GLOBALS['site']['code']]) && !(!empty($_GET['sid']) && check_sid_for_login($_GET['sid'], TRUE))) {
        //cookie login
        $cookie_sid = $_COOKIE['sid' . $GLOBALS['site']['code']];
        $visitor = get_visitor_small($cookie_sid);
        $_SESSION['sid' . $GLOBALS['site']['code']] = $cookie_sid;

        $remember_token_orig = trim((string)$visitor['remember_token']);
        $cookie_index = $GLOBALS['site']['code'] . '_remember_login';
        $remember_token_compare = trim((string)$_COOKIE[$cookie_index]);
        if (
            ($GLOBALS['visitor']['frontend_login'] && !(bool)$_SESSION['pass_auth'])
            &&
            (
                (
                    $GLOBALS['visitor']['cookie_only']
                    &&
                    (
                        empty($remember_token_orig)
                        ||
                        empty($remember_token_compare)
                    )
                )
                ||
                (
                    !empty($remember_token_orig)
                    &&
                    (
                        empty($remember_token_compare)
                        ||
                        !($remember_token_compare == $remember_token_orig)
                    )
                )
            )
        ) {
            $visitor['frontend_login'] = 0;
            $GLOBALS['visitor']['frontend_login'] = 0;
            $query = 'UPDATE main_visitor SET frontend_login = 0 WHERE id=' . $GLOBALS['visitor']['id'];
            @mysqli_query($GLOBALS['mysql_con'], $query);
            logQuery(date('c'), $query, __FILE__, __LINE__, $GLOBALS['querylog'], FALSE, FALSE, __FUNCTION__, TRUE, TRUE);
        }
    }


    //Get session date
    $session_time = strtotime($GLOBALS['visitor']['session_date']);
    $time_diff = time() - $session_time;
    //90 Minutes
    $diff_limit = 90 * 60;

    if (
        $visitor['frontend_login']
        &&
        (!$_SESSION['pass_auth'])
        &&
        (!empty($remember_token_compare))
        &&
        $remember_token_compare == $remember_token_orig
        &&
        $cookie_preset
        //&&
        //($time_diff > $diff_limit)
    ) {
        cookie_login_postprocessing($visitor, $_COOKIE);
    }
    $_SESSION['pass_auth'] = FALSE;
    $GLOBALS['visitor']['pass_auth'] = FALSE;
    $GLOBALS['visitor_set'] = 1;

} elseif (isset($_GET['live_edit']) && $_GET['live_edit'] == 1) {
    ini_set("session.use_cookies", 1);
    ini_set("session.use_only_cookies", 1);
    ini_set("session.use_trans_sid", 1);
    $GLOBALS["insert_live_edit_js"] = TRUE;
    session_name("sid" . $site['code']);
    session_start();
    if (isset($_SESSION['sidcms']) && $_SESSION['sidcms'] == $_SESSION['sid' . $GLOBALS['site']['code']]) {
        if (session_regenerate_id()) {
            $_SESSION['sid' . $GLOBALS['site']['code']] = session_id();
        }
    }
} else {
    session_start();
}

// // Temporary debug switch for test environment
// if (isset($_SESSION['login_id']) && (int)$_SESSION['login_id'] === 827) {
//     $_SESSION['login_id'] = 1054;  // Rainer Braun 

//     // Clear stale user-related globals
//     unset($GLOBALS['main_contact']);
//     unset($GLOBALS['admin_user_frontend']);
// }

if (!$GLOBALS["site"]["use_session_id"]) {

}

// Aktuellen Besucher auslesen und ggf. Währung speichern
if ($visitor_set !== 1 || !((int)$GLOBALS['visitor']['id'] > 0)) {
    $visitor = get_visitor();
}

if (!empty($_GET['currency'])) {
    $query = "UPDATE main_visitor
			  SET currency_code = '" . $_GET['currency'] . "'
			  WHERE id = " . $visitor['id'];
    mysqli_query($GLOBALS['mysql_con'], $query);
    $visitor = get_visitor_small(session_id());
}

renew_session_dates($visitor);
$visitor = get_visitor_small(session_id());
$GLOBALS["visitor"] = $visitor;
if (isset($_COOKIE['sidcms'])) {
    $admin_visitor = get_visitor_small($_COOKIE['sidcms']);
    $admin_user_frontend = get_admin_user($admin_visitor);
} else {
    $admin_user_frontend = get_admin_user($visitor);
}

$GLOBALS["admin_user_frontend"] = $admin_user_frontend;


$query = "SELECT * FROM main_contact WHERE id = '".$_SESSION['login_id'] . "' LIMIT 1";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
foreach (@mysqli_fetch_assoc($result) as $key => $value) {
	$GLOBALS['main_contact'][$key] = $value;
}

$query2 = "SELECT * FROM main_contact_department WHERE main_contact_id = '".$_SESSION['login_id'] . "' AND main_mandant_id = '".$GLOBALS['main_contact']['current_mandant_id']."' LIMIT 1";
$result2 = @mysqli_query($GLOBALS['mysql_con'], $query2);
$row2 = @mysqli_fetch_assoc($result2);
$GLOBALS['main_contact']['current_role_id'] = $row2['main_role_id'];
$GLOBALS['main_contact']['current_department_id'] = $row2['main_department_id'];

// Aktuelle Sprache und Sprachvariablen auslesen
language_change();
$lang_getfrombrowser = FALSE;
if ($lang_getfrombrowser) {
    $language = (isset($_GET["language"]) && $_GET["language"] <> '') ? language_getbycode($_GET["language"]) : language_getbycode(lang_getfrombrowser());
} else {
    $language = (isset($_GET["language"]) && $_GET["language"] <> '') ? language_getbycode($_GET["language"], $GLOBALS["site"]["id"]) : language_getbyid($site["std_main_language_id"]);
}

$GLOBALS["language"] = $language;

// Check 404
if(gettype($GLOBALS["language"]) != 'array'  ){
     
    $queryLanguage  = 'SELECT mn.*, ml.code as lanCode, ms.code as siteCode FROM main_navigation as mn INNER JOIN main_language as ml on mn.main_language_id = ml.id INNER JOIN main_site as ms on mn.main_site_id = ms.id WHERE mn.code= "404" LIMIT 1';
    $resultLanguage = @mysqli_query($GLOBALS['mysql_con'], $queryLanguage);
    if(@mysqli_num_rows($resultLanguage) != 0){
       $rowLanguage = @mysqli_fetch_array($resultLanguage);
        
       $address = "/" . $rowLanguage["siteCode"] . "/" . $rowLanguage["lanCode"] . "/" . '404/'; 
       header('Location:'.$address);
       exit;
    }

}

// Check 404
 
if(gettype($GLOBALS["language"]) != 'array'  ){
     
    $queryLanguage  = 'SELECT mn.*, ml.code as lanCode, ms.code as siteCode FROM main_navigation as mn INNER JOIN main_language as ml on mn.main_language_id = ml.id INNER JOIN main_site as ms on mn.main_site_id = ms.id WHERE mn.code= "404" and ms.id = '.$GLOBALS["site"]['id'].' LIMIT 1';
    $resultLanguage = @mysqli_query($GLOBALS['mysql_con'], $queryLanguage);
    if(@mysqli_num_rows($resultLanguage) != 0){
       $rowLanguage = @mysqli_fetch_array($resultLanguage);
        
       $address = "/" . $rowLanguage["siteCode"] . "/" . $rowLanguage["lanCode"] . "/" . '404/'; 
       header('Location:'.$address);
       exit;
    }

}

// check 404
       
$URLS = explode('/', $_SERVER['REQUEST_URI']);  
$URLS_reverse = array_reverse($URLS);
if (strpos($URLS_reverse[0], "?") === false) {
    if(array_key_exists(1,$URLS) && $URLS['1'] != ''){
        $code = $URLS['1'];
        $querySite = "SELECT * FROM main_site WHERE code = '".$code."' AND id = ".$GLOBALS['site']['id']." ORDER BY id";
        $resultSite = @mysqli_query($GLOBALS['mysql_con'], $querySite);

        if(@mysqli_num_rows($resultSite) < 1){
            $queryLanguage  = 'SELECT mn.*, ml.code as lanCode, ms.code as siteCode FROM main_navigation as mn INNER JOIN main_language as ml on mn.main_language_id = ml.id INNER JOIN main_site as ms on mn.main_site_id = ms.id WHERE mn.code= "404" AND ms.id = '.$GLOBALS["site"]['id'].' LIMIT 1';
            $resultLanguage = @mysqli_query($GLOBALS['mysql_con'], $queryLanguage);
            if(@mysqli_num_rows($resultLanguage) != 0){
                $rowLanguage = @mysqli_fetch_array($resultLanguage);
                $address = "/" . $rowLanguage["siteCode"] . "/" . $rowLanguage["lanCode"] . "/" . '404/'; 
                header('Location:'.$address);
                exit;
            }
        }
    } 

    if(array_key_exists(0,$URLS_reverse) && $URLS_reverse['0'] != ''){
        $code = $URLS['0'];
        $querySite = "SELECT * FROM main_site WHERE code = '".$code."' AND id = ".$GLOBALS['site']['id']." ORDER BY id";
        $resultSite = @mysqli_query($GLOBALS['mysql_con'], $querySite);

        if(@mysqli_num_rows($resultSite) < 1){
            $queryLanguage  = 'SELECT mn.*, ml.code as lanCode, ms.code as siteCode FROM main_navigation as mn INNER JOIN main_language as ml on mn.main_language_id = ml.id INNER JOIN main_site as ms on mn.main_site_id = ms.id WHERE mn.code= "404" AND ms.id = '.$GLOBALS["site"]['id'].' LIMIT 1';
            $resultLanguage = @mysqli_query($GLOBALS['mysql_con'], $queryLanguage);
            if(@mysqli_num_rows($resultLanguage) != 0){
                $rowLanguage = @mysqli_fetch_array($resultLanguage);
                $address = "/" . $rowLanguage["siteCode"] . "/" . $rowLanguage["lanCode"] . "/" . '404/'; 
                header('Location:'.$address);
                exit;
            }
        }
    }
    
    if(array_key_exists(3,$URLS) && $URLS['3'] != ''){
        $code = $URLS['3'];
        $querySite = "SELECT * FROM main_navigation WHERE code = '".$code."' AND main_site_id = ".$GLOBALS["site"]['id']." ORDER BY id";
        $resultSite = @mysqli_query($GLOBALS['mysql_con'], $querySite);

        if(@mysqli_num_rows($resultSite) < 1){
            $queryLanguage  = 'SELECT mn.*, ml.code as lanCode, ms.code as siteCode FROM main_navigation as mn INNER JOIN main_language as ml on mn.main_language_id = ml.id INNER JOIN main_site as ms on mn.main_site_id = ms.id WHERE mn.code= "404" AND ms.id = '.$GLOBALS["site"]['id'].' LIMIT 1';
            $resultLanguage = @mysqli_query($GLOBALS['mysql_con'], $queryLanguage);
            if(@mysqli_num_rows($resultLanguage) != 0){
                $rowLanguage = @mysqli_fetch_array($resultLanguage);
                $address = "/" . $rowLanguage["siteCode"] . "/" . $rowLanguage["lanCode"] . "/" . '404/'; 
                header('Location:'.$address);
                exit;
            }
        }
    }
}
   
   // check 404 end

// echo '<div class="startCheck" style="display:none;">data ust ';print_r($GLOBALS["language"]);echo '</div>';

// Textbausteine auslesen
$text_constant = array();
$text_constant_path = rtrim(dirname(__DIR__), '/') . '/common/text_constants.inc.php';
if (is_file($text_constant_path) && is_readable($text_constant_path)) {
    require_once($text_constant_path);
}
$GLOBALS["tc"] = $text_constant[$language["code"]];

// Aktuelles Layout auslesen
$layout = layout_getbyid($language["main_layout_id"]);
$GLOBALS["layout"] = $layout;

// layout klassen auslesen
$GLOBALS["layout_classes"] = get_layout_classes($language["main_layout_id"]);

// Aktuelle Naviationsebene auslesen
$navigation = navigation_get($site, $language);
$GLOBALS["navigation"] = $navigation;

// Tabcounter steuert globale Auswahlfolge von Input-Feldern
$GLOBALS["tabcounter"] = 1;

// deaktivierten bausteine der aktuellen seite lesen
$GLOBALS["inactive_components"] = get_inactive_components($navigation['forward_page_id']);

// pruefen um was es sich fuer ein menupunkt handelt
switch ($navigation['forward_type']) {
    case 1: // seite includen
        $GLOBALS["page"] = page_getbyid($GLOBALS["navigation"]['forward_page_id']);
        // weiteres passiert erst in der get_content() funktion
        break;

    case 2: // interne weiterleitung
        forward_intern($navigation['forward_navigation_id']);
        break;

    case 3: // externe weiterleitung
        forward_extern($navigation['forward_url']);
        break;

    case 5: // interne pfad weiterleitung
        forward_url_intern($navigation['forward_url']);
        break;
}

//Seiten-Meta-Tag-Inhalte in Globals schreiben
set_global_meta_tag_content_site();

//ini_set('display_errors',1);
//include(rtrim($_SERVER['DOCUMENT_ROOT'],'/') . '/mysyde/DcAutoloader.php');
//$dcAutoloader = new DcAutoloader();
//$dcAutoloader->register();
$initPath = rtrim($rootDir, '/') . '/mysyde/init.php';
include_once($initPath);


$sessionStorageKeyPrefix = 'dc-one';
$flashMessageBag = new \DynCom\mysyde\common\classes\NativeSessionFlashMessageBag($sessionStorageKeyPrefix);
$GLOBALS['flashMessageBag'] = $flashMessageBag;
