<?php 
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    


    

    if(isset($_POST['functionname'])){
        if($_POST['functionname'] == "getDomains") {
          getDomains();
        }
        elseif($_POST['functionname'] == "checkRelay"){
            checkRelay();
        }elseif($_POST['functionname'] == "callTransportMapScript"){
            callTransportMapScript();
        }
    }

    function getDomains(){
         $GLOBALS['VMailDomain'] = exec('ls /var/vmail/ | grep -v escritorio.lan | grep -v sieve', $output, $error); 
                $domains = array();
                $i = 0;
                while(list(,$VMailDomain) = each($output)){
                   //echo $VMailDomain;
                   $domains[$i] = $VMailDomain;
                  // echo $domains[$i];
                   $i++;         
                }  
        echo json_encode($domains);
      //  return json_encode($domains);
    } 


    function countRows(){
        $file="/tmp/dashboard/sendPostfix";
        $arr = array();
        $handle = fopen($file, "r");
        while(!feof($handle)){
            $line = fgets($handle);
            $json = json_decode($line, true);
            $arr[] = $json['idUser'];        
        }

        $filter =array_filter($arr);
        $lastID = array_pop($filter);
        $nextID = $lastID + 1;

        fclose($handle);      
        return (string)($nextID);

    }


    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }


 function checkRelay(){
    //clearstatcache();
    $filename = "/tmp/dashboard/relay";
    $res = 0;
    if(trim(file_get_contents($filename)) != false){
        $res = 1;
    }
    echo json_encode($res);
   // clearstatcache();
 }



function list_ldap(){

    $filename = '/home/administrator/DashboardWACS/BindPW'; 
    if (!file_exists($filename)) {
      echo "The file $filename does not exist";
    }else{
        $ldappass = trim(file_get_contents($filename));
        $ldaphost = "ldap://localhost";
        $ldapport = 389;
        $ldapuser = "wacs@escritorio.lan";
        $filter = '(&(objectclass=User)(mail=*))'; 
        //$attr = array('mail'); 
        $dn = 'cn=Users,dc=escritorio,dc=lan';

        $ldapconn = ldap_connect($ldaphost) or die("Could not connect to $ldaphost"); 
        if($ldapconn){
            $ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass );     

            if($ldapbind){
               $result = null;
               $search = ldap_search($ldapconn,$dn, $filter, array("mail")) or die ("Error in search query: ".ldap_error($ldapconn));
               $data = ldap_get_entries($ldapconn, $search);   

             }else{
               switch (ldap_errno($ldapconn)) {
               case 0: ## sem erros
                 break;
               case 49: ## credenciais erradas
                 echo "Credenciais LDAP erradas";
                 break;
               default:

                 echo ldap_error($ldapconn);
               }
             }
        }else{
            echo "Não foi possível estabelecer ligação ao servidor LDAP";
        }

    }
    return $data;
}
    function write_temp($arr, $mode, $info){
      if($info == "user"){
        
        $filename = '/tmp/dashboard/sendPostfix';   
        if ($mode == "ap"){
            if(file_put_contents($filename, json_encode($arr, TRUE) . PHP_EOL, FILE_APPEND | LOCK_EX) === false){
                echo "Não foi possível escrever no ficheiro " . $filename; 
            }   
        }elseif($mode == "del"){
            if(file_put_contents($filename, $arr, LOCK_EX) === false){
                echo "Não foi possível escrever no ficheiro " . $filename; 
            }
        }
      }else if($info == "relay"){
        $filename = '/tmp/dashboard/relay';   
        if ($mode == "ap"){
            if(file_put_contents($filename, json_encode($arr, TRUE) ) === false){
                echo "Não foi possível escrever no ficheiro " . $filename; 
            }   
        }elseif($mode == "del"){
            if(file_put_contents($filename, $arr, LOCK_EX) === false){
                echo "Não foi possível escrever no ficheiro " . $filename; 
            }
        }
      }   
    }
