<?php 

define('ATTACHMENTS_DIR','emails/attachments');

class EmailDaemon {
    
    private $imap;
    private $db;
    private $users;
    private $mailbox;
    private $emailAddress;
    private $login;
    public $emails;
    public $id;
    public $savedid;

    public function __construct(){
        require_once('emails/ImapMailbox.php');
        
        $this->db=$GLOBALS['db'];
        $this->emailAddress = new SugarEmailAddress();
    }
    
    public function getUsers(){
        $usersBean =    new User();
        $this->users = $usersBean->get_full_list('',"deleted=0 and status='Active' and google_login is not null and google_password is not null");
    }
    
    public function setConnection($host,$login,$password,$box){
    	$this->login=$login;
        $this->mailbox = New ImapMailbox($host,$login, $password, ATTACHMENTS_DIR, 'utf-8');
    }
    
    public function generateEmailID($header){
        return md5($header[0]->udate."".$header[0]->date."".$header[0]->to."".$header[0]->subject);
    }
    
    public function isExistEmail($id){
        $emailsBean =    new Email();
        $email = $emailsBean->get_full_list('',"message_id='".$id."'");
        if(count($email)>0){
            return true;
        } else {
            return false;
        }

    }
    // pobiera ID emaili na poczcie
    public function getEmailsId($date){
        if($date!='' && $date!='0000-00-00 00:00:00'){
            $da=date("d M Y",strtotime($date)-86400);
        }else {
            $da=date("d M Y",strtotime("-1 day"));
        }
        $this->emails = $this->mailbox->searchMailBox("SINCE \"$da\"");
    }
    
    // pobiera całego emaila
    public function getFullEmailData($email){
        return $this->mailbox->getMail($email);
    }
    
    // tylko nagłowek emaila
    public function getEmailHeader($email){
        return $this->mailbox->getMailInfo($email);
    }
    
    //ustawia flagę jako nieprzeczytany
    public function setNotReadedFlag($email){
        $this->mailbox->markMailAsUnread($email);
    }
    
    public function getUserPassword($id){
        $r=$this->db->query("select CAST(AES_DECRYPT(google_password, 'jakistamhash123') as CHAR)
AS google_password FROM users where id='".$id."'");
        $dane=$this->db->fetchByAssoc($r);
        return $dane['google_password'];
    }
    public function getNewEmails(){
        $this->getUsers();
        foreach ($this->users as $user){ 
        
           if($user->mail_server==''){
               $server='{imap.gmail.com:993/imap/ssl}[Gmail]/Wszystkie';
           } else {
               $server=$user->mail_server;
           }

            $this->setConnection($server,$user->google_login,$this->getUserPassword($user->id));
            
            $this->getEmailsId($user->google_last_login);
            $this->checkEmails();
            break; 
        }
    } 
    
    public function checkEmails(){
        foreach ($this->emails as $email){
            
            $header=$this->getEmailHeader($email);
            
            $this->id=$this->generateEmailID($header);
            
            if($this->isExistEmail($this->id)!=true){
                $this->saveEmail($email);
            }
            
        }
    }
    
    public function cleanEmails($addrs)
    {	

    	$res = array();
    	if(is_array($addrs)){
    		
    		foreach($addrs as $addr=>$who) {
    			echo $addr.' '.$who;
    			if(!empty($who)) {
    				$res[] = "{$who} <{$addr}>";
    			} else {
    				$res[] .= $addr;
    			}
    		}
    		return join(", ", $res);
    	} else {
    		$res[] .= $addrs;
    		return join(", ", $res);
    	}
    	
    }
    
    public function searchEmail($address){
    	$zap=$this->db->query("select id from email_addresses where (email_address=LOWER('".$address."') or email_address=UPPER('".$address."')) and deleted=0"); 
    	$res=$this->db->fetchByAssoc($zap);
    	
    	return $res['id'];
    }
    
    public function insertRelation($dane){
    	$this->db->query("insert into email_id_rel set email_id='".$this->savedid."',bean_id='".$dane['bean_id']."',module_id='".$dane['bean_module']."',deleted='0',id='".create_guid()."'");
    }
    
    public function searchOwner($id){
    	$zap=$this->db->query("select * from email_addr_bean_rel where email_address_id='".$id."' and deleted=0");
    	while($dane=$this->db->fetchByAssoc($zap)){
    		$this->insertRelation($dane);
    	}
    }
    
    public function createRelationTo($email){
    	$id=$this->searchEmail($email->fromAddress);
    	if($id!=''){
    		$this->searchOwner($id);
    	}
    }
    
    public function createRelationFrom($email){
    	foreach ($email->to as $key=>$val){
    		$id=$this->searchEmail($key);
    		if($id!=''){
    			$this->searchOwner($id);
    		}	
    	}

    }
    
    public function saveAttachments($email){
    	if(count($email->attachments)>0){
    		foreach ($email->attachments as &$value) {
    			$note = new Note();
    			$note->name="Załącznik do emaila ".$value->name;
    			$note->filename=$value->name;
    			$note->parent_type='Emails'; 
    			$note->parent_id=$this->savedid;
    			$file_id= $note->save();
    			rename($value->filePath, '/var/www/html/system/upload/'.$file_id);
    		}
    	}
    }
    
    public function saveEmail($email){
    	$type=0;
    	$id=$email;
    	
        $email=$this->getFullEmailData($email);
        echo "<pre>";
        var_dump($email);
        
        $e = new Email();
        
        $e->from_addr_name = $this->cleanEmails($email->fromAddress);
        $e->to_addrs_names = $this->cleanEmails($email->to);
        $e->cc_addrs_names = $this->cleanEmails($email->cc);
        $e->reply_to_addr = $this->cleanEmails($email->replyTo);
        $e->description_html = html_entity_decode($email->textHtml,ENT_COMPAT,'UTF-8');
        $e->description =$email->textPlain ;
        $e->name =  $email->subject;
        $e->date_sent=$email->date;
        $e->message_id = $this->id;
        
        $this->savedid=$e->save();
        
        $this->saveAttachments($email);
        
        foreach ($email->to as $key=>$val){
        	if($key==$this->login){
        		$this->mailbox->markMailAsUnread($id);
        		$type=1;
        	}
        }
        
        if($type==1){
        	$this->createRelationTo($email);
        } else {
        	$this->createRelationFrom($email);
        }
        
    }
}

$ed= New EmailDaemon();
$ed->getNewEmails();
$ed->getEmailsId();

?>
