<?php
/**
* @package ccNewsletter
* @version 1.0.9
* @author  Chill Creations <info@chillcreations.com>
* @link    http://www.chillcreations.com
* @copyright Copyright (C) 2008 - 2010 Chill Creations-All rights reserved
* @license GNU/GPL, see LICENSE.php for full license.
* See COPYRIGHT.php for more copyright notices and details.

This file is part of ccNewsletter.
This program 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.

This program 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.
**/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.controller' );

// extend our main controller for the newsletter
class ccNewsletterControllernewsletter extends JController
{
	function __construct()
	{
		parent::__construct();
		$this->registerTask( 'add'  , 'edit' );
		$this->registerTask( 'apply',		'save' );
		$this->registerTask( 'unpublish'  , 'publish' );
	}
	function display()
	{
		JRequest::setVar( 'view', 'newsletters');
		parent::display();
	}
	function edit()
	{
		JRequest::setVar( 'view', 'newsletter');
		JRequest::setVar( 'layout', 'form'  );
		JRequest::setVar('hidemainmenu', 1);
		parent::display();
	}
	function save()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$model = $this->getModel('newsletter');
		$newslettterid	= JRequest::getInt( 'id', '', 'post', '' );
		$id=$model->store();
		if ($id) {
			$msg = JText::_( 'CC_NEWSLETTER_SAVED' );
		}
		else {
			$msg = JText::_( 'CC_ERROR_SAVING_NEWSLETTER' );
		}
		if($this->_task == 'apply')
		{
			$link 	= 'index.php?option=com_ccnewsletter&controller=newsletter&task=edit&cid[]='.$id;
		}
		else
		{
			$link = 'index.php?option=com_ccnewsletter&controller=newsletter';
		}
		$this->setRedirect($link, $msg);
	}

	function remove()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$model = $this->getModel('newsletter');
		if(!$model->delete()) {
			$msg = JText::_( 'CC_MSG_MULTINEWSLETTER_DELETED' );
		}
		else {
			$msg = JText::_( 'CC_MSG_NEWSLETTER_DELETED' );
		}
		$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=newsletter', $msg );
	}
	function cancel()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$msg = JText::_( 'CC_MSG_CANCELED' );
		$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=newsletter', $msg );
	}
	/**
	* Compiles information to add or edit a module
	* @param string The current GET/POST option
	* @param integer The unique id of the record to edit
	*/
	function copy()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$model = $this->getModel('newsletter');
		if(!$model->copy()) {
			$msg = JText::_( 'CC_ERR_COPYNEWSLTTER' );
		}
		else {
			$msg = JText::_( 'CC_MSG_COPYNEWSLTTER' );
		}
		$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=newsletter', $msg );
	}
	function publish()
	{

		// Initialize variables
		$db			=& JFactory::getDBO();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$task		= JRequest::getCmd( 'task' );
		$publish	= ($task == 'publish');
		$n			= count( $cid );
		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'CC_NO_ITEMS_SELECTED' ) );
		}
		JArrayHelper::toInteger( $cid );
		$cids = implode( ',', $cid );
		$query = 'UPDATE #__ccnewsletter_newsletters '
		. ' SET enabled = ' . (int) $publish
		. ' WHERE id IN ( '. $cids.'  )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}
		$msg = $n . ' ' . JText::sprintf( $publish ? JText::_( 'CC_SUBS_ENABLED' ) :  JText::_( 'CC_SUBS_DISABLED' ));
		$this->setRedirect( 'index.php?option=com_ccNewsletter&controller=newsletter', $msg );
	}
	function desableenable()
	{
		$db			=& JFactory::getDBO();
		$cid		= JRequest::getInt( 'id','0');
		$status		= JRequest::getInt( 'status','0');
		if($cid)
		{
			$query = 'UPDATE #__ccnewsletter_newsletters'
			. ' SET enabled = ' . (int) $status
			. ' WHERE id IN ( '. $cid.'  )'
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				return JError::raiseWarning( 500, $db->getErrorMsg() );
			}
			$n=1;
			$msg = $n . ' ' . JText::sprintf( $status ? JText::_( 'CC_SUBS_ENABLED' ) :  JText::_( 'CC_SUBS_DISABLED' ));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=newsletter', $msg );
		}
	}
	function deletesubscriber()
	{
		$db = JFactory::getDBO();
		$id = JRequest::getInt("id","");
		$sql = "DELETE FROM #__ccnewsletter_newsletters WHERE id=".$id;
		$db->setQuery($sql);
		$db->query();
		$msg = JText::_("CC_MSG_NEWSLETTER_DELETED");
		$link = "index.php?option=com_ccnewsletter&controller=newsletter";
		$this->setRedirect( $link ,$msg);
	}
	function send_batch_msg( $ccsend = false )
	{
		$db =& JFactory::getDBO();
		echo '<link href="components/com_ccnewsletter/assets/ccnewsleter.css" rel="stylesheet" type="text/css" />';
		flush();
		$params = $this->getComponentParameters();

		//configuration
		$query ="SELECT * FROM #__ccnewsletter_configuration WHERE id=1";
		$db->setQuery( $query );
		$configurationrow     = $db->loadObject();

		$subject = JRequest::getVar( 'subject','', 'post', 'string');
		//$id = JRequest::getVar( 'id','', 'post', 'string');
		$fromName = JRequest::getVar( 'fromName','', 'post', 'string');
		$fromEmail = JRequest::getVar( 'fromEmail','', 'post', 'string');


		$eid = JRequest::getVar( 'id','', 'post', 'string');
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$cidvalue = $cid[0];

		if($eid == "")
		{
			$id = $cidvalue;
		}
		elseif($cidvalue== "")
		{
			$id = $eid;
		}
		else
		{
			$id = "";
		}

		$fromName = $configurationrow->fromname;
		$fromEmail = $configurationrow->fromemail;

		$db =& JFactory::getDBO();
		$query ="SELECT `body`, `name` FROM #__ccnewsletter_newsletters WHERE id='".$id."'";
		$db->setQuery( $query );
		$row     = $db->loadObject();
		$subject =$row->name;

		$query = "SELECT *  FROM #__ccnewsletter_subscribers WHERE `enabled`=1 AND (`lastSentNewsletter` != $id OR `lastSentNewsletter` IS NULL)";
		$db->setQuery( $query );
		$subscribers = $db->loadObjectList();

		// total up number of records to send
		$n = count( $subscribers );
		$str = $subject;
		$subject = htmlentities($str, ENT_QUOTES, 'UTF-8');
		$newsletterModel =$this->getModel('sendNewsLetter');
		$subject = $newsletterModel->UTF8entities($subject);

		JToolBarHelper::title( JText::_( 'CC_NEWSLETTER_TITLE') . ' - ' . JText::_( 'CC_SEND_NEWSLETTER_TITLE' ), 'ccnewsletter.png' );
		$conf_html ="<div>";
		$conf_html = '<form action="index.php"><center><div class="main-wrapper">';
		$conf_html .= '<div class="clear"></div>';
		$conf_html .= '<div class="content-wrapper"><div class="content">';
		$conf_html .= '<div class="status_conf">';
		$conf_html .= '<font size="4">'.JText::_( 'CC_CONFORMATION').'</font>';
		$conf_html .= '</br>';
		$conf_html .=JText::_( 'CC_CONFORMATION_FIRST');
		$conf_html .= '</div>';
		$conf_html .= '<div class="status">';
		$conf_html .=JText::_( 'CC_SEND_NEWS').'&nbsp;"'.$subject.'"&nbsp;'.JText::_( 'CC_SEND_TO').'&nbsp;'.$n.'&nbsp;'.JText::_( 'CC_SEND_SUB');
		$conf_html .= '</br>';
		$conf_html .= '<div class="confirmation">';
		if ( $ccsend )
		{
			$conf_html.='<a href="index.php?option=com_ccnewsletter&controller=newsletter&task=ccsend_all_first&id='.$id.'">';
		}
		else
		{
			$conf_html.='<a href="index.php?option=com_ccnewsletter&task=send_all&id='.$id.'">';
		}

		$conf_html .=JText::_( 'CC_SEND_YES');
		$conf_html.='</a>'.'&nbsp;'.'&nbsp;'.'&nbsp;'.'&nbsp;';
		$conf_html.='<a href="index.php?option=com_ccnewsletter&controller=newsletter&id='.$id.'">';
		$conf_html .=JText::_( 'CC_SEND_CANCEL');
		$conf_html.='</a>';
		$conf_html .= '</div>';
		$conf_html .= '</div>';
		$conf_html .= '</div></div>';
		$conf_html .= JHTML::_( 'form.token' )."</form>";
		$conf_html .="</div>";
		echo $conf_html;
		flush();

	}

	function send_batch_msg_testing( $ccsend = false )
	{

		global $mainframe;
		$db =& JFactory::getDBO();
		echo '<link href="components/com_ccnewsletter/assets/ccnewsleter.css" rel="stylesheet" type="text/css" />';
		flush();

		//$subject = JRequest::getVar( 'subject','', 'post', 'string');
		$eid = JRequest::getVar( 'id','', 'post', 'string');
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$cidvalue = $cid[0];

		if($eid == "")
		{
			$id = $cidvalue;
		}
		elseif($cidvalue== "")
		{
			$id = $eid;
		}
		else
		{
			$id = "";
		}

		$query ="SELECT `body`, `name` FROM #__ccnewsletter_newsletters WHERE id='".$id."'";
		$db->setQuery( $query );
		$row     = $db->loadObject();
		$subject =$row->name;

		$str = $subject;
		$subject = htmlentities($str, ENT_QUOTES, 'UTF-8');
		$newsletterModel =$this->getModel('sendNewsLetter');
		$subject = $newsletterModel->UTF8entities($subject);

		//$fromName = JRequest::getVar( 'fromName','', 'post', 'string');
		$fromEmail = JRequest::getVar( 'fromEmail','', 'post', 'string');
		$params = $this->getComponentParameters();
		//configuration
		$query ="SELECT * FROM #__ccnewsletter_configuration WHERE id=1";
		$db->setQuery( $query );
		$configurationrow     = $db->loadObject();

		$testEmailAddress = $configurationrow->testemail;
		$fromName = $configurationrow->fromname;

		$query = "SELECT *  FROM #__ccnewsletter_subscribers WHERE `enabled`=1 AND (`lastSentNewsletter` != $id OR `lastSentNewsletter` IS NULL)";
		$db->setQuery( $query );
		$subscribers = $db->loadObjectList();
		// total up number of records to send
		$n = count( $subscribers );
		JToolBarHelper::title( JText::_( 'CC_NEWSLETTER_TITLE') . ' - ' . JText::_( 'CC_SEND_NEWSLETTER_TITLE' ), 'ccnewsletter.png' );
		$conf_html ="<div>";
		$conf_html = '<form action="index.php"><center><div class="main-wrapper">';
		$conf_html .= '<div class="content-wrapper"><div class="content">';

		$conf_html .= '<div class="status">';
		$conf_html .=JText::_( 'CC_TEST_NEWS').'&nbsp;"'.$subject.'"&nbsp;'.JText::_( 'CC_SEND_TO').'&nbsp;'.$testEmailAddress.'&nbsp;'.JText::_( 'CC_TEST_QUESTION');
		$conf_html .= '</br>';
		$conf_html .= '<div class="confirmation">';
		if ( $ccsend )
		{
			$conf_html.='<a href="index.php?option=com_ccnewsletter&controller=newsletter&task=ccsend_all_first&id='.$id.'&testing=1">';
		}
		else
		{
			$conf_html.='<a href="index.php?option=com_ccnewsletter&task=send_all&id='.$id.'">';
		}
		$conf_html .=JText::_( 'CC_SEND_YES');
		$conf_html.='</a>'.'&nbsp;'.'&nbsp;'.'&nbsp;'.'&nbsp;';
		$conf_html.='<a href="index.php?option=com_ccnewsletter&controller=newsletter&id='.$id.'">';
		$conf_html .=JText::_( 'CC_SEND_CANCEL');
		$conf_html.='</a>';
		$conf_html .= '</div>';
		$conf_html .= '</div>';
		$conf_html .= '</div></div>';
		$conf_html .= JHTML::_( 'form.token' )."</form>";
		$conf_html .="</div>";
		echo $conf_html;
		flush();
	}

	/**
	 * @brief Alternative function to confirm sending the newsletter
	 *
	 * @author Emmanuel Guiton <egn@ccdig.fr>
	 * @version 1.0.5
	 * @since 1.0.5
	 * @date September 2009
	 */
	function ccsend()
	{
		$this->send_batch_msg(true);
	}

	function ccsendtesting()
	{

		$this->send_batch_msg_testing(true);
	}

	/**
	 * @brief Initiate first call to ccsend_all()
	 *
	 * @author Emmanuel Guiton <egn@ccdig.fr>
	 * @version 1.0.5
	 * @since 1.0.5
	 * @date September 2009
	 */
	function ccsend_all_first()
	{

		$this->ccsend_all( false );
	}
	function getComponentParameters()
	{
		// get parameters for the form
		$params = &JComponentHelper::getParams( 'com_ccnewsletter' );
		return $params;
	}
	function ccsend_all( $ajax = true )
	{
		global $mainframe;

		if ( $ajax )
		{
			ob_clean(); // Clean the output buffer
			header('Content-Type: text/xml'); // Set sent content as XML
			echo '<?xml version="1.0"?>';
		}

		$newsletterModel =& $this->getModel( 'sendNewsletter' );
		$newsletterModel->ccsend_all( $ajax );


		if ( !$ajax )
		{
			// Display sending interface
			$view = & $this->getView( 'sendnewsletter', 'html' );
			// Push the model into the view
			$view->setModel($newsletterModel, true);
			// Set the layout
			$view->setLayout( 'ccsend' );
			$view->display();

			return true; // <-Exit Point. Task Successful.
		}
		else
		{
			$ccdata = $newsletterModel->get_ccdata();
			foreach( $ccdata['results'] as $result )
			{
				?><tr>
					<td style="text-align: center;"><?php echo $result['index']; ?></td>
					<td><?php echo $result['email']; ?></td>
					<td style="text-align: center;"><?php echo $result['sent']; ?></td>
				</tr><?php
			}
			if ( isset($ccdata['message']) )
			{
				?><input id="stop" value="stop" type="hidden" /><?php
			}
			// Discards any further HTML output
			ob_flush(); // Sends the output buffer
			exit; // Stops the script
		}
	}


	function preview()
	{
		JRequest::setVar( 'view', 'newsletters');
		JRequest::setVar( 'layout', 'preview'  );
		parent::display();
	}

	function ajaxpreview()
	{
		JRequest::setVar( 'view', 'newsletters');
		JRequest::setVar( 'layout', 'ajaxpreview'  );
		parent::display();
		exit;
	}
}
?>
