<?php
set_time_limit(0);

date_default_timezone_set('Europe/Warsaw');
mb_internal_encoding("UTF-8");

function create_guid_section($characters)
{
	$return = "";
	for($i=0; $i<$characters; $i++)
	{
		$return .= sprintf("%x", mt_rand(0,15));
	}
	return $return;
}

function ensure_length(&$string, $length)
{
	$strlen = strlen($string);
	if($strlen < $length)
	{
		$string = str_pad($string,$length,"0");
	}
	else if($strlen > $length)
	{
		$string = substr($string, 0, $length);
	}
}

function create_guid()
{
    $microTime = microtime();
	list($a_dec, $a_sec) = explode(" ", $microTime);

	$dec_hex = sprintf("%x", $a_dec* 1000000);
	$sec_hex = sprintf("%x", $a_sec);

	ensure_length($dec_hex, 5);
	ensure_length($sec_hex, 6);

	$guid = "";
	$guid .= $dec_hex;
	$guid .= create_guid_section(3);
	$guid .= '-';
	$guid .= create_guid_section(4);
	$guid .= '-';
	$guid .= create_guid_section(4);
	$guid .= '-';
	$guid .= create_guid_section(4);
	$guid .= '-';
	$guid .= $sec_hex;
	$guid .= create_guid_section(6);

	return $guid;

}

