<?php
   include_once '../account/session.php';
   include_once '../../scripts/bd.php';
   session_start();
   $id_server=$_SESSION['id-server'];
   $id_mailer=$_SESSION['id-mailer'];
   $username_mailer=$_SESSION['username-mailer'];
   

   if($_SESSION["type"] == 'it') {
      die("404 not found: <a href='/app/manager/offer/show.php'>Go back</a>");
    }
    
   if(isset($_GET['action'])){
    $action=$_GET['action'];
    if($action=='get_servers')get_servers();
    if($action=='get_domains')get_domains();
    if($action=='get_vmtas')get_vmtas();
    if($action=='get_sponsors')get_sponsors();
    if($action=='get_offers')get_offers();
    if($action=='get_news')get_news();
    if($action=='get_isps')get_isps();
    if($action=='get_data_lists')get_data_lists();
	if($action=='get_ips')get_ips();
	if($action=='add_vmta')add_vmta();
	if($action=='reset_vmtas')reset_vmtas();
    if($action=='show')show();
    if($action=='edit')edit();
    if($action=='stop_campaign')stop_campaign();
    if($action=='get_real_sent')get_real_sent();
    if($action=='get_real_status')get_real_status();
    if($action=='count_send')count_send();
   }
   
   function get_servers(){
      $data=array();
      $query = bd::query("SELECT id,name FROM server WHERE active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }

    function count_send(){
      $sql = bd::query("SELECT count(*) as count FROM campaign WHERE status = 'Sending'");
      $data = mysql_fetch_array($sql);
      echo $data['count'];
   }
   
   function get_domains(){
      $data=array();
      $query = bd::query("SELECT host_name FROM server_vmta WHERE id_server='{$_GET["server"]}' && active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_vmtas()
   {
      $data=array();
      $query = bd::query("SELECT V.id,V.name,V.address_ip,V.host_name,S.main_ip FROM server_vmta V,server S WHERE V.id_server='{$_SESSION['id-server']}' && V.active='1' and S.id = V.id_server");
      while ($row = mysql_fetch_object($query)) 
	  {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_sponsors(){
      $data=array();
      $query = bd::query("SELECT id,name FROM sponsor WHERE active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_offers(){
      $data=array();
      $query = bd::query("SELECT id,name FROM offer WHERE id_sponsor='{$_GET["sponsor"]}' &&  active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_news(){
      $data=array();
      $query = bd::query("SELECT id,name FROM data_news WHERE active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_isps(){
      $data=array();
      $query = bd::query("SELECT id,name FROM data_isp WHERE active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_data_lists(){
      $data=array();
      if(!empty($_GET["news"]) && !empty($_GET["isp"])  ){
        calculate_data_isp();
        $query = bd::query("SELECT id,name,count_isp FROM data_list WHERE id_news='{$_GET["news"]}' && data_table!='' && active='1'");
        while ($row = mysql_fetch_object($query)) {
            $data[]=$row;
        } 
      }
      echo json_encode($data);
   }

   function get_ips(){
      $data=array();
      $query = bd::query("SELECT address_ip FROM server_vmta WHERE id_server='{$_SESSION['id-server']}' && host_type='0' && active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }

   function verify_name_vmta($id,$name,$id_server){
       $query = bd::query("SELECT * FROM server_vmta where name like '$name' && id_server='{$_SESSION['id-server']}' && id!='$id'");
       if(mysql_num_rows($query)>0){
           return true;
       }
       return false;
   }

   function add_vmta(){
        $name=trim($_POST["name"]);
        $address_ips=$_POST["address_ips"];
        $host_name=$_POST["host_name"];
        $active=1;
        $date_add=date('Y-m-d h:i:s');
        $date_set=date('Y-m-d h:i:s');
        
        $ok='0';
		$name_inital=$name;
		$address_ips=explode(';', $address_ips);
		foreach($address_ips as $address_ip){
			$cpt=1;	
			while(verify_name_vmta('0',$name,$id_server)){
				$cpt++;
				$name=$name_inital.$cpt;
			}

			$vmta_config_file = fopen($_SERVER["DOCUMENT_ROOT"]."/app/mailer/server/vmta/config.d/vmtas1.txt", "a+");
			if($vmta_config_file){
				$vMtaString =   "<virtual-mta $name>\r\n";
				$vMtaString.=   "\tsmtp-source-ip $address_ip\r\n";
				$vMtaString.=   "\thost-name $host_name\r\n"; 
				$vMtaString.=   "</virtual-mta>\r\n\n";
				$rep=bd::query("INSERT INTO server_vmta VALUES (NULL, '{$_SESSION['id-server']}', '$name', '$address_ip', '$address_ip', '$host_name', '1', '$active', '$date_add', '$date_set');");
				if($rep){
					fwrite($vmta_config_file, $vMtaString);
				}else{
					$ok='Error data base';
				}
			}else{
			   $ok="Unable to open VMTA config file !";
			}
		}

		if($ok=='0'){
			exec("sudo /etc/init.d/pmta reload",$output,$report);
			if($report!='0'){
				$ok="Cannot reload PowerMTA !";
			}
		}
        echo $ok;
   }

   function reset_vmtas(){
		$ok='0';
		$vmta_config_file = fopen($_SERVER["DOCUMENT_ROOT"]."/app/mailer/server/vmta/config.d/vmtas1.txt", "a+");
		if($vmta_config_file){
			$rep=bd::query("DELETE FROM server_vmta where id_server={$_SESSION['id-server']} && host_type='1'");
			if($rep){
				ftruncate($vmta_config_file, 0);
				exec("sudo /etc/init.d/pmta reload",$output,$report);
			}else{
				$ok='Error data base';
			}
		}else{
		   $ok="Unable to open VMTA config file !";
		}
		echo $ok;
   }
   
   function calculate_data_isp(){
      $query = bd::query("SELECT regex FROM data_isp WHERE id={$_GET["isp"]}");
      $row=  mysql_fetch_array($query);
      $regexisp=$row['regex'];
      $query = bd::query("SELECT id,data_table FROM data_list WHERE id_news='{$_GET["news"]}' && data_table!='' && active='1' ");
      while($row=mysql_fetch_row($query)){
          bd::query("UPDATE data_list set count_isp=(select count(*) from $row[1] where email_address REGEXP '$regexisp') where id='$row[0]' ");
      } 
   }
    
   function show(){
      $data=array();
      $query = bd::query("SELECT campaign.id, campaign.id_mailer, campaign.id_server, campaign.date_send, campaign.id_offer, campaign.id_news, campaign.id_isp, campaign.id_data_list, campaign.data_from, campaign.data_count, campaign.data_sent, campaign.status, offer.name as offer_name, data_news.name as news_name, data_isp.name as isp_name, data_list.name as list_name, account_mailer.username as username, server.name as name_server FROM campaign, offer, data_news, data_isp, data_list, account_mailer, server WHERE campaign.id_offer=offer.id && campaign.id_news=data_news.id && campaign.id_isp=data_isp.id && campaign.id_data_list=data_list.id && account_mailer.id=campaign.id_mailer && server.id=campaign.id_server ORDER BY campaign.date_send DESC LIMIT 0,100");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function edit(){
      $data=array();
      $query = bd::query("SELECT * FROM campaign WHERE id='{$_GET["id_campaign"]}' && id_mailer='{$_SESSION['id-mailer']}'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function stop_campaign(){
	  $id_campaign=$_GET["id_campaign"];
	  $campaign_status_file = fopen($_SERVER["DOCUMENT_ROOT"]."/app/mailer/campaign/instance/campaign_status_".$id_campaign, "w");
	  ftruncate($campaign_status_file,0);
	  fseek($campaign_status_file,0);
	  fwrite($campaign_status_file, 'Stopped');
	  fclose($campaign_status_file);
     /* $res=bd::query("select status from campaign where id='{$_GET["id_campaign"]}'");
        $rowstatus= mysql_fetch_array($res);
        if($rowstatus['status']=='Sending'){
            $res = bd::query("UPDATE campaign set status='Stopped' where id='{$_GET["id_campaign"]}'");
            if($res){
                echo "Campaign {$_GET["id_campaign"]} Stopped";
            }else{
                echo "There was an error Stopping your Campaign";
            }
        }else{
            echo "You cannot stop this Campaign! Try again";
        }*/
      
   }
   
   function get_real_sent(){
       /*$res=bd::query("select data_sent from campaign where id='{$_GET["id_campaign"]}'");
       $rowsent= mysql_fetch_array($res);
       echo $rowsent['data_sent'];*/

	   $res=bd::query("select status,data_sent from campaign where id='{$_GET["id_campaign"]}'");
	   $rowsent= mysql_fetch_array($res);
	   if($rowsent['status']=='Sending'){
		   $campaign_sent_file = fopen($_SERVER["DOCUMENT_ROOT"]."/app/mailer/campaign/instance/campaign_sent_".$_GET["id_campaign"], "r");
		   echo trim(fgets($campaign_sent_file));
		   fclose($campaign_sent_file);
	   }else{
		   echo $rowsent['data_sent'];
	   }
   }
   
   function get_real_status(){
       $res=bd::query("select status from campaign where id='{$_GET["id_campaign"]}'");
       $rowstatus= mysql_fetch_array($res);
       echo $rowstatus['status'];
   }

   function RandomPrefix($length){
        $random= "";
        srand((double)microtime()*1000000);
        $data = "bc";
        $data .= "adeijklmnopqrstuvwxyz";
        $data .= "fgh";
        for($i = 0; $i < $length; $i++){
            $random .= substr($data, (rand()%(strlen($data))), 1);
        }
        return $random;
    }