<?php

/**
 * @framework       Infinity Framework
 * @version         1.0
 * @author          Ahmed El Mertala <ahmed@redevmarketing.com>
 * @date            2019
 * @name            index.php
 */





# defining start time
define('IR_START', microtime(true));

# defining the base path
define('BASE_PATH', dirname(__FILE__));

# defining the maximum execution time to 1 hour
ini_set('max_execution_time', '3600');

# defining the socket timeout to 1 min
ini_set('default_socket_timeout', '60');

# defining the maximum memory limit
ini_set('memory_limit', '-1');

# disabling remote file include
ini_set("allow_url_fopen", '1');
ini_set("allow_url_include", '0');

# defining the default time zone
date_default_timezone_set("UTC");

# getting the peak of memory, in bytes, that's been allocated to our PHP script.
define('START_MEMORY', memory_get_peak_usage(true));
define('START_TIME', microtime(true));

# defining separators
define('DS', DIRECTORY_SEPARATOR);
define('RDS', '/');




/**
 * @name getIp
 * @description get client ip
 * @access public
 * @return string
 */
function getIp()
{
    $ip = "";

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $ipv4 = hexdec(substr($ip, 0, 2)) . "." . hexdec(substr($ip, 2, 2)) . "." . hexdec(substr($ip, 5, 2)) . "." . hexdec(substr($ip, 7, 2));
        $ip = $ipv4;
    }

    if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $match = array();

        if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $ip, $match)) {
            $ip = count($match) > 0 && filter_var($match[0], FILTER_VALIDATE_IP) ? $match[0] : "";
        }
    }

    return $ip;
}



/**
 * @name checkForImage
 * @description checks if the link is an image
 * @param string $url 
 * @return
 */
