<?php
$overall_memory_usage = memory_get_peak_usage();
$overall_time_counter = microtime(true);
require 'vendor/autoload.php';
define("DEBUG_MODE", !empty($_SERVER['HTTP_HOST']) && substr($_SERVER['HTTP_HOST'], -4) == '.int');
if( DEBUG_MODE ) {
    error_reporting(E_ALL);
    @ini_set( 'display_errors', 1 );
} else {
    error_reporting(false);
    @ini_set( 'display_errors', false );
    set_time_limit(45);
}

//рутовый путь
define( "ROOT_PATH", str_replace("\\", '/', realpath(".")));
// подключение классов ядра

require('includes/class.config.php');       // Config (конфигурация сайта)
Config::Init();
require('includes/class.host.php');         // Host (вспомогательные данные по текущему хосту)
Host::Init();


require('includes/class.convert.php');      // Convert, Validate (конвертирование, проверки валидности)
require('includes/class.storage.php');      // Session, Cookie, Responce, Request

Session::Init();
Request::Init();
Cookie::Init();

require('includes/class.memcache.php');     // MCache (memcached, кеширование в памяти)m
require('includes/class.db.mysqli.php');    // mysqli_db (база данных)
require('includes/class.auth.php');         // Auth (авторизация)
require('includes/class.template.php');     // Template (шаблонизатор), FileCache (файловое кеширование)
require('includes/class.filedata.php');     // FileData (работа с файловым хранилищем рабочих данных)
require('includes/class.page.php');         // Page
require('includes/functions.php');          // набор функций
require('includes/class.video.php');
require('includes/class.playlists.php');
require('includes/class.playlists.tracks.php');
require('includes/class.academy.php');
require('includes/class.services.php');

//словарь
require('includes/class.dictionary.php');
Dictionary::Init();

if(!empty($_GET['showtime']) ) printf("\n1: Execution time: %01.4f", round(microtime(true) - $overall_time_counter, 4));
$overall_time_counter = microtime(true);

$memcache = new MCache(Config::$values['memcache']['host'], Config::$values['memcache']['port']);
// Инициализация рабочих классов
$db = new mysqli_db(Config::$values['mysql']['host'], Config::$values['mysql']['user'], Config::$values['mysql']['pass']);

$lc_time_names = Dictionary::$language == 'ru' ? 'ru_RU' : 'en_US';
$db->querys("set names ".Config::$values['mysql']['charset']);
$db->querys("SET lc_time_names = '".$lc_time_names."';");
$db->select_db(Config::$values['mysql']['db']);

if(!empty($_GET['showtime']) ) printf("\n2: Execution time: %01.4f", round(microtime(true) - $overall_time_counter, 4));
$overall_time_counter = microtime(true);

require('includes/class.db.mysqli.common.php');    // CommonDB
CommonDB::Init();
require('includes/class.notifications.php');    // CommonDB
FileCache::Init('filecache');
$auth = new Auth();
if( !empty( $_GET['logout'] ) || !empty( $_GET['clear_cookie'] ) ) {
    $auth->ClearCookiesData();
    Session::SetParameter('auth_data', []);
    Session::SetArray('auth_data', []);
    unset($_SESSION['auth_data']);
    Response::SetBoolean('authorized', false);
    if( !empty( $_GET['logout'] ) ) {
        ?><script>document.location.href='/?clear_cookie=1';</script><?php
    }
    else {
        if( $_GET['clear_cookie'] == 3 )   { ?><script>document.location.href='/';</script><?php }
        else { ?><script>document.location.href='/?clear_cookie=<?=$_GET['clear_cookie']+1?>';</script><?php }
    }
} else {
// проверка авторизации
    $_authorized = $auth->checkAuth();
    Response::SetBoolean('authorized', $auth->authorized);
}


if(!empty($_GET['showtime']) ) printf("\n3: Execution time: %01.4f", round(microtime(true) - $overall_time_counter, 4));
$overall_time_counter = microtime(true);

// старт запрошенной страницы
$RequestedUri = Host::getRequestedUri();
$requested_page = new Page($RequestedUri);

if(!empty($_GET['showtime']) ) printf("\n4: Execution time: %01.4f", round(microtime(true) - $overall_time_counter, 4));
$overall_time_counter = microtime(true);
if( empty( $requested_page->is_manage_page ) ) {
    $GLOBALS['js_set'][] = '/js/bootstrap.bundle.min.js';
    $GLOBALS['js_set'][] = '/js/bootstrap.min.js';
    $GLOBALS['js_set'][] = '/js/popper.min.js';
    $GLOBALS['css_set'][] = '/css/bootstrap.min.css';

    $GLOBALS['js_set'][] = '/js/jquery.min.js';
    $GLOBALS['css_set'][] = '/js/datepicker/jquery-ui-1.8.16.custom.css';
    $GLOBALS['js_set'][] = '/js/datepicker/jquery-ui.min.js';
    $GLOBALS['css_set'][] = '/js/range.slider/styles.css';
    $GLOBALS['js_set'][] = '/js/range.slider/script.js';
    $GLOBALS['css_set'][] = '/css/variables.css';
    $GLOBALS['js_set'][] = '/js/interface.js';
    $GLOBALS['css_set'][] = '/css/fonts.css';
    $GLOBALS['js_set'][] = '/js/inputmask/inputmask.min.js';
    $GLOBALS['js_set'][] = '/js/popup.window/script.js';
    $GLOBALS['css_set'][] = '/js/popup.window/styles.css';
    $GLOBALS['js_set'][] = '/js/tracks.manage.js';
    $GLOBALS['js_set'][] = '/js/main.js';
    $GLOBALS['css_set'][] = '/css/reset.css';
    $GLOBALS['css_set'][] = '/css/common.css';
    $GLOBALS['css_set'][] = '/css/central.css';
    $GLOBALS['js_set'][] = '/js/client.js';
    $GLOBALS['css_set'][] = '/css/topmenu.css';
    $GLOBALS['js_set'][] = '/js/form.validate.js';
    $GLOBALS['css_set'][] = '/css/controls.css';
    $GLOBALS['js_set'][] = '/js/owlcarousel/owl.carousel.min.js';
    $GLOBALS['css_set'][] = '/js/owlcarousel/owl.carousel.min.css';
    $GLOBALS['js_set'][] = '/js/wavesurfer.js';

}
if(!empty($_GET['showtime']) ) printf("\n5: Execution time: %01.4f", round(microtime(true) - $overall_time_counter, 4));
$overall_time_counter = microtime(true);

require_once('includes/class.content.php');
Response::SetBoolean('debug',DEBUG_MODE);

$content = $requested_page->Render(); 
header('Content-Type: text/html; Charset='.Config::$values['site']['charset']);
header("Last-Modified: ".gmdate('D, d M Y H:i:s', time()-86164*(!empty($days_last_modify)?$days_last_modify:5)).' GMT');
$content = str_replace( array("\r\n", "\r", "\n", "\t", '    ', '    '), '', $content );

echo $content;

$querylog = Convert::ArrayKeySort($db->querylog, 'time', true);
$overall_time_counter = round(microtime(true) - $overall_time_counter, 4);
$overall_memory_usage = memory_get_peak_usage() - $overall_memory_usage;
if($overall_time_counter>0.5) file_put_contents('query.log',print_r($querylog,true));
if(!empty($_GET['showtime']) ){
    printf("\nExecution time: %01.4f", $overall_time_counter);
    printf("\nAlocated memory: %d", $overall_memory_usage);
}
?>
