<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/

class Mailer
{
    static public $mailer = null;
    static public $transport = null;
    static public $from = null;
    static public $to = null;
    static public $cc = null;
    static public $bcc = null;
    static public $subject = null;
	
	function __construct($data = null) {
	// Logger::debug('Mail CONSTRUCT: ' . print_r($data, true));
		if (isset($data) && is_array($data)) {
			Logger::debug('Mail INIT --  mail_system: ' . $data['mail_system']);
			switch ($data['mail_system']) {
				case 1: $this->setSmtpTransport($data); // we use an external SMTP server
						break;
				case 0: $this->setMailTransport(); // we use ZEND mail() function
						break;
				case 2: break; // we use PHP mail() funciton
				default: break;
			}
		}
	}
	
    static function init($data){
		self::$mailer = new Zend\Mail\Message();
		
		if (!empty($data[0]->to)) {
			$arrTo = explode(',', $data[0]->to);
			foreach ($arrTo as $to){
				if (!empty($to)) {
					self::$mailer->addTo($to);
				}
			}
		}
		
		if (!empty($data[0]->cc)) {
			$arrCc = explode(',', $data[0]->cc);
			foreach ($arrCc as $cc){
				if (!empty($cc)) {
					self::$mailer->addCc($cc);
				}
			}
		}

		if (!empty($data[0]->bcc)) {
			$arrBcc = explode(',', $data[0]->bcc);
			foreach ($arrBcc as $bcc){
				if (!empty($bcc)) {
					self::$mailer->addBcc($bcc);
				}
			}
		}

		if (!empty($data[0]->from)) {
			self::$mailer->addFrom($data[0]->from);
		}
		
		// first create the parts
		$text = new Zend\Mime\Part($data[0]->content);
		$text->type = Zend\Mime\Mime::TYPE_HTML;
		$text->encoding = Zend\Mime\Mime::ENCODING_BASE64;
		$text->charset = 'utf-8';

		$mimeMessage = new Zend\Mime\Message();
		$mimeMessage->addPart($text);

		if (!empty($data[0]->file)) {
			$arrFile = $data[0]->file;
			foreach ($arrFile as $f){
				foreach ($f as $k => $v){
					if (file_exists($k)) {
						$attachment = new Zend\Mime\Part(file_get_contents($k));
						$attachment->filename = basename($k);
						$attachment->type = $v;
						$attachment->disposition = Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
						$attachment->encoding = Zend\Mime\Mime::ENCODING_BASE64;
						$mimeMessage->addPart($attachment);
					}
				}
			}
		}

		// and finally we create the actual email
		// $message = new Message();
		self::$mailer->setBody($mimeMessage);
		self::$mailer->setSubject($data[0]->subject);
		// Logger::debug('Mail content: ' . self::$mailer->toString());
	}
	
	public static function setMailTransport(){
		// Logger::debug('Mail Transport set');
		self::$transport = new Zend\Mail\Transport\Sendmail();
	}

	public static function setSmtpTransport($data){
		Logger::debug('SMTP Transport set');
		// Setup SMTP transport using LOGIN authentication
		self::$transport = new Zend\Mail\Transport\Smtp();
		$options = new Zend\Mail\Transport\SmtpOptions(array(
			'name'              => $data['smtp_name'],
			'host'              => $data['smtp_host'],
			'port'              => $data['smtp_port'],
			'connection_class'  => $data['smtp_class'],
			'connection_config' => array(
				'username' => $data['smtp_user'],
				'password' => $data['smtp_password'],
				'ssl'      => $data['smtp_ssl'],
			),
		));
		// Logger::debug('SMTP Options: ' . print_r($options,true));
		self::$transport->setOptions($options);
	}

	public static function sendMail($data){
		self::init($data);
		Logger::debug(' --> Mailer Ready to send: ' . print_r($data, true));
		try{
			if (self::$transport==null){
				Logger::debug(' --> Mailer - Tranport is NULL, PHP mail function used: ');
				// $frontiere = '-----=' . md5(uniqid(mt_rand()));

				$rn = "\r\n";
				$rn = "\n";
				$n = "\n";
				$boundary = md5(rand());
				$boundary_content = md5(rand());
				$message = "";

				$headers = 'MIME-Version: 1.0' . $rn;
				// $headers .= 'Content-type: multipart/mixed; charset=utf-8' . $rn;
				// $headers .= 'Content-Type: multipart/related;boundary=' . $boundary . $rn;
				$headers .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'"'. $rn;

				// Headers
				if (!empty($data[0]->from)) $headers .= "From: " . $data[0]->from . $rn;
				if (!empty($data[0]->cc)) $headers .= "Cc: " . $data[0]->cc . $rn;
				if (!empty($data[0]->bcc)) $headers .= "Bcc: " . $data[0]->bcc . $rn;
				$headers .= $rn;

				// Message Body
				$message .= $n . '--' . $boundary . $n;
				$message .= "Content-Type: multipart/alternative;" . $n;
				$message .= " boundary=\"$boundary_content\"" . $n;

				//Body Mode text
				$message .= $n . "--" . $boundary_content . $n;
				$message .= 'Content-Type: text/plain; charset=utf-8' . $n;
				$message .= strip_tags($data[0]->content) . $n;

				//Body Mode Html        
				$message .= $n . "--" . $boundary_content . $n;
				$message .= 'Content-Type: text/html; charset=utf-8' . $n;
				$message .= 'Content-Transfer-Encoding: quoted-printable' . $n;
				//equal sign are email special characters. =3D is the = sign
				$message .= $n . '<div>' . nl2br(str_replace("=", "=3D", $data[0]->content)) . '</div>' . $n;
				$message .= $n . '--' . $boundary_content . '--' . $n;

				 if (!empty($data[0]->file)){
					foreach ($data[0]->file as $f) {
						foreach ($f as $k => $v){
							if (file_exists($k)) {
								Logger::debug(' --> Mailer - file has been found');
								$attachment = chunk_split(base64_encode(file_get_contents($k)));
								$message .= "--" . $boundary . $n;
								$message .= 'Content-Type: application/octet-stream; name=' . basename($k) . $n;
								$message .= "Content-Transfer-Encoding: base64" . $n;
								$message .= "Content-Disposition: attachment" . $n;
								$message .= $n . $attachment . $n . $n;
							}
						}
					}
					$message .= $n . '--' . $boundary . $n;

				 }else{
					Logger::debug(' --> Mailer - file value is empty');
				 }

				// Fin
				$message .= $n . '--' . $boundary . '--' . $n;
				
				Logger::debug(' --> Mailer - Ready to send the mail - headers: ' . $headers);
				Logger::debug(' --> Mailer - Ready to send the mail - message: ' . $message);
				$res = mail($data[0]->to, $data[0]->subject, $message, $headers);
				Logger::debug(' --> Mailer - Mail sent. result is: ' . $res);

			}else{
				Logger::debug(' --> Mailer - Transport is set, ZEND mail function or SMTP used: ');
				$res = self::$transport->send(self::$mailer);
				Logger::debug(' --> Mailer - Mail sent. result is: ' . $res);
			}
			return true;
		} catch (Exception $e) {
			Logger::debug('Mail ERROR: ' . print_r($e,true));
			return false;
		}
	}
}

?>