<?

require_once '/home/auto11/public_html/vendor/autoload.php';

use Aws\Ses\SesClient;
/*/
	@purpose
		this class encapsulates the PHP mail() function.
		implements CC, Bcc, Priority headers
	@version	1.3 
	- added ReplyTo( $address ) method
	- added Receipt() method - to add a mail receipt
	- added optionnal charset parameter to Body() method. this should fix charset problem on some mail clients
	@created-by Leo West - lwest@free.fr
	@example:
		include "libmail.php";
		$m= new Mail; // create the mail
		$m->From( "leo@isp.com" );
		$m->To( "destination@somewhere.fr" );
		$m->Subject( "the subject of the mail" );	
		$message= "Hello world!\nthis is a test of the Mail class\nplease ignore\nThanks.";
		$m->Body( $message);	// set the body
		$m->Cc( "someone@somewhere.fr");
		$m->Bcc( "someoneelse@somewhere.fr");
		$m->Priority(4) ;	// set the priority to Low 
		$m->Attach( "/home/leo/toto.gif", "image/gif" ) ;	// attach a file of type image/gif
		$m->Send();	// send the mail
		echo "the mail below has been sent:<br><pre>", $m->Get(), "</pre>";
	MODIFICATION HISTORY:
		� 7/28/2004 - Nathan @ Locke Enterprises (www.iLocke.com) - some code reformatting / cleanup
		� 9/7/2004 - Nathan @ Locke Enterprises (www.iLocke.com) - added the SendMail() utility routine
		� 5/28/2005 - Nathan @ Locke Enterprises (www.iLocke.com) - got this to work for .biz domains
		� 3/7/2005 - Nathan @ Locke Enterprises (www.iLocke.com) - got this to work for .biz domains
/*/


///-------------------------------------------------------------------------
class Mail {

