<?php
/**
 * ****************************************************************
 * Project:      *
 * Copyright:    Copyright (c) 2007
 * Company:      Thomas Niemann
 * ****************************************************************
 * Workfile:     EmailHelper.php
 * ****************************************************************
 * Description:
 *
 * ***************************************************************/
class EmailHelper {
	private $mail = null;
    private $smtpinfo = array();

	public function __construct() {
		// Zeichen fuer Zeilenumbruch
		$eol = "\n";
		$this->mail = new Mail_mime($eol);
        $this->fromName               = (string)ConfigLoader::getInstance()->getAppSettings('email_from_name');
        $this->fromEmail              = (string)Configloader::getInstance()->getEmail('info');

        $this->smtpinfo["host"]       = (string)ConfigLoader::getInstance()->getAppSettings('smtp_server');
        $this->smtpinfo["port"]       = (int)ConfigLoader::getInstance()->getAppSettings('smtp_port');
        $this->smtpinfo["auth"]       = (boolean)ConfigLoader::getInstance()->getAppSettings('smtp_auth');
        $this->smtpinfo["username"]   = (string)ConfigLoader::getInstance()->getAppSettings('smtp_user');
        $this->smtpinfo["password"]   = (string)ConfigLoader::getInstance()->getAppSettings('smtp_pwd');
        #$this->smtpinfo["debug"]    = (boolean)ConfigLoader::getInstance()->getAppSettings('smtp_debug');
        $this->smtpinfo['Return-Path'] = sprintf("-f %s", $this->fromEmail);
        #$this->smtpinfo["debug"] = "True";
	}
    public function sendEmail($_subject, $emailContent, $_recipient = null,$_htmlemail = false, $_bcc = null,$_cc = null,$_attachment = null) {
    	$_htmlemail = false;
		/**
		* den HTML-Body der Mail setzen. Alternativ kann der
		* HTML-Code auch aus einer Datei kommen. Dann geben
		* Sie als ersten Parameter den Dateinamen und als zweiten
		* Parameter TRUE an.
		*/
		// Absender festlegen
		$from_params = empty ($this->fromName) ? $this->fromEmail : ('"'.$this->fromName.'" <'.$this->fromEmail.'>');
        //recipient
        if(empty($_recipient)){
            $_recipient = $from_params;
        }
		if(!empty($_cc)){
			$this->mail->addCc($_cc);
		}
		// Bcc festlegen
		if(!empty($_bcc)){
			$this->mail->addBcc((string)$_bcc);
		}
		// Betreff der Mail festlegen
		$this->mail->setSubject($_subject);

		//anhang
		if (!empty ($_attachment)) {
			$this->_setAttachment($_attachment);
		}

		// Den Inhalt der Mail definieren
		if($_htmlemail){
            $this->mail->setHTMLBody($emailContent);
            $body = $this->mail->get(array('html_charset' => 'utf-8', 'text_encoding' => '8bit', 'head_charset' => 'utf-8'));
		}
		else{
            $this->mail->setTXTBody($emailContent);
            $body = $this->mail->get(array('text_charset' => 'utf-8', 'text_encoding' => '8bit', 'head_charset' => 'utf-8'));
        }
		// Koerper der Mail auslesen
		$headers = $this->mail->headers(array ('From'     => $from_params,
                                               'To'      => $_recipient,
                                               'Charset' => 'UTF-8',
                                               'Subject' => $_subject));
		/**
		* Mail verschicken
		*/
		if (is_array($_recipient)) {
			foreach ($_recipient as $rec) {
				if (!empty ($rec)) {
					$res = $this->_send($rec, 'smtp', $headers, $body);
				}
			}
		}
        else {
			$res = $this->_send($_recipient, 'smtp', $headers, $body);
		}
		return !PEAR::isError($res)? true :$res->getMessage();
	}
	/**
	* Mail senden
	* @access public
	* @param string $to G?ltige eMail-Adresse als Empf?ger
	* @param string $type Zu verwendende eMail-Engine ((default)'mail' oder 'smtp')
	* @param array $typeoptions Sendeoptionen der SMTP-Engine
	* @return boolean true oder PEAR::Error-Objekt
	* @see Validate,Mail_mime,Mail
	*/
	private function _send($to, $type = "mail", $mailheader, $mailbody) {

		//$sendmail = new Mail();
		if (Validate::email($this->fromEmail, true) == true) {
            $mail=&Mail::factory("smtp", $this->smtpinfo);
            $result = $mail->send($to, $mailheader, $mailbody) ? true : PEAR::raiseError('Fehler beim senden der eMail');
            return $result;

		} else {
			//loggen der falschen email adresse
			//ErrorLogLoader::getInstance()->logInvalidEmail($to);
			return PEAR::raiseError('eMail-Adresse ungültig!');
		}
	}
	/**
	* Anh?ge hinzuf?gen
	* @access private
	* @param array $attachments Array mit Pfaden zu Dateianh?gen
	*/
	private function _setAttachment($_attachments) {
		if (is_array($_attachments)) {
			foreach ($_attachments as $attachment) {
				if (is_file(realpath($attachment))) {
					$this->mail->addAttachment($attachment);
				}
			}
		} else
			if (is_file(realpath($_attachments))) {
				$this->mail->addAttachment($_attachments);
			}
	}
}