function sprawdz_czy_od_klienta($od,$id,$do=false,$uid){
	$r=mysql_query("select adres.id as email_adres_od ,rel.bean_id as id_kontra,rel.bean_module as modul from email_addresses as adres
INNER join email_addr_bean_rel as rel on adres.id=rel.email_address_id
 where rel.deleted=0 and adres.email_address='".$od."' 
or adres.email_address_caps='".strtoupper($od)."' and rel.deleted=0");
	if(mysql_num_rows($r)>0){
	if($do==true){
		$dane=mysql_fetch_assoc($r);
			mysql_query("INSERT INTO emails_email_addr_rel
				(`id`,
				`email_id`,
				`address_type`,
				`email_address_id`,
				`deleted`,
				`user_id`) 
				VALUES
				('".create_guid()."',
				'".$id."',
				'from',
				'".$dane['email_adres_od']."',
				'0',
				'".$uid."');");
				return $dane;
		}
	} else {
	  return false;
	}
	
}
function sprawdz_czy_od_klienta2($od,$id,$do=false,$uid){
	$r=mysql_query("select adres.id as email_adres_od ,rel.bean_id as id_kontra,rel.bean_module as modul from email_addresses as adres
INNER join email_addr_bean_rel as rel on adres.id=rel.email_address_id
 where rel.deleted=0 and adres.email_address='".$od."' 
or adres.email_address_caps='".strtoupper($od)."' and rel.deleted=0");

	if(mysql_num_rows($r)>0){
	if($do==true){
	$dane=mysql_fetch_assoc($r);
				mysql_query("INSERT INTO emails_email_addr_rel
(`id`,
`email_id`,
`address_type`,
`email_address_id`,
`deleted`,
`user_id`)
VALUES
('".create_guid()."', 
'".$id."',
'to',
'".$dane['email_adres_od']."',
'0',
'".$uid."');");
return $dane;
}
	} else {
	  return false;
	}
	
}
function pobierz_moj_email_dodaj_relacje($to,$id,$uid){
		$r=mysql_query("SELECT adres.id as id FROM email_addresses as adres
 where adres.email_address='".$to."' 
or adres.email_address_caps='".strtoupper($to)."'");
	if(mysql_num_rows($r)>0){
	$dane=mysql_fetch_assoc($r);
		mysql_query("INSERT INTO emails_email_addr_rel
(`id`,
`email_id`,
`address_type`,
`email_address_id`,
`deleted`,
`user_id`)
VALUES
('".create_guid()."',
'".$id."',
'to',
'".$dane['id']."',
'0',
'".$uid."');");
		return true;
	} else {
		return false;
	}
}
function pobierz_moj_email_dodaj_relacje2($to,$id,$uid){
		$r=mysql_query("SELECT adres.id as id FROM email_addresses as adres
		
 where adres.email_address='".$to."' 
or adres.email_address_caps='".strtoupper($to)."'");
	if(mysql_num_rows($r)>0){
	$dane=mysql_fetch_assoc($r);
		 mysql_query("INSERT INTO emails_email_addr_rel
(`id`,
`email_id`,
`address_type`,
`email_address_id`,
`deleted`,
`user_id`)
VALUES
('".create_guid()."',
'".$id."',
'from',
'".$dane['id']."',
'0',
'".$uid."');");
		return true;
	} else {
		return false;
	}
}
include_once("../import/class.dbf.php");
include_once("../config.php");


global $sugar_config;
$sql=mysql_connect($sugar_config['dbconfig']['db_host_name'],$sugar_config['dbconfig']['db_user_name'],$sugar_config['dbconfig']['db_password']);
mysql_select_db($sugar_config['dbconfig']['db_name']);

require_once('ImapMailbox.php');
define('ATTACHMENTS_DIR', dirname(__FILE__) . '/attachments');
mysql_query ('SET NAMES utf8');
mysql_query ('SET CHARACTER_SET utf8_unicode_ci');
$r=mysql_query("select id,google_login,google_skrzynka,google_lastupdate,CAST(AES_DECRYPT(google_password, 'jakistamhash123') as CHAR) 
AS google_password,google_calendar_name FROM users where id='6826e9ec-9e04-4f3b-76fc-4ce320b4e457'");
while($dane=mysql_fetch_array($r)){
	if($dane['google_login']!='' && $dane['google_password']!=''){
		// IMAP must be enabled in Google Mail Settings
		echo "Dla konta: ".$dane['google_login']." znaleziono: ";
		$mailbox = new ImapMailbox('{imap.saas-systems.pl:143/imap/novalidate-cert/tls}'.$dane['google_skrzynka'].'',$dane['google_login'], $dane['google_password'], ATTACHMENTS_DIR, 'utf-8');
		$mails = array();
		
		// pobierz idki maili
		if($dane['google_lastupdate']!='' && $dane['google_lastupdate']!='0000-00-00 00:00:00'){ 
		$da=date("d M Y",strtotime($dane['google_lastupdate'])-86400);
		}else {
		$da=date("d M Y",strtotime("-1 day"));
		}
		echo $da;
		$mailsIds = $mailbox->searchMailBox("SINCE \"$da\"");
		echo count($mailsIds)." emaili<br>";
		print_r($mailsIds);
		//$mailsIds = array_slice($mailsIds, 1, 2);
		$i=0; 
		print_r($mailbox->getMailBoxes());
		$bc=0; 
	//	if($dane['google_login']!='outtervision@gmail.com') continue;

		foreach ($mailsIds as &$value) {
				// pobierz dane o emailu id flagi itp
				$udate=$mailbox->getMailInfo($value);
				echo "<pre>";
				print_r($udate);
				echo "</pre>";
				//$mail=$mailbox->getMail($value);
				//sprawdź czy email jest w bazie danych
				$dodaj=0;
				if($dane['google_lastupdate']!='' && $dane['google_lastupdate']!='0000-00-00 00:00:00'){
				$dzis=strtotime($dane['google_lastupdate']);
				 if($udate[0]->udate > $dzis-820){
				  $dodaj=1;
					} else {
					continue;
					}
				} else {
				 $dzis=strtotime(date("Y-m-d 00:00:01"));
				 if($udate[0]->udate > $dzis){
				  $dodaj=1;
					} else {
					continue;
					}
				}
				$gen_id=md5($udate[0]->udate."".$udate[0]->date."".$udate[0]->to."".$udate[0]->subject);
				$r2=mysql_query("select id from emails where message_id='".$gen_id."'");
				
				// jesli nie dodaj
				
				if(mysql_num_rows($r2)==0 && $dodaj==1){
				
				$rel=0;
				$rel2=0;
				$dodano=0;
				//		echo '<br><br><h1>'.$i.'</h1><br><br>';
					//pobierz zawartosc maila
					$mail=$mailbox->getMail($value);
					// sprawdz czy wiadomosc nieprzeczytana jesli tak pozostaw...
					if($udate[0]->seen==0){
					$mailbox->markMailAsUnread($value);
					}
					$id=create_guid();
					// pobierz do kogo odpowiedziec
					foreach ($mail->replyTo as $key => $item) {
						 $reply= $key;
					}
					// pobierz do kogo wyslany
					$do="";
					
					// pobierz do kogo wysłane i utwórz relacje 
					if(count($mail->to)>1){
						// jak do wielu...
						$tid=0;
						foreach ($mail->to as $key => $item) {
							// parsuje adresatów
							if($tid+1==count($mail->to)){
								$do.=$key;
							} else {
								$do.=$key.",";
							}
							$tid++;
							if($key==$dane['google_login']){
								
								pobierz_moj_email_dodaj_relacje($key,$id,$dane['id']);
								
							} else {
								if(!sprawdz_czy_od_klienta2($key,$id,false,$dane['id'])){
									$check=sprawdz_czy_od_klienta2($key,$id,true,$dane['id']);
									$modul=$check['modul'];
									$id_kontra=$check['id_kontra'];
								if($modul=='Accounts' || $modul=='Contacts' || $modul=='Leads' || $modul=='ContactLeads'){
									$rel=1;
									$modul2=$check['modul'];
									$id_kontra2=$check['id_kontra'];
									}
								}
							}
						}					
					} else {
					$tid=0;
					// jak do jednego
						foreach ($mail->to as $key => $item) {
							$do=$item.' <'.$key.'>';
							if($key==$dane['google_login']){
								// relacja dla szkodnika
								pobierz_moj_email_dodaj_relacje($key,$id,$dane['id']);
								
							} else {
								// relacja dla kl.
								if(!sprawdz_czy_od_klienta2($key,$id,false,$dane['id'])){
									$check=sprawdz_czy_od_klienta2($key,$id,true,$dane['id']);
									$modul=$check['modul'];
									$id_kontra=$check['id_kontra'];
						
									if($modul=='Accounts' || $modul=='Contacts' || $modul=='Leads' || $modul=='ContactLeads'){
									$rel=1;
									$modul2=$check['modul'];
									$id_kontra2=$check['id_kontra'];
									}
								}
							}
						} 
					}
					// wysłaneod
					$od="";
							$od=$mail->fromAddress;
							if($key==$dane['google_login']){
								$i++;
										if(!sprawdz_czy_od_klienta($mail->fromAddress,$id,false,$dane['id'])){
									$check=sprawdz_czy_od_klienta($mail->fromAddress,$id,true,$dane['id']);
									$modul=$check['modul'];
									$id_kontra=$check['id_kontra'];
									if($modul=='Accounts' || $modul=='Contacts' || $modul=='Leads' || $modul=='ContactLeads'){
									$rel=1;
									$modul2=$check['modul'];
									$id_kontra2=$check['id_kontra'];
									}
								}
							} else {
							$i++;
								pobierz_moj_email_dodaj_relacje2($mail->fromAddress,$id,$dane['id']);
								
							} 
					// do wiadomości
					foreach ($mail->cc as $key => $item) {
						$cc= $key;
					} 
					// czy w mailu są załączniki
					//if($rel==0) continue;
					echo 'dodaje!!!!';
					if(count($mail->attachments)>0){
						// jeśli tak zapisz ...
						foreach ($mail->attachments as &$value) {
								

								$note=create_guid();
								substr($value->filePath,strlen(ATTACHMENTS_DIR.'/')).'<br>';
								rename($value->filePath, '/var/www/html/crm/upload/'.$note);
								unlink($value->filePath);
								mysql_query("INSERT INTO `notes`
								(`id`,
								`date_entered`,
								`date_modified`,
								`modified_user_id`,
								`created_by`,
								`name`,
								`filename`,
								`file_mime_type`,
								`parent_type`,
								`parent_id`,
								`contact_id`,
								`portal_flag`,
								`embed_flag`,
								`description`,
								`deleted`)
								VALUES
								('".$note."',
								'".date("Y-m-d H:i:s")."',
								'".date("Y-m-d H:i:s")."',
								'".$dane['id']."',
								'".$dane['id']."',
								'".$value->name."',
								'".$value->name."',
								null,
								'Emails',
								'".$id."',
								null,
								'0',
								'0',
								null,
								'0');
								");
							
						}
					}					
					
		
					// generuj id maila
					
					// sprawdz czy przychodzacy czy wychodzacy
					
					if($mail->fromAddress==$dane['google_login']){
						$typ='out';
					} else {
						$typ='inbound';
					}
					
					// dodaj tekst emaila
					
					mysql_query("INSERT INTO `emails_text`
						(`email_id`,
						`from_addr`,
						`reply_to_addr`,
						`to_addrs`,
						`cc_addrs`,
						`bcc_addrs`,
						`description`,
						`description_html`,
						`raw_source`,
						`deleted`,
						`user_id`,
						`gid`,
						`tid`)
						VALUES
						('".$id."',
						'".$od."',
						'".$reply."',
						'".$do."',
						'".$cc."',
						'',
						'".mysql_real_escape_string($mail->textPlain)."',
						'".mysql_real_escape_string($mail->textHtml)."',
						'',
						'0',
						'".$dane['id']."',
						'".$udate[0]->udate."',
						'".$tid."');"); 

						// dodaj email
						mysql_query("INSERT INTO `emails`
						(`id`,
						`date_entered`,
						`date_modified`,
						`assigned_user_id`,
						`modified_user_id`,
						`created_by`,
						`deleted`,
						`date_sent`,
						`message_id`,
						`name`,
						`type`,
						`status`,
						`intent`,
						`mailbox_id`,
						`parent_type`,
						`parent_id`,
						`flagged`,
						`reply_to_status`,
						`tid`)
						VALUES
						('".$id."',
						'".date("Y-m-d H:i:s")."',
						'".date("Y-m-d H:i:s")."',
						'".$dane['id']."',
						'".$dane['id']."',
						'".$dane['id']."',
						'0',
						'".$mail->date."',
						'".$gen_id."',
						'".$mail->subject."',
						'".$typ."', 
						'archived',
						'read',
						'',
						'".$modul2."',
						'".$id_kontra2."',
						'0',
						'0',
						'".$tid."');"); 
						if($modul=='Contacts' || $modul=='ContactLeads'){
							$relacjaid=mysql_query("select ac.id from accounts ac inner join accounts_contacts acc on acc.account_id=ac.id and acc.deleted=0 and acc.contact_id='".$id_kontra2."'");
							if(mysql_num_rows($relacjaid)==1){
							while($idekk=mysql_fetch_array($relacjaid)){
								mysql_query("INSERT INTO `email_id_rel`
								(`id`,
								`email_id`,
								`bean_id`,
								`module_id`,
								`deleted`)
								VALUES
								('".create_guid()."',
								'".$id."',
								'".$idekk['id']."',
								'Accounts',
								'0');
								");
							}
							}
									mysql_query("INSERT INTO `email_id_rel`
										(`id`,
										`email_id`,
										`bean_id`,
										`module_id`,
										`deleted`)
										VALUES
										('".create_guid()."',
										'".$id."',
										'".$id_kontra2."',
										'Contacts',
										'0');
										");
										echo "INSERT INTO `email_id_rel`
										(`id`,
										`email_id`,
										`bean_id`,
										`module_id`,
										`deleted`)
										VALUES
										('".create_guid()."',
										'".$id."',
										'".$id_kontra2."',
										'".$modul."',
										'0');
										";
						} else {
							mysql_query("INSERT INTO `email_id_rel`
										(`id`,
										`email_id`,
										`bean_id`,
										`module_id`,
										`deleted`)
										VALUES
										('".create_guid()."',
										'".$id."',
										'".$id_kontra2."',
										'".$modul."',
										'0');
										");
						}
						$dodano=1;
				} else {
				$bc++;
				}
				
			} 

				mysql_query("update users set google_lastupdate='".date("Y-m-d H:i:s")."' where id='".$dane['id']."'");

	echo "Dodano: ".$i." maili z czego ".$bc." znajduje się w bazie<br>";		
	}
	
}

//var_dump($mail->getAttachments());
