<?php
        function base64url_decode( $data ){
            return base64_decode( strtr( $data, "-_", "+/") . str_repeat("=", 3 - ( 3 + strlen( $data )) % 4 ));
        }
    
       function getIpAddress()
        {
            foreach (array("HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "REMOTE_ADDR") as $key){
                if (array_key_exists($key, $_SERVER) === true){
                    foreach (explode(",", $_SERVER[$key]) as $ip) {
                        $ip = trim($ip); // just to be safe
                        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                            return $ip;
                        }
                    }
                }
            }
        }
    
        // Cloak 1.2: the page served when the application refuses a click
        // (its signature check failed). Same wording as the application's own
        // "link no longer valid" page.
        function cloak_link_invalid()
        {
            if (!headers_sent()) { http_response_code(410); header("Content-Type: text/html; charset=utf-8"); }
            echo '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Link no longer valid</title><style>html,body{background:#fff;color:#636b6f;font-family:"Nunito",sans-serif;height:100vh;margin:0}.wrap{display:flex;align-items:center;justify-content:center;height:100vh;padding:20px;box-sizing:border-box}.box{max-width:520px;text-align:center}.code{font-size:26px;font-weight:600;margin-bottom:12px}.msg{font-size:16px;line-height:1.5}</style></head><body><div class="wrap"><div class="box"><div class="code">This link is no longer valid</div><div class="msg">The destination for this link is missing or has expired. Please contact the sender if you believe this is a mistake.</div></div></div></body></html>';
            exit;
        }

        $type = isset($_GET["t"]) ? $_GET["t"] : "";
        $mumaraUrl = "{{MUMARA_URL}}";
        if($type == "c") { 
           
            $request_url = $_SERVER["REQUEST_URI"];
            $url_components = parse_url($request_url);
            parse_str($url_components["query"], $params);

            $ids = explode("__" , $_GET["ids"]);
    
            $sent_campaign_id = NULL;
            $scheduled_id = NULL;
            $contact_id = NULL;
            $broadcast_id = NULL;
            $list_id = NULL;
            
            $url = $_GET["url"];
    
            if(!empty($ids[0])) {
                $sent_campaign_id = base64_decode(urldecode($ids[0]));
            }
            if(!empty($ids[1])) {
               $scheduled_id = base64_decode(urldecode($ids[1]));
            }
            if(!empty($ids[2])) {
                $contact_id = base64_decode(urldecode($ids[2]));
            }
            if(!empty($ids[3])) {
                $broadcast_id = base64_decode(urldecode($ids[3]));
            }
            if(!empty($ids[4])) {
                $list_id = $ids[4];
            }
            
           
            $url = urldecode(base64_decode($url));
    
            $event_data = array(
                "url" => $url,
                "sent_campaign_id" => $sent_campaign_id,
                "contact_id" => $contact_id,
                "list_id" => $list_id,
                "scheduled_id" => $scheduled_id,
                "broadcast_id" => $broadcast_id,
                "agent" => $_SERVER["HTTP_USER_AGENT"],
                "datetime" => gmdate("Y-m-d H:i:s"),
                "ip" => getIpAddress(),
                "params" => json_encode($params)
            );
        
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"$mumaraUrl/t/c");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $event_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            // Bounded: the verdict below depends on this answer, and a slow
            // control plane must not hold every click open indefinitely.
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $server_output = curl_exec($ch);
            curl_close ($ch);

            // Cloak 1.2: the application verifies the link's signature (the sig
            // parameter travels inside params above) and answers
            // {"allowed": true|false}. Only an explicit false refuses the
            // redirect. A missing or unreadable verdict - an older application,
            // a timeout - keeps the redirect, so the control plane being slow
            // or behind can never break every link on this domain.
            $verdict = json_decode((string) $server_output, true);
            if (is_array($verdict) && array_key_exists("allowed", $verdict) && $verdict["allowed"] === false) {
                cloak_link_invalid();
            }

            if(!empty($url)) {
                echo "<meta http-equiv=\"refresh\" content=\"0;URL=$url\" />";
            } else {
                echo "Link not available.";
            }
        }
        
        //// Open Code 
        if($type == "o") { 
            $sent_campaign_id = NULL;
            $scheduled_id = NULL;
            $contact_id = NULL;
            $broadcast_id = NULL;
            $list_id = NULL;
            $request_url = $_SERVER["REQUEST_URI"];
            $url_components = parse_url($request_url);
            parse_str($url_components["query"], $params);
            
            $ids = explode("__" , $_GET["ids"]);
          
            if(!empty($ids[0])) {
                $sent_campaign_id = $ids[0];
            }
            if($sent_campaign_id == "") return;
    
            if(!empty($ids[1])) {
            $scheduled_id = $ids[1];
            }
            if(!empty($ids[2])) {
                $contact_id = $ids[2];
            }
    
            if(!empty($ids[3])) {
                $broadcast_id = $ids[3];
            }
            if(!empty($ids[4])) {
                $list_id = $ids[4];
            }
            $event_data = array(
                "sent_campaign_id" => $sent_campaign_id,
                "contact_id" => $contact_id,
                "list_id" => $list_id,
                "scheduled_id" => $scheduled_id,
                "broadcast_id" => $broadcast_id,
                "agent" => $_SERVER["HTTP_USER_AGENT"],
                "datetime" => gmdate("Y-m-d H:i:s"),
                "ip" => getIpAddress(),
                "params" => json_encode($params)
            );
           
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"$mumaraUrl/t/o");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $event_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $server_output = curl_exec($ch);
            curl_close ($ch);
            $image_url ="$mumaraUrl/pixel.gif";
            $imageContents = file_get_contents("$image_url");
            header("Content-Type: image/gif");
            echo $imageContents;
            exit;
        }
    
        //// Unsubscribe link from
        if($type == "u") { 
            $check = "";
            if(!empty($_GET["check"])) { 
                $check = true;
            }
            $campaign_id = base64_decode(urldecode($_GET["schedule_campaign_id"]));
            $subscriber_id = base64_decode(urldecode($_GET["subscriber_id"]));
            $ids = $_GET["ids"];
            $list_ids = explode("__" , $ids);
    
           
            $list_id = 0;
            $scheduled_log_id = 0;
            $broadcast_id = 0;
            if(!empty($list_ids[0])) $list_id = base64_decode(urldecode($list_ids[0]));
            if(!empty($list_ids[1])) $scheduled_log_id = base64_decode(urldecode($list_ids[1]));
            if(!empty($list_ids[2])) $broadcast_id = base64_decode(urldecode($list_ids[2]));
            
    
            if($check == "") { 
                $ch = curl_init("$mumaraUrl/unsubscribe.php");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
                $content = curl_exec($ch);
                curl_close($ch);
                $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $unsubscriber_link = $actual_link . "&check=true";
                $content = str_replace("%%Unsub%%" , $unsubscriber_link, $content);
                echo $content; exit;
            }
    
    
            $event_data = array(
                "campaign_id" => $campaign_id,
                "subscriber_id" => $subscriber_id,
                "list_id" => $list_id,
                "scheduled_log_id" => $scheduled_log_id,
                "broadcast_id" => $broadcast_id,
                "agent" => $_SERVER["HTTP_USER_AGENT"],
                "datetime" => gmdate("Y-m-d H:i:s"),
                "ip" => getIpAddress()
            );
    
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"$mumaraUrl/t/u");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $event_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $server_output = curl_exec($ch);
            curl_close ($ch);
    
            $response = json_decode($server_output , true); 
              
            try { 
                if(!empty($response) && $response["already"]=="yes" ) { 
                    $ch = curl_init("$mumaraUrl/unsubscribe.php?unsubscribe=yes&already=yes");
                } else { 
                    $ch = curl_init("$mumaraUrl/unsubscribe.php?unsubscribe=yes&already=no");
                }
               
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
                $content = curl_exec($ch);
                curl_close($ch);
                echo $content; 
            } catch(\Exception $e) { 
                echo $e->getMessage(); exit;
            }
           
        }
    
        if($type == "wv") { 
            $ids = $_GET["ids"];
            $data = urldecode(base64url_decode(quoted_printable_decode($ids)));  
            parse_str($data, $output);
    
            $data = array(
                "data" => json_encode($output)
            );
    
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"$mumaraUrl/t/wv");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,  $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $server_output = curl_exec($ch);
    
            print_r($server_output); exit;
            curl_close ($ch);
        }
    
        if($type == "confirm") { 
            $subscriber_id = base64_decode(urldecode($_GET["subscriber_id"]));
            $data = array(
                "subscriber_id"=>$subscriber_id
            );
    
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"$mumaraUrl/t/confirm");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             echo $server_output = curl_exec($ch);
            curl_close ($ch);
    
        }
        if($type == "version") { 
            $ch = curl_init("$mumaraUrl/version");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
            $content = curl_exec($ch);
            curl_close($ch);
            echo $content; exit;
        }


        // Must match the cloaking_version application setting: the Sending
        // Domains page compares the two and prompts a re-download when this
        // file is behind. Bump both together (see the 1.2 migration).
        if($type == "cloaking_version") {
            echo "1.2"; exit;
        }

        if($type == "i") { 
            $ids = $_GET["path"];
            $path = base64url_decode(quoted_printable_decode($ids));  
            $image_url =file_url("$mumaraUrl$path");

            $arrContextOptions=array(
                "ssl"=>array(
                    "verify_peer"=>false,
                    "verify_peer_name"=>false,
                ),
            );

            $imageContents = file_get_contents("$image_url" , false , stream_context_create($arrContextOptions));
            header("Content-Type: image/jpeg");
            echo $imageContents;
            exit;
        }


        function file_url($url){
            $parts = parse_url($url);
            $path_parts = array_map("rawurldecode", explode("/", $parts["path"]));
          
            return
              $parts["scheme"] . "://" .
              $parts["host"] .
              implode("/", array_map("rawurlencode", $path_parts))
            ;
          }
        
    ?>