function checkForImage($url, $domain)
{
    $parts = explode('.', $url);
    $extention = end($parts);
    $extention = strtolower($extention);

    if (in_array($extention, ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
        $image = "$domain/media/" . end(explode(RDS, $url));
        header("Content-type:image/{$extention}");
        echo file_get_contents($image);
        die();
    }
}

/**
 * @name parseURL
 * @description parse url
 * @param string $url
 * @return
 */
function parseURL($url)
{
    $data = [];

    if (strpos($url, '/') === FALSE && strpos($url, 'act') === FALSE) {
        
        $url = exec("./app -action=GetUnecryptedurl -li=" . base64_decode(str_replace("_", "=", $url)));
    }



    $parts = parse_url("http://{$_SERVER['HTTP_HOST']}/{$url}");
    $query = key_exists('query', $parts) ? $parts['query'] : null;
    $path = $parts['path'];
    $output = [];

    if ($query != '') {
        if (strpos($query, 'act=') !== FALSE) {
            $params = explode('&', $query);

            if ($params != null && count($params) > 0) {
                foreach ($params as $param) {
                    $keyValue = explode('=', $param);

                    if ($keyValue != null && count($keyValue) == 2) {
                        $output[$keyValue[0]] = $keyValue[1];
                    }
                }
            }
        }
    } else if (strpos(trim($path, '/'), '/') !== FALSE) {
        $params = explode('/', trim($path, '/'));

        if (count($params)) {
            if (in_array($params[0], ['op', 'cl', 'un', 'oop'])) {
                if (count($params) == 7) {
                    $output["act"] = $params[0];
                    $output["pid"] = $params[1];
                    $output["uid"] = $params[2];
                    $output["vid"] = $params[3];
                    $output["ofid"] = $params[4];
                    $output["lid"] = $params[5];
                    $output["cid"] = $params[6];
                }
            }
        }
    }

    if (count($output) == 0) {
        die('<pre>Could not parse url !</pre>');
    }

    if (count($output) && key_exists('act', $output)) {
        $data['act'] = key_exists('pid', $output) ? $output['act'] : 0;
        $data['process-id'] = 0;

        if (key_exists('pid', $output)) {
            if (strpos($output['pid'], '_') === FALSE) {
                $data['process-id'] = intval($output['pid']);
                $data['process-type'] = 'md';
            } else {
                $parts = explode('_', $output['pid']);

                if (count($parts) == 2) {
                    $data['process-id'] = intval($parts[0]);
                    $data['process-type'] = $parts[1];
                }
            }
        }

        $data['user-id'] = key_exists('uid', $output) ? intval($output['uid']) : 0;
        $data['vmta-id'] = key_exists('vid', $output) ? intval($output['vid']) : 0;
        $data['offer-id'] = key_exists('ofid', $output) ? intval($output['ofid']) : 0;
        $data['list-id'] = key_exists('lid', $output) ? intval($output['lid']) : 0;
        $data['client-id'] = key_exists('cid', $output) ? intval($output['cid']) : 0;
    } else {
        die('<pre>Could not parse url !</pre>');
    }

    return $data;
}


# parse url to get parameters
$url = (filter_input(INPUT_SERVER, 'HTTP_X_REWRITE_URL') != null) ? ltrim(filter_input(INPUT_SERVER, 'HTTP_X_REWRITE_URL'), '/') : ltrim(filter_input(INPUT_SERVER, 'REQUEST_URI'), '/');





checkForImage($url , "$p_domain");

if($url == "") {

    require "home.html";
    die();
}
if(strpos($url, 'status') !== false) {

    $ $prev = file('/proc/stat');
    $prev_cpu = explode(' ', $prev[0]);
    $prev_total = $prev_cpu[2] + $prev_cpu[3] + $prev_cpu[4] + $prev_cpu[5] + $prev_cpu[6] + $prev_cpu[7] + $prev_cpu[8];
    $prev_idle = $prev_cpu[5];
    
    usleep(100000);
    
    $current = file('/proc/stat');
    $current_cpu = explode(' ', $current[0]);
    $current_total = $current_cpu[2] + $current_cpu[3] + $current_cpu[4] + $current_cpu[5] + $current_cpu[6] + $current_cpu[7] + $current_cpu[8];
    $current_idle = $current_cpu[5];
    
    $total = $current_total - $prev_total;
    $idle = $current_idle - $prev_idle;
    
    $usage = round(100 * (($total - $idle) / $total), 2);
    
    // Memory info
    $memInfo = file_get_contents('/proc/meminfo');
    preg_match_all('/(?<name>\w+):\s+(?<value>\d+)\s/', $memInfo, $matches);
    $memInfo = array_combine($matches['name'], $matches['value']);
    
    // Memory usage in GB
    $memory = [
        'total' => round($memInfo['MemTotal'] / 1024 / 1024, 2),
        'free' => round($memInfo['MemFree'] / 1024 / 1024, 2),
        'available' => round($memInfo['MemAvailable'] / 1024 / 1024, 2),
        'cached' => round($memInfo['Cached'] / 1024 / 1024, 2),
        'used' => round(($memInfo['MemTotal'] - $memInfo['MemFree'] - $memInfo['Cached'] - $memInfo['Buffers']) / 1024 / 1024, 2)
    ];

    // Disk usage
    $disk = [];
    $partitions = explode(PHP_EOL, trim(shell_exec('df -P')));
    array_shift($partitions); // Remove header

    foreach($partitions as $partition) {
        $parts = preg_split('/\s+/', trim($partition));
        if (substr($parts[0], 0, 4) === '/dev') {
            $disk[] = [
                'device' => $parts[0],
                'total' => round($parts[1] / 1024 / 1024, 2), // Convert to GB
                'used' => round($parts[2] / 1024 / 1024, 2),  // Convert to GB
                'free' => round($parts[3] / 1024 / 1024, 2),  // Convert to GB
                'mount' => $parts[5]
            ];
        }
    }

    $result = [
        'memory' => $memory,
        'disk' => $disk
    ];

    header('Content-Type: application/json');
    echo json_encode(['cpu_usage' => $usage , 'memory' => $memory, 'disk' => $disk]);
    die();
}




if (strpos($url, 'isok') !== false) {

    header("Content-Type: application/json");
    die(json_encode(["status" => 200, "message" => "ok"]));
}

if (strpos($url, 'postback') !== false) {

    $query_str = parse_url($url, PHP_URL_QUERY);
    parse_str($query_str, $query_params);


    # check if email is the same
    $result = json_decode(exec("./app -iyeqiuywe=fs5bBpNmhEqP2H3Rjkf1Jfp5uL7FAR1cVtEQoGpRFnKeukWDIH74pb0BID5HCHT5tIOBend4VnIf2r3AHWU6cQ== -par=" . base64_encode($query_str)), true);



    die(json_decode($result, true));
}


# prepare data array
$data = parseURL($url);



# start tracking
if (count($data)) {
    if ($data['process-id'] > 0 || $data['offer-id'] > 0) {

        $data['ip'] = getIp();


        $data['agent'] = (filter_input(INPUT_SERVER, 'HTTP_USER_AGENT') != null) ? filter_input(INPUT_SERVER, 'HTTP_USER_AGENT') : '';
        $data['language'] = (filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE') != null) ? strtoupper(substr(filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE'), 0, 2)) : '';

        if ($data['act'] == 'oop') {
            $message = "";

            if (count($_POST)) {
                $email = (filter_input(INPUT_POST, 'email') != null) ? filter_input(INPUT_POST, 'email') : '';

                # send tracking information
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $message = "<span style='color:red'>Please check your email !</span>";
                } else {





                    $result = json_decode(exec("./app -iyeqiuywe=fs5bBpNmhEqP2H3Rjkf1Jfp5uL7FAR1cVtEQoGpRFnKeukWDIH74pb0BID5HCHT5tIOBend4VnIf2r3AHWU6cQ== -email=" . md5($email) . " -clientId=" . $data['client-id'] . " -listId=" . $data['list-id']), true);




                    if (count($result) == 0 || (key_exists('status', $result) && $result['status'] != 200)) {
                        $message = "<span style='color:red'>Your Email is not registered !</span>";
                    }

                    if (strtolower(trim($result['message'])) == 'email is correct !') {
                        # execute tracking job
                        foreach ($data as $key => $value) {
                            $searchVal = array("&", "'", "\"", "/", "\\", "|");
                            $value  =  str_replace($searchVal, "", $value);
                            $data[$key] = htmlentities($value);
                        }



                        exec("nohup ./app -action=ProcceedTracking -iyeqiuywe=fs5bBpNmhEqP2H3Rjkf1Jfp5uL7FAR1cVtEQoGpRFnKeukWDIH74pb0BID5HCHT5tIOBend4VnIf2r3AHWU6cQ== -type=$type -processId=" . $data['process-id'] . " -processType=" . $data["process-id"] . " -userId=" . $data['user-id'] . " -vmtaId=" . $data['vmta-id'] . " -listId=" .  $data['listId']   . " -clientId=" . $data['client-id'] .  " -ip=" . $data['ip'] . " -langauge=" . base64_encode($data["language"]) . " -agent=" . base64_encode($data["agent"]) .  " > /dev/null 2>&1 &");

                        $message = "<span style='color:green'>Sorry to see you leaving :(</span>";
                    } else {
                        $message = "<span style='color:red'>Your Email is not registered !</span>";
                    }
                }
            }

            include_once BASE_PATH . DS . 'optout.php';
        } else {
            # generating link and redirecting
            $link = '';
            $actionId = 0;

            if (in_array($data['act'], ['cl', 'un'])) {
                # get offer link


                $type = $data['act'] == 'cl' ? 'preview' : 'unsub';


                $result = json_decode(exec("./app -action=GetLink -iyeqiuywe=fs5bBpNmhEqP2H3Rjkf1Jfp5uL7FAR1cVtEQoGpRFnKeukWDIH74pb0BID5HCHT5tIOBend4VnIf2r3AHWU6cQ== -type=$type -processId=" . $data['process-id'] . " -processType=" . $data["process-type"] . " -userId=" . $data['user-id'] . " -vmtaId=" . $data['vmta-id'] . " -listId=" .  $data['list-id']   . " -clientId=" . $data['client-id'] .  " -ip=" . $data['ip']), true);



                if ($result === FALSE || count($result) == 0) {
                    die('<pre>405 : Bad request !</pre>');
                }

                if ($result['status'] != 200) {
                    die('<pre>' . $result['status'] . ' : ' . $result['message'] . '</pre>');
                }

                if (
                    key_exists('data', $result)
                    && key_exists('link', $result['data'])
                    && trim($result['data']['link']) != ''
                ) {
                    $link = trim($result['data']['link']);
                    $actionId = intval($result['data']['action_id']);
                } else {
                    echo '<pre>Incorrect redirection !</pre>';
                }
            }


            # send tracking information to master app
            if (in_array($data['act'], ['op', 'cl', 'un']) && $data['process-id'] > 0) {
                # execute tracking job
                foreach ($data as $key => $value) {
                    $searchVal = array("&", "'", "\"", "/", "\\", "|");
                    $value  =  str_replace($searchVal, "", $value);
                    $data[$key] = htmlentities($value);
                }


                $command = "./app -action=ProcceedTracking -iyeqiuywe=fs5bBpNmhEqP2H3Rjkf1Jfp5uL7FAR1cVtEQoGpRFnKeukWDIH74pb0BID5HCHT5tIOBend4VnIf2r3AHWU6cQ== " .
                "-type=" . escapeshellarg($data['act']) . 
                " -actionName=" . escapeshellarg($data['act']) . 
                " -processId=" . escapeshellarg($data['process-id']) . 
                " -processType=" . escapeshellarg($data["process-type"]) . 
                " -userId=" . escapeshellarg($data['user-id']) . 
                " -vmtaId=" . escapeshellarg($data['vmta-id']) . 
                " -listId=" . escapeshellarg($data['list-id']) . 
                " -clientId=" . escapeshellarg($data['client-id']) .  
                " -ip=" . escapeshellarg($data['ip']) . 
                " -langauge=" . escapeshellarg(base64_encode($data["language"])) . 
                " -agent=" . escapeshellarg(base64_encode($data["agent"])) . 
                " > /dev/null 2>&1 &";
            
            exec("nohup $command"); 

            }

            # redirecting in case of a click or unsub
            if ($link != '') {
                header('Location: ' . $link);
                exit();
            } else {
                echo '<pre>Operation completed !</pre>';
            }
        }
    } else {
        echo '<pre>No drop found !</pre>';
    }
} else {
    echo '<pre>No parameters found !</pre>';
}