<?php

/**
* Utility tool for sending mail to multiple recipient with hmlt format and optionnal attachments
* @author valentin carruesco
* @category Core
* @license MIT
*/

class Mail{
	public $title,$expeditor,$firm,$recipients,$message,$format,$encoding,$reply,$attachments;

	function __construct(){
		global $myUser, $myFirm;
		$this->encoding = 'utf-8';
		$this->firm = utf8_decode($myFirm->label);
		$this->expeditor = $myUser->mail;
		$this->reply = $myUser->mail;
		$this->recipients = array('to'=>array(),'cc'=>array(),'cci'=>array());
		$this->attachments = array();
	}

	//Remplis le corps du message a partir d'un fichier
	//template et d'un tableau de données
	public function template($path,$data,$mustache = false){
		if(!file_exists($path)) return;
		$stream = file_get_contents($path);
		$this->message = template($stream,$data,$mustache);
	}

	public function send(){

		// clé aléatoire de limite
		$boundary = md5(uniqid(microtime(), TRUE));

		// Headers
		$headers = 'From: '.$this->expeditor."\r\n";
		$headers .= "Reply-to: ".$this->reply."\r\n";
		$headers .= 'X-Mailer: PHP/' . phpversion(). "\r\n" ;

		if(isset($this->recipients['cc']) &&  count($this->recipients['cc'])>0) $headers .= 'Cc: '.implode(',',$this->recipients['cc']) . "\r\n";
     	if(isset($this->recipients['cci']) && count($this->recipients['cci'])>0) $headers .= 'Bcc: '.implode(',',$this->recipients['cci']) . "\r\n";

		$headers .= "Organization: \"".$this->firm."\"\r\n";
		$headers .= 'Mime-Version: 1.0'."\r\n";
		$headers .= 'Content-Type: multipart/mixed;boundary='.$boundary."\r\n";
		$headers .= "\r\n";


		// Message
		$stream = '--'.$boundary."\r\n";
		$stream .= 'Content-Type: multipart/alternative; boundary="alt-'.$boundary."\"\r\n\r\n";
		$stream .= '--alt-'.$boundary."\r\n";
		$stream .= 'Content-Type: text/plain; charset=utf-8'."\r\n";
		$stream .= 'Content-Transfer-Encoding: 8bit'."\r\n\r\n";

		$plainMessage = preg_replace('/<hr[^>]*>/i','-----------------------------------',$this->message);
		$plainMessage = preg_replace('/\t/i','',trim(strip_tags($plainMessage)));
		$plainMessage = preg_replace('/(\r?\n){2,}/i',"\n\n",$plainMessage);
		$stream .= $plainMessage."\r\n\r\n";
		$stream .= '--alt-'.$boundary."\r\n";

		// Message HTML
		$stream .= 'Content-type: text/html; charset='.$this->encoding."\r\n";
		$stream .= 'Content-Transfer-Encoding: 8bit'."\r\n\r\n";
		$stream .= '<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\r\n";
		$stream .= '<html><head><meta http-equiv="Content-Type" content="text/html; charset='.$this->encoding.'" />'."\r\n";
		$stream .= '<style>body{font-family:Calibri,Arial,Verdana;color:#222222;font-size:1em;}</style>'."\r\n";
		$stream .= '</head><body>'."\r\n";
		$stream .= $this->message.'</body></html>'."\r\n\r\n";
		$stream .= '--alt-'.$boundary."--\r\n\r\n";

		foreach($this->attachments as $attachment) {
			$stream .= '--'.$boundary."\r\n";
			if(isset($attachment['cid'])) {
				$stream .= 'Content-Disposition: inline; filename="'.utf8_decode($attachment['name']).'"'."\r\n";
				$stream .= 'Content-ID: '.$attachment['cid']."\r\n";
				$stream .= 'Content-type:'.$attachment['type'].';name="'.utf8_decode($attachment['name']).'"'."\r\n";
				$stream .= 'Content-transfer-encoding:base64'."\n\n";
				$stream .= chunk_split(base64_encode($attachment['stream']))."\r\n";
			} else {
				$stream .= 'Content-type:'.$attachment['type'].';name="'.utf8_decode($attachment['name']).'"'."\r\n";
				$stream .= 'Content-transfer-encoding:base64'."\r\n";
				$stream .= 'Content-Disposition:attachment; filename="'.utf8_decode($attachment['name']).'"'."\n\n";
				$stream .= chunk_split(base64_encode($attachment['stream']))."\r\n";
			}
		}

		// Fin
		$stream .= '--'.$boundary.'--';

		$title = mb_encode_mimeheader($this->title,'UTF-8');
		try{
			set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
				throw new Exception("Erreur d'envoi de mail n°".$errno." :".$errstr);
			});
			mail(implode(',',array_unique($this->recipients['to'])), $title, $stream, $headers);
			restore_error_handler();
		}catch(Exception $e){
			return $e->getMessage();
		}
	}
}
?>