<?php
//© Copyright Approcket. All rights reserved.
//Majoris Panel Script is considered a proprietary software.
//To gain information about the laws regarding the use of these script,
//please visit www.approcket.ir

require('./majoris_version.php');
require('./majoris_config.php');
require('./majoris_core_config.php');

date_default_timezone_set('Asia/Tehran');

if( MAJORIS_DEBUG_DISPLAY ){
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
} else {
    error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
    ini_set('display_errors', '0');
}

if( MAJORIS_DEBUG_LOG ){

    ini_set("log_errors", 1);
    ini_set("error_log", "./z_php_error.log");
    set_exception_handler(function($e) {
        error_log(
            date('Y-m-d H:i:s').' | '.$_SERVER['REQUEST_URI'].' | '.$e->getMessage().PHP_EOL,
            3,
            "./z_sql_error.log"
        );
    });

} else {

    ini_set("log_errors", 0);
    ini_set("error_log", "./z_php_error.log");
    set_exception_handler(function($e) {
        error_log(
            date('Y-m-d H:i:s').' | '.$_SERVER['REQUEST_URI'].' | '.$e->getMessage().PHP_EOL,
            3,
            "./z_sql_error.log"
        );
    });

}


//PHP VERSION CHECK AND IONCUBE LOADER CHECK
if(MAJORIS_ROOT != 'http://localhost:8080/integrated-majoris-server' && MAJORIS_SELF_HOSTED_MODE){
    $currentPhpVersion = PHP_VERSION;
    $phpMajorMinor = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;
    //check php
    if ($phpMajorMinor !== '8.2') {
        echo 'Your PHP version is '.$currentPhpVersion.'. This application requires PHP version 8.2 Please switch your PHP version accordingly using <a href="https://approcket.ir/academy/change-php-version-in-cpanel-shared-hostings">this tutorial</a>.';
        exit;
    }
    //check ionCube Loader enabled
    if (!extension_loaded('ionCube Loader')) {
        echo 'ioncube_loader extenction is not enabled. enable it with help of <a href="https://approcket.ir/academy/change-php-version-in-cpanel-shared-hostings">this tutorial</a> or ask your hosting provider to enable it on php extentions in Cpanel';
        exit;
    }
    //check ionCube Loader version is 14+
    $loaderVersion = phpversion('ionCube Loader');
    if (version_compare($loaderVersion, '14.0.0', '<')) {
        echo 'your current ionCube Loader is '.$loaderVersion.' while Loader 14.0.0 or higher is required. pelease ask your hosting provider to enable loader 14+';
        exit;
    }
}

//import all files inside _dist/classes folder:
//NOTE: we cant do glob("./core/_dist/classes/*.php") as $filename loop
// because older versions of panel have repeated files in /lib folder and cause fatal Error
require_once "./core/_dist/classes/_const.php";
require_once "./core/_dist/classes/_database.php";
require_once "./core/_dist/classes/Functions.php";
require_once "./core/_dist/classes/Loginer.php";
require_once "./core/_dist/classes/Message.php";


//import all files inside _dist/libs folder:
foreach (glob("./core/_dist/libs/*.php") as $filename) {
    require_once $filename;
}


session_start();

db::init();

//we need lang class in panel for somewhere like:
//sms sender in update_payment.php and maybe other places in fature
include ('./api/v3/class/Lang.php');
$lang = include('./api/v3/libs/lang/fa.php');
lang::init($lang);


#UTILS

function logger($log_msg){
    $log_file_data = './z_logger.log'; // create this file from cpanel.
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    file_put_contents($log_file_data, "[" . date('Y-M-d : h:i:sa') . "]" . " LOGGER: " . $log_msg . "\n", FILE_APPEND);
}

function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
    $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

function startWith($string , $start) {
    if (strpos($string,$start) === 0) {
        return true;
    }else{
        return false;
    }
}

function startsWith($haystack, $needle){
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}   

function endsWith( $haystack, $needle ) {
    $length = strlen( $needle );
    if( !$length ) {
        return true;
    }
    return substr( $haystack, -$length ) === $needle;
}

function safeUrl($url) {

    //used to sanitize urls to prevent xss in links hrefs

    // Return safe fallback if empty
    if (empty($url) || !is_string($url)) {
        return '#';
    }
    
    $url = trim($url);
    
    // Block dangerous protocols
    $dangerousProtocols = ['javascript:', 'data:', 'vbscript:', 'file:'];
    
    foreach ($dangerousProtocols as $protocol) {
        if (stripos($url, $protocol) === 0) {
            return '#unsafe-url'; // Block and return safe fallback
        }
    }
    
    // Escape HTML special characters
    return htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
}

?>