<commit_before><?php

if(!defined('ENMDIR')) define('ENMDIR', EXTENSIONS . "/email_newsletter_manager");

require_once(ENMDIR . '/lib/class.recipientgroupmanager.php');
require_once(ENMDIR . '/lib/class.sendermanager.php');
require_once(ENMDIR . '/lib/class.emailbackgroundprocess.php');

require_once(EXTENSIONS . '/email_template_manager/lib/class.emailtemplatemanager.php');

class EmailNewsletterException extends Exception{
}

class EmailNewsletter{

	public $limit = 10;
	protected $_completed = array();

	protected $_id;
	protected $_pid;
	protected $_pauth;

	protected $_template;
	protected $_sender;
	protected $_recipientgroups = array();

	public function __construct($id){
		$this->_id = $id;
		$this->_sender = $this->getSender();
		$this->_recipientgroups = $this->getRecipientGroups();
		$this->_template = $this->getTemplate();
		if(is_a($this->_sender, 'NewsletterSender')){
			$sender_about = $this->_sender->about();
			$this->limit = $sender_about['throttle-emails'];
		}
	}

	public function getId(){
		return $this->_id;
	}

	public function getPId(){
		if(empty($this->_pid)){
			$pid = Symphony::Database()->fetchCol('pid','SELECT pid from tbl_email_newsletters where id = \'' . $this->getId() .'\'');
			$this->_pid = $pid[0];
		}
		return $this->_pid;
	}

	public function setPId($pid){
		if(!empty($pid)){
			return Symphony::Database()->update(array('pid' => $pid), 'tbl_email_newsletters','id = \'' . $this->getId() . '\'');
		}
	}

	public function getPAuth(){
		if(empty($this->_pauth)){
			$auth = Symphony::Database()->fetchCol('pauth','SELECT pauth from tbl_email_newsletters where id = \'' . $this->getId() .'\'');
			$this->_pauth = $auth[0];
		}
		return $this->_pauth;
	}

