<html>
    <head>
        <link type="text/css" href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link type="text/css" href="../../css/theme.css" rel="stylesheet">
    </head>
    <body>
        

<?php
    
    include_once '../account/session.php';
    include_once '../../scripts/bd.php';
    $id_mailer=$_SESSION['id-mailer'];
    $username_mailer=$_SESSION['username-mailer'];
    //session_write_close();
    //set_time_limit(0);
    //ignore_user_abort ( true );

    if(isset($_GET['action']))
	{
        $action=$_GET['action'];
        if($action=='preview')preview();
        if($action=='testauto')test_auto();
        if($action=='testcampaign')test_campaign();
        if($action=='sendcampaign')send_campaign();
    }
    
    function preview()
	{
        $text_body=$_POST['text_body'];
        $html_body=$_POST['html_body'];
        $message='';
        if($body_type==0){
            $message = $text_body;
        }elseif ($body_type==1) {
            $message = $html_body;
        }elseif($body_type==2){
            $message = ''; 
            $message.="--{text}".chr(10);                       
            $message.=$text_body.chr(10);                  
            $message.="--{html}".chr(10);               
            $message.=$html_body.chr(10);
        }
        
        $message = str_replace("[Domain]",$domain_body,$message);
        //create_redirect($message);
        header("location: preview.php?message=$message");
    }

    function test_auto()
	{
        echo '<pre>';
        show_status("<div class='text-info'>Test Auto Started.</div>",0);
        if(check_data_test_auto()){
            /*********************************** INITIAL ***********************************/
            $id_server=$_SESSION["id-server"];
            $id_mailer=$_SESSION['id-mailer'];
            /*******************************************************************************/
            /********************************* SPAN 1 DATA *********************************/
            $from_name=$_POST['from_name'];
            $subject=$_POST['subject'];
            $from_email=$_POST['from_email'];
            $reply_email=$_POST['reply_email'];
            $bounce_email=$_POST['bounce_email'];
            $return_path=$_POST['return_path'];
            $received=$_POST['received'];
            $xmailer=$_POST['xmailer'];
            $header_nbr=$_POST['header_nbr'];
            $header_format=$_POST['header_format'];

            $server_body=$_POST['server_body'];
            $domain_body=$_POST['domain_body'];
            $redirect_type=$_POST['redirect_type'];
            $open_tracker=$_POST['open_tracker'];
            $body_type=$_POST['body_type'];
            $text_body=$_POST['text_body'];
            $html_body=$_POST['html_body'];
            /*******************************************************************************/
            /***************************** SPAN 1 DATA ADVANCED ****************************/
            $multiple_type=$_POST['multiple_type'];
            $multiple_values=$_POST['multiple_values'];
			$astuce_tag_active=$_POST['astuce_tag_active'];
			$astuce_tag_email_address=$_POST['astuce_tag_email_address'];
            /*******************************************************************************/
            /********************************* SPAN 2 DATA *********************************/
            $vmtas=$_POST['vmtas'];
            /*******************************************************************************/
            /********************************* SPAN 3 DATA *********************************/
            $sponsor=$_POST['sponsor'];
            $offer=$_POST['offer'];
            /*******************************************************************************/
            /********************************* SPAN 4 DATA *********************************/
            $news=$_POST['news'];
            $isp=$_POST['isp'];
            $data_list=$_POST['data_list'];
            /*******************************************************************************/
            /********************************* SPAN 5 DATA *********************************/
            $test_emails_to=$_POST['test_emails_to'];
            $message_id_email_to=$_POST['message_id_email_to'];
            $test_period=$_POST['test_period'];
            $xdelay=$_POST['xdelay'];
            $change_ip=$_POST['change_ip'];
            $data_from=$_POST['data_from'];
            $data_count=$_POST['data_count'];
            

            /*******************************************************************************/
            /***************************** EXTRACT TEST EMAILS *****************************/
            $test_emails_to= explode(';', $test_emails_to);
            /*******************************************************************************/
            /******************************** MESSAGE CONFIG *******************************/
            $message='';
            if($body_type==0)
			{
                $message = $text_body;
            }
			elseif ($body_type==1) 
			{
                $message = $html_body;
            }
			elseif($body_type==2)
			{
                $message = ''; 
                $message.="--{text}".chr(10);                       
                $message.=$text_body.chr(10);                  
                $message.="--{html}".chr(10);               
                $message.=$html_body.chr(10);
            }
            $message_tmp = $message;
            $message = str_replace("[Domain]",$domain_body,$message);
            /*******************************************************************************/
            /******************************** SEND FUNCTION ********************************/
                if($multiple_type==0){
                    foreach ($vmtas as $row) {
                        $cols=explode(';', $row);
                        $vmta=$cols[1];
                        $ip=$cols[2];
						$domain=$cols[3];
                        $main_ip=$cols[4];
						show_status("<div class='text-warning'>From IP: ".$ip."</div>");
                        foreach ($test_emails_to as $to) {
							if($astuce_tag_active==1){
								preg_replace( "/\r|\n/", "",$astuce_tag_email_address);
								$astuce_tag_email_addresses=explode("\n", $astuce_tag_email_address);
								$ato=$to;
								$to=trim($astuce_tag_email_addresses[0]);
								for($i=0; $i < strlen($ato) ;$i++){
									if(RandomPrefixStr(1)==1){
										$ato=str_replace(substr($ato,$i,1),strtoupper(substr($ato,$i,1)),$ato);
									}
								}
								$xmailer=$ato;
							}
                            sendmail($main_ip,$vmta, $ip, $domain, $from_name, $subject, $from_email, $reply_email, $bounce_email, $return_path, $received, $xmailer, $to, $header_format, $message, '0', '0' ,'0',$message_id_email_to);
                            show_status("<div>Sent to: ".$to."</div>");
                            sleep(1);
                        } 
                    }
                }else{
                    preg_replace( "/\r|\n/", "",$multiple_values);
                    $multiple_values=explode("\n", $multiple_values);
                    foreach ($multiple_values as $value) {
                        if($multiple_type==1){
                            //$from_email_str=  explode('@', $from_email);
                            $from_email=$value;
                            show_status("<div>From Email: ".$from_email."</div>");
                        }
                        if($multiple_type==2){
                            $return_path=$value;
                            //show_status("<div>Return Path: ".$return_path."</div>");
                        }
                        if($multiple_type==3){
                            $message = str_replace("[Domain]",$value,$message_tmp);
                            //show_status("<div>Domain Creative: ".$value."</div>");
                        }
                        if($multiple_type==4){
                            $message=$value;
                            usleep($xdelay);
                            //show_status("<div>Body: ".$message."</div>");
                        }
						if($multiple_type==5){
							$from_str=  explode('@', $from_email);
                            $from_email=$from_str[0].'@'.$value;
							show_status("<div>From Email: ".$from_email."</div>");
                        }
                        
                        foreach ($vmtas as $row) {
                            $cols=explode(';', $row);
							$vmta=$cols[1];
							$ip=$cols[2];
							$domain=$cols[3];
							$main_ip=$cols[4];
							show_status("<div class='text-warning'>From IP: ".$ip."</div>");
							foreach ($test_emails_to as $to) {
								sendmail($main_ip,$vmta, $ip, $domain, $from_name, $subject, $from_email, $reply_email, $bounce_email, $return_path, $received, $xmailer, $to, $header_format, $message, '0', '0' ,'0',$message_id_email_to);
								show_status("<div>Sent to: ".$to."</div>");
                                sleep(1);
							} 
                        }
                    }
                }
            /*******************************************************************************/
            show_status("<div class='text-success'>Test has been sent successfully.</div>",0);
        }else{
            show_status("<div class='text-error'>Test Campaign Failed.</div>",0);
        }
        show_status("<div class='text-info'>Test Auto Finished.</div>",0);
        echo '</pre>';
    }
    
    function test_campaign()
	{
        echo '<pre>';
        show_status("<div class='text-info'>Test Campaign Started.</div>",0);
        if(check_data_test()){

            /*********************************** INITIAL ***********************************/
            $id_server=$_SESSION["id-server"];
            $id_mailer=$_SESSION['id-mailer'];
            /*******************************************************************************/
            /********************************* SPAN 1 DATA *********************************/
            $from_name=$_POST['from_name'];
            $subject=$_POST['subject'];
            $from_email=$_POST['from_email'];
            $reply_email=$_POST['reply_email'];
            $bounce_email=$_POST['bounce_email'];
            $return_path=$_POST['return_path'];
            $received=$_POST['received'];
            $xmailer=$_POST['xmailer'];
            $header_nbr=$_POST['header_nbr'];
            $header_format=$_POST['header_format'];
            $server_body=$_POST['server_body'];
            $domain_body=$_POST['domain_body'];
            $redirect_type=$_POST['redirect_type'];
            $open_tracker=$_POST['open_tracker'];
            $body_type=$_POST['body_type'];
            $text_body=$_POST['text_body'];
            $html_body=$_POST['html_body'];
            /*******************************************************************************/
            /********************************* SPAN 2 DATA *********************************/
            $vmtas=$_POST['vmtas'];
            /*******************************************************************************/
            /********************************* SPAN 3 DATA *********************************/
            $sponsor=$_POST['sponsor'];
            $offer=$_POST['offer'];
            /*******************************************************************************/
            /********************************* SPAN 4 DATA *********************************/
            $news=$_POST['news'];
            $isp=$_POST['isp'];
            $data_list=$_POST['data_list'];
            /*******************************************************************************/
            /********************************* SPAN 5 DATA *********************************/
            $test_emails_to=$_POST['test_emails_to'];
            $message_id_email_to=$_POST['message_id_email_to'];
            $test_period=$_POST['test_period'];
            $xdelay=$_POST['xdelay'];
            $change_ip=$_POST['change_ip'];
            $data_from=$_POST['data_from'];
            $data_count=$_POST['data_count'];

            $additional_negative_active=$_POST['additional_negative_active'];
            $repeat_negative=$_POST['repeat_negative'];
            $additional_negative=$_POST['additional_negative'];


            /*******************************************************************************/
            /***************************** EXTRACT TEST EMAILS *****************************/
            $test_emails_to= explode(';', $test_emails_to);
            /*******************************************************************************/
            /******************************** MESSAGE CONFIG *******************************/
            $message='';
            if($body_type==0){
                $message = $text_body;
            }elseif ($body_type==1) {
                $message = $html_body;
            }elseif($body_type==2){
                $message = ''; 
                $message.="--{text}".chr(10);                       
                $message.=$text_body.chr(10);                  
                $message.="--{html}".chr(10);               
                $message.=$html_body.chr(10);
            }
            $message = str_replace("[Domain]",$domain_body,$message);
            /*******************************************************************************/
            /******************************* PREPARE REDIRECT ******************************/
            $php_file_redirect="rdt.php";
            $redirect_landing_page=$php_file_redirect."?track=[LandingPage]&id_campaign=".$id_campaign."&id_list=[ListID]&id_user=[UserID]";
            $message = str_replace("[OfferPage]",$redirect_landing_page,$message);
            $redirect_unsubscribe=$php_file_redirect."?track=[Unsubscribe]&id_campaign=".$id_campaign."&id_list=[ListID]&id_user=[UserID]";
            $message = str_replace("[OfferUnsub]",$redirect_unsubscribe,$message);
            $redirect_unsubscribe_server=$php_file_redirect."?track=[UnsubServer]&id_campaign=".$id_campaign."&id_list=[ListID]&id_user=[UserID]";
            $message = str_replace("[ServerUnsub]",$redirect_unsubscribe_server,$message);
            /*******************************************************************************/
            /******************************* CREATE REDIRECT *******************************/
            show_status("<div>Creating Redirect...</div>",0);
            if(create_redirect($message,0)){
                show_status("<div class='text-success'>Redirect has been created successfully.</div>",0);
            }else{
                show_status("<div class='text-error'>Creating redirect failed.</div>",0);
            }
            /*******************************************************************************/
            /******************************** SEND FUNCTION ********************************/
            /*************** REDIRECT REPLACE LIST ***************/
            $message = str_replace("[ListID]","0",$message);
            if($additional_negative_active==1){
                $negative="";
                for($i=0;$i<$repeat_negative;$i++){
                    $negative.="\n".$additional_negative;
                }
                $negative='<style>'.$negative."\n".'</style>';
                $message=$message."\n".$negative;
            }
            /****************************************************/
            foreach ($vmtas as $row) {
                $cols=explode(';', $row);
                $vmta=$cols[1];
                $ip=$cols[2];
                $domain=$cols[3];
		$main_ip=$cols[4];
                show_status("<div class='text-warning'>From IP: ".$ip."</div>");
                foreach ($test_emails_to as $to) {
                /*************** REDIRECT REPLACE USER ***************/
                $message_user = str_replace("[UserID]","0",$message);
                /****************************************************/
                    sendmail($main_ip,$vmta, $ip, $domain, $from_name, $subject, $from_email, $reply_email, $bounce_email, $return_path, $received, $xmailer, $to, $header_format, $message_user, '0','0','0',$message_id_email_to);
                    show_status("<div>Sent to: ".$to."</div>");
                    sleep(1);
                } 
            }
            /*******************************************************************************/
            show_status("<div class='text-success'>Test has been sent successfully.</div>",0);
        }else{
            show_status("<div class='text-error'>Test Campaign Failed.</div>",0);
        }
        show_status("<div class='text-info'>Test Campaign Finished.</div>",0);
        echo '</pre>';
    }
    
    function send_campaign()
	{
        echo '<pre>';
        show_status("<div class='text-info'>Send Campaign Started.</div>",0);
        if(check_data()){
            /*********************************** INITIAL ***********************************/
            $id_server=$_SESSION["id-server"];
            $id_mailer=$_SESSION['id-mailer'];
            /*******************************************************************************/
            /********************************* SPAN 1 DATA *********************************/
            $from_name=$_POST['from_name'];
            $subject=$_POST['subject'];
            $from_email=$_POST['from_email'];
            $reply_email=$_POST['reply_email'];
            $bounce_email=$_POST['bounce_email'];
            $return_path=$_POST['return_path'];
            $received=$_POST['received'];
            $xmailer=$_POST['xmailer'];
            $header_nbr=$_POST['header_nbr'];
            $header_format=$_POST['header_format'];
            $server_body=$_POST['server_body'];
            $domain_body=$_POST['domain_body'];
            $redirect_type=$_POST['redirect_type'];
            $open_tracker=$_POST['open_tracker'];
            $body_type=$_POST['body_type'];
            $text_body=$_POST['text_body'];
            $html_body=$_POST['html_body'];
            /*******************************************************************************/
            /***************************** SPAN 1 DATA ADVANCED ****************************/
            $additional_negative_active=$_POST['additional_negative_active'];
            $repeat_negative=$_POST['repeat_negative'];
            $additional_negative=$_POST['additional_negative'];
            $send_multiple_type=$_POST['send_multiple_type'];
            $send_multiple_values=$_POST['send_multiple_values'];
            $send_rotate_values=$_POST['send_rotate_values'];
			$astuce_tag_active=$_POST['astuce_tag_active'];
			$astuce_tag_email_address=$_POST['astuce_tag_email_address'];
            /*******************************************************************************/
            /********************************* SPAN 2 DATA *********************************/
            $vmtas=$_POST['vmtas'];
            /*******************************************************************************/
            /********************************* SPAN 3 DATA *********************************/
            $sponsor=$_POST['sponsor'];
            $offer=$_POST['offer'];
            /*******************************************************************************/
            /********************************* SPAN 4 DATA *********************************/
            $data_list=$_POST['data_list'];
            /*******************************************************************************/
            /********************************* SPAN 5 DATA *********************************/
            $test_emails_to=$_POST['test_emails_to'];
            $message_id_email_to = $_POST['message_id_email_to'];
            $test_period=$_POST['test_period'];
            $xdelay=$_POST['xdelay'];
            $change_ip=$_POST['change_ip'];
            $data_from=$_POST['data_from'];
            $data_count=$_POST['data_count'];
            /*******************************************************************************/
            /***************************** EXTRACT TEST EMAILS *****************************/
            $test_emails_to_x=$test_emails_to;
            $test_emails_to= explode(';', $test_emails_to);
            /*******************************************************************************/
            /******************************** MESSAGE CONFIG *******************************/
            $message='';
            if($body_type==0){
                $message = $text_body;
            }elseif ($body_type==1) {
                $message = $html_body;
            }elseif($body_type==2){
                $message = ''; 
                $message.="--{text}".chr(10);                       
                $message.=$text_body.chr(10);                  
                $message.="--{html}".chr(10);               
                $message.=$html_body.chr(10);
            }
            $message_tmp = $message;
            $message = str_replace("[Domain]",$domain_body,$message);
            /*******************************************************************************/
            /******************************* EXTRACT ID VMTAS ******************************/
            $id_vmtas='';
            foreach ($vmtas as $row) {
                $cols=explode(';', $row);
                $id_vmta=$cols[0];
                $id_vmtas.=$id_vmta.';';
            }
            $id_vmtas=substr($id_vmtas,0,strlen($id_vmtas)-1);
            /*******************************************************************************/
            /****************************** CONNECT DATA BASE ******************************/
            show_status("<div>Connecting to Data Base...</div>",0);
            $api_key=RandomPrefix(50);
            $from_name_x=addslashes($from_name);
            $subject_x=addslashes($subject);
            $header_format_x=addslashes($header_format);
            $text_body_x=addslashes($text_body);
            $html_body_x=addslashes($html_body);
            $date_send=date('Y-m-d h:i:s');
            $res=bd::query("INSERT INTO campaign VALUES(NULL,'$id_server','$id_mailer','$api_key','$from_name_x','$subject_x','$from_email','$reply_email','$bounce_email','$return_path','$received','$xmailer','$header_nbr','$header_format_x','$server_body','$domain_body','$redirect_type','$open_tracker','$body_type','$text_body_x','$html_body_x','$id_vmtas','$sponsor','$offer','NULL','HOTMAIL','MESSAGE_ID','$test_emails_to_x','$test_period','$xdelay','$change_ip','$data_from','$data_count','0','Starting','$date_send')");
            $id_campaign = mysql_insert_id();
            if($res){
                show_status("<div class='text-success'>Connection has been established successfully.</div>",0);
            }else{
                show_status("<div class='text-error'>Connection to Data Base failed.</div>",0);
            }
        
            $jobid = $id_campaign;
         
            if($open_tracker=="1"){
                $message.="\n"."<img src='http://".$domain_body."/app/redirection/open.php?id_campaign=".$id_campaign."&id_list=[ListID]&id_user=[UserID]' width='0' height='0'/>";
            }

            $php_file_redirect="rdt.php";
            $redirect_landing_page=$php_file_redirect."?track=[LandingPage]&id_campaign=".$id_campaign."&id_list=[ListID]&id_user=[UserID]";
            $message = str_replace("[OfferPage]",$redirect_landing_page,$message);
            $redirect_unsubscribe=$php_file_redirect."?track=[Unsubscribe]&id_campaign=".$id_campaign."&id_list=[ListID]&id_user=[UserID]";
            $message = str_replace("[OfferUnsub]",$redirect_unsubscribe,$message);
            $redirect_unsubscribe_server=$php_file_redirect."?track=[UnsubServer]&id_campaign=".$id_campaign."&id_list=[ListID]&id_user=[UserID]";
            $message = str_replace("[ServerUnsub]",$redirect_unsubscribe_server,$message);
            /*******************************************************************************/
            /******************************* CREATE REDIRECT *******************************/
            show_status("<div>Creating Redirect...</div>",0);
            if(create_redirect($message,$id_campaign)){
                show_status("<div class='text-success'>Redirect has been created successfully.</div>",0);
            }else{
                show_status("<div class='text-error'>Creating redirect failed.</div>",0);
            }
            /*******************************************************************************/
            /******************************* SUPPRESSION FILE ******************************/
            show_status("<div>Suppression file...</div>",0);
            $hdl= file_get_contents("http://5.9.106.133/app/manager/offer/suppression/scripts.php?action=print_data&api_key=$api_key&id_campaign=$id_campaign&id_offer=$offer&id_isp=0&id_data_list=0&data_country=$data_list&data_from=$data_from&data_count=$data_count");
            $json = json_decode($hdl,true);
            $message = str_replace("[ListID]","HOTMAIL_".$data_list,$message);
            /****************************************************/
            if($additional_negative_active==1){
                $negative="";
                for($i=0;$i<$repeat_negative;$i++){
                    $negative.="\n".$additional_negative;
                }
                $negative='<style>'.$negative."\n".'</style>';
                $message=$message."\n".$negative;
            }
            /****************************************************/
            $cpt_email_send_rotate_values=0;
            $indice_send_rotate_values=0;
            if($send_multiple_type!=0){
                preg_replace( "/\r|\n/", "",$send_multiple_values);
                $send_multiple_values=explode("\n", $send_multiple_values);
                $value=$send_multiple_values[0];
                if($send_multiple_type==1){
                    $from_email=$value;
                    //show_status("<div>From Email: ".$from_email."</div>");
                }
                if($send_multiple_type==2){
                    $return_path=$value;
                    //show_status("<div>Return Path: ".$return_path."</div>");
                }
                if($send_multiple_type==3){
                    $message = str_replace("[Domain]",$value,$message_tmp);
                    //show_status("<div>Domain Creative: ".$value."</div>");
                }
				if($send_multiple_type==5){
                    $from_str=  explode('@', $from_email);
					$from_email=$from_str[0].'@'.$value;
                }
            }


			//$cpt_astuce_tag_email_address=0;
			$indice_astuce_tag_email_address=0;
			if($astuce_tag_active==1){
				preg_replace( "/\r|\n/", "",$astuce_tag_email_address);
				$astuce_tag_email_addresses=explode("\n", $astuce_tag_email_address);
			}

            $cpt=0;
            $stop=false;
            $cpt_email_test_period=0;
            $cpt_email_vmta=0;
            $indice_vmta=0;
            $row_vmta=$vmtas[$indice_vmta];
            $cols_vmta=explode(';', $row_vmta);
            $vmta=$cols_vmta[1];
            $ip=$cols_vmta[2];
            $domain=$cols_vmta[3]; 
			$main_ip=$cols[4];	
			

			$res = bd::query("UPDATE campaign set status='Sending' where id='$id_campaign'");

			$file_status=$_SERVER["DOCUMENT_ROOT"]."/app/mailer/hotmail/instance/campaign_status_".$id_campaign;
			$file_sent=$_SERVER["DOCUMENT_ROOT"]."/app/mailer/hotmail/instance/campaign_sent_".$id_campaign;

			$campaign_status_file = fopen($file_status, "w");
			$campaign_sent_file = fopen($file_sent, "w");

			if($campaign_status_file && $campaign_sent_file){
				fwrite($campaign_status_file, 'Sending');
				fwrite($campaign_sent_file, '0');
				fclose($campaign_status_file);
				$campaign_status_file = fopen($file_status, "r");
			}else{
				show_status("<div class='text-error'>Unable to Create Instance File!</div>",0);
				$check_ok=false;
			}

            show_status("<div>Sending...</div>",0);
            //$res = bd::query("UPDATE campaign set status='Sending' where id='$id_campaign'");
            //add_log("start sending the Campaign number <span class='badge'>".$id_campaign."</span> to ".$data_count." mailboxes");
            
            foreach ($json as $item) {
		
                if($item!=''){
                    /******************* SEND MULTIPLE *******************/
                    if($send_multiple_type!=0 && $send_rotate_values>0){
                        if($send_rotate_values==$cpt_email_send_rotate_values){
                            if($indice_send_rotate_values==sizeof($send_multiple_values)-1){
                                $indice_send_rotate_values=0;
                            }else{
                                $indice_send_rotate_values++;
                            }
                            $value=$send_multiple_values[$indice_send_rotate_values];
                            if($send_multiple_type==1){
                                $from_email=$value;
                                show_status("<div>From Email: ".$from_email."</div>");
                            }
                            if($send_multiple_type==2){
                                $return_path=$value;
                                show_status("<div>Return Path: ".$return_path."</div>");
                            }
                            if($send_multiple_type==3){
                                $message = str_replace("[Domain]",$value,$message_tmp);
                                show_status("<div>Domain Creative: ".$value."</div>");
                            }
							if($send_multiple_type==5){
                                $from_str=  explode('@', $from_email);
								$from_email=$from_str[0].'@'.$value;
								show_status("<div>From Email: ".$from_email."</div>");
                            }
                            $cpt_email_send_rotate_values=0;
                        }
                    }
                    /******************************************************/

                    if($cpt==0){
                        show_status("<div>Sending Test Period...</div>");
                        foreach ($test_emails_to as $to) {
                            /*************** REDIRECT REPLACE USER ***************/
                            $message_user = str_replace("[UserID]","0",$message);
                            /****************************************************/
							if($astuce_tag_active==1){
								$ato=$to;
								$to=trim($astuce_tag_email_addresses[$indice_astuce_tag_email_address]);
								for($i=0; $i < strlen($ato) ;$i++){
									if(RandomPrefixStr(1)==1){
										$ato=str_replace(substr($ato,$i,1),strtoupper(substr($ato,$i,1)),$ato);
									}
								}
								$xmailer=$ato;
								//echo '<br><br>'.$to.' - '.$ato.' - '.$subject.'<br><br>';
								if($indice_astuce_tag_email_address==count($astuce_tag_email_addresses)-1){
									$indice_astuce_tag_email_address=0;
								}else{
									$indice_astuce_tag_email_address++;
								}
							}
                            sendmail($main_ip,$vmta, $ip, $domain, $from_name, $subject, $from_email, $reply_email, $bounce_email, $return_path, $received, $xmailer, $to, $header_format, $message_user, '0', '0', '0',$message_id_email_to);
                            usleep($xdelay);
                            show_status("<div>Sent to: ".$to."</div>");
                        }
                    }
                    
                    $cols_item=explode(',', $item);
                    $to=$cols_item[1];
                    $id_to=$cols_item[0];

                    /******************* REPLACE USER *******************/
                    $message_user = str_replace("[UserID]",$id_to,$message);
                    /****************************************************/
                     /******************* REPLACE USER RETURNPATH *******************/
                    //$message_user = str_replace("[UserID]",$id_to,$message);
                    /****************************************************/

                    //show_status("<div>".$to."</div>",0);

					if($astuce_tag_active==1){
						$ato=$to;
						$to=trim($astuce_tag_email_addresses[$indice_astuce_tag_email_address]);
						for($i=0; $i < strlen($ato) ;$i++){
							if(RandomPrefixStr(1)==1){
								$ato=str_replace(substr($ato,$i,1),strtoupper(substr($ato,$i,1)),$ato);
							}
						}
						$xmailer=$ato;
						//echo '<br><br>'.$to.' - '.$ato.' - '.$subject.'<br><br>';
						if($indice_astuce_tag_email_address==count($astuce_tag_email_addresses)-1){
							$indice_astuce_tag_email_address=0;
						}else{
							$indice_astuce_tag_email_address++;
						}
					}

                    sendmail($main_ip,$vmta, $ip, $domain, $from_name, $subject, $from_email, $reply_email, $bounce_email, $return_path, $received, $xmailer, $to, $header_format, $message_user, $jobid, $data_list, $id_to, trim($cols_item[4]));
                    usleep($xdelay);

                    $cpt++;

                    
					//$res=bd::query("UPDATE campaign set data_sent='$cpt' where id='$id_campaign'");
                    
					ftruncate($campaign_sent_file,0);
					fseek($campaign_sent_file,0);
					fwrite($campaign_sent_file, $cpt);
					
					//$stop= verify_campaign_status($id_campaign);
                    
					$campaign_status=fgets($campaign_status_file);
					fseek($campaign_status_file,0);
					if($campaign_status=='Stopped') $stop=true;
					else $stop=false;
					
					
					
					$cpt_email_test_period++;
                    $cpt_email_vmta++;
                    $cpt_email_send_rotate_values++;

                    if($cpt_email_vmta==$change_ip){
                        if($indice_vmta==sizeof($vmtas)-1){
                            $indice_vmta=0;
                        }else{
                            $indice_vmta++;
                        }
                        $row_vmta=$vmtas[$indice_vmta];
                        $cols_vmta=explode(';', $row_vmta);
                        $vmta=$cols_vmta[1];
                        $ip=$cols_vmta[2];
						$domain=$cols_vmta[3];
                        $main_ip=$cols_vmta[4];
                        //show_status("<div class='text-warning'>Change VMTA To: ".$vmta."</div>");
                        $cpt_email_vmta=0;
                    }

                    if($cpt_email_test_period==$test_period){
                        show_status("<div class='text-warning'>".$cpt_email_test_period." Messages sent</div>",0);
                        show_status("<div>Sending Test Period...</div>");
                        foreach ($test_emails_to as $to) {
                            /*************** REDIRECT REPLACE USER ***************/
                            $message_user = str_replace("[UserID]","0",$message);
                            /****************************************************/
							if($astuce_tag_active==1){
								$ato=$to;
								$to=trim($astuce_tag_email_addresses[$indice_astuce_tag_email_address]);
								for($i=0; $i < strlen($ato) ;$i++){
									if(RandomPrefixStr(1)==1){
										$ato=str_replace(substr($ato,$i,1),strtoupper(substr($ato,$i,1)),$ato);
									}
								}
								$xmailer=$ato;
								//echo '<br><br>'.$to.' - '.$ato.' - '.$subject.'<br><br>';
								if($indice_astuce_tag_email_address==count($astuce_tag_email_addresses)-1){
									$indice_astuce_tag_email_address=0;
								}else{
									$indice_astuce_tag_email_address++;
								}
							}
                            sendmail($main_ip,$vmta, $ip, $domain, $from_name, $subject, $from_email, $reply_email, $bounce_email, $return_path, $received, $xmailer, $to, $header_format, $message_user, '0', '0', '0',$message_id_email_to);
                            usleep($xdelay);
                            show_status("<div>Sent to: ".$to."</div>");
                        }
                        $cpt_email_test_period=0;
                    }

                    if($stop)break;
                }
            }
            /*******************************************************************************/
            if($stop){
                $res = bd::query("UPDATE campaign set status='Stopped' where id='$id_campaign'");
                show_status("<div class='text-error'>Campaign has been Stopped.</div>",0);
            }else{
                $res = bd::query("UPDATE campaign set status='Finished' where id='$id_campaign'");
                show_status("<div class='text-success'>Campaign has been sent successfully.</div>",0);
            }


			$campaign_sent_file = fopen($file_sent, "r");
			$data_sent=trim(fgets($campaign_sent_file));
			$res=bd::query("UPDATE campaign set data_sent=$data_sent where id=$id_campaign");

			fclose($campaign_status_file);
			fclose($campaign_sent_file);
			if(file_exists($file_status) && file_exists($file_sent)){
				unlink($file_status);
				unlink($file_sent);
			}

            /********************************* CLEAN BOUNCE ********************************/
            clean_bounce_campaign($id_campaign);
            /*******************************************************************************/
            
        }else{
            show_status("<div class='text-error'>Send Campaign Failed.</div>",0);
        }
        show_status("<div class='text-info'>Send Campaign Finished.</div>",0);
        echo '</pre>';
    }
    
    function verify_campaign_status($id_campaign)
	{
        $res=bd::query("select status from campaign where id='$id_campaign'");
        $rowstatus= mysql_fetch_array($res);
        if($rowstatus['status']=='Stopped'){
            return true;
        }else{
            return false;
        }
    }
    
    function clean_bounce_campaign($id_campaign_x)
	{
        foreach (new DirectoryIterator('/var/log/pmta/') as $file) {
            if ($file->isFile()){
               if(preg_match('#acct-#i', $file)){
                    ini_set("memory_limit","10000M");
                    $table = explode("\n", file_get_contents($file->getFileInfo()));
                    foreach ($table as $row) {
                        $str=explode('"', $row);
                        $row=$str[0].$str[2];
                        $fields=explode(',', $row);
                        $email_address=$fields[5];
                        $bounce_error=$fields[9];
                        $id_campaign=$fields[20];
                        if($id_campaign==$id_campaign_x){
                            if($fields[0]=='b' && $fields[20]!='' && $fields[20]!='0'){
                                $query=bd::query("select campaign.id_isp,data_isp.hard_bounce_code,campaign.id_data_list,data_list.data_table from campaign,data_list,data_isp where campaign.id='$id_campaign' && campaign.id_data_list=data_list.id && campaign.id_isp=data_isp.id");
                                $row=mysql_fetch_array($query);
                                $id_data_list=$row['id_data_list'];
                                $data_table=$row['data_table'];
                                $hard_bounce_code=$row['hard_bounce_code'];
                                $date_bounce=date('Y-m-d h:i:s');
                                if(preg_match('#'.$hard_bounce_code.'#i', $bounce_error)){
                                    $bounce_error=addslashes($bounce_error);
                                    bd::query("INSERT INTO track_hard_bounce VALUES(NULL,'$id_campaign','$id_data_list','$email_address','$bounce_error','$date_bounce')");
                                    bd::query("DELETE FROM $data_table WHERE email_address='$email_address'");
                                }else{
                                    if($bounce_error==''){
                                        $bounce_error=addslashes($bounce_error);
                                        bd::query("INSERT INTO track_hard_bounce VALUES(NULL,'$id_campaign','$id_data_list','$email_address','$bounce_error','$date_bounce')");
                                    }/*else{
                                        $bounce_error=addslashes($bounce_error);
                                        bd::query("INSERT INTO track_soft_bounce VALUES(NULL,'$id_campaign','$id_data_list','$email_address','$bounce_error','$date_bounce')");
                                    }*/
                                    
                                }
                            }
                            /*if($fields[0]=='d' && $fields[20]!='' && $fields[20]!='0'){
                                $bounce_error=addslashes($bounce_error);
                                bd::query("INSERT INTO track_deliver VALUES(NULL,'$id_campaign','$id_data_list','$email_address','$bounce_error','$date_bounce')");
                            }*/
                            
                        }
                    }
                }
            }
        }
    }

	function create_redirect(&$message,$id_campaign)
	{
        $ok=true;
        
        $query      =   bd::query("SELECT platform FROM sponsor WHERE id='{$_POST["sponsor"]}'");
        $row        =   mysql_fetch_array($query);
        $platform   =   $row['platform'];
        
        $query      =   bd::query("SELECT page_link,unsub_link FROM offer WHERE id='{$_POST["offer"]}'");
        $row        =   mysql_fetch_array($query);
        
        if($row['page_link']!=null)
        {
            $link       =   $row['page_link'];
            $http_link  =   '';
            $track_link =   '';
            if($platform=='HitPath')
            {
                $str        =   explode('&c1=', $link);
                $http_link  =   $str[0];
                $track_link =   "&c1=".$_SESSION['id-mailer']."&c2=".$_SESSION["id-server"]."&c3=".$id_campaign;
            }
            if($platform=='Cake')
            {
                $str        =   explode('&s1=', $link);
                $http_link  =   $str[0];
                $track_link =   "&s1=&s2=".$_SESSION['id-mailer']."&s3=".$_SESSION["id-server"]."&s4=".$id_campaign;
            }
            $link_global=$http_link.$track_link;
            $track_id=RandomPrefix(25);
            $date_add=date('Y-m-d h:i:s');
            $res = bd::query("INSERT INTO redirect VALUES(NULL,'{$_SESSION["id-server"]}','{$_SESSION["id-mailer"]}','{$_POST["offer"]}','$id_campaign','$link_global','[LandingPage]','$track_id','$date_add')");
            if($res){
                $message = str_replace("[LandingPage]",$track_id,$message);
            }else{
                $ok=false;
                show_status("<div class='text-error'>Creating redirect of [LandingPage] failed.</div>",0);
            }
        }
        
        if($row['unsub_link']!=null){
            $link=$row['unsub_link'];
            $track_id=RandomPrefix(25);
            $res = bd::query("INSERT INTO redirect VALUES(NULL,'{$_SESSION["id-server"]}','{$_SESSION["id-mailer"]}','{$_POST["offer"]}','$id_campaign','$link','[Unsubscribe]','$track_id','$date_add')");
            if($res){
                $message = str_replace("[Unsubscribe]",$track_id,$message);
            }else{
                $ok=false;
                show_status("<div class='text-error'>Creating redirect of [Unsubscribe] failed.</div>",0);
            }
        }
        
        if($ok){
            $link="http://".$_POST['domain_body']."/app/unsubscribe/index.php?id_server=".$_SESSION["id-server"];
            $track_id=RandomPrefix(25);
            $res = bd::query("INSERT INTO redirect VALUES(NULL,'{$_SESSION["id-server"]}','{$_SESSION["id-mailer"]}','{$_POST["offer"]}','$id_campaign','$link','[UnsubServer]','$track_id','$date_add')");
            if($res){
                $message = str_replace("[UnsubServer]",$track_id,$message);
            }else{
                $ok=false;
                show_status("<div class='text-error'>Creating redirect of [UnsubServer] failed.</div>",0);
            }
        }
        return $ok;
    }
   
	function show_status($update,$delay)
	{
        echo $update;
        ob_flush();
        flush();
        sleep($delay);
    }
    
    function check_data_test_auto()
	{
        show_status("<div>Checking data fields...</div>",0);
        $ok=true;
        if(empty($_POST['vmtas'])){
            show_status("<div class='text-warning'>VMTA is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['test_emails_to']==null)){
            show_status("<div class='text-warning'>Test Emails To is required.</div>",0);
            $ok=false;
        }
        if($ok){
            show_status("<div class='text-success'>Data has been checked successfully.</div>",0);
        }else{
            show_status("<div class='text-error'>checking data failed.</div>",0);  
        }
        return $ok;
    }
    
    function check_data_test()
	{
        show_status("<div>Checking data fields...</div>",0);
        $ok=true;
        if((trim($_POST['from_name'])==null)){
            show_status("<div class='text-warning'>From Name is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['subject']==null)){
            show_status("<div class='text-warning'>Subject is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['header_format'])==null){
            show_status("<div class='text-warning'>Header is required.</div>",0);
            $ok=false;
        }
        if($_POST['domain_body']=="0"){
            show_status("<div class='text-warning'>Domain Creative is required.</div>",0);
            $ok=false;
        }
        if($_POST['body_type']==0){
            if(trim($_POST['text_body'])==null){
                show_status("<div class='text-warning'>Text Creative is required.</div>",0);
                $ok=false;
            }
        }
        if($_POST['body_type']==1){
            if(trim($_POST['html_body'])==null){
                show_status("<div class='text-warning'>HTML Creative is required.</div>",0);
                $ok=false;
            }
        }
        if($_POST['body_type']==2){
            if(trim($_POST['text_body'])==null){
                show_status("<div class='text-warning'>Text Creative is required.</div>",0);
                $ok=false;
            }
            if(trim($_POST['html_body'])==null){
                show_status("<div class='text-warning'>HTML Creative is required.</div>",0);
                $ok=false;
            }
        }
        if(empty($_POST['vmtas'])){
            show_status("<div class='text-warning'>VMTA is required.</div>",0);
            $ok=false;
        }
        if($_POST["sponsor"]==0){
            show_status("<div class='text-warning'>Sponsor is required.</div>",0);
            $ok=false;
        }
        if($_POST["offer"]==0){
            show_status("<div class='text-warning'>Offer is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['test_emails_to']==null)){
            show_status("<div class='text-warning'>Test Emails To is required.</div>",0);
            $ok=false;
        }
        if($ok){
            show_status("<div class='text-success'>Data has been checked successfully.</div>",0);
        }else{
            show_status("<div class='text-error'>checking data failed.</div>",0);  
        }
        return $ok;
    }

	function check_data()
	{
        show_status("<div>Checking data fields...</div>",0);
        $ok=true;
        if((trim($_POST['from_name'])==null)){
            show_status("<div class='text-warning'>From Name is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['subject']==null)){
            show_status("<div class='text-warning'>Subject is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['header_format'])==null){
            show_status("<div class='text-warning'>Header is required.</div>",0);
            $ok=false;
        }
        if($_POST['domain_body']=="0"){
            show_status("<div class='text-warning'>Domain Creative is required.</div>",0);
            $ok=false;
        }
        if($_POST['body_type']==0){
            if(trim($_POST['text_body'])==null){
                show_status("<div class='text-warning'>Text Creative is required.</div>",0);
                $ok=false;
            }
        }
        if($_POST['body_type']==1){
            if(trim($_POST['html_body'])==null){
                show_status("<div class='text-warning'>HTML Creative is required.</div>",0);
                $ok=false;
            }
        }
        if($_POST['body_type']==2){
            if(trim($_POST['text_body'])==null){
                show_status("<div class='text-warning'>Text Creative is required.</div>",0);
                $ok=false;
            }
            if(trim($_POST['html_body'])==null){
                show_status("<div class='text-warning'>HTML Creative is required.</div>",0);
                $ok=false;
            }
        }
        if(trim($_POST['additional_negative'])!=null){
            if($_POST['additional_negative_active']==0){
                show_status("<div class='text-warning'>it looks that you forgot activate additional negative.</div>",0);
                $ok=false;
            }
        }
        if($_POST['additional_negative_active']==1){
            if(trim($_POST['repeat_negative']==null)){
                show_status("<div class='text-warning'>Repeat Negative is required.</div>",0);
                $ok=false;
            }else{
                if(!is_numeric(trim($_POST['repeat_negative']))){
                    show_status("<div class='text-warning'>Repeat Negative is not an integer number.</div>");
                    $ok=false;
                }
                if(trim($_POST['repeat_negative'])<=0){
                    show_status("<div class='text-warning'>Repeat Negative must contain value>0.</div>");
                    $ok=false;
                }
            }
            if(trim($_POST['additional_negative'])==null){
                show_status("<div class='text-warning'>Additional Negative is required.</div>",0);
                $ok=false;
            }
        }
        if(empty($_POST['vmtas'])){
            show_status("<div class='text-warning'>VMTA is required.</div>",0);
            $ok=false;
        }
        if($_POST["sponsor"]==0){
            show_status("<div class='text-warning'>Sponsor is required.</div>",0);
            $ok=false;
        }
        if($_POST["offer"]==0){
            show_status("<div class='text-warning'>Offer is required.</div>",0);
            $ok=false;
        }

        if(empty($_POST["data_list"])){
            show_status("<div class='text-warning'>Country List is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['test_emails_to']==null)){
            show_status("<div class='text-warning'>Test Emails To is required.</div>",0);
            $ok=false;
        }
        if(trim($_POST['test_period']==null)){
            show_status("<div class='text-warning'>Test Period To is required.</div>",0);
            $ok=false;
        }else{
            if(!is_numeric(trim($_POST['test_period']))){
                show_status("<div class='text-warning'>Test Period is not an integer number.</div>");
                $ok=false;
            }
            if(trim($_POST['test_period'])==0){
                show_status("<div class='text-warning'>Cannot type 0 in Test Period.</div>");
                $ok=false;
            }
            if(trim($_POST['test_period'])<0){
                show_status("<div class='text-warning'>Cannot type a negative number in Test Period</div>");
                $ok=false;
            }
        }
        if(trim($_POST['change_ip']==null)){
            show_status("<div class='text-warning'>Change IP is required.</div>",0);
            $ok=false;
        }else{
            if(!is_numeric(trim($_POST['change_ip']))){
                show_status("<div class='text-warning'>Change IP is not an integer number.</div>");
                $ok=false;
            }
            if(trim($_POST['change_ip'])==0){
                show_status("<div class='text-warning'>Cannot type 0 in Change IP.</div>");
                $ok=false;
            }
            if(trim($_POST['change_ip'])<0){
                show_status("<div class='text-warning'>Cannot type a negative number in Change IP.</div>");
                $ok=false;
            }
        }
        if(trim($_POST['data_from']==null)){
            show_status("<div class='text-warning'>Data From is required.</div>",0);
            $ok=false;
        }else{
            if(!is_numeric(trim($_POST['data_from']))){
                show_status("<div class='text-warning'>Data From is not an integer number.</div>");
                $ok=false;
            }
            /*if(trim($_POST['data_from'])==0){
                show_status("<div class='text-warning'>Cannot type 0 in Data From.</div>");
                $ok=false;
            }*/
            if(trim($_POST['data_from'])<0){
                show_status("<div class='text-warning'>Cannot type a negative number in Data From.</div>");
                $ok=false;
            }
        }
        if(trim($_POST['data_count']==null)){
            show_status("<div class='text-warning'>Data Count is required.</div>",0);
            $ok=false;
        }else{
            if(!is_numeric(trim($_POST['data_count']))){
                show_status("<div class='text-warning'>Data Count is not an integer number.</div>");
                $ok=false;
            }
            if(trim($_POST['data_count'])==0){
                show_status("<div class='text-warning'>Cannot type 0 in Data Count.</div>");
                $ok=false;
            }
            if(trim($_POST['data_count'])<0){
                show_status("<div class='text-warning'>Cannot type a negative number in Data Count.</div>");
                $ok=false;
            }
        }
        if($ok){
            show_status("<div class='text-success'>Data has been checked successfully.</div>",0);
        }else{
            show_status("<div class='text-error'>checking data failed.</div>",0);  
        }
        return $ok;
    }
    
    function RandomPrefix($length)
	{
        $random= "";
        srand((double)microtime()*1000000);
        //$data = "bc";
        $data = "0123456789abcdefghijklmnopqrstuvwxyz";
        //$data .= "fgh";
        for($i = 0; $i < $length; $i++){
            $random .= substr($data, (rand()%(strlen($data))), 1);
        }
        return $random;
    }
    
    function RandomPrefix2($type,$length)
	{
        $random= '';
        srand((double)microtime()*1000000);
        $data='';
        $data1='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $data2='abcdefghijklmnopqrstuvwxyz';
        $data3='0123456789';
        if(strlen($type)==1){
            switch ($type) {
                case 'A': $data=$data1;
                    break;
                case 'a': $data=$data2;
                    break;
                case 'N': $data=$data3;
                    break;
                case 'n': $data=$data3;
                    break;
                default: $data=0;
                    break;
            }
        }else{
            if(strlen($type)==2){
                switch ($type) {
                    case 'AN': 
                    case 'NA': 
                    case 'An': 
                    case 'nA': $data=$data1.$data3;
                        break;
                    case 'aN': 
                    case 'Na': 
                    case 'an': 
                    case 'na': $data=$data2.$data3;
                        break;
                    default: $data=0;
                        break;
                }
            }else{
                $data=0;
            }
        }
        
        for($i = 0; $i < $length; $i++){
            $random .= substr($data, (rand()%(strlen($data))), 1);
        }
        return $random;
    }

	function RandomPrefixStr($length){
        $random= "";
        srand((double)microtime()*1000000);
        $data = "01";
        for($i = 0; $i < $length; $i++){
            $random .= substr($data, (rand()%(strlen($data))), 1);
        }
        return $random;
    }
    
    function sendmail($main_ip,$vmta,$ip,$domain,$from_name,$subject,$from_email,$reply_email,$bounce_email,$return_path,$received,$xmailer,$to,$header_format,$message,$jobid,$listID,$userid,$message_id_email_to = null)
	{
        $textMSG='';
        $htmlMSG='';
        $pmta_instance=$main_ip; 
		//$pmta_instance='127.0.0.1';
        $port=2500;
        /*
		switch ($_SESSION["id-server"]) 
		{
            case 7: $pmta_instance='5.135.249.47';
                break;
            case 8: $pmta_instance='104.223.15.157';
                break;
            case 9: $pmta_instance='23.254.204.55';
                break;
            case 10: $pmta_instance='64.140.157.199';
                break;
            default: $pmta_instance='127.0.0.1';
                break;
        }
		*/
        //$from_email=$from_name.' <'.$from_email.'@'.$domain.'>';
        //$from_email='<'.$from_email.'>';
        //$reply_email = "$reply_email@$domain";
        //$from_email = $from_name.' <'.str_replace("[Domain]",$domain,$from_email).'>';
        
        $from_email=trim($from_email);
        $reply_email = trim($reply_email);
        $bounce_email=trim($bounce_email);
        $return_path = trim($return_path);
        $received = trim($received);
        
        $from_email = str_replace("[Domain]",$domain,$from_email);
        $from = $from_name.' <'.$from_email.'>';
        $reply_email = str_replace("[Domain]",$domain,$reply_email);
        
        $subject = str_replace('[FromEmail]',$from_email,$subject);
        $subject = str_replace('[Domain]',$domain,$subject);
        $subject = str_replace('[Ip]',$ip,$subject);
        $subject = str_replace('[Vmta]',$vmta,$subject);
        $subject = str_replace('[To]',$to,$subject);
        $subject = str_replace("[ReturnPath]",$return_path,$subject);
        $fname = explode('@',$to);
        $fname = $fname[0];
        $subject = str_replace("[Fname]",$fname,$subject);
        
        $received = str_replace('[Ip]',$ip,$received);
        $received = str_replace('[Domain]',$domain,$received);
        $return_path = str_replace('[Domain]',$domain,$return_path);
        $bounce_email = str_replace('[CampaignID]',$jobid,$bounce_email);
        
        if(stristr($bounce_email,'[Dynamique]')) {
            $dyn_var = '';
            for($ih=0;$ih<14;$ih++) {
                    $dyn_var.=rand(0,9);
            }
            $tab = explode('@',$to);
            $user = $tab[0];
            $user_dom = $tab[1];
            $dynExp = $user_dom.'.'.$dyn_var.'.'.$user;
            $bounce_email = str_replace('[Dynamique]', $dynExp, $bounce_email);
        }
        
        if($bounce_email==''){
            $bounce_email='null';
        }

        if(empty($return_path)){
            $return_path=$bounce_email."@".$domain;
        }else{
            if($return_path=='[Empty]'){
               $return_path='';
			  }elseif($return_path=='[ATo]'){
             $return_path=$xmailer;
			 
            }else{
                $return_path=$bounce_email.'@'.$return_path;
            }
        }
        
        if(preg_match('#\[Random\([AaNn]{1,2}+,[0-9]+\)\]#', $return_path)){
            $regex=explode('[Random(',$return_path);
            $regex=explode(')]', $regex[1]);
            $regex=explode(',',$regex[0]);
            $value=RandomPrefix2($regex[0], $regex[1]);
            $return_path=preg_replace('#\[Random\([AaNn]{1,2}+,[0-9]+\)\]#',$value, $return_path);
        }

        #{mta socket} 

        $smtp = fsockopen($pmta_instance,$port);
        if ($smtp < 0){
                Show_Status("Can't connect to PMTA!!");
                //continue;
        }

        $DateF=date("Y.m.d-H.i.s");
        $smtpDate=date("r");
        $uniqID=md5(uniqid(null));
        $uzr=explode('@',$to);
        $fname_domain=$uzr[0].'@'.$domain;
        //$firstSTR = $uzr[0];
        
        $fqn = explode( '.', $domain );
        if ( count($fqn) == 3 ){
            $domain_abstract = $fqn[1].'.'.$fqn[2];
        }
        
        $return_path = str_replace('[DomainAbstract]',$domain_abstract,$return_path);
        $return_path = str_replace('[ListID]',$listID,$return_path);
        $return_path = str_replace('[UserID]',$userid,$return_path);

        #.....Replcae defined varaibles
        $header = str_replace('[Subject]',$subject,$header_format);
        $header = str_replace('[FromName]',$from_name,$header);
        $header = str_replace('[FromEmail]',$from_email,$header);
        $header = str_replace('[From]',$from,$header);
        $header = str_replace('[To]',$to,$header);
        $header = str_replace('[ReplyEmail]',$reply_email,$header);
        $header = str_replace('[ReturnPath]',$return_path,$header);
        $header = str_replace('[SMTPDate]',$smtpDate,$header);
        $header = str_replace('[Date]',$DateF,$header);
        $header = str_replace('[UniqueID]',$uniqID,$header);
        $header = str_replace('[BounceEmail]',$bounce_email,$header);
        $header = str_replace('[Ip]',$ip,$header);
        $header = str_replace('[Domain]',$domain,$header);
        $header = str_replace('[DomainAbstract]',$domain_abstract,$header);
        $header = str_replace('[XSmfbl]',base64_encode($to),$header);
        $header = str_replace('[Fname]',$fname,$header);
        $header = str_replace('[FnameDomain]',$fname_domain,$header);
        $header = str_replace('[XMailer]',trim($xmailer),$header);
        $header = str_replace('[CampaignID]',$jobid,$header);
        $header = str_replace('[ListID]',$listID,$header);
        $header = str_replace('[UserID]',$userid,$header);
		$header = str_replace('[ATo]',$xmailer,$header);
        
        $message=str_replace('[Fname]',$fname,$message);

        
        if( $body_type == 2 ){
            $textMSG="";
            $htmlMSG="";
            $multipartMSG=explode(chr(10),$message);
            foreach ($multipartMSG as $ln){
                if(preg_match("/^--{text}/",$ln)){ $type="text";continue;}
                if(preg_match("/^--{html}/",$ln)){ $type="html";continue;}
                if($type=='text') $textMSG.=$ln.chr(10);
                if($type=='html') $htmlMSG.=$ln.chr(10);
                echo $ln.'tttt';
            }

        }		
        $header = str_replace("[TextMessage]",$textMSG,$header);
        $header = str_replace("[HtmlMessage]",$htmlMSG,$header);
        $header .="\r\nMessage-ID: <".$message_id_email_to.">";
        $header_form=explode(chr(10),$header);

        #fputs($smtp,"ehlo $domain\r\n");

        fputs($smtp,"ehlo $received\r\n");
        fputs($smtp,"mail from: $return_path\r\n");
        fputs($smtp,"rcpt to: $to\r\n");
        fputs($smtp,"data\r\n");
        fputs($smtp,"X-virtual-MTA: ".$vmta."\r\n");
        fputs($smtp,"x-job: ".$jobid."\r\n");
        fputs($smtp,"x-envid: ".$uniqID."\r\n"); 
        
        foreach ($header_form as $ln){
            
            if(preg_match('#\[Random\([AaNn]{1,2}+,[0-9]+\)\]#', $ln)){
                $regex=explode('[Random(',$ln);
                $regex=explode(')]', $regex[1]);
                $regex=explode(',',$regex[0]);
                $value=RandomPrefix2($regex[0], $regex[1]);
                $ln=preg_replace('#\[Random\([AaNn]{1,2}+,[0-9]+\)\]#',$value, $ln);
            }

            fputs($smtp, $ln);
        }

        fputs($smtp,"\r\n");

        if($body_type!=2){
                $Nbody=stripslashes($message);
                fputs($smtp,"$Nbody\r\n");
        }
        fputs($smtp,".\r\n");

        while($line = fgets($smtp,1024)){
                if(preg_match("/250 .*message received/",$line)){
                        fputs($smtp, "QUIT\r\n");  
                        fclose($smtp);
                        break;
                }
        }							

        #END;

    }

    
	function verify_links($message_to_check,$id_campaign,$id_sponsor,$id_offer)
	{
		$res=bd::query("select affiliate_id from sponsor where id='$id_sponsor'");
		$row= mysql_fetch_array($res);
		$sponsor_affiliate_id=$row['affiliate_id'];
		$res=bd::query("select sid from offer where id='$id_offer'");
		$row= mysql_fetch_array($res);
		$offer_sid=$row['sid'];
		//echo $sponsor_affiliate_id.'<br>';
		//echo $offer_sid.'<br>';
		
		$cpt_links=0;
		$cpt_offer_page=0;
		$cpt_offer_unsubscribe=0;
		$cpt_server_unsubscribe=0;

		$regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i';
		preg_match_all($regex, $message_to_check, $matches);
		$urls = $matches[0];
		foreach($urls as $url) {
			$url=trim($url);
			if(!isImage($url)){
				$cpt_links++;
				//echo '<br>***********START LINK***********<br>';
				$ok=true;
				$cpt=0;
				
				do{
					$cpt++;
					//echo "<br>Original URL (".$cpt."): ".$url."<br/>";
					if(stristr($url,'app/redirection/rdt.php?track=')){
						//echo 'OKIZZ';
						$str = explode('track=',$url);
						$str = $str[1];
						$str = explode('&id_campaign',$str);
						$redirect_track = $str[0];
						$res=bd::query("select tag from redirect where track='$redirect_track'");
						$row= mysql_fetch_array($res);
						$offer_tag=$row['tag'];
						if($offer_tag=='[LandingPage]'){
							//echo 'this link for Landing Page'.'<br>';
							$cpt_offer_page++;
							$ok=false;
						}

						if($offer_tag=='[Unsubscribe]'){
							//echo 'this link for Unsubscribe offer Page'.'<br>';
							$cpt_offer_unsubscribe++;
							$ok=false;
						}

						if($offer_tag=='[UnsubServer]'){
							//echo 'this link for Unsubscribe server Page'.'<br>';
							$cpt_server_unsubscribe++;
							$ok=false;
						}
					}/*else{
						echo 'NOOOO';
					}*/
					ob_flush();
					flush();
					
					$newurl = get_next_url($url);
					if($newurl==$url)$ok=false;
					else $url=$newurl;
				
				}while($ok);
				//echo '<br>************END LINK************<br>';
			}
		}

		if($cpt_offer_page==0 || $cpt_offer_unsubscribe==0 || $cpt_server_unsubscribe==0){
			$alert="alert";
			$date_alert=date('Y-m-d h:i:s');
			$res = bd::query("INSERT INTO campaign_alert VALUES(NULL,'$id_campaign','{$_SESSION["id-mailer"]}','$alert','$cpt_links','$cpt_offer_page','$cpt_offer_unsubscribe','$cpt_server_unsubscribe','$date_alert')");
			//////////////////////////
		}
	}

	function isImage($url)
	{
		$pos = strrpos( $url, ".");
		if ($pos === false)
		  return false;
		$ext = strtolower(trim(substr( $url, $pos)));
		$imgExts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif");
		if ( in_array($ext, $imgExts) )return true;
		return false;
	}

	function get_next_url($url)
	{
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_HEADER,true);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false);
        $header = curl_exec($ch);

        $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));

        for($i=0;$i<count($fields);$i++){
            if(strpos($fields[$i],'Location') !== false)
            {
                $url = str_replace("Location: ","",$fields[$i]);
            }
        }
        return $url;
    }



?>


    </body>
</html>
