<?php
    //error_reporting(-1);
        //ini_set('display_errors', 'On');
    
        
        function getSuppressionFileFolderPath()
        {
            $result =   null;

            include('../../../scripts/bdd.php');
            $sqlSuppressionFileFolderPath   =    'SELECT value_setting FROM settings WHERE name_setting = ?';
            $cmdSuppressionFileFolderPath   =   $bdd->prepare($sqlSuppressionFileFolderPath);
            $cmdSuppressionFileFolderPath->execute(array('suppression_file_folder_path'));
            $setting                    =   $cmdSuppressionFileFolderPath->fetch(PDO::FETCH_ASSOC);
            $cmdSuppressionFileFolderPath->closeCursor();
            if($setting)
            {
                $result                 =   $setting['value_setting'];
            }else
            {//mtk
                echo "nothing getSuppressionFileFolderPath";
            }
            return $result;
        }
    
        function getOptizmoAccessToken()
        {
            $result =   null;

            include('../../../scripts/bdd.php');
            $sqlGetOptizmoAccessToken   =    'SELECT value_setting FROM settings WHERE name_setting = ?';
            $cmdGetOptizmoAccessToken   =   $bdd->prepare($sqlGetOptizmoAccessToken);
            $cmdGetOptizmoAccessToken->execute(array('optismo_access_token'));
            $setting                    =   $cmdGetOptizmoAccessToken->fetch();
            $cmdGetOptizmoAccessToken->closeCursor();
            if($setting)
            {
                $result                 =   $setting['value_setting'];
            }

            return $result;
        }
        
    function getSuppressionFileUrlFromSponsor($p_id_offer)
    {
        $result                     =   null;
        if((is_numeric($p_id_offer)))
        {

                        include('../../../scripts/bdd.php');
                        $sqlGetOfferInfos   =   
                        '
                            SELECT  O.sid,S.affiliate_id,S.platform,S.api_key,S.api_host
                            FROM    offer O,sponsor S
                            WHERE   O.id    =   ?
                            AND     S.id    =   O.id_sponsor
                        ';
                        $cmdGetOfferInfos   =   $bdd->prepare($sqlGetOfferInfos);
                        $cmdGetOfferInfos->execute(array($p_id_offer));

                        $offer              =   $cmdGetOfferInfos->fetch(PDO::FETCH_OBJ);
                        $cmdGetOfferInfos->closeCursor();
                        
                        if(!empty($offer))
                        {

                            $sid_offer      =   $offer->sid;
                            $affilate_id    =   $offer->affiliate_id;
                            $api_key        =   $offer->api_key;
                            $api_host       =   $offer->api_host;
                            $platform       =   $offer->platform;
                            
                            if($platform == 'Cake') {
                            	$url            =   
                            	$api_host.'/affiliates/api/2/offers.asmx/GetSuppressionList?api_key='.$api_key.'&affiliate_id='.$affilate_id.'&offer_id='.$sid_offer;
                            	$curl_response                  =   makeGetCurlRequest($url);
                                 $xmlSuppression_list_response   =   simplexml_load_string($curl_response);
                                 var_dump($xmlSuppression_list_response);
                                 die;

                                if ($xmlSuppression_list_response === false) 
                                {
                                    $result =   null;
                                }
                                else
                                {
                                    $result =   $xmlSuppression_list_response->download_url;
                                }

                                return $result;
                            } else {
                            	$url            =   $api_host;

                            	$curl_response                  =   makePostCurlRequest($url,$api_key,$sid_offer);
                            	if($curl_response == 'PLEASE WAIT A FEW MINUTES BEFORE NEXT API CALL') {
                            		return '1';
                            	} else if($curl_response == 'API KEY REQUIRED') {
                            		return "2";
                            	} else if($curl_response == 'INVALID CAMPAIGNID') {
                            		return "3";
                            	} else {
                            		$xmlSuppression_list_response   =   json_decode(json_encode(simplexml_load_string($curl_response, 'SimpleXMLElement', LIBXML_NOCDATA),true), true);

	                                if ($xmlSuppression_list_response === false) 
	                                {
	                                    $result =   null;
	                                }
	                                else
	                                {
	                                    $result =   $xmlSuppression_list_response['data']['suppurl'];
	                                }


	                                return $result;
                            	}
                                
                            }
                                
                               
                    	}
                        else 
                        {
                            return $result;
                        }
                }
        else
        {
                    return $result;
        }
    }
    
    
    function getCampaignAccessKeyFromSupressionFileUrl($p_supression_file_url)
    {
            //https://p.b2suppress.com/dl/2dc7f59c5ef29eb0be50631fcabd225d.zip
            //https://mailer.optizmo.net/sm-rvch-i03-3e45e415d7d370ebcb21264acce51e24&one=1&icma=2b14cbfb79a9df6de7128960f627abb6
            $result =   null;
            if(!empty($p_supression_file_url))
            {
                $tab1   =   explode('/',$p_supression_file_url);
                var_dump($tab1);
                if(count($tab1)>=3)
                {
                        $tab2   =   explode('&',$tab1[3]);
                        if(count($tab2)>=1)
                        {
                            $result =   $tab2[0];
                        }
                }
            }

            return $result;
    }
    

    function makePostCurlRequest($p_url_request,$apikey,$campaignid)
    {
        $result =   null;
        if(empty($p_url_request))
        {
            return $result;
        }
        else
        {
           
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL,$p_url_request);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('apikey' => $apikey, 'apifunc' => 'getsuppression', 'campaignid' => $campaignid));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $server_output = curl_exec ($ch);

            curl_close ($ch);
            return $server_output;
        }
    }
    
    function makeGetCurlRequest($p_url_request)
    {
        $result =   null;
        if(empty($p_url_request))
        {
            return $result;
        }
        else
        {
            //2-1 : Set curl Options :
            $options    =
            array
            (
                CURLOPT_URL            => $p_url_request, // Url cible (l'url la page que vous voulez télécharger)
                CURLOPT_RETURNTRANSFER => true, // Retourner le contenu téléchargé dans une chaine (au lieu de l'afficher directement)
                CURLOPT_HEADER         => false, // Ne pas inclure l'entête de réponse du serveur dans la chaine retournée
                CURLOPT_SSL_VERIFYHOST => false, // 
                CURLOPT_SSL_VERIFYPEER => false
            );
            
            
            // 2-2 : Get cURL resource
            $curl       =   curl_init();
            if(empty($curl))
            {
                $result =   "ERREUR curl_init : Il semble que cURL ne soit pas disponible.";
            }
            
            // 2-3 : We are passing options to curl instance 
            curl_setopt_array($curl, $options);

            // 2-4 : Send the request & save response to $resp
            $result = curl_exec($curl);
            
            // 2-5 : Si il s'est produit une erreur lors du téléchargement
            if(curl_errno($curl))
            {
                $result =   "ERREUR curl_exec : ".curl_error($curl);
            }
            
            // 2-6 : Close request to clear up some resources
            curl_close($curl);
            $curl   =   null;
            
            return $result;
        }
    }
    
    
    function optizmoListPreparation($p_optismo_access_token,$p_campaign_access_key)
    {
            $result         =   null;
            if(!empty($p_optismo_access_token) and !empty($p_campaign_access_key))
            {

            	$json_url = 'https://mailer_api.optizmo.net/accesskey/download/'.$p_campaign_access_key.'?token='.$p_optismo_access_token.'&format=md5&deltas=1';
				$json = file_get_contents($json_url);
				$json=str_replace('},

				]',"}

				]",$json);
				$data = json_decode($json);

				if(isset($data->error)) {
					$url        =   'https://mailer_api.optizmo.net/accesskey/download/'.$p_campaign_access_key.'?token='.$p_optismo_access_token.'&format=plain&deltas=1';
				} else {
					$url        =   'https://mailer_api.optizmo.net/accesskey/download/'.$p_campaign_access_key.'?token='.$p_optismo_access_token.'&format=md5&deltas=1';
				}
                    

                    $curl_result    =   makeGetCurlRequest($url);
                    $tab_result     =   json_decode($curl_result, true);
                    if(count($tab_result)>=6)
                    {
                            $result     =   $tab_result['download_link'];
                    }
            }
            return $result;
    }
    

    function DNSADDownloadSuppressionFile($p_final_link,$p_destination_folder){
         //set_time_limit(0); 
            ini_set("memory_limit","2048M");
            ini_set("upload_max_filesize","3000M");
            ini_set("post_max_size","3000M");
            ini_set("max_execution_time","0");
            ini_set("max_input_time","0");

            $destination_folder     =   $p_destination_folder;
            $suppression_file_name  =   'list.zip';
            $file_content           =   makeGetCurlRequest($p_final_link);
            $save_to                =   $destination_folder.$suppression_file_name;

            $downloaded_file        =   fopen($save_to, 'w+');
            fwrite($downloaded_file, $file_content);
            fclose($downloaded_file);
    }

    function optizmoDownloadSuppressionFile($p_optismo_final_link,$p_destination_folder)
    {
            //set_time_limit(0); 
            ini_set("memory_limit","2048M");
            ini_set("upload_max_filesize","3000M");
            ini_set("post_max_size","3000M");
            ini_set("max_execution_time","0");
            ini_set("max_input_time","0");

            $destination_folder     =   $p_destination_folder;
            $suppression_file_name  =   'list.zip';
            $file_content       =   makeGetCurlRequest($p_optismo_final_link);
            $save_to                    =   $destination_folder.$suppression_file_name;

            $downloaded_file            =   fopen($save_to, 'w+');
            fwrite($downloaded_file, $file_content);
            fclose($downloaded_file);
    }

     function DownloadSuppressionFile($p_optismo_final_link,$p_destination_folder)
    {
            ini_set("memory_limit","2048M");
            ini_set("upload_max_filesize","3000M");
            ini_set("post_max_size","3000M");
            ini_set("max_execution_time","0");
            ini_set("max_input_time","0");

            $suppression_file_name  =   'list.zip';
            $newfname = $p_destination_folder.$suppression_file_name;
            $file = fopen ($p_optismo_final_link, 'r');
            if ($file) {
                $newf = fopen ($newfname, 'w+');
                if ($newf) {
                    while(!feof($file)) {
                        fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
                    }
                }
            }
            if ($file) {
                fclose($file);
            }
            if ($newf) {
                fclose($newf);
            }
    }
    
    
    function deleteAllExistingFiles($p_folder)
        {
            $directory          =   $p_folder;
            $tab_files          =   array_diff(scandir($directory), array('..', '.'));
            foreach($tab_files as $file) {
                unlink($p_folder.'/'.$file);
            }
        }
        
        
        function openExtractZipArchive($p_source_archive,$p_desctination_extract_archive)
    {
            /* Open the Zip file */
            $zip            =   new ZipArchive;
            $extractPath    =   $p_desctination_extract_archive;
            if($zip->open($p_source_archive) == "true")
            {
                   $zip->extractTo($extractPath);
                    $zip->close();
            } 



            /* Extract Zip File */
            
    }
    
    
    function renameSupressionFile($p_folder)
    {
            $directory          =   $p_folder;
            $tab_files          =   array_diff(scandir($directory), array('..', '.','domains.txt'));
            foreach($tab_files as $file) {
               /* if(strpos($file, "suppression_list--") === 0)
                {
                    rename($p_folder.'/'.$file, $p_folder.'/list');
                }
                elseif(strpos($file, "MD5") === 0)
                {
                    rename($p_folder.'/'.$file, $p_folder.'/list');
                }
                elseif(string_ends_with($file, "unsubs.txt"))
                {
                    rename($p_folder.'/'.$file, $p_folder.'/list');
                } elseif(strpos($file, "GSF_All") === 0)
                {
                	rename($p_folder.'/'.$file, $p_folder.'/list');
                }
                else
                {
                    unlink($p_folder.'/'.$file);
                } */
                rename($p_folder.'/'.$file, $p_folder.'/list');
            }
            $directory          =   $p_folder;
            $tab_files          =   array_diff(scandir($directory), array('list'));
            foreach($tab_files as $file) {
                unlink($p_folder.'/'.$file);
            }
    }
    
        
    function update_suppression_status($p_id_offer)
        {
        $date_now                   =   date('d F Y');
        $suppressionFileFolder      =   getSuppressionFileFolderPath();
        $offerSuppressionFolder     =   $suppressionFileFolder.$p_id_offer.'/';
        $offerSuppressionFile       =   $offerSuppressionFolder.'list';
        if (file_exists($offerSuppressionFile)) 
        {
            $date_suppression   =   date ('d F Y', filemtime($offerSuppressionFile));
            $str                =   strtotime($date_now) - (strtotime($date_suppression));
            $days               =   floor($str/3600/24);
            $diff               =   10-$days;
            if($days<=5)
            {
                $value  =  "<span class='badge badge-success'>".$date_suppression."</span> ";
            }
            if($days>5 && $days<=10)
            {
                $value  = "<span class='badge badge-warning'>".$date_suppression."</span> ";
            }
            if($days>10)
            {
                $value  =  "<span class='badge badge-important'>".$date_suppression."</span> ";
            }
            
            include('../../../scripts/bdd.php');
            $sqlUpdateSuppressionFileStatus     =   "UPDATE offer SET suppression_status= ? WHERE id = ?";
            $cmdUpdateSuppressionFileStatus     =   $bdd->prepare($sqlUpdateSuppressionFileStatus);
            $cmdUpdateSuppressionFileStatus->execute(array($value,$p_id_offer));
        }
        else
        {
            $value  =  "<span class='badge badge-inverse'>No Suppression</span> ";
            include('../../../scripts/bdd.php');
            $sqlUpdateSuppressionFileStatus     =   "UPDATE offer SET suppression_status= ? WHERE id = ?";
            $cmdUpdateSuppressionFileStatus     =   $bdd->prepare($sqlUpdateSuppressionFileStatus);
            $cmdUpdateSuppressionFileStatus->execute(array($value,$p_id_offer));
        }
    }
        
    
        function getUnsubLinkTechnology($p_url_suppression_list)
        {
            $result =   null;
            if(!empty($p_url_suppression_list))
            {
                $domainUnsubTechnology  =   getParentDomain($p_url_suppression_list);
                if(!empty($domainUnsubTechnology))
                {
                    switch ($domainUnsubTechnology) 
                    {
                        case 'b2suppress.com':
                            $result     =   '[STATIC_LINK]';
                            break;
                        case 'dnsad.com':
                            $result     =   '[FTP_DNSAD]';
                            break;
                        
                        case 'unsubcentral.com':
                            $result     =   '[UNSUB_CENTRAL]';
                            break;
                        
                        case 'unsub-pa.com':
                            $result     =   '[EZEPO]';
                            break;
                            
                        case 'box.com':
                            $result     =   '[BOX_PLATEFORM]';
                            break;
                        
                        case 'optizmo.net':
                            $result     =   '[OPTIZMO]';
                            break;
                        
                        default:
                            $result     =   '[UNKNOWN]';
                            break;
                    }
                    //mtk echo " getUnsubLinkTechnology : ".$result."";
                    return $result;
                }
            }
        }
    
    
    function getDomain($Address) 
    { 
        $parseUrl = parse_url(trim($Address)); 
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); 
    }


    function getParentDomain($url)
    {
        preg_match("/[a-z0-9\-]{1,63}\.[a-z\.]{2,6}$/", parse_url($url, PHP_URL_HOST), $_domain_tld);
        echo $_domain_tld[0];
        return $_domain_tld[0];
    } 
    
    
    function string_ends_with($string, $ending)
    {
        $len        =   strlen($ending);
        $string_end =   substr($string, strlen($string) - $len);

        return $string_end == $ending;
    }   
        
        // download b API
    if((isset($_GET['id_offer'])) and (is_numeric($_GET['id_offer']))    and ($_GET['id_offer'] > 0) and (!isset($_GET['url'])))
    {

        $id_offer                   =       $_GET['id_offer'];
        $suppressionFileFolder      =       getSuppressionFileFolderPath();
        //mtk echo " supp file path : ".$suppressionFileFolder.$id_offer."/ ;   ";
        $offerSuppressionFolder     =       $suppressionFileFolder.$id_offer.'/';
        $sponsorSupressionFileURL   =       getSuppressionFileUrlFromSponsor($id_offer);
        if($sponsorSupressionFileURL == '1') {
        	echo "PLEASE WAIT A FEW MINUTES BEFORE NEXT API CALL";
        	die;
        } else if($sponsorSupressionFileURL == '2') {
        	echo "API KEY REQUIRED";
        	die;
        } else if($sponsorSupressionFileURL == '3') {
        	echo "INVALID CAMPAIGNID";
        	die;
        }
  

        //mtk echo " url sponsor downlaod : ".$sponsorSupressionFileURL.";  "; //https://mailer.optizmo.net/sm-rvch-i03-3e45e415d7d370ebcb21264acce51e24&one=1&icma=2b14cbfb79a9df6de7128960f627abb6
        $technologySuppressionFile  =       getUnsubLinkTechnology($sponsorSupressionFileURL);
        // mtk echo "techno : ".$technologySuppressionFile."; ";
        if(!empty($technologySuppressionFile))
        {
            if($technologySuppressionFile     == '[OPTIZMO]')
            {
                $optismoAccessToken                 =       getOptizmoAccessToken(); // mtk : mochkil f hadi f cas d offre id 20 
                if($optismoAccessToken)
                {
                    if($sponsorSupressionFileURL)
                    {
                        $campaignAccessKey          =   getCampaignAccessKeyFromSupressionFileUrl($sponsorSupressionFileURL);
                        echo 'Campaign Access Key :'.$campaignAccessKey."<br/>"; 
                        if($campaignAccessKey)
                        {
                            $suppressionFileLink    =   optizmoListPreparation($optismoAccessToken,$campaignAccessKey);
                            if($suppressionFileLink)
                            {

                                deleteAllExistingFiles($offerSuppressionFolder);
                                optizmoDownloadSuppressionFile($suppressionFileLink,$offerSuppressionFolder);
                                openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
                                renameSupressionFile($offerSuppressionFolder);
                                update_suppression_status($id_offer);

                                $techno       =   'OPTIZMO';
                                //echo $techno.'_ MTK _'.$suppressionFileLink;
                            }
                            else
                            {
                                echo '0 -> optizmoListPreparation()';
                            }
                        }
                        else
                        {
                            echo '0 -> getCampaignAccessKeyFromSupressionFileUrl()';
                        }
                    }
                    else
                    {
                        echo '0 -> getSuppressionFileUrlFromSponsor()';
                    }
                }
                else
                {
                    echo '0 ->getOptizmoAccessToken()';
                }
            }
            elseif($technologySuppressionFile == '[STATIC_LINK]')
            {
                if($sponsorSupressionFileURL)
                {
                    $techno       =   'STATIC_LINK';
                    deleteAllExistingFiles($offerSuppressionFolder);
               DownloadSuppressionFile($sponsorSupressionFileURL,$offerSuppressionFolder);
                openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
                renameSupressionFile($offerSuppressionFolder);
                update_suppression_status($id_offer);
                 //   echo $techno.'___'.$sponsorSupressionFileURL;
                }
            }
            elseif($technologySuppressionFile == '[UNSUB_CENTRAL]')
            {
                if($sponsorSupressionFileURL)
                {
                    $techno       =   'UNSUB_CENTRAL';
                    deleteAllExistingFiles($offerSuppressionFolder);
               DownloadSuppressionFile($sponsorSupressionFileURL,$offerSuppressionFolder);
                openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
                renameSupressionFile($offerSuppressionFolder);
                update_suppression_status($id_offer);
                //    echo $techno.'___'.$sponsorSupressionFileURL;
                }
            }
            elseif($technologySuppressionFile == '[BOX_PLATEFORM]')
            {
                if($sponsorSupressionFileURL)
                {
                    $techno       =   'BOX_PLATEFORM';
                    deleteAllExistingFiles($offerSuppressionFolder);
               DownloadSuppressionFile($sponsorSupressionFileURL,$offerSuppressionFolder);
                openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
                renameSupressionFile($offerSuppressionFolder);
                update_suppression_status($id_offer);
                  //  echo $techno.'___'.$sponsorSupressionFileURL;
                }
            }
            elseif($technologySuppressionFile == '[EZEPO]')
            {
                if($sponsorSupressionFileURL)
                {
                    $techno       =   'EZEPO';
                    deleteAllExistingFiles($offerSuppressionFolder);
               DownloadSuppressionFile($sponsorSupressionFileURL,$offerSuppressionFolder);
                openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
                renameSupressionFile($offerSuppressionFolder);
                update_suppression_status($id_offer);
               //     echo $techno.'___'.$sponsorSupressionFileURL;
                }
            }
            elseif($technologySuppressionFile == '[UNKNOWN]')
            {
               $techno       =   'UNKNOWN';
               deleteAllExistingFiles($offerSuppressionFolder);
               DownloadSuppressionFile($sponsorSupressionFileURL,$offerSuppressionFolder);
                openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
                renameSupressionFile($offerSuppressionFolder);
                update_suppression_status($id_offer);
             //   echo $techno.'_MTK_'.$sponsorSupressionFileURL;

            }
            elseif($technologySuppressionFile == '[FTP_DNSAD]')
            {
                echo "folder ".$offerSuppressionFolder;
                deleteAllExistingFiles($offerSuppressionFolder);
                DNSADDownloadSuppressionFile($sponsorSupressionFileURL,$offerSuppressionFolder);
                openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
                renameSupressionFile($offerSuppressionFolder);
                update_suppression_status($id_offer);

            }
            echo "SUCCESS !";
            
        }
    }



    //Static Link :
    elseif(  (isset($_GET['id_offer'])) and (is_numeric($_GET['id_offer']))    and ($_GET['id_offer'] > 0) and (isset($_GET['url'])) and !empty($_GET['url'])  )
    {
        $id_offer                   =       $_GET['id_offer'];
        $suppressionFileFolder      =       getSuppressionFileFolderPath();
        $offerSuppressionFolder     =       $suppressionFileFolder.$id_offer.'/';
        $sponsorSupressionFileURL   =       $_GET['url'];
        if($sponsorSupressionFileURL)
        {
            deleteAllExistingFiles($offerSuppressionFolder);
            optizmoDownloadSuppressionFile($sponsorSupressionFileURL,$offerSuppressionFolder);
            openExtractZipArchive($offerSuppressionFolder.'list.zip',$offerSuppressionFolder);
            renameSupressionFile($offerSuppressionFolder);
            update_suppression_status($id_offer);

            $techno       =   'STATIC_LINK';
            echo $techno.'___'.$sponsorSupressionFileURL;
        }
    }
    else
    {
        echo 0;
    }
        
        
?>

