<?php
/**
 * Mail module
 * 
 * Provide a function to send email using Swift class
 * 
 * @package linea21\core\mail
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;


/**
 * @param array $emailContainer
 * @return boolean True if sent, else false
 */
function send_email($emailContainer) {
	
	if(defined('MAIL_LIBRARY') && MAIL_LIBRARY == 'swiftMailer') $mailerLibrary = 'swiftMailer';
    else $mailerLibrary = 'mailer'; // alternative 'swiftMailer'

	
    // https://symfony.com/doc/current/mailer.html
    $mailer_dsn = 'native://default'; // default configuration
    
	// We create the Transport
	if (defined ( 'MAIL_MAILER' )) {
		
		// sendmail
		if (MAIL_MAILER == 'sendmail') {
		    $mailer_dsn = 'sendmail://default';
			$transport = new Swift_SendmailTransport(MAIL_SENDMAIL); // alternative 'swiftMailer'
		}

		// smtp
		if (MAIL_MAILER == 'smtp') {
			if (defined ( 'MAIL_SMTP_AUTH' ) && MAIL_SMTP_AUTH == 1) {
				if (defined ( 'MAIL_SMTP_ENCRYPTION')) {
				    $mailer_dsn = 'smtp://'.MAIL_SMTP_USER.':'.MAIL_SMTP_PASS.'@'.MAIL_HOST.':'.MAIL_PORT;
					if($mailerLibrary == 'swiftMailer') $transport = (new Swift_SmtpTransport(MAIL_HOST, MAIL_PORT, MAIL_SMTP_ENCRYPTION))->setUsername(MAIL_SMTP_USER)->setPassword(MAIL_SMTP_PASS); // alternative 'swiftMailer'
				} else {
				    $mailer_dsn = 'smtp://'.MAIL_SMTP_USER.':'.MAIL_SMTP_PASS.'@'.MAIL_HOST.'?verify_peer=0:'.MAIL_PORT;
                    if($mailerLibrary == 'swiftMailer') $transport = (new Swift_SmtpTransport(MAIL_HOST, MAIL_PORT))->setUsername ( MAIL_SMTP_USER )->setPassword ( MAIL_SMTP_PASS ); // alternative 'swiftMailer'
				}
			} else {
			    $mailer_dsn = 'smtp://'.MAIL_HOST.':'.MAIL_PORT;
                if($mailerLibrary == 'swiftMailer') $transport = (new Swift_SmtpTransport(MAIL_HOST, MAIL_PORT)); // alternative 'swiftMailer'
			}
		}
	}
	
	// we define mailer transport settings
	$transportMailer = Transport::fromDsn($mailer_dsn);
	$mailer = new Mailer($transportMailer);

    // Create the Swift_Mailer using the Transport if set as mailer library
	if( $mailerLibrary == 'swiftMailer') $mailer = new Swift_Mailer($transport);
	
	$html = new simple_html_dom();
	$html->load($emailContainer['html_body']);
	
	// Find all images
	foreach($html->find('img') as $el) {
	    if(Stringy\Stringy::create($el->src, CHARSET)->startsWith('http')) {

	    // list($width, $height) = getimagesize($el->src); // @todo tested but to long with remote images .....
	    $el->class = 'emailImage';
	    $el->height = null; // to make auto fit ...
	    // if($width > 520) $el->width = '100%';
	    if(isset($el->width) && (int) $el->width > 520) $el->width = '100%';
        else $el->width = null;

	    }
	}
	$emailContainer['html_body'] = (string) $html; // cast to string to prevent error on mime detection using symfony/mailer

	
	
	// echo "destinataire : ".$emailContainer['recipient']."<br />";
	// echo "sujet : ".$emailContainer['subject']."<br />";
	// echo "body : ".$emailContainer['html_body']."<br />";
	// echo "body (txt) : ".$emailContainer['txt_body']."<br />";
	
	isset ( $emailContainer ['from'] ) ? $from = $emailContainer ['from'] : $from = MAIL_FROM;
	isset ( $emailContainer ['from_name'] ) ? $fromname = $emailContainer ['from_name'] : $fromname = MAIL_FROMNAME;
	// $replyto must be an array()
	isset ( $emailContainer ['reply_to'] ) ? $replyto = $emailContainer ['reply_to'] : $replyto = array( MAIL_REPLY => MAIL_REPLYNAME );
	$emailContainer ['txt_body'] = str_replace ( '&amp;', '&', $emailContainer ['txt_body'] );
	
	// if only one email is given we put it an array
	if (is_string ( $emailContainer ['recipient'] )) {
		$tmp = $emailContainer ['recipient'];
		$emailContainer ['recipient'] = array ();
		array_push ( $emailContainer ['recipient'], $tmp );
	}
	
	// Create a message
	if( $mailerLibrary == 'swiftMailer') {
		$message = (new Swift_Message($emailContainer ['subject'] ))->setFrom ( array (
			$from => $fromname 
		) )->setBody ( $emailContainer ['html_body'], 'text/html' )->addPart ( $emailContainer ['txt_body'], 'text/plain' )->setReplyTo ( $replyto );
	} else {
		// default case using symfony/mailer
		$message = (new Email())
				->from(new Address($from, $fromname))
				//->to('you@example.com')
				//->cc('cc@example.com')
				//->bcc('bcc@example.com')
				->replyTo(new Address(MAIL_REPLY, MAIL_REPLYNAME))
				//->priority(Email::PRIORITY_HIGH)
				->subject($emailContainer ['subject'])
				->text($emailContainer ['txt_body'])
				->html($emailContainer ['html_body']);
				// ->html($op);
	}
	
	if (is_array ( $emailContainer ['recipient'] )) {
		
		for($i = 0; $i < count ( $emailContainer ['recipient'] ); $i ++) {
			
			if( $mailerLibrary == 'swiftMailer') {
				$message->setTo ( $emailContainer ['recipient'] [$i] ); // swiftMailer
				$r = $mailer->Send($message);
			} else {
				$message->to( $emailContainer ['recipient'] [$i] ); // symfony/mailer
				try {
					$mailer->send($message);
					$r = 1;
				} catch (TransportExceptionInterface $e) {
					// some error prevented the email sending; display an
					// error message or try to resend the message
					$r = 0;
				}
			}
			
			if (! $r) {
				$logmsg = 'not sent';
			} else {
				$logmsg = 'sent';
			}
			
			logfile ( LOG_MAILER, array ($emailContainer ['subject'], $emailContainer['recipient'][$i], i2c_realip(), $logmsg, $mailerLibrary));
			
			if (! $r && MOD_DEBUG == 1) {
				_debug ( '<b>Mail has not been sent</b>. "' . $emailContainer ['recipient'] [$i] . ' / ' . $emailContainer ['subject'] . '" : ' . $logmsg );
			}
		}
	}
	
	// we clear SimpleHTMLDom to prevent memory leaks
	$html->clear();
	unset($html);
	
	if (! $r)
		return false;
	else
		return true;
}

?>