<?php
/**
 * @version    $Id$
 * @package    In-Portal
 * @copyright    Copyright (C) 1997 - 2013 Intechnic. All rights reserved.
 * @license      GNU/GPL
 * In-Portal is Open Source software.
 * This means that this software may have been modified pursuant
 * the GNU General Public License, and as distributed it includes
 * or is derivative of works licensed under the GNU General Public License
 * or other free or open source software licenses.
 * See http://www.in-portal.org/license for copyright notices and details.
 */

defined('FULL_PATH') or die('restricted access!');

class EmailQueueEventHandler extends kDBEventHandler {

	/**
	 * Allows to override standard permission mapping
	 *
	 * @return void
	 * @access protected
	 * @see kEventHandler::$permMapping
	 */
	protected function mapPermissions()
	{
		parent::mapPermissions();

		$permissions = Array (
			'OnProcessAjax' => Array ('self' => 'view'),
			'OnProcess' => Array ('self' => true),
		);

		$this->permMapping = array_merge($this->permMapping, $permissions);
	}

	/**
	 * Process emails from queue
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnProcessAjax(kEvent $event)
	{
		$mailing_list_helper = $this->Application->recallObject('MailingListHelper');
		/* @var $mailing_list_helper MailingListHelper */

		$emails_sent = 0;
		$email_queue_progress = $this->Application->RecallVar('email_queue_progress');

		if ( $email_queue_progress === false ) {
			$total_emails = $mailing_list_helper->getMessages(true);

			$this->Application->StoreVar('email_queue_progress', $emails_sent . ':' . $total_emails);
		}
		else {
			list ($emails_sent, $total_emails) = explode(':', $email_queue_progress);
		}

		$message_count = $mailing_list_helper->processQueue();

		if ( !$message_count ) {
			// no messages left to send in queue
			$this->Application->RemoveVar('email_queue_progress');
			$this->Application->Redirect($this->Application->GetVar('finish_template'));

			return;
		}

		$emails_sent += $message_count;

		if ( $emails_sent >= $total_emails ) {
			$this->Application->RemoveVar('email_queue_progress');
			$this->Application->Redirect($this->Application->GetVar('finish_template'));
		}

		$this->Application->StoreVar('email_queue_progress', $emails_sent . ':' . $total_emails);
		$event->status = kEvent::erSTOP;

		echo ($emails_sent / $total_emails) * 100;
	}

	/**
	 * [SCHEDULED TASK] Process email queue from cron
	 *
	 * @param kEvent $event
	 *
	 * @return void
	 */
	protected function OnProcess(kEvent $event)
	{
		$mailing_list_helper = $this->Application->recallObject('MailingListHelper');
		/* @var $mailing_list_helper MailingListHelper */

		$mailing_list_helper->processQueue();
	}
}
