<?php
/*
 * This file is part of the easy-CMS project.
 * easy-CMS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * easy-CMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with easy-CMS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/**
 * @package    Core
 * @subpackage Engines
 */

include_once('classes/core/engines/BatchEngine.class.php');

include_once('classes/core/DBManipulator.class.php');
include_once('classes/core/contents/ContentsManager.class.php');

include_once('classes/system/Mail.class.php');
include_once('mailing/langs/langs.inc.php');


class MailingEngine extends BatchEngine {

		var $contentsManager;
		var $dbManipulator;
		var $queue;

		function MailingEngine(&$contentsManager) {
			$this->contentsManager = &$contentsManager;
      $this->dbManipulator = &$contentsManager->getDBManipulator();
			$this->queue = array();

			// insert non sent e-mails in queue
			$query = "SELECT * FROM `easy_cms_mailing_queue` WHERE `date_out` = '0000-00-00' LIMIT 0 , ".BATCH_SIZE.";";
			$result = $this->dbManipulator->sendQuery($query);
			$i = 0;
			while($row = $this->dbManipulator->fetchArray($result)){
				$this->queue[$i] = array();
				$this->queue[$i]['id'] = $row['id'];
				$this->queue[$i]['message_id'] = $row['message_id'];
				$this->queue[$i]['subscriber_id'] = $row['subscriber_id'];
				$this->queue[$i]['date_in'] = $row['date_in'];
				++$i;
			}
		}

		function doStep() {
			if($this->operations < count($this->queue)) {
				$subscriberId = $this->queue[$this->operations]['subscriber_id'];
				$messageId = $this->queue[$this->operations]['message_id'];

  			$subscriber = &$this->contentsManager->getContent($subscriberId, "mailing_subscriber", 1);
  			$message = &$this->contentsManager->getContent($messageId, "mailing_message");

				$subscriberFirstNameObj = $subscriber->getContentFieldValue(1, 'firstname');
				$subscriberLastNameObj  = $subscriber->getContentFieldValue(1, 'lastname');
				$subscriberEmailObj     = $subscriber->getContentFieldValue(1, 'email');

				$subscriberFirstName  = $subscriberFirstNameObj->getValue();
				$subscriberLastName   = $subscriberLastNameObj->getValue();
				$subscriberEmail      = $subscriberEmailObj->getValue();

				$mailingListId = 1;
				$query = "SELECT * FROM `easy_cms_content_type_mailing_message` WHERE `id` = '$messageId';";
				$result = $this->dbManipulator->sendQuery($query);
				if($row = $this->dbManipulator->fetchArray($result)) {
					$mailingListId = $row['mailing_list_id'];
				}

				// message language is the first lang found with non-empty subject
				$selectLangId = 1;
				$langsArray = $this->contentsManager->getLangsArray();
				foreach($langsArray as $langId => $langName) {
					$messageSubjectObj = $message->getContentFieldValue($langId, 'subject');
					if(strlen($messageSubjectObj->getValue()) > 0) {
						$selectLangId = $langId;
						break;
					}
				}
        /* TODO : improve that */
      	switch($selectLangId) {
      		case 1:
      			$lang = LANG_EN;
      			break;
      		case 2:
      			$lang = LANG_FR;
      			break;
      		case 3:
      			$lang = LANG_NL;
      			break;
      	}
        global $emlmTranslationsFiles;
        include_once('mailing/langs/'.$emlmTranslationsFiles[$lang]);
				$messageBodyObj 		= $message->getContentFieldValue($selectLangId, 'body');
				$messageDateObj 		= $message->getContentFieldValue($selectLangId, 'date');

				$html = "<html>\n";
				$html .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
				$html .= "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
				$html .= "<head>\n";
				$html .= "  <title>".$messageSubjectObj->getValue()."</title>\n";
				$html .= "  <meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />\n";
				$html .= "</head>\n";
				$html .= $messageBodyObj->getValue();
				$html .= "<br /><br /><br /><span style=\"font-size: 9px;\">";

				$unsubscribeLink = ORG_URL."easy-mlm.php?action=unsubscribe&ml_id=".$mailingListId."&address=".$subscriberEmail."&lg_id=".$selectLangId;

				$html .= str_replace("__%LINK%__", $unsubscribeLink, LANG_EMLM_UNSUBSCRIBE_NOTICE);
				$html .= "</span>\n</html>";

				$mail = &new Mail($messageSubjectObj->getValue(), $html);
				$mail->setSenderMail(ORG_MAIL);
				$mail->setSenderFirstname(ORG_NAME);
				$mail->addRecipientTO($subscriberEmail, $subscriberFirstName, $subscriberLastName);

        $mail->send();

				$itemId = $this->queue[$this->operations]['id'];
				$now = date('Y-m-d');
				$query = "UPDATE `easy_cms_mailing_queue` SET `date_out` = '$now' WHERE `id` = '$itemId';";
				$this->dbManipulator->sendQuery($query);

				return true;
			}
			return false;
		}

		function stop() {
			$this->debug("MailingEngine::stop(), notice: ".$this->operations." operations executed in ".$this->duration." seconds.", 10);
		}
}

?>