<?php
ini_set('display_errors', '1');
error_reporting(E_ALL & ~(E_NOTICE | E_DEPRECATED | E_STRICT | E_WARNING));

/**
 * обработка запросов к api (для веб-серверов с настройками типа try_files ... /index.php?$uri&$query_string) 
 */
if (\strpos($_SERVER['REQUEST_URI'],'/api/dev')===0) {
    require_once 'vendor/autoload.php';
    \CB\ApiDev\Runner::run();
    exit;
}

session_start();
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding("UTF-8");

$config['site_root'] = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/"));
$script_filename = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']);
$config['site_path'] = substr($script_filename, 0, strrpos($script_filename, "/"));

require_once "include/config.php";
if (!$config['site_path']) {
    die('Invalid $config[\'site_path\']. Please set correct site_path in config.php file. For example, it can be C:/apache/www, or /var/www for web hosting.');
}
if (!$config["lang"]) {
    die("Invalid config.php file, no \$config['lang'] was set.");
}
// ИД сессии
$ses_id = $config['site_path'];
require_once "vendor/autoload.php";
require_once "include/constants.php";
require_once "include/functions1.php";
require_once "include/functions2.php";
require_once "include/sql_functions.php";
require_once "include/bm.errors.php";
$lang_name = $config['lang'] == 'american' ? 'english' : $config['lang'];
if (!file_exists($config['site_path'] . '/lang/' . $lang_name . '.php')) {
    die('File not exists: ' . $config['site_path'] . '/lang/' . $lang_name . '.php');
}
require_once $config['site_path'] . '/lang/' . $lang_name . '.php';
$config["system_lang"] = $config["lang"];

@date_default_timezone_set('Europe/Moscow'); // Устанавливаем зону, т.к. смарти использует временные фукнции, им необходима временная зона

//Чистим неправильный site_path для локальных версий
if (($config["type"] == "LOCAL") && ($_SESSION[$ses_id]["clear_site_root"])) {
    $config["site_root"] = "";
}

