<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/private/mail_preprocessing.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
if ( $requestName=="CREATE" || $requestName=="UPDATE"){
	if(!function_exists('get_mail_files_together')){
		function get_mail_files_together(&$mime,$attachment,$dest_dir,&$attachments_filenames){
			if (is_dir($attachment) && $dir = @opendir($attachment)) {
				//$values['Folder']=$values['Attachments'];
				
				$attachments_filenames = array();
				if(substr($attachment,-1)!='/')
					$attachment.='/';
				while($file = readdir($dir)) {
					$complete_file = $attachment.$file;
					if ($file != "." && $file != ".." && file_exists($complete_file) && !is_dir($complete_file)){
						
						$attachments_filenames[]=$file;
						if($complete_file!=$GLOBALS["directoryRoot"].$dest_dir.$file)
							@copy($complete_file,$GLOBALS["directoryRoot"].$dest_dir.$file);
					}
				}
				
				//
			}else if(is_file($attachment)){
				
				$basefilename = BaseFilename($attachment);
				$attachments_filenames[]=$basefilename;
				if($attachment!=$GLOBALS["directoryRoot"].$dest_dir.$basefilename)
					@copy($attachment,$GLOBALS["directoryRoot"].$dest_dir.$basefilename);
				//$values['Folder']=getShortPath(dirname($attachment));
			}
		}
		function stripEmail($complete_to){
			if (getServerOS()!=='windows')
				return $complete_to;
			$tos = explode(',',$complete_to);
			for($i=0;$i<sizeof($tos);$i++){
				$to = $tos[$i];
				$pos_lt = strpos($to,'<');
				if($pos_lt!==false){
					$pos_gt = strpos($to,'>',$pos_lt);
					//$to = '"'.substr($to,0,$pos_lt).'"'.substr($to,$pos_lt);
					$to = substr($to,$pos_lt+1,$pos_gt-$pos_lt-1);
					$tos[$i]=$to;
				}
			}
			$complete_to = implode(',',$tos);
			//debug_log($complete_to);
			return $complete_to;
		}
	}
	if($values['Type']=='out'){
		require_once(dirname(__FILE__).'/../common/mail.class.php');
		
		$mime = new ServerMail();
		
		// must generate Plaintext
		if(!function_exists('CSStoPlain')){
			function CSStoPlain(&$xml,$path){
				$eol="\n";
				$li_white_space = ' ';
				$childs = $xml->match($path."/* | ".$path."//li");
				$k = 0;
				foreach($childs as $child_path){
					$childnode = $xml->getElement($child_path);
					$childnodeName = $xml->nodeName($child_path);
					
					$k++;
					if($childnodeName=='ul'){
						;
					}else{
						$grandchilds_match = $child_path."/node()";
						$grandchilds = $xml->match($grandchilds_match);
						$white_spaces='';
						if($childnodeName=='li'){
							$nb_parents = sizeof($xml->match($child_path."/ancestor::ul"));
							for($j=0;$j<$nb_parents;$j++)
								$white_spaces.= $li_white_space;
							$str.=$white_spaces;
							$str.='* ';
							$white_spaces.= '  '; // if <br>, we shift just after the * and not a the same height
						}
						foreach($grandchilds as $grandchild_path){
							$this_node = $xml->getElement($grandchild_path);
							
							$grandchildnodeName = $xml->nodeName($grandchild_path);
							
							$grandchildvalue = decode_from_xml($xml->getData($grandchild_path));
							switch($grandchildnodeName){
								case 'a':
									$str.=$grandchildvalue;
									$href = $xml->getData($grandchild_path.'/@href');
									$href = str_replace('[files_url]',$GLOBALS["files_url"],$href);
									if($href!=trim($grandchildvalue) && $href!='mailto:'.$grandchildvalue && $href!=$grandchildvalue.'/' && $grandchildvalue!=$href.'/' && $href!='http://'.$grandchildvalue.'/' && $href!='http://'.$grandchildvalue)
										$str.=' '.$href.' ';
									break;
								case 'img':
									$src = $xml->getData($grandchild_path.'/@src');
									$alt = $xml->getData($grandchild_path.'/@alt');
									if($alt){
										$str.=$alt;
									}else{
										$src = str_replace('[files_url]',$GLOBALS["files_url"],$src);
										$str.='<'.$src.'>';
									}
									
									break;
								case 'br':$str.=$eol.$white_spaces;break;
								case 'strong':$str.='*'.$grandchildvalue.'*';break;
								//text node
								default:$str.=$grandchildvalue;
							}
							
						}
						$str.=$eol;
					}
					
				}
				return $str;
			}
		}
		if(!function_exists('CSStoStyledQuote')){
			function CSStoStyledQuote($xml,$path){
				$eol="\n";
				$li_white_space = ' ';
				$childs = $xml->match($path."/*");
				$current_i = 0;
				$quote_colors = array('FF0000','0000FF','00FF00');
				foreach($childs as $child_path){
					$childnode = $xml->getNode($child_path);
					$childnodeName = $xml->nodeName($child_path);
					
					$node_content = decode_from_xml(UnicodeEntities_To_utf8($xml->getData($child_path)));
					if(substr($node_content,0,1)=='>'){
						$i = 0;
						while(substr($node_content,0,1)=='>'){
							$node_content = substr($node_content,1);
							$i++;
						}
						$prec_i = $current_i;
						$current_i = $i;
						//$xml->setAttribute($child_path,'style','margin-left:'.($i*20).'px;');
						if(trim($node_content)=='')
							$node_content = '';
						$xml->replaceData($child_path, $node_content);
						if($prec_i < $current_i){
							for($j=$prec_i;$j<$current_i;$j++){
								if(isset($quote_colors[$j]))
									$quote_color = $quote_colors[$j];
								else
									$quote_color = $quote_colors[sizeof($quote_colors)-1];
								$str.='<blockquote style="color:#'.$quote_color.';border-left:2px solid #'.$quote_color.';">';
							}
						}else if($prec_i > $current_i){
							for($j=$current_i;$j<$prec_i;$j++){
								$str.='</blockquote>';
							}
						}
						//$str.=$node_content;
						$str.=$xml->toString($child_path,'');
					}else{
						$prec_i = $current_i;
						$current_i = 0;
						for($j=$current_i;$j<$prec_i;$j++){
							$str.='</blockquote>';
						}
						$str.=$xml->toString($child_path,'');
					}
					
				}
				return $str;
			}
		}
		$time0 =  time();
		
		// transforming the styled version to a plaintext version
		$values['PlainText'] = CSStoPlain($xml,$firstNodePath."/INFO/STYLEDTEXT/CSS");
		
		// ensuring that no timeout occurs
		$time1 = time();
		if($time1>$time0+30){
			header('X-pmaPing: Pong');
			$time0 = $time1;
		}
		// adding the plaintext version
		$mime->setText(UnicodeEntities_To_utf8($values['PlainText']));
		
		//$mailaccountModuleInfo= moduleInfo('mailsaccount');
		//$account = getInfo($mailaccountModuleInfo,$values['AccountID']);
		
		$styled_text = CSStoStyledQuote($xml,$firstNodePath."/INFO/STYLEDTEXT/CSS");
		
		// ensuring that no timeout occurs
		$time1 = time();
		if($time1>$time0+30){
			header('X-pmaPing: Pong');
			$time0 = $time1;
		}
		
		// replacing [files_url] by a real url
		$styled_text = str_replace('[files_url]',$GLOBALS["files_url"],$styled_text);
		$styled_text = str_replace('&apos;',"'",$styled_text);
		
		// replacing empty paragraphs by paragraphs with only a carriage return
		$styled_text = str_replace(array('<p/>','<h1/>','<h2/>','<h3/>'),array('<p><br></p>','<h1><br></h1>','<h2><br></h2>','<h3><br></h3>'),$styled_text);
		
		// including the css corresponding to the html
		if(file_exists($GLOBALS["library_dir"].'mail/css/inside_mail.css'))
			$css = file_in_string($GLOBALS["library_dir"].'mail/css/inside_mail.css');
		
		// adding the HTML version of the mail
		$richtext = '<html><head><title>'.encode_to_xml($values['Subject']).'</title></head><body><style>'.$css.'</style>'.$styled_text.'</body>';
		$mime->setHTML($richtext);
		
		// handling the attachments
		if($values['Attachments']!='' || $values['Folder']!=''){
			
			 // determining the destination folder of the attachments
			if($values['Folder'] && substr($values['Folder'],0,6)=='/mail/' && strpos($values['Folder'],'/received/')===false){
				if(is_dir($GLOBALS["directoryRoot"].$values['Folder'])){
					$dest_dir = $values['Folder'];
				}else{
					$dest_dir = getShortPath(dirname($GLOBALS["directoryRoot"].$values['Folder']));
				}
			}else if($values['Attachments'] && substr($values['Attachments'],0,6)=='/mail/' && strpos($values['Attachments'],'/received/')===false){
				if(is_dir($GLOBALS["directoryRoot"].$values['Attachments'])){
					$dest_dir = $values['Attachments'];
				}else{
					$dest_dir = getShortPath(dirname($GLOBALS["directoryRoot"].$values['Attachments']));
				}
			}else{
				$dest_dir = '/mail/'.$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID'].'/'.date('Y-m').'/sent/'.date('d').'/'.date('H-i-s').'/';
			}
			makeDir($GLOBALS["directoryRoot"].$dest_dir);
			
			
			$attachments_filenames = array();
			if($values['Attachments']){
				$attachment = $GLOBALS["directoryRoot"].$values['Attachments'];
				get_mail_files_together($mime,$attachment,$dest_dir,$attachments_filenames);
			}
			if($values['Folder']){
				$attachment2 = $GLOBALS["directoryRoot"].$values['Folder'];
				get_mail_files_together($mime,$attachment2,$dest_dir,$attachments_filenames);
			}
			// now really attach the files
			$dir = @opendir($GLOBALS["directoryRoot"].$dest_dir);
			if($dir){
				while($file = readdir($dir)){
					$complete_file = $GLOBALS["directoryRoot"].$dest_dir.$file;
					if ($file != "." && $file != ".." && file_exists($complete_file) && !is_dir($complete_file)){
						$mime->addAttachment($complete_file);
					}
				}
			}
			$values['Folder'] = $dest_dir;
			$values['Attachments'] = implode(',',$attachments_filenames);
			$return_values['Folder']=$values['Folder'];
			$return_values['Attachments']=$values['Attachments'];
		}
		/*$message = $mime->get(array("text_charset"=>"utf-8","text_format"=>"flowed","head_charset"=>"utf-8","html_charset"=>"utf-8"));
		$hdrs = array();
		$from = decode_from_XML(UnicodeEntities_To_utf8($values['From']));
		$hdrs = array(
              'From'    => $from,
			  'return-path' => $from,
			  'errors-to' => $from,
			  'bounces-to' => $from,
			  'X-Mailer' => 'Nectil Mail'
              );
		if($values['Cc'])
			$hdrs['Cc']= decode_from_XML(UnicodeEntities_To_utf8(stripEmail($values['Cc'])));
		if($values['Bcc'])
			$hdrs['Bcc']= decode_from_XML(UnicodeEntities_To_utf8(stripEmail($values['Bcc'])));
			
		if($values['Priority']!=0)
			$hdrs['X-Priority']= $values['Priority'];
		
		$mime->headers($hdrs);
		// to have to: and subject: correctly encoded
		$to = decode_from_XML(UnicodeEntities_To_utf8($values['To']));
		$to = stripEmail($to);
		$subject = decode_from_XML(UnicodeEntities_To_utf8($values['Subject']));
		$headers_array = $mime->_encodeHeaders(array('To'=>$to,'Subject'=>$subject));
		$headers = $mime->txtHeaders();*/
		$mime->setSender(decode_from_XML(UnicodeEntities_To_utf8($values['From'])));
		$mime->addRecipient(decode_from_XML(UnicodeEntities_To_utf8(stripEmail($values['To']))));
		$mime->addCC(decode_from_XML(UnicodeEntities_To_utf8(stripEmail($values['Cc']))));
		$mime->addBCC(decode_from_XML(UnicodeEntities_To_utf8(stripEmail($values['Bcc']))));
		$mime->setSubject(decode_from_XML(UnicodeEntities_To_utf8($values['Subject'])));
		$mime->setPriority($values['Priority']);
		
		
		// ensuring no timeout occurs
		$time1 = time();
		if($time1>$time0+30){
			header('X-pmaPing: Pong');
			$time0 = $time1;
		}
		// sending the mail
		//$res = mail($headers_array['To'], $headers_array['Subject'], $message, $headers);
		$res = $mime->execute();
		
		if($res){
			$values['Type']='sent';
			$values['SendingDate']=$GLOBALS["sushee_today"];
		}else
			return generateMsgXML(1,"The message could not be sent.",0,'',$name);
	}else if($values['Type']=='draft'){
		if(/*$values['Attachments']!='' ||*/ $values['Folder']!=''){
			if($values['Folder'] && substr($values['Folder'],0,6)=='/mail/' && strpos($values['Folder'],'/received/')===false){
				if(is_dir($GLOBALS["directoryRoot"].$values['Folder']))
				$dest_dir = $values['Folder'];
				else
				$dest_dir = getShortPath(dirname($GLOBALS["directoryRoot"].$values['Folder']));
			}else if($values['Attachments'] && substr($values['Attachments'],0,6)=='/mail/' && strpos($values['Attachments'],'/received/')===false){
				if(is_dir($GLOBALS["directoryRoot"].$values['Attachments']))
				$dest_dir = $values['Attachments'];
				else
				$dest_dir = getShortPath(dirname($GLOBALS["directoryRoot"].$values['Attachments']));
			}else
				$dest_dir = '/mail/'.$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID'].'/'.date('Y-m').'/sent/'.date('d').'/'.date('H-i-s').'/';
			//debug_log($dest_dir);
			makeDir($GLOBALS["directoryRoot"].$dest_dir);
			$attachments_filenames = array();
			if($values['Attachments']){
				$attachment = $GLOBALS["directoryRoot"].$values['Attachments'];
				get_mail_files_together($mime,$attachment,$dest_dir,$attachments_filenames,false);
			}
			if($values['Folder']){
				$attachment2 = $GLOBALS["directoryRoot"].$values['Folder'];
				get_mail_files_together($mime,$attachment2,$dest_dir,$attachments_filenames);
			}
			$values['Attachments']=implode(',',$attachments_filenames);
			$values['Folder'] = $dest_dir;
			$return_values['Folder']=$values['Folder'];
			$return_values['Attachments']=$values['Attachments'];
		}
	}
}else if($requestName=='KILL' || $requestName=='DELETE'){
	
	$mail_sql = 'SELECT `Folder`,`ID` FROM `'.$moduleInfo->tableName.'` WHERE `ID` IN ('.implode(',',$IDs_array).') AND `Folder`!=""';
	
	$folders_rs = $db_conn->Execute($mail_sql);
	while($mail = $folders_rs->FetchRow()){
		$complete_folder = $GLOBALS['directoryRoot'].$mail['Folder'].$mail['ID'].$GLOBALS['slash'];
		if(file_exists($complete_folder)){
			killDirectory($complete_folder);
		}
	}
	//die();
}
return TRUE;
?>
