<?php

/*
$time_start = microtime( true );
*/

// for bad hosters
ini_set( "display_errors", "Off" );

$cms["kernel_version"] = "25.02";
$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__ );

// 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";
}

// if 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

//#todo? It seems there is no point in adding /u for the URL and checking preg_replace for null
$url = "{$protocol}://{$_SERVER['SERVER_NAME']}/" . preg_replace( "/^{$regex_base_path}/", "", $_SERVER['REQUEST_URI'] );
$cms["url"] = parse_url( $url );
$cms["url"]["path"] = urldecode( $cms["url"]["path"] );
// 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 );
}


if ( ! empty( $cms["config"]["locale"] ) ) {
    setlocale( LC_ALL, $cms["config"]["locale"] );
}


if ( ! empty( $cms["config"]["timezone"] ) ) {
    date_default_timezone_set ( $cms["config"]["timezone"] );
}

    
// Init hooks
// Отключение производится добавлением disable => true рядом с next
$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 );
    }
}

// Отсортировать маршруты чтобы короткие совпадения не перекрывали более длинные
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 ) {
    // Нет смысла в /u для URL
    if ( $url = preg_replace( "/\//", "\\/", $url ) ) { // Escape / for regexp
        if ( preg_match( "/{$url}/", $cms["base_path"] . $cms["url"]["path"], $cms["url"]["match"] ) ) {
            $cms["hook"] = $hook;
            break;
        }
    }
}
// Казалось бы можно убрать $cms["base_path"] и так же избавить модули от необходимости его добавлять.
// Но с base_path больше гибкости.
// Модули смогут перехватывать запросы к корню сайта, даже если CMS находится не в корневой папке.

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

// Saving accumulated debugging information to a file
if ( ! empty( $cms["config"]["debug"] ) && ! empty( $cms["debug"] ) ) {
    $debug_file = $cms["cms_dir"] . "/debug.log.php";
    $new_debug = $cms["debug"];
    if ( is_file( $debug_file ) && $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 );
}

/* Measuring speed and memory consumption
if ( $cms["url"]["path"] == $cms["config"]["admin.mod.php"]["api_url"] ) {
    $fn = $_POST["fn"] . " ";
} else {
    $fn = "";
}
file_put_contents( dirname( __FILE__ ) . "/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( dirname( __FILE__ ) . "/cms.log.php", '<?php $cms = ' . var_export( $cms, true ) . ";\n" );