if ($_REQUEST["clear_site_root"] == 1) {
    $_SESSION[$ses_id]["clear_site_root"] = 1;
    $config["site_root"] = "";
};
if ($_REQUEST["not_clear_site_root"] == 1) {
    $_SESSION[$ses_id]["clear_site_root"] = 0;
};
if ($config["type"] == "LOCAL") {
    if ($config["site_root"] == "") {
        header("Location: /login.php");
    } else {
        ?>
        <div id="alert_div"></div>
        <link rel="stylesheet" type="text/css" href="themes/clientbase/libs/jquery/jquery-ui.css"/>
        <link rel="stylesheet" href="style.css" type="text/css">
        <script type="text/javascript" src="themes/clientbase/libs/jquery/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="themes/clientbase/libs/jquery/jquery-migrate-1.2.1.js"></script>
        <script type='text/javascript' src='themes/clientbase/libs/jquery/jquery-ui.min.js'></script>
        <script type="text/javascript" src="include/js/help_sys.js"></script>
        <script type="text/javascript" src="themes/clientbase/libs/jquery/jquery-dialog.js"></script>
        <script type="text/javascript" src="themes/clientbase/libs/jquery/jquery.cookie.js"></script>
        <script type="text/javascript" src="lang/<?php echo $config['lang'] ?>.js"></script>
        <script language="JavaScript" type="text/javascript">

            $.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
                _title: function (title) {
                    if (!this.options.title) {
                        title.html("&#160;");
                    } else {
                        title.html(this.options.title);
                    }
                }
            }));

            if (window.devicePixelRatio >= 2) {
                $.cookie("screen_width", screen.width * 2);
                $.cookie("screen_height", screen.height * 2);
            }
            else {
                $.cookie("screen_width", screen.width);
                $.cookie("screen_height", screen.height);
            }

            function start_alert(text) {
                text = text.replace(/\n/g, "<br>");
                $("<div id=jalert><div class=\"hr1\" ></div><p align=\"left\" style=\"padding-left: 6px;\">" + text + "</p><p align=center><button class=\"al_button\" id=\"jalert_ok\">OK</button></p></div>").prependTo("#alert_div");
                bind_help_bt("alert_div"); // привязываем подсказки
                title = lang.Attention;
                title_html = '<table cellpadding=0 cellspacing=0 ><tr><td height=10><p style=\"font-size:16px; font-weight:normal; color:#999; margin-top:0;padding-left:4px;\">' + title + '<\/p><\/td><td><\/td><\/tr><\/table>';
                var obj = {};
                obj.modal = true;
                obj.width = 500;
                obj.title = "";
                obj.open = function (event, ui) {
                    $(this).parent().find('.ui-dialog-title').html(title_html);
                };
                obj.close = function (ev, ui) {
                    $(this).remove();
                };
                obj.draggable = false;
                obj.resizable = false;
                $("#jalert").dialog(obj);
                overlayHandler();
                $(window).bind('resize', overlayHandler);
                $("div.ui-dialog").focus();
                $("#jalert_ok").click(function () {
                    $("#jalert").dialog('close');
                    $(window).unbind('resize', overlayHandler);
                    location.href = location.href + 'index.php?clear_site_root=1&r=' + Math.random();
                    return false;
                });
                $("#jclose_link").one('click', function () {
                    $("#jalert").dialog('close');
                    $(window).unbind('resize', overlayHandler);
                    location.href = location.href + 'index.php?clear_site_root=1&r=' + Math.random();
                });
                return false;
            }

            function well() {
                if (test_ip_res)
                    location.href = "<?php echo $config["site_root"];?>/login.php";
                else {
                    start_alert("<?php echo $lang["your_ip_invalid"] . "<br/><a href='https://clientbase.ru/help/for_admin_16/opredeleni/' target='_blank'>" . $lang['All_help'] . "</a>"; ?>");
                }
            }
            ;

            var test_ip_res = false;
            var img_test = document.createElement('img');
            var onload_break = 0;

            img_test.onload = function () {
                if (onload_break) return;
                onload_break = 1;
                if (img_test.width == 1) test_ip_res = true;
                else test_ip_res = false;
                well();
            }
            img_test.onerror = function () {
                if (onload_break) return;
                onload_break = 1;
                test_ip_res = false;
                well();
            }
            img_test_onerror = function () {
                if (onload_break) return;
                onload_break = 1;
                test_ip_res = false;
                well();
            }
            function test_ip() {
                test_ip_res = false;
                onload_break = 0;
                img_test.src = "<?php echo $config["site_root"];?>/images/empty.gif?r=" + Math.random();
                setTimeout(img_test_onerror, 3000) // Таймаут 3 секунды
            }
            test_ip();
        </script>
        <?php
    }
} else {
    if (($_SERVER['SERVER_NAME'] == "demo.clientbase.ru") || ($_SERVER['SERVER_NAME'] == "demo.basemaster.com") ||
        ($_SERVER['SERVER_NAME'] == "beta.clientbase.ru") || ($_SERVER['SERVER_NAME'] == "beta.basemaster.com")
    ) {
        if ($_SESSION[$ses_id]['demo_base'] || $_SESSION[$ses_id]['demo_basemaster']) {
            header("Location:login.php");
        } else {
            header("Location:setup.php");
        }
    }
    if ($config['installed']) {
        if ($_REQUEST['check_all']) {
            $checks = check_distr('all');
        }
        header("Location:login.php");
    } else {
        $checks = check_distr();
        if ($checks['critical'] || $checks['check_access']) { // Выводим список ошибок
            $version = (int)substr($config['version'], 0, 2) . "." . (int)substr($config['version'], 2,
                    2) . "." . (int)substr($config['version'], 4, 2);

            $smarty = new Smarty;
            $smarty->compile_dir = sys_get_temp_dir();
            $smarty->assign("config", $config);
            $smarty->assign("lang", $lang);
            $smarty->assign("checks", $checks);
            $smarty->assign("cur_title", $lang["Installation"]);
            $smarty->display("templates/setup_checks.tpl");
            ?>
            </div>
            </div>

            <div id="footback_div_id"
                 style="width:100%; background:#fff url(images/bg-footer.png) repeat-x top left; border-top:1px solid #ddd; position:relative; z-index:3;">
                <table border=0 cellspacing=0 cellpadding=0 class="footback no_print"
                       style="width:100%; height:29px; padding:17px 0px 50px 17px;" id="footback_table_id">
                    <tr>
                        <td align=center>
                            <?php
                            $copy = get_copyright_name();
                            $tpl = 'Copyright&nbsp;&copy;&nbsp;<a href="//%s">%s</a>';
                            vprintf($tpl, $copy);
                            ?>
                            <br><br>
                            <br><br>
                        </td>
                    </tr>
                </table>
            </div>
            </BODY>
            </HTML>
            <?php
            exit;
        } else {
            header("Location:setup.php");
        }
    }
}