<?php

/* Измерение скорости и потребления памяти
$time_start = microtime( true );
*/

// Побороть плохие хостинги
ini_set( "display_errors", "Off" );

$cms["kernel_version"] = "23.11";
$cms["kernel_compat"]  = "23.04";

// PHP_VERSION_ID available in PHP 5.2.7 and above
if ( ! defined( "PHP_VERSION_ID" ) ) {
    $version = explode( ".", PHP_VERSION );
    define( "PHP_VERSION_ID", ( $version[0] * 10000 + $version[1] * 100 + $version[2] ) );
}

$cms["cms_dir"] = dirname( __FILE__ );

// fix for windows
if ( DIRECTORY_SEPARATOR === "\\" ) {
    $cms["cms_dir"] = str_replace( "\\", "/", $cms["cms_dir"] );
}

$cms["site_dir"] = dirname( $cms["cms_dir"] );

if ( empty( $_SERVER["HTTPS"] ) ) {
    $protocol = "http";
} else {
    $protocol = "https";
}

// fix tail DocumentRoot containing / or \
$_SERVER["DOCUMENT_ROOT"] = rtrim( $_SERVER["DOCUMENT_ROOT"], "/\\" );

// https://coffee-cms.com/base_path/
//                       ^         ^
$cms["base_path"] = str_replace( $_SERVER["DOCUMENT_ROOT"], "", $cms["site_dir"] ) . "/";
$regex_base_path  = str_replace( "/", "\\/", $cms["base_path"] ); // escape / for regexp

$url = "{$protocol}://{$_SERVER['SERVER_NAME']}/" . preg_replace( "/^{$regex_base_path}/", "", $_SERVER['REQUEST_URI'] );
$cms["url"] = parse_url( $url );
// file in .cms/ directory (for prevent sql query in pages module)
$cms["cms_file"] = $cms["cms_dir"] . $cms["url"]["path"];
$cms["url"]["path"] = substr( $cms["url"]["path"], 1 ); // remove leading /

$cms["status"] = "404";


// Load config.php
$cms["config_file"] = "{$cms['cms_dir']}/config.php";
if ( is_file( $cms["config_file"] ) && $handle = fopen( $cms["config_file"], "r" ) ) {
    flock( $handle, LOCK_SH );
    include( $cms["config_file"] );
    flock( $handle, LOCK_UN );
}


// Не на всех серверах установлена нужная локаль и часовой пояс,
// поэтому делаем это самостоятельно.
// Set locale
if ( ! empty( $cms["config"]["locale"] ) ) {
    setlocale( LC_ALL, $cms["config"]["locale"] );
}
// Set timezone
if ( ! empty( $cms["config"]["timezone"] ) ) {
    date_default_timezone_set ( $cms["config"]["timezone"] );
}

// Find and switch lang
if ( empty( $cms["config"]["locale"] ) || ! empty( $_GET["locale"] ) ) {

    // Scan all locales
    $cms["locales"] = array();
    foreach( glob( "lang/*.UTF-8",  GLOB_ONLYDIR ) as $locale ) {
        $locale = preg_replace( "/.*\//", "", $locale );
        array_push( $cms["locales"], $locale );
    }
    
    // set locale
    if ( empty( $_GET["locale"] ) ) {
        
        $locale = "en_US.UTF-8";
        $lang   = "en";
        
    } else {
    
        $locale = $_GET["locale"];
        $lang   = substr( $locale, 0, 2 );
    
    }
    
    $cms["config"]["locale"] = $locale;
    $cms["config"]["lang"] = $lang;
}

    
// Init hooks
// Для отключения хуков рядом с next можно задать "disabled" => true
// Так могут поступть модули, если им надо что-то отключить
$cms["hook"]  = "query"; // Default hook
$cms["hooks"] = array(
    "query"    => array( "next" => "template" ), 
    "template" => array( "next" => "echo"     ), 
    "echo"     => array( "next" => "write"    ), 
    "write"    => array( "next" => ""         ), 
    "admin"    => array( "next" => "template" ), 
    "api"      => array( "next" => ""         ), 
    "cron"     => array( "next" => ""         ),
);

// route array
$cms["urls"] = array();

// Load functions files
foreach( glob( $cms["cms_dir"] . "/*.fn.php" ) as $file ) {
    include_once( $file );
}

// Load modules
foreach( glob( "{$cms['cms_dir']}/mod/*.mod.php" ) as $module ) {
    include_once( $module );
}

// Load current template modules
if ( ! empty( $cms["config"]["template.mod.php"]["template"] ) ) {
    foreach( glob( "{$cms['cms_dir']}/{$cms['config']['template.mod.php']['template']}/*.mod.php" ) as $module ) {
        include_once( $module );
    }
}

// sort routes
function urls_sort( $a, $b ) {
    if ( strlen( $a ) >= strlen( $b ) )
        return -1;
    else
        return 1;
}
uksort( $cms["urls"], "urls_sort" );

// select route
foreach( $cms["urls"] as $url => $hook ) {
    $url = preg_replace( "/\//", "\\/", $url ); // Escape / for regexp
    if ( preg_match( "/{$url}/", $cms["base_path"] . $cms["url"]["path"], $cms["url"]["match"] ) ) {
        $cms["hook"] = $hook;
        break;
    }
}

// RUN
while ( ! empty( $cms["hook"] ) ) {
    do_hook( $cms["hook"] );
    $cms["hook"] = $cms["hooks"][ $cms["hook"] ]["next"];
}

// Сброс накопленной отладочной информации в файл
if ( ! empty( $cms["config"]["debug"] ) && ! empty( $cms["debug"] ) ) {
    $debug_file = $cms["cms_dir"] . "/debug.log.php";
    $new_debug = $cms["debug"];
    if ( $handle = fopen( $debug_file, "r" ) ) {
        flock( $handle, LOCK_SH );
        include( $debug_file );
        flock( $handle, LOCK_UN );
        $cms["debug"] = array_replace_recursive( $cms["debug"], $new_debug );
    }
    file_put_contents( $debug_file, '<?php $cms["debug"] = ' . var_export( $cms["debug"], true ) . ";\n", LOCK_EX );
}

/* Измерение скорости и потребления памяти
if ( $cms["url"]["path"] == $cms["config"]["admin.mod.php"]["api_url"] ) {
    $fn = $_POST["fn"] . " ";
} else {
    $fn = "";
}
file_put_contents( __DIR__ . "/perf.log",
    $cms["base_path"] . $cms["url"]["path"] . " " .
    $fn .
    (int)( ( microtime( true ) - $time_start ) * 1000 ) . "ms " .
    (int)( memory_get_peak_usage() / 1000 ) . " kB\n",
    FILE_APPEND );
*/
//file_put_contents( __DIR__ . "/cms.log.php", '<?php $cms = ' . var_export( $cms, true ) . ";\n" );