	public function start(){
		if(!is_object($this->getTemplate())){
			$this->setStatus('error_template');
			return;
		}
		if(!is_object($this->getSender())){
			$this->setStatus('error_sender');
			return;
		}
		$rec_groups = $this->getRecipientGroups();
		if(empty($rec_groups)){
			$this->setStatus('error_recipients');
			return;
		}
		// Never start if the newsletter is sending or completed
		if($this->getStatus() == 'sending' || $this->getStatus() == 'completed'){
			return;
		}
		$this->generatePAuth();
		Symphony::Database()->query("CREATE TABLE IF NOT EXISTS `tbl_tmp_email_newsletters_sent_". $this->getId() . "` (
		  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
		  `email` varchar(255),
		  `result` varchar(255),
		  PRIMARY KEY (`id`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
		Symphony::Database()->query('DELETE FROM `tbl_tmp_email_newsletters_sent_'. $this->getId() . '` WHERE `result` = \'idle\'');
		$this->setStatus('sending');
		Symphony::Database()->update(array('started_on' => date('Y-m-d H:i:s', time())), 'tbl_email_newsletters', 'id = ' . $this->getId());
		EmailBackgroundProcess::spawnProcess($this->getId(), $this->getPAuth());
	}

	public function pause(){
		EmailBackgroundProcess::killProcess($this->getPId());
		$this->setStatus('paused');
		return true;
	}

	public function stop(){
		EmailBackgroundProcess::killProcess($this->getPId());
		Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_tmp_email_newsletters_sent_'. $this->getId() . '`');
		$this->setStatus('stopped');
		return true;
	}

	public function sendBatch($pauth){
		if($this->getPAuth() != $pauth){
			$this->setStatus('error');
			throw new EmailNewsletterException('Incorrect Process Auth used. This usually means there is more than one process running. Aborting.');
		}
		$recipients = $this->_getRecipients($this->limit);

		if(count($recipients) == 0){
			Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_tmp_email_newsletters_sent_'. $this->getId() . '`');
			$this->setStatus('completed');
			return 'completed';
		}

		foreach($recipients as $recipient){
			try{
				$template = $this->getTemplate();
				$sender = $this->getSender();
				$about = $sender->about();

				if(is_array($about['smtp'])){
					$email = Email::create('smtp');
					$email->setSenderName($about['smtp']['from_name']);
					$email->setSenderEmailAddress($about['smtp']['from_address']);
					$email->setHost($about['smtp']['host']);
					$email->setPort($about['smtp']['port']);
					$email->setSecure($about['smtp']['secure']);
					if($about['smtp']['auth'] == 1){
						$email->setAuth(true);
						$email->setUser($about['smtp']['username']);
						$email->setPass($about['smtp']['password']);
					}
				}
				elseif(is_array($about['amazon_ses'])){
					$email = Email::create('amazon_ses');
					$email->setSenderName($about['amazon_ses']['from_name']);
					$email->setSenderEmailAddress($about['amazon_ses']['from_address']);
					$email->setAwsKey($about['amazon_ses']['aws_key']);
					$email->setAwsSecretKey($about['amazon_ses']['aws_secret_key']);
					$email->setFallback($about['amazon_ses']['fallback']);
					$email->setReturnPath($about['amazon_ses']['return_path']);
				}
				elseif(is_array($about['sendmail'])){
					$email = Email::create('sendmail');
					$email->setSenderName($about['sendmail']['from_name']);
					$email->setSenderEmailAddress($about['sendmail']['from_address']);
				}
				else{
					throw new EmailNewsletterException('Currently only sendmail and SMTP are supported. This will be fixed when the API supports it.');
				}
				$template->addParams(array('etm-sender' => $sender->getHandle()));

				Symphony::ExtensionManager()->notifyMembers(
					'preEmailGenerate',
					'/extension/email_newsletter_manager/',
					array(
						'newsletter'	=> &$this,
						'email'			=> &$email,
						'template' 		=> &$template,
						'recipient'		=> &$recipient
					)
				);

				$email->setRecipients(array($recipient['name'] => $recipient['email']));
				$template->recipients = '"'.$recipient['name'] . '" <' . $recipient['email'] . '>';<commit_msg>Revert "Add the sender handle as template parameter." Is useless now.<commit_after><?php

if(!defined('ENMDIR')) define('ENMDIR', EXTENSIONS . "/email_newsletter_manager");

require_once(ENMDIR . '/lib/class.recipientgroupmanager.php');
require_once(ENMDIR . '/lib/class.sendermanager.php');
require_once(ENMDIR . '/lib/class.emailbackgroundprocess.php');

require_once(EXTENSIONS . '/email_template_manager/lib/class.emailtemplatemanager.php');

class EmailNewsletterException extends Exception{
}

class EmailNewsletter{

	public $limit = 10;
	protected $_completed = array();

	protected $_id;
	protected $_pid;
	protected $_pauth;

	protected $_template;
	protected $_sender;
	protected $_recipientgroups = array();

	public function __construct($id){
		$this->_id = $id;
		$this->_sender = $this->getSender();
		$this->_recipientgroups = $this->getRecipientGroups();
		$this->_template = $this->getTemplate();
		if(is_a($this->_sender, 'NewsletterSender')){
			$sender_about = $this->_sender->about();
			$this->limit = $sender_about['throttle-emails'];
		}
	}

	public function getId(){
		return $this->_id;
	}

	public function getPId(){
		if(empty($this->_pid)){
			$pid = Symphony::Database()->fetchCol('pid','SELECT pid from tbl_email_newsletters where id = \'' . $this->getId() .'\'');
			$this->_pid = $pid[0];
		}
		return $this->_pid;
	}

	public function setPId($pid){
		if(!empty($pid)){
			return Symphony::Database()->update(array('pid' => $pid), 'tbl_email_newsletters','id = \'' . $this->getId() . '\'');
		}
	}

	public function getPAuth(){
		if(empty($this->_pauth)){
			$auth = Symphony::Database()->fetchCol('pauth','SELECT pauth from tbl_email_newsletters where id = \'' . $this->getId() .'\'');
			$this->_pauth = $auth[0];
		}
		return $this->_pauth;
	}

	public function start(){
		if(!is_object($this->getTemplate())){
			$this->setStatus('error_template');
			return;
		}
		if(!is_object($this->getSender())){
			$this->setStatus('error_sender');
			return;
		}
		$rec_groups = $this->getRecipientGroups();
		if(empty($rec_groups)){
			$this->setStatus('error_recipients');
			return;
		}
		// Never start if the newsletter is sending or completed
		if($this->getStatus() == 'sending' || $this->getStatus() == 'completed'){
			return;
		}
		$this->generatePAuth();
		Symphony::Database()->query("CREATE TABLE IF NOT EXISTS `tbl_tmp_email_newsletters_sent_". $this->getId() . "` (
		  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
		  `email` varchar(255),
		  `result` varchar(255),
		  PRIMARY KEY (`id`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
		Symphony::Database()->query('DELETE FROM `tbl_tmp_email_newsletters_sent_'. $this->getId() . '` WHERE `result` = \'idle\'');
		$this->setStatus('sending');
		Symphony::Database()->update(array('started_on' => date('Y-m-d H:i:s', time())), 'tbl_email_newsletters', 'id = ' . $this->getId());
		EmailBackgroundProcess::spawnProcess($this->getId(), $this->getPAuth());
	}

	public function pause(){
		EmailBackgroundProcess::killProcess($this->getPId());
		$this->setStatus('paused');
		return true;
	}

	public function stop(){
		EmailBackgroundProcess::killProcess($this->getPId());
		Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_tmp_email_newsletters_sent_'. $this->getId() . '`');
		$this->setStatus('stopped');
		return true;
	}

	public function sendBatch($pauth){
		if($this->getPAuth() != $pauth){
			$this->setStatus('error');
			throw new EmailNewsletterException('Incorrect Process Auth used. This usually means there is more than one process running. Aborting.');
		}
		$recipients = $this->_getRecipients($this->limit);

		if(count($recipients) == 0){
			Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_tmp_email_newsletters_sent_'. $this->getId() . '`');
			$this->setStatus('completed');
			return 'completed';
		}

		foreach($recipients as $recipient){
			try{
				$template = $this->getTemplate();
				$sender = $this->getSender();
				$about = $sender->about();

				if(is_array($about['smtp'])){
					$email = Email::create('smtp');
					$email->setSenderName($about['smtp']['from_name']);
					$email->setSenderEmailAddress($about['smtp']['from_address']);
					$email->setHost($about['smtp']['host']);
					$email->setPort($about['smtp']['port']);
					$email->setSecure($about['smtp']['secure']);
					if($about['smtp']['auth'] == 1){
						$email->setAuth(true);
						$email->setUser($about['smtp']['username']);
						$email->setPass($about['smtp']['password']);
					}
				}
				elseif(is_array($about['amazon_ses'])){
					$email = Email::create('amazon_ses');
					$email->setSenderName($about['amazon_ses']['from_name']);
					$email->setSenderEmailAddress($about['amazon_ses']['from_address']);
					$email->setAwsKey($about['amazon_ses']['aws_key']);
					$email->setAwsSecretKey($about['amazon_ses']['aws_secret_key']);
					$email->setFallback($about['amazon_ses']['fallback']);
					$email->setReturnPath($about['amazon_ses']['return_path']);
				}
				elseif(is_array($about['sendmail'])){
					$email = Email::create('sendmail');
					$email->setSenderName($about['sendmail']['from_name']);
					$email->setSenderEmailAddress($about['sendmail']['from_address']);
				}
				else{
					throw new EmailNewsletterException('Currently only sendmail and SMTP are supported. This will be fixed when the API supports it.');
				}

				Symphony::ExtensionManager()->notifyMembers(
					'preEmailGenerate',
					'/extension/email_newsletter_manager/',
					array(
						'newsletter'	=> &$this,
						'email'			=> &$email,
						'template' 		=> &$template,
						'recipient'		=> &$recipient
					)
				);

				$email->setRecipients(array($recipient['name'] => $recipient['email']));
				$template->recipients = '"'.$recipient['name'] . '" <' . $recipient['email'] . '>';
{'fraction_non_alphanumeric': 0.2021468441391155, 'fraction_numerical': 0.0027479604980678403, 'mean_word_length': 4.908675799086758, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 176, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4486156', 'n_tokens_mistral': 4478, 'n_tokens_neox': 3781, 'n_words': 612}