<?php
    include_once '../account/session.php';
    include_once '../../scripts/bd.php';

    if(isset($_GET['action'])){
        $action=$_GET['action'];
        if($action=='fetch_data')fetch_data();
        if($action=='lookup')lookup();
        if($action=='get_isps')get_isps();
        
        if(   ($action=='get_ips') && isset($_GET['id_server'])  && is_numeric($_GET['id_server']) && ($_GET['id_server'] > 0) )
            get_ips($_GET['id_server']);
        
        
        if
        (   
            ($action=='create_fake_vmta') && 
            isset($_GET['id_server'])     && is_numeric($_GET['id_server']) && ($_GET['id_server'] > 0) && 
            isset($_GET['id_ip'])         && is_numeric($_GET['id_ip'])     && ($_GET['id_ip'] > 0)     && 
            isset($_GET['fake_domain'])   && !empty($_GET['fake_domain']) 
        )
        create_fake_vmta($_GET['id_server'],$_GET['id_ip'],$_GET['fake_domain']);
        
        
        
    }

    function fetch_data(){
        $id_isp=$_POST["isp"];
        $email_address=$_POST["email_address"];
        $password=$_POST["password"];
        $folder=$_POST["folder"];
        $data_retrieved=$_POST["data_retrieved"];
        
        $query=bd::query("SELECT imap_host FROM data_isp WHERE id='$id_isp'");
        $row=mysql_fetch_array($query);
        $imap_host=$row['imap_host'];
        
        echo '<textarea class="span12" rows="25" id="" name="">';
        /*echo $id_isp.'<br>';
        echo $imap_host.'<br>';
        echo $email_address.'<br>';
        echo $password.'<br>';
        echo $folder.'<br><br><br>';*/
        
        $socket = imap_open($imap_host.$folder,$email_address,$password) or die('Cannot connect to MAILBOX: ' . imap_last_error());
        $emails = imap_search($socket,'ALL');
        
        if($emails) {
                $output = '';
                rsort($emails);
               
                foreach($emails as $email_number) {
                        $overview = imap_fetch_overview($socket,$email_number,0);
                        //echo imap_fetchbody($socket,$email_number,1);
                        //echo $message."\n";
                        //$output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
                         //$output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
                        //$output.= '<span class="from">'.$overview[0]->from.'</span>';
                        //$output.= '<span class="date">on '.$overview[0]->date.'</span>';
                        //$output.= '</div>';
                        //$output.= '<div class="body">'.$message.'</div>';
                        
                        if($data_retrieved=='from'){
                            echo $overview[0]->from."\n";
                        }
                        if($data_retrieved=='subject'){
                            echo $overview[0]->subject."\n";
                        }
                        if($data_retrieved=='body'){
                            $message= imap_fetchbody($socket,$email_number,1);
                            $message = preg_replace('/\s+/', ' ', trim($message));
                            echo $message."\n";
                        }
                        
                }
                

                //echo $output;
        }
        
        imap_close($socket);
        
        
        echo '</textarea>';
    }
    
    function lookup(){
        $host=$_POST["host"];
        $dns_type=$_POST["dns_type"];
        echo '<pre>';
        echo "<div class='module-body'>";
            echo "<table class='table'>";
                echo "<thead>";
                echo "<th>Host</th><th>Type</th><th>Class</th><th>Result</th><th>TTL</th>";
                echo "</thead>";
                echo "<tbody>";
                if(filter_var($host, FILTER_VALIDATE_IP)) {
                    $host=gethostbyaddr($host);
                }
                $dnsresult = dns_get_record($host);
                foreach ($dnsresult  as $record) {
                    echo "<tr>";
                    if($dns_type==='ALL'){
                        echo "<td><div class='text-info'>".$record['host']."</div></td>";
                        echo "<td><div class='text-warning'>".$record['type']."</div></td>";
                        echo "<td>".$record['class']."</td>";
                        $result='Not Found';
                        if($record['type']=='A'){
                            $result=$record['ip'];
                        }
                        if($record['type']=='TXT'){
                            $result=$record['txt'];
                        }
                        if($record['type']=='NS'){
                            $result=$record['target'];
                        }
                        if($record['type']=='MX'){
                            $result=$record['target'];
                        }
                        if($record['type']=='SOA'){
                            $result=$record['mname'].' - '.$record['rname'].' - '.$record['serial'];
                        }
                        if($record['type']=='AAAA'){
                            $result=$record['ipv6'];
                        }
                        echo "<td><div class='text-success'>".$result."</div></td>";
                        echo "<td><div class='text-error'>".$record['ttl']."</div></td>";
                    }else{
                        if($dns_type==$record['type']){
                            echo "<td><div class='text-info'>".$record['host']."</div></td>";
                            echo "<td><div class='text-warning'>".$record['type']."</div></td>";
                            echo "<td>".$record['class']."</td>";
                            $result='Not Found';
                            if($record['type']=='A'){
                                $result=$record['ip'];
                            }
                            if($record['type']=='TXT'){
                                $result=$record['txt'];
                            }
                            if($record['type']=='NS'){
                                $result=$record['target'];
                            }
                            if($record['type']=='MX'){
                                $result=$record['target'];
                            }
                            if($record['type']=='SOA'){
                                $result=$record['mname'].' - '.$record['rname'].' - '.$record['serial'];
                            }
                            if($record['type']=='AAAA'){
                                $result=$record['ipv6'];
                            }
                            echo "<td><div class='text-success'>".$result."</div></td>";
                            echo "<td><div class='text-error'>".$record['ttl']."</div></td>";
                        }
                    }
                    echo "</tr>";
                }
                    
                echo "</tbody>";
                
            echo "</table>";
        echo "</div>";
        
        
        
        //print_r($dnsresult );
       
        /*echo "<div class='text-info'>##### A Record</div>";
        $get_A_records = dns_get_record($host, DNS_A);
        if(!empty($get_A_records)){
            foreach ($get_A_records as $Arecord) {
                echo $Arecord['ip']."\n";
            }
        }else{
            echo "<div class='text-error'>Record Not Found</div>";
        }
        echo "<div class='text-info'>#####\n\n</div>";
        
        echo "<div class='text-info'>##### AAAA(IPv6) Record</div>";
        $get_AAAA_records = dns_get_record($host, DNS_AAAA);
        if(!empty($get_AAAA_records)){
            foreach ($get_AAAA_records as $AAAArecord) {
                echo $AAAArecord['ipv6']."\n";
            }
        }else{
            echo "<div class='text-error'>Record Not Found</div>";
        }
        echo "<div class='text-info'>#####\n\n</div>";
        
        echo "<div class='text-info'>##### PTR Record</div>";
        $get_PTR_records = dns_get_record($host, DNS_PTR);
        if(!empty($get_PTR_records)){
            foreach ($get_PTR_records as $PTRrecord) {
                echo $PTRrecord['target']."\n";
            }
        }else{
            echo "<div class='text-error'>Record Not Found</div>";
        }
        echo "<div class='text-info'>#####\n\n</div>";
        
        echo "<div class='text-info'>##### TXT Record</div>";
        $get_TXT_records = dns_get_record($host, DNS_TXT);
        if(!empty($get_TXT_records)){
            foreach ($get_TXT_records as $TXTrecord) {
                echo $TXTrecord['txt']."\n";
            }
        }else{
            echo "<div class='text-error'>Record Not Found</div>";
        }
        echo "<div class='text-info'>#####\n\n</div>";
        
        echo "<div class='text-info'>##### MX Record</div>";
        $get_MX_records = dns_get_record($host, DNS_MX);
        if(!empty($get_MX_records)){
            foreach ($get_MX_records as $MXrecord) {
                echo $MXrecord['pri'].' '.$MXrecord['target']."\n";
            }
        }else{
            echo "<div class='text-error'>Record Not Found</div>";
        }
        echo "<div class='text-info'>#####\n\n</div>";*/
        
        echo '</pre>';
    }
    
    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_ips($p_id_server)
    {
        include('../../scripts/bdd.php');
        $sqlGetIPs          =   
        "
            select distinct(I.address_ip),I.id from server_vmta I where I.id_server=? and I.active=?
        ";
        $cmdGetIPs          =   $bdd->prepare($sqlGetIPs);
        $cmdGetIPs->execute(array($p_id_server,1));
        $res                =   null;
        while($IPs          =   $cmdGetIPs->fetch())
        {
            $res            =   $res.'<option value="'.$IPs["id"].'">'.$IPs["address_ip"].'</option>';
        }
        $cmdGetIPs->closeCursor();
        
        echo $res;
    }
    
    function getIpAddressByIdIP($p_id_ip)
    {
        $result             =   null;
        include('../../scripts/bdd.php');
        $sqlGetIP          =   
        "
            select I.address_ip from server_vmta I where I.id = ? and I.active = ?
        ";
        $cmdGetIP          =   $bdd->prepare($sqlGetIP);
        $cmdGetIP->execute(array($p_id_ip,1));
        
        $res                =   $cmdGetIP->fetch();
        if($res)
            $result         =   $res['address_ip'];
        $cmdGetIP->closeCursor();   
        
        return  $result;
    }
    
    function getVmtaConfigString($p_id_ip,$p_fake_domain)
    {
        $vMtaString =   "<virtual-mta FAKE-[IP]>\r\n";
        $vMtaString.=   "\tsmtp-source-ip [IP]\r\n";
        $vMtaString.=   "\thost-name [FAKE_DOMAINE]\r\n"; 
        $vMtaString.=   "</virtual-mta>\r\n"; 
        
        
       $vMtaString = str_replace("[IP]",getIpAddressByIdIP($p_id_ip),$vMtaString);
       $vMtaString = str_replace("[FAKE_DOMAINE]",$p_fake_domain,$vMtaString);
        
        return $vMtaString;
    }
    
    
    function reloadPMTA($p_id_server)
    {
        $commandglobal="restart";
        if(!empty($commandglobal))
        {
            $commandglobal  =   trim($commandglobal);
            $command        =   "sudo /etc/init.d/pmta ".$commandglobal;
            exec($command,$output,$report);
        }
    }
    
    
    function saveFakeVmtaIntoDB($p_id_server,$p_id_ip,$p_fake_domain)
    {
        $result                 =   null;
        
        $now                    =   date('Y-m-d h:i:s');
        $adressIP               =   getIpAddressByIdIP($p_id_ip);
        $nameFakeVMTA           =   'FAKE-'.$adressIP;
        
        include('../../scripts/bdd.php');
        $sqlInsertVMTA          =   
        "
            INSERT INTO server_vmta(id_server,name,block_ip,address_ip,host_name,host_type,active,date_add) VALUES(?,?,?,?,?,?,?,?);
        ";
        $cmdInsertVMTA          =   $bdd->prepare($sqlInsertVMTA);
        $result                 =   $cmdInsertVMTA->execute(array($p_id_server,$nameFakeVMTA,$adressIP,$adressIP,$p_fake_domain,'FAKE DOMAIN',1,$now));
        
        return $result;
    }
    
    function create_fake_vmta($p_id_server,$p_id_ip,$p_fake_domain)
    {
        $vmta_config_file   =   fopen($_SERVER["DOCUMENT_ROOT"]."/app/mailer/server/vmta/config.d/vmtas.txt", "a+");
        if($vmta_config_file)
        {
            $txt            =   getVmtaConfigString($p_id_ip,$p_fake_domain);
            fwrite($vmta_config_file, $txt);
            fclose($vmta_config_file);
            echo "Fake VMTA Created successfully !";
        
            if(saveFakeVmtaIntoDB($p_id_server,$p_id_ip,$p_fake_domain))
            {
                echo "Fake VMTA Saved into DB successfully !";
                reloadPMTA($p_id_server);
            }
            else
            {
                 echo "Error : Unable to save Fake VMTA into DB !";
            }
            
            
        }
        else
        {
           echo "Unable to open file !";
        }
    }