//escreve transport e relayhost_map
    function write_transport($arr){

        $transport = '/etc/postfix/transport';
        $relayHost = '/etc/postfix/relayhost_map';
        
       // if (!file_exists($filename) || empty($_POST["VMailDomain"])) {
         if (!file_exists($transport) || empty($arr['Dominio']) || !file_exists($relayHost)) {
            echo "The file $transport or $relayHost does not exist or Virtual Mail Domain not set.";
        }else{
           
            $isemptyTransport = trim(file_get_contents($transport));
            $found = false;
            $content = file($transport);
            foreach($content as $lineNumber => &$lineContent) { 
                // se encontrar o domínio no ficheiro adiciona o utilizador à linha seguinte 
              if(strpos($lineContent, $arr['Dominio'])) { 
              //   $lineContent .=  $arr['Email'] . "@" . $arr['Dominio'] . " :" . PHP_EOL; 
                 $lineContent .=  $arr['Email'] . " :" . PHP_EOL; 
                 $allContent = implode("", $content); 
                 file_put_contents($transport, $allContent);   
                 $found = true; 
                 break;
              }
            }
            // se não encontrar o dominio
            if(!$found){
                if ($isemptyTransport == false) {
                    //se estiver vazio, escreve 
               //   file_put_contents($filename, $arr['Email'] . "@" . $arr['Dominio'] . " :\n" .  $arr['Dominio'] . " smtp:[" . $arr['smtp'] . "]\n");
                  file_put_contents($transport, $arr['Email'] . " :\n" .  $arr['Dominio'] . " smtp:[" . $arr['smtp'] . "]\n");

                }else{
                    //se já contém dados, faz append
               //   file_put_contents($filename, $user . "@" . $arr['Dominio'] . " :\n" .  $arr['Dominio']  . " smtp:[" . $arr['smtp'] . "]\n" , FILE_APPEND | LOCK_EX);
                  file_put_contents($transport, $arr['Email']. " :\n" .  $arr['Dominio']  . " smtp:[" . $arr['smtp'] . "]\n" , FILE_APPEND | LOCK_EX);
                }  
            }
             
             //escreve relayhost_map 
            $isemptyRelay = trim(file_get_contents($relayHost));
            if($isemptyRelay == false){
                file_put_contents($relayHost,  $arr['Email'] . " [" . $arr['smtp'] . "] \n");
             }else{
                file_put_contents($relayHost,  $arr['Email'] . " [" . $arr['smtp'] . "] \n", FILE_APPEND | LOCK_EX);
            }
       }
    }


    function write_RelayToPasswd($arr){
        
            $filename = '/etc/postfix/passwd';
            if (!file_exists($filename)) {
                echo "The file $filename does not exist.";
            }else{
                if(file_get_contents("/tmp/dashboard/relay") != false){
                    file_put_contents($filename, "[" . $arr['smtp'] . "] " .  $arr['UserName'] . ":" . $arr['pass'] , FILE_APPEND | LOCK_EX);
                }
            }
      
        
    }

   function write_UserToPasswd(){
       //apagar tudo do passwd
       $passwd = '/etc/postfix/passwd';
       file_put_contents($passwd, "");
      
       //ler o array dos users do temp e voltar a escrever tudo 
       $sndPstfx = "/tmp/dashboard/sendPostfix";
       $handle = fopen($sndPstfx, "r");
       $arr = [];
       
       if ($handle) { 
            while (($line = fgets($handle)) !== false) {
                $json = json_decode($line, true);
                if(empty($json) == TRUE){
                    continue;
                }else{
                    array_push($arr, $json);
                }    
            }
           fclose($handle);
       } 
       else {    
           echo "não foi possível abrir o ficheiro.";
       } 
       foreach ($arr as $user){
            file_put_contents($passwd, $user['Email'] . " " . $user['NameUser'] . ":" . $user['pass'] . "\n", FILE_APPEND | LOCK_EX);
       }       
}


   function read_transportMap() {
        $filename = '/etc/postfix/transport';
        if (!file_exists($filename)) {
            echo "O ficheiro $filename não existe";
            
        }else{
            $current = file_get_contents($filename);
            return $current;
        }
        
   }

    function callTransportMapScript(){
        //$old_path = getcwd();
       // chdir('/home/administrator/');
        $output = shell_exec('sh /etc/postfix/SendToPostfix.sh');
        echo "<pre>$output</pre>";
       // echo print_r($output);
      //  chdir($old_path);
    }


  


?>
