<?php

/*
 * @name        JMY CMS
 * @link        https://jmy.su/
 * @copyright   Copyright (C) 2012-2025 JMY LTD
 * @license     LICENSE.txt (see attached file)
 * @version     VERSION.txt (see attached file)
 * @author      Komarov Ivan
 * @edited      Orlov Alexsey
 */

if (!defined('ACCESS')) {
    header('Location: /');
    exit;
}
global $core, $db, $url, $config, $user, $security, $lang;
$config_multiLang = 0;
if ($config_multiLang && $config['lang'] != $core->lang) {
    foreach (glob(ROOT . 'etc/' . $core->lang . '.*.config.php') as $confFile) {
        require $confFile;
    }
}
$core->initCore();
if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('#(up-browser)|(blackberry)|(windows ce)|MIDP-2.0|symbian|palm|nokia#i', $_SERVER['HTTP_USER_AGENT'])) {
    define("SMART", true);
}
if (count($url) == 1 && eregStrt('.htm', $url[0])) {
    $GLOBALS['url'][1] = $url[0];
    $GLOBALS['url'][0] = 'content';
}
if ($user['isBan'] == 1) {
    $banIp = configMatch($security['banIp']);
    $banArr = explode("\n", $banIp);
    foreach ($banArr as $v) {
        if (trim($v) != '') {
            $banned = explode('=', $v);
            preg_match("#" . Only1br($banned[0], '') . "#", $_SERVER['REMOTE_ADDR'], $match);
            if (isset($match[0])) {
                $core->ban = true;
                if (isset($banned[1])) $core->banReason = $banned[1];
            }
        }
    }
    if (!$core->ban && $core->auth->banUser) $core->ban = true;
}
if (($config['off'] == 0 || $core->auth->isAdmin == 1 || $url[0] == ADMIN) && !$core->ban) {
    $core->LoadLang(false, true);
    if ($config_multiLang == 1) {
        if (isset($_GET['lang']) && isset($_GET['theme'])) {
            if (isset($core->langsLang[$_GET['lang']]) && $_GET['lang'] == $config['lang']) {
                setcookie('lang', false, time() - 86400, '/');
            } elseif (isset($core->langsLang[$_GET['lang']])) {
                setcookie('lang', filter($_GET['lang'], 'a'), time() + 86400, '/');
            }
            $theme = filter($_GET['theme'], 'a');
            if (is_dir(ROOT . 'usr/tpl/' . $theme . '/') && file_exists(ROOT . 'usr/tpl/' . $theme . '/index.tpl')) setcookie('theme', $theme, time() + 86400, '/');
            location('?nocache=' . time());
        }
        if (isset($_GET['lang'])) {
            if (isset($core->langsLang[$_GET['lang']]) && $_GET['lang'] == $config['lang']) {
                setcookie('lang', false, time() - 86400, '/');
                location('?nocache=' . time());
            } elseif (isset($core->langsLang[$_GET['lang']])) {
                setcookie('lang', filter($_GET['lang'], 'a'), time() + 86400, '/');
                location('?nocache=' . time());
            }
        }
    }
    if (isset($_GET['theme'])) {
        $theme = filter($_GET['theme'], 'a');
        if (is_dir(ROOT . 'usr/tpl/' . $theme . '/') && file_exists(ROOT . 'usr/tpl/' . $theme . '/index.tpl')) {
            setcookie('theme', $theme, time() + 86400, '/');
            location('?nocache=' . time());
        }
    }
    if (isset($_GET['phone_change'])) {
        if ($_COOKIE['smartphone'] == 1) {
            setcookie('smartphone', 0);
        } else {
            setcookie('smartphone', 1);
        }
        location('?nocache=' . time());
    }
    if ($core->auth->isAdmin) {
        $logFiles = glob(ROOT . 'tmp/*.log');
        if (!empty($logFiles)) foreach (@glob(ROOT . 'tmp/*.log') as $logFile) compress($logFile);
    }
    if (!file_exists(ROOT . 'tmp/cache/categories.cache')) {
        $query = $core->select_data('categories', false, 'name, parent_id', 'id, name, altname, description, module, icon, parent_id as pid');
        while ($rows = $db->getRow($query)) {
            $cat_array[$rows['module']][$rows['id']] = array('title' => $rows['name'], 'parent' => $rows['pid'], 'altname' => $rows['altname'], 'icon' => $rows['icon'], 'description' => $rows['description']);
            $checkCatArr[$rows['altname']] = $rows['module'];
        }
        if (isset($cat_array)) setcache('categories', $cat_array);
    }
    if (file_exists(ROOT . 'usr/modules/' . mb_strtolower($url[0]) . '/index.php') && !isset($_GET['download'])) {
        $core->LoadLang();
        $modAccess = modAccess($url[0]);
        pmNew();
        $config_fullajax = 0;
        if (!$config_fullajax) {
            if (!isset($no_head)) $core->tpl->head();
            if ($modAccess == 'groupOk') {
                require ROOT . 'usr/modules/' . mb_strtolower($url[0]) . '/index.php';
            } elseif ($modAccess == 'groupError') {
                $core->tpl->info(str_replace('[group]', $core->auth->group_info['gname'], $lang['gr_denide']));
            } else {
                $core->tpl->info($lang['mod_not_found'], 'warning');
                delcache('plugins');
            }
            if (!isset($no_head)) $core->tpl->foot();
        } else {
            $initFullAjax = (isset($_SERVER['HTTP_AJAX_ENGINE']) || eregStrt('FULL_AJAX', $_SERVER['QUERY_STRING']) || isset($_REQUEST['fullajax']));
            ob_start();
            if ($modAccess == 'groupOk') {
                require ROOT . 'usr/modules/' . mb_strtolower($url[0]) . '/index.php';
            } elseif ($modAccess == 'groupError') {
                $core->tpl->info('Группе "' . $core->auth->group_info['gname'] . '" закрыт доступ в данный раздел.');
            } else {
                $core->tpl->info('Данный раздел не найден на нашем сайте.', 'warning');
            }
            $module_content = ob_get_contents();
            ob_end_clean();
            if (isset($no_head)) {
                echo $module_content;
            } else {
                if (!$initFullAjax) {
                    $core->tpl->head();
                    echo $module_content;
                    $core->tpl->foot();
                } else {
                    $meta = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>' . html_entity_decode((!empty($core->tpl->title) && !empty($_REQUEST['url']) ? $core->tpl->title . $config['name'] : $config['name'] . $config['divider'] . $config['slogan']), ENT_QUOTES) . '</title>';
                    array_unique($core->tpl->headerIncludes);
                    foreach ($core->tpl->headerIncludes as $metas) {
                        if ($metas) $meta .= $metas;
                    }
                    $meta .= '</head>';
                    ob_start();
                    echo $meta;
                    $core->tpl->head();
                    echo $module_content;
                    $core->tpl->foot(true);
                    $fullAjaxContent = ob_get_contents();
                    ob_end_clean();
                    $uniqAuth = '<!-- authGr: ' . $core->auth->group . ' -->';
                    $etag = md5($fullAjaxContent . $uniqAuth);
                    header('Etag:' . $etag);
                    if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
                        header("HTTP/1.1 304 Not Modified");
                        exit;
                    } else {
                        header('Content-type: text/html; charset=utf-8');
                        echo $fullAjaxContent;
                    }
                }
            }
        }
    } elseif ($url[0] == ADMIN && (($core->auth->isUser && $core->auth->isAdmin) || !$core->auth->isUser)) {
        $core->LoadLang(false, false, true);
        $core->LoadLang(true, false, true);
        require ROOT . 'root/index.php';
    } elseif (isset($_GET['download'])) {
        $downId = intval($_GET['download']);
        $q = $core->select_data('attach', 'id = "' . $downId . '"');
        if ($db->numRows($q) > 0) {
            $rows = $db->getRow($q);
            if (file_exists($rows['url'])) {
                $core->upd_data('attach', 'downloads+1 = "' . $id . '"', 'id = "' . $downId . '"');
                location($rows['url']);
            } else {
                location();
            }
        } else {
            location();
        }
    } else {
        if (isset($_SERVER['HTTP_AJAX_ENGINE'])) {
            $core->tpl->info($lang['MOD_NOT_FOUND'], 'warning');
            exit();
        } else {
            $core->tpl->open('404');
            $core->tpl->loadFile('404');
            $core->tpl->setVar('ERROR_TITLE', $lang['404_title']);
            $core->tpl->setVar('ERROR', $lang['404_error']);
            $core->tpl->setVar('TEXT', $lang['404_text']);
            $core->tpl->end();
            $core->tpl->close();
        }
    }
} elseif ($core->ban) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? getenv('HTTP_X_FORWARDED_FOR');
    if ($url[0] == ADMIN && (($core->auth->isUser && $core->auth->isAdmin) || !$core->auth->isUser)) {
        $core->tpl->open('banned');
        $core->tpl->loadFile('banned');
        $core->tpl->setVar('TITLE', str_replace('[ip]', $ip, $security['banIpMessage']));
        $core->tpl->setVar('SUPPORT_MAIL', $config['support_mail']);
        $core->tpl->setVar('BAN_IP', $ip);
        $core->tpl->end();
        $core->tpl->close();
    } else {
        $core->tpl->info(!empty($core->banReason) ? $core->banReason : str_replace('([ip])', '', $security['banIpMessage']));
    }
} else {
    include ROOT . 'usr/tpl/lock.tpl';
}