	var $sendto = array();  // list of To addresses
	var $acc = array();
	var $abcc = array();
	var $aattach = array();  // paths of attached files
	var $xheaders = array();  // list of message headers
	var $priorities = array( '1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)' );  // message priorities referential
	var $charset = "us-ascii";  // character set of message
	var $ctencoding = "7bit";
	var $receipt = 0;
	var $isMIME;
        public $useClassic = false;

/*Mail contructor*/
function Mail() {

	$this->autoCheck( true );
	$this->boundary= "--" . md5( uniqid("myboundary") );

} // Mail()


/*activate or desactivate the email addresses validator
ex: autoCheck( true ) turn the validator on
by default autoCheck feature is on
@param boolean	$bool set to true to turn on the auto validation
@access public*/
function autoCheck( $bool ) {

	if( $bool ) $this->checkAddress = true;
	else $this->checkAddress = false;

} // autoCheck()


/*Define the subject line of the email
@param string $subject any monoline string*/
function Subject( $subject ) {

	$this->xheaders['Subject'] = strtr( $subject, "\r\n" , "  " );

} // Subject()


/*set the sender of the mail
@param string $from should be an email address*/
function From( $from ) {
        if (!$this->useClassic) {
            $this->xheaders['From'] = 'no-reply@autoglassquoting.net';
            return;
        }        
	if( ! is_string($from) ) {
		echo "oMail.From: [Error] 'From:' is not a string.<br>\n";
		return;
	}
	$this->xheaders['From'] = $from;

} // From()


/* set the Reply-to header 
 @param string $email should be an email address*/ 
function ReplyTo( $address ) {

	if( ! is_string($address) ) {
		return false;
	}
	$this->xheaders["Reply-To"] = $address;

} // ReplyTo()

/*add a receipt to the mail ie.  a confirmation is returned to the "From" address (or "ReplyTo" if defined) 
when the receiver opens the message.
@warning this functionality is *not* a standard, thus only some mail clients are compliants.*/
function Receipt() {

	$this->receipt = 1;

} // Receipt()


/*set the mail recipient
@param string $to email address, accept both a single address or an array of addresses */
function To( $to ) {

	// TODO : test validit� sur to
	if( is_array( $to ) ) {
		$this->sendto= $to;
        }
	else {
            if (strpos($to, ';') !== false) {
                $this->sendto = explode(';', $to);
            } else {
                $this->sendto[]= $to;
            }	
        }
	if( $this->checkAddress == true )
		$this->CheckAdresses( $this->sendto );

} // To()


/* Cc() set the CC headers ( carbon copy )
 * $cc : email address(es), accept both array and string */
function Cc( $cc ) {

	if( is_array($cc) ) {
		$this->acc= $cc;
	} else {
            if (strpos($cc, ';') !== false) {
                $this->acc = explode(';', $cc);
            } else {
                $this->acc[]= $cc;
            }		
	}
		
	if( $this->checkAddress == true )
		$this->CheckAdresses( $this->acc );
 
} // Cc()


/* Bcc() set the Bcc headers ( blank carbon copy ). 
 * $bcc : email address(es), accept both array and string */
function Bcc( $bcc ) {

	if( is_array($bcc) ) {
		$this->abcc = $bcc;
	} else {
            if (strpos($bcc, ';') !== false) {
                $this->abcc = explode(';', $bcc);
            } else {
                $this->abcc[]= $bcc;
            }	
	}
	if( $this->checkAddress == true ) {
		$this->CheckAdresses( $this->abcc );
	}

} // Bcc()


/* Body( text [, charset] )
 * set the body (message) of the mail
 * define the charset if the message contains extended characters (accents)
 * default to us-ascii
 * $mail->Body( "m�l en fran�ais avec des accents", "iso-8859-1" ); */
function Body( $body, $charset="" ) {

	$this->body = $body;
	
	if( $charset != "" ) {
		$this->charset = strtolower($charset);
		if( $this->charset != "us-ascii" ) $this->ctencoding = "8bit";
	}

} // Body()


/* Organization( $org ) set the Organization header */
function Organization( $org ) {

	if( trim( $org != "" )  ) $this->xheaders['Organization'] = $org;

} // Organization()


/* Priority( $priority )  set the mail priority 
 * $priority : integer taken between 1 (highest) and 5 ( lowest )
 * ex: $mail->Priority(1) ; => Highest */
function Priority( $priority ) {

	if( ! intval( $priority ) ) return false;
	if( ! isset( $this->priorities[$priority-1]) ) return false;
	$this->xheaders["X-Priority"] = $this->priorities[$priority-1];
	return true;

} // Priority()


/* Attach a file to the mail
 @param string $filename : path of the file to attach
 @param string $filetype : MIME-type of the file. default to 'application/x-unknown-content-type'
 @param string $disposition : instruct the Mailclient to display the file if possible ("inline") or always as a link ("attachment") possible values are "inline", "attachment" */
function Attach( $filename, $filetype = "", $disposition = "inline" ) {

	// TODO : si filetype="", alors chercher dans un tablo de MT connus / extension du fichier

	if( $filetype == "" ) $filetype = "application/x-unknown-content-type";
	$this->aattach[] = $filename;
	$this->actype[] = $filetype;
	$this->adispo[] = $disposition;

} // Attach()


/* set whether or not we should be MIME */
function isMIME ($b) {

	if ($b == false) {
		$this->isMIME = false;
	} else {
		$this->isMIME = true;	
	}

} // isMIME ()


/* Build the email message
@access protected*/
function BuildMail() {

	// build the headers
	$this->headers = "";
	$this->xheaders['To'] = implode( ", ", $this->sendto );

	if( count($this->acc) > 0 )
		$this->xheaders['CC'] = implode( ", ", $this->acc );
	
	if( count($this->abcc) > 0 ) 
		$this->xheaders['BCC'] = implode( ", ", $this->abcc );
	
	if( $this->receipt ) {
		if( isset($this->xheaders["Reply-To"] ) )
			$this->xheaders["Disposition-Notification-To"] = $this->xheaders["Reply-To"];
		else 
			$this->xheaders["Disposition-Notification-To"] = $this->xheaders['From'];
	}
	
	if( $this->charset != "" ) {
		if ($this->isMIME == true) {
			$this->xheaders["Mime-Version"] = "1.0";
			//$this->xheaders["Content-Type"] = "text/html; charset=$this->charset";
			//$this->xheaders["Content-Transfer-Encoding"] = $this->ctencoding;
		}
	}
	//$this->xheaders["X-Mailer"] = "Php/libMailv1.3";
	
	// include attached files
	if( count( $this->aattach ) > 0 ) {
		$this->_build_attachement();
	} else {
		$this->fullBody = $this->body;
	}
	reset($this->xheaders);
	while( list( $hdr,$value ) = each( $this->xheaders )  ) {
		$this->headers .= "$hdr: $value\n";
	}
	
} // BuildMail()


/* fornat and send the mail
	@access public */ 
function Send() {
        
        if (!$this->useClassic) {
            $this->BuildMail();

            $client = SesClient::factory(array(
               'credentials' => array(
                   'key' => 'AKIAJNBQXP4A5E4LAZQA',
                   'secret'  => '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',
               ),
               'region' => 'us-west-2',
               'version' => 'latest'
           ));
            $msg = array();
            $msg['Source'] = $this->xheaders['From'];

            $msg['Destination']['ToAddresses'] = $this->sendto;
            if (!empty($this->abcc)) {
                $msg['Destination']['BccAddresses'] = $this->abcc;
            }

            if (!empty($this->acc)) {
                $msg['Destination']['CcAddresses'] = $this->acc;
            }

            $msg['Message']['Subject']['Data'] = $this->xheaders['Subject'];
            $msg['Message']['Subject']['Charset'] = "UTF-8";

            $msg['Message']['Body']['Html']['Data'] = $this->body;
            $msg['Message']['Body']['Html']['Charset'] = "UTF-8";

            try {
                $attach = current($this->aattach);
                if (empty($attach)) {
                    $m = new SimpleEmailServiceMessage();
                    $m->addTo($this->sendto);
                    $m->setFrom($this->xheaders['From']);
                    $m->addBCC($this->abcc);
                    $m->addCC($this->acc);                    
                    $m->setSubject($this->xheaders['Subject']);
                    $m->setMessageFromString('', $this->body);

                    $ses = new SimpleEmailService('AKIAJNBQXP4A5E4LAZQA', 'O7onpL9KTGRaMRHRT5CAvpB+bJMEKooG9Ypc7q0B', SimpleEmailService::AWS_US_WEST_2);
                    $res = $ses->sendEmail($m);
                    file_put_contents('/home/auto11/www/log.log', "SEND TO:".json_encode($this->sendto). PHP_EOL, FILE_APPEND);
                    file_put_contents('/home/auto11/www/log.log', "SEND TO BCC:".json_encode($this->abcc). PHP_EOL, FILE_APPEND);
                    file_put_contents('/home/auto11/www/log.log', "SEND TO CC:".json_encode($this->acc). PHP_EOL, FILE_APPEND);
                    file_put_contents('/home/auto11/www/log.log', "RESPONSE:".json_encode($res). PHP_EOL, FILE_APPEND);
                } else {
                    $m = new SimpleEmailServiceMessage();
                    $m->addTo(current($this->sendto));
                    $m->setFrom($this->xheaders['From']);
                    $m->setSubject($this->xheaders['Subject']);
                    $m->setMessageFromString('This is the message body.');
                    $m->addAttachmentFromFile(current($this->aattach), current($this->aattach), current($this->actype));

                    $ses = new SimpleEmailService('AKIAJNBQXP4A5E4LAZQA', 'O7onpL9KTGRaMRHRT5CAvpB+bJMEKooG9Ypc7q0B', SimpleEmailService::AWS_US_WEST_2);
                    $ses->sendEmail($m);
                }
            } catch (\Exception $e) {
                file_put_contents('/home/auto11/www/log.log', $e->getMessage() . PHP_EOL);
            }
        } else {

            $this->BuildMail();
            $this->strTo = implode( ", ", $this->sendto );

            $res = @mail( $this->strTo, $this->xheaders['Subject'], $this->fullBody, $this->headers );

            //foreach( $this->sendto as $index => $to ) $res = @mail( $to, $this->xheaders['Subject'], $this->fullBody, $this->headers );
        }

} // Send()


/* Get() return the whole e-mail , headers + message can be used for displaying the message in plain text or logging it  */
function Get() {

	$this->BuildMail();
	$mail = "To: " . $this->strTo . "\n";
	$mail .= $this->headers . "\n";
	$mail .= $this->fullBody;
	return $mail;

} // Get()


/* check an email address validity
 @access public
 @param string $address : email address to check
 @return true if email adress is ok */
function ValidEmail($address) {

	if( ereg( ".*<(.+)>", $address, $regs ) ) {
		$address = $regs[1];
	}
 	if(ereg( "^[^@  ]+@([a-zA-Z0-9\-]+\.)+(com|net|org|mil|gov|edu|int|biz|info|museum|name|pro|coop|web|[a-zA-Z0-9\-]{2})\$",$address) ) return true; // 2-letter country code or any of the common 3-letter codes
 	else return false;

} // ValidEmail()


/* check validity of email addresses 
	@param	array $aad - 
	@return if unvalid, output an error message and bail out, this may -should- be customized */
function CheckAdresses( $aad ) {

	for( $i=0; $i<count($aad); $i++ ) {
		if( ! $this->ValidEmail( $aad[$i]) ) {
			echo "oMail.CheckAddresses: [ERROR] invalid address '".$aad[$i]."'<br>\n";
			return;
		}
	}

} // CheckAdresses()


/* check and encode attach file(s) . internal use only
 @access private*/
function _build_attachement() {

	//$this->xheaders["Content-Type"] = "multipart/mixed;\n boundary=\"$this->boundary\"";
	$this->fullBody = "This is a multi-part message in MIME format.\n--$this->boundary\n";
	//$this->fullBody .= "Content-Type: text/plain; charset=$this->charset\nContent-Transfer-Encoding: $this->ctencoding\n\n" . $this->body ."\n";
	
	$sep= chr(13) . chr(10);
	
	$ata= array();
	$k=0;
	
	// for each attached file, do...
	for( $i=0; $i < count( $this->aattach); $i++ ) {
		
		$filename = $this->aattach[$i];
		$basename = basename($filename);
		$ctype = $this->actype[$i];	// content-type
		$disposition = $this->adispo[$i];
		
		if( ! file_exists( $filename) ) {
			echo "oMail.attach: [ERROR] file $filename can't be found.<br>\n";
			return;
		}
		$subhdr= "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n  filename=\"$basename\"\n";
		$ata[$k++] = $subhdr;
		// non encoded line length
		$linesz= filesize( $filename)+1;
		$fp= fopen( $filename, 'r' );
		$ata[$k++] = chunk_split(base64_encode(fread( $fp, $linesz)));
		fclose($fp);
	}
	$this->fullBody .= implode($sep, $ata);

} // BuildMail()


} // class Mail


//-------------------------------------------------------------------------
// SendMail:  Package the use of the mail object into this wrapper so that callers have more compact code.
//-------------------------------------------------------------------------
function SendMail( $from, $to, $subject, $body=" ", $mime=false, $bcc="" ) {

	$oMail = new Mail;
	$oMail->From( $from );
	$oMail->To( $to );
	if( $bcc != "" ) $oMail->Bcc( $bcc );
	$oMail->Subject( $subject );	
	$oMail->isMIME( $mime );
	$oMail->Body( $body );
	$oMail->Send();

} // SendMail()


?>