<?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 ccNewsletterControllerimport extends JController
{
	function __construct()
	{
		parent::__construct();
		// Register Extra tasks, in this case we are saying to treat add like edit;
	}
	function display()
	{
		JRequest::setVar( 'view', 'import');
		parent::display();
	}
	function getstringcsv($rows)
	{
		$output_file="export.csv";
		$file = fopen($output_file,'w');
		$strcsv="";
		$strcsv.="Name,";
		$strcsv.="E-mail,";
		$strcsv.="Plain Text,";
		$strcsv.="Enabled,";
		$strcsv.="Sent Date,";
		$strcsv.="Last sent newsletter,";
		$newcsvdata[]=explode(",",$strcsv);

		foreach($newcsvdata as $newdata)
			fputcsv($file, $newdata);
	}
	function saveEmails()
	{
		$file = JRequest::getVar( 'filename', 'post', 'string' );
		$path = JRequest::getVar( 'path', 'post', 'string' );

	}
	//export csv file...
	function doExport()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		global $mainframe;
		$database =& JFactory::getDBO();
		$query = "SELECT name,email,plainText,enabled,sdate,lastSentNewsletter FROM  #__ccnewsletter_subscribers ORDER BY id";
		$database->setquery($query);
		$rows = $database->loadAssocList();
		$output_file=$date =date("d-M-Y s").".csv";
		$file = fopen($output_file,'w');
		$strcsv="";
		$strcsv.="Name,";
		$strcsv.="E-mail,";
		$strcsv.="Plain Text,";
		$strcsv.="Enabled,";
		$strcsv.="Sent Date,";
		$strcsv.="Last sent newsletter,";
		$newcsvdata[]=explode(",",$strcsv);
		foreach($newcsvdata as $newcsvdatas)
			fputcsv($file, $newcsvdatas);
		foreach($rows as $row)
		{
			fputcsv($file, $row);
		}
		fclose($file);
		$file_name=$output_file;
		$file_name = basename($file_name);
		$file_path = JURI::root()."administrator/".$file_name;
		header("location:".$file_path);
	}
	function importfromdb()
	{
			$selection = JRequest::getVar( 'selection', 'post', 'string' );
			$deletesubs = JRequest::getVar( 'deletesubs', 'post', 'string' );
			$my	=& JFactory::getUser();
			$database =& JFactory::getDBO();
			$msg = JText::_( 'CC_IMPORTED_SUCCESSFULLY' );
			if($deletesubs== "deletesubs")
			{
				$query = "DELETE  FROM #__ccnewsletter_subscribers";
				$database->setQuery( $query );
				$database->query();
			}
			if($selection == "yanc")
			{
				$database->setQuery( "SELECT * FROM #__yanc_subscribers" );
				$subscribers = $database->loadObjectList();
				$error = $database->getErrorMsg();
				foreach($subscribers as $subscriber)
				{
					$subscriber_state = $subscriber->state;
					if($subscriber->uid == 0)
					{
						$subscriber_name = $subscriber->name;
						$subscriber_email = $subscriber->email;
					}
					else
					{
						$query = "SELECT * FROM #__users WHERE id=".$subscriber->uid;
						$database->setquery($query);
						$row = $database->loadObject();
						$subscriber_name = $row->name;
						$subscriber_email = $row->email;
					}
					$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$database->Quote($subscriber_email)."";
					$database->setquery($query);
					$count = $database->loadResult();
					if($count<1)
					{
						$query = "INSERT INTO #__ccnewsletter_subscribers (`id`, `name`, `email`, `plainText`, `enabled`, `sdate`) VALUES ( '', ".$database->Quote($subscriber_name).", ".$database->Quote($subscriber_email).", '', ".$database->Quote($subscriber_state).", '')";
						$database->setQuery( $query );
						$database->query();
					}
				}
			}
			if($selection == "acajoom")
			{
					$database->setQuery( "SELECT * FROM #__acajoom_subscribers" );
					$subscribers = $database->loadObjectList();
					$error = $database->getErrorMsg();
					foreach($subscribers as $subscriber)
					{
						$subscriber_email = $subscriber->email;
						$subscriber_state = $subscriber->confirmed;
						$subscriber_name = $subscriber->name;
						$subscriber_date =  $subscriber->subscribe_date;
						$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$database->Quote($subscriber_email)."";
						$database->setquery($query);
						$count = $database->loadResult();
						if($count<1)
						{
							$query = "INSERT INTO #__ccnewsletter_subscribers (`id`, `name`, `email`, `plainText`, `enabled`, `sdate`) VALUES ( '', ".$database->Quote($subscriber_name).", ".$database->Quote($subscriber_email).", '', ".$database->Quote($subscriber_state).", ".$database->Quote($subscriber_date).")";
							$database->setQuery( $query );
							$database->query();
						}
					}
			}
			if($selection == "vmod")
			{
					$database->setQuery( "SELECT * FROM #__vemod_news_mailer_subs" );
					$subscribers = $database->loadObjectList();
					$error = $database->getErrorMsg();
					foreach($subscribers as $subscriber)
					{
						$query = "SELECT * FROM #__users WHERE id=".$subscriber->userid;
						$database->setquery($query);
						$row = $database->loadObject();
						$subscriber_name = $row->name;
						$subscriber_email = $row->email;
						$subscriber_date =  $row->registerDate;
						$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$database->Quote($subscriber_email)."";
						$database->setquery($query);
						$total = $database->loadResult();
						if($total==0)
						{
							$query = "INSERT INTO #__ccnewsletter_subscribers (`id`, `name`, `email`, `plainText`, `enabled`, `sdate`) VALUES ( '', ".$database->Quote($subscriber_name).", ".$database->Quote($subscriber_email).", '', 1, ".$database->Quote($subscriber_date).")";
							$database->setQuery( $query );
							$database->query();
						}
					}
			}
			if($selection == "communicator")
			{
				$database->setQuery( "SELECT * FROM #__communicator_subscribers" );
				$subscribers = $database->loadObjectList();
				$error = $database->getErrorMsg();
				foreach($subscribers as $subscriber)
				{
					$subscriber_email = $subscriber->subscriber_email;
					$subscriber_state = $subscriber->confirmed;
					$subscriber_name = $subscriber->subscriber_name;
					$subscriber_date =  $subscriber->subscribe_date;
					$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$database->Quote($subscriber_email)."";
					$database->setquery($query);
					$count = $database->loadResult();
					if($count<1)
					{
						$query = "INSERT INTO #__ccnewsletter_subscribers (`id`, `name`, `email`, `plainText`, `enabled`, `sdate`) VALUES ( '', ".$database->Quote($subscriber_name).", ".$database->Quote($subscriber_email).", '', ".$database->Quote($subscriber_state).", ".$database->Quote($subscriber_date).")";
						$database->setQuery( $query );
						$database->query();
					}
				}
			}
			if($selection == "letterman")
			{
				$database->setQuery( "SELECT * FROM #__letterman_subscribers" );
				$subscribers = $database->loadObjectList();
				$error = $database->getErrorMsg();
				foreach($subscribers as $subscriber)
				{
					$subscriber_email = $subscriber->subscriber_email;
					$subscriber_state = $subscriber->confirmed;
					$subscriber_name = $subscriber->subscriber_name;
					$subscriber_date =  $subscriber->subscribe_date;
					$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$subscriber_email."";
					$database->setquery($query);
					$count = $database->loadResult();
					if($count<1)
					{
						$query = "INSERT INTO #__ccnewsletter_subscribers (`id`, `name`, `email`, `plainText`, `enabled`, `sdate`) VALUES ( '', ".$database->Quote($subscriber_name).", ".$database->Quote($subscriber_email).", '', ".$database->Quote($subscriber_state).", ".$database->Quote($subscriber_date).")";
						$database->setQuery( $query );
						$database->query();
					}
				}
			}
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg );
	 }

	function emailonly()
	{
		$deletesubsfromfile = JRequest::getVar( 'deletesubsfromfile', 'post', 'string' );
		$database =& JFactory::getDBO();
		$textarea = JRequest::getVar( 'emailtext', '', '', 'string' );

		if($textarea)
		{
			$emailids = explode(",", $textarea);
			$totalcount = count($emailids);
			if($deletesubsfromfile=="deletesubsfromfile")
			{
				if($totalcount>0)
				{
					$query = "DELETE  FROM #__ccnewsletter_subscribers";
					$database->setQuery( $query );
					$database->query();
				}
			}
			for($i=0; $i < $totalcount;$i++)
			{
					$emailids[$i] = trim($emailids[$i]);
					jimport('joomla.mail.helper');
					$valid = JMailHelper :: isEmailAddress($emailids[$i]);

					if($valid)
					{
						$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$emailids[$i]."";
						$database->setquery($query);
						$count = $database->loadResult();
						if($count<1)
						{
							if($emailids[$i])
							{
								$query = "INSERT INTO #__ccnewsletter_subscribers (`id`, `name`, `email`, `plainText`, `enabled`, `sdate`) VALUES ( '', '', ".$database->Quote($emailids[$i]).", '', '1', '')";
								$database->setQuery( $query );
								$database->query();
								$lastid = $database->insertid();
							}
						}
					}
			}
		}
		if($lastid)
		{
			$msg = JText::_( 'CC_IMPORT_EMAIL_SUCCESSFULLY' );
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg );
		}
		else
		{
			JError::raiseWarning(100, JText::_('CC_IMPORT_EMAIL_ERR'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import' );
		}
	}
	function importtxtcsv()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$deletesubsfromfile = JRequest::getVar( 'deletesubsfromfile', 'post', 'string' );
		$fieldseparator = JRequest::getVar( 'delimiter', 'post', 'string' );
		$fieldseparator1 = JRequest::getVar( 'delimiter1', 'post', 'string' );
		$database =& JFactory::getDBO();
		if($deletesubsfromfile=="deletesubsfromfile")
		{
			$query = "DELETE  FROM #__ccnewsletter_subscribers";
			$database->setQuery( $query );
			$database->query();
		}
		$lineseparator = "\n";
		$textarea = JRequest::getVar( 'emailtext', '', '', 'string' );
	  	$post	= JRequest::get( 'post' );
		$import_file = JRequest::getVar( 'importfile', '', 'files', 'array' );
		$deletesubsfromfile = JRequest::getVar( 'deletesubsfromfile', 'post', 'string' );
		$csvfile = $import_file['tmp_name'];
		$msg = JText::_( 'CC_IMPORT_SUCCESSFULLY' );
		jimport('joomla.filesystem.file');
		$addauto = 0;
		$save = 0;
		$format = strtolower(JFile::getExt($import_file['name']));
		if($csvfile=="")
		{
			JError::raiseWarning(100, JText::_('CC_NO_FILE_WARNING'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
	 	elseif($format != "txt")
		{
			$err = true;
			JError::raiseWarning(100, JText::_('CC_ERROR_NOT_CORRECT_FORMAT'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
		else
		{
			if(!file_exists($csvfile))
			{
			    echo "File not found. Make sure you specified the correct path.\n";
			    exit;
			}
		}
		$file = fopen($csvfile,"r");
			if(!$file)
			{
		    echo "Error opening data file.\n";
		    exit;
		}
		$size = filesize($csvfile);
			if(!$size)
			{
		    echo "File is empty.\n";
		    exit;
		}
		$tmp='\t';
		if($fieldseparator==$tmp)
			$fieldseparator="\t";

		$tmp='\r';
		if($fieldseparator1==$tmp)
			$fieldseparator1="\r";
		$tmp='\n';
		if(trim($fieldseparator1)==$tmp)
			$fieldseparator1="\n";

		$filecontent = trim(file_get_contents($csvfile)); // default : delimiter = comma, enclosure = double quote, escape character = backslash
		if($fieldseparator1=="")
			$fieldseparator1=",";
		$order   = array($fieldseparator1);
		$replace = '!,!';
		$filecontent = str_replace($order, $replace, $filecontent);
		$emails=explode("!,!",$filecontent);

		$i=0;
		$emailnotifier_count=substr_count($filecontent,"@");
		$rownotifiew_count=substr_count($filecontent,",");

		if($fieldseparator=="" OR $fieldseparator=="post")
		{
			foreach($emails as $email)
			{
				$email.=",";
				$newarray[$i]=explode(",",$email);
				$i++;
			}
		}
		else
		{
			foreach($emails as $email)
			{
				$newarray[$i]=explode($fieldseparator,$email);
				$i++;
			}
		}
		if(count($newarray[0])>="1" AND count($newarray[0])<="6")
		{
			$col0=strpos($newarray[0][0],"@");
			$col1=strpos($newarray[0][1],"@");
			$col2=strpos($newarray[0][2],"@");
			$col3=strpos($newarray[0][3],"@");
			$col4=strpos($newarray[0][4],"@");
			$col5=strpos($newarray[0][5],"@");

 			if(!$col0 AND !$col1 AND !$col2 AND !$col3 AND !$col4 AND !$col5)
			{
				$col0=strpos($newarray[1][0],"@");
				$col1=strpos($newarray[1][1],"@");
				$col2=strpos($newarray[1][2],"@");
				$col3=strpos($newarray[1][3],"@");
				$col4=strpos($newarray[1][4],"@");
				$col5=strpos($newarray[1][5],"@");
				//echo $line[1];
				if(!$col0 AND !$col1 AND !$col2 AND !$col3 AND !$col4 AND !$col5)
				{
					$err = true;
					$msg="";
					JError::raiseWarning(100, JText::_('CC_ERROR_NOT_CORRECT_FORMAT'));
					$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import',$msg);
				}
				else
				{
					if($col0)
					{
						$name_field=1;
						$email_field=0;
					}
					if($col1)
					{
						$name_field=0;
						$email_field=1;
					}
					if($col2)
					{
						$name_field=1;
						$email_field=2;
					}
					if($col3)
					{
						$name_field=2;
						$email_field=3;
					}
					if($col4)
					{
						$name_field=3;
						$email_field=4;
					}
					if($col5)
					{
						$name_field=4;
						$email_field=5;
					}
				}
			}
			else
			{
					if($col0)
					{
						$name_field=1;
						$email_field=0;
					}
					if($col1)
					{
						$name_field=0;
						$email_field=1;
					}
					if($col2)
					{
						$name_field=1;
						$email_field=2;
					}
					if($col3)
					{
						$name_field=2;
						$email_field=3;
					}
					if($col4)
					{
						$name_field=3;
						$email_field=4;
					}
					if($col5)
					{
						$name_field=4;
						$email_field=5;
					}
			}
			if($err!="true")
			{
				foreach($newarray as $lines)
				{
					$this->InsertRecordCsv($email_field,$name_field,$lines);
				}
			}
		}
		else
		{
			$msg="Please check text file format!";
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg);
		}
		$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg);
	}
	// import csv coding
	function importcsv()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		ini_set('max_execution_time', 500);
		ini_set('memory_limit','256M');
		$import_file = JRequest::getVar( 'importfile', '', 'files', 'array' );
		$deletesubsfromfile = JRequest::getVar( 'deletesubsfromfile', 'post', 'string' );
		$database =& JFactory::getDBO();
		$err=false;
		if($deletesubsfromfile=="deletesubsfromfile")
		{
			$query = "DELETE  FROM #__ccnewsletter_subscribers";
			$database->setQuery( $query );
			$database->query();
		}
		$msg = JText::_( 'CC_IMPORT_SUCCESSFULLY' );
		$csvfile=$import_file['tmp_name'];
		jimport('joomla.filesystem.file');
		$format = strtolower(JFile::getExt($import_file['name']));
		if($csvfile=="")
		{
			JError::raiseWarning(100, JText::_('CC_NO_FILE_WARNING'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
	 	elseif($format != "csv")
		{
			$err = true;
			JError::raiseWarning(100, JText::_('CC_ERROR_NOT_CORRECT_FORMAT'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
		else
		{
			if(!file_exists($csvfile))
			{
			    echo "File not found. Make sure you specified the correct path.\n";
			    exit;
			}
		}
		$file = fopen($csvfile,"r");
		if(!$file)
		{
		    echo "Error opening data file.\n";
		    exit;
		}
		$size = filesize($csvfile);
		if(!$size)
		{
		    echo "File is empty.\n";
		    exit;
		}
		$line = fgetcsv($file);

		if(count($line)>="1" AND count($line)<="7")
		{

			$col0=strpos($line[0],"@");
			$col1=strpos($line[1],"@");
			$col2=strpos($line[2],"@");
			$col3=strpos($line[3],"@");
			$col4=strpos($line[4],"@");
			$col5=@strpos($line[5],"@");

			if(!$col0 AND !$col1 AND !$col2 AND !$col3 AND !$col4 AND !$col5)
			{
				$line = fgetcsv($file);
				$col0=strpos($line[0],"@");
				$col1=strpos($line[1],"@");
				$col2=strpos($line[2],"@");
				$col3=strpos($line[3],"@");
				$col4=strpos($line[4],"@");
				$col5=@strpos($line[5],"@");
				//echo $line[1];
				if(!$col0 AND !$col1 AND !$col2 AND !$col3 AND !$col4 AND !$col5)
				{
					$err = true;
					$msg="";
					JError::raiseWarning(100, JText::_('CC_ERROR_NOT_CORRECT_FORMAT'));
					$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import',$msg);
				}
				else
				{
					if($col0)
					{
						$name_field=1;
						$email_field=0;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col1)
					{
						$name_field=0;
						$email_field=1;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col2)
					{
						$name_field=1;
						$email_field=2;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col3)
					{
						$name_field=2;
						$email_field=3;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col4)
					{
						$name_field=3;
						$email_field=4;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col5)
					{
						$name_field=4;
						$email_field=5;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
				}
			}
			else
			{
					if($col0)
					{
						$name_field=1;
						$email_field=0;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col1)
					{
						$name_field=0;
						$email_field=1;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col2)
					{
						$name_field=1;
						$email_field=2;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col3)
					{
						$name_field=2;
						$email_field=3;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col4)
					{
						$name_field=3;
						$email_field=4;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
					if($col5)
					{
						$name_field=4;
						$email_field=5;
						$this->InsertRecordCsv($email_field,$name_field,$line);
					}
			}
			if($err!="true")
			{
				while($line = fgetcsv($file))
				{
					$this->InsertRecordCsv($email_field,$name_field,$line);
				}
			}
		}
		else
		{
			$msg="Please check csv column format!";
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg);
		}
		$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg);
	}
	function InsertRecordCsv($email_field,$name_field,$line)
	{
		$database =& JFactory::getDBO();
		$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$database->quote($line[$email_field]);
		$database->setquery($query);
		$count = $database->loadResult();
		if($count<1)
		{
			if(count($line)=="3")
			{
				$line0=$line[$name_field];
				$line1=$line[$email_field];
				$line3=$line[2];
				$line2=$line[3];
				$line4=$line[4];
				$line5=@$line[5];
				if(trim($line0)=="")
					$line0=" ";
				if(trim($line1)=="")
					$line1="NULL";
				if(trim($line2)=="")
					$line2="0";
				if(trim($line3)=="")
					$line3="1";
				if(trim($line4)=="")
					$line4="0000-00-00 00:00:00";
				if(trim($line5)=="")
					$line5="NULL";
				if($line1!="NULL")
				{
					$query = "INSERT into #__ccnewsletter_subscribers (`name`, `email`,`plainText`,`enabled`,`sdate`,`lastSentNewsletter`) values(".$database->quote($line0).", ".$database->quote($line1).",".$line2.",".$line3.",".$database->quote($line4).",$line5)";
					$database->setQuery( $query );
					$database->query();
				}
			}
			elseif(count($line)=="6" or count($line)=="5" or count($line)=="2" or count($line)=="1")
			{
				$line0=$line[$name_field];
				$line1=$line[$email_field];
				$line2=$line[2];
				$line3=$line[3];
				$line4=$line[4];
				$line5=@$line[5];
				if(trim($line0)=="")
					$line0=" ";
				if(trim($line1)=="")
					$line1="NULL";
				if(trim($line2)=="")
					$line2="0";
				if(trim($line3)=="")
					$line3="1";
				if(trim($line4)=="")
					$line4="0000-00-00 00:00:00";
				if(trim($line5)=="")
					$line5="NULL";
				if($line1!="NULL")
				{
					$query = "INSERT into #__ccnewsletter_subscribers (`name`, `email`,`plainText`,`enabled`,`sdate`,`lastSentNewsletter`) values(".$database->quote($line0).", ".$database->quote($line1).",".$line2.",".$line3.",".$database->quote($line4).",$line5)";
					$database->setQuery( $query );
					$database->query();
				}
			}
			else
			{
				$err = true;
				JError::raiseWarning(100, JText::_('CC_ERROR_NOT_CORRECT_FORMAT'));
				$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
			}
		}
	}
	function importxml()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		global $mainframe;
		$post	= JRequest::get( 'post' );
		$import_file = JRequest::getVar( 'importfile', '', 'files', 'array' );
		$deletesubsfromfile = JRequest::getVar( 'deletesubsfromfile', 'post', 'string' );
		$xmlfile = $import_file['tmp_name'];
		jimport('joomla.filesystem.file');
		$format = strtolower(JFile::getExt($import_file['name']));
		if($xmlfile=="")
		{
			JError::raiseWarning(100, JText::_('CC_NO_FILE_WARNING'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
		elseif($format != "xml")
		{
			$err = true;
			JError::raiseWarning(100, JText::_('CC_ERROR_NOT_CORRECT_FORMAT'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
		else
		{
		$database =& JFactory::getDBO();
		$xml = new JSimpleXML;
		$csvfile = $import_file['tmp_name'];
  		$xml->loadFile($csvfile);
  		if($deletesubsfromfile=="deletesubsfromfile")
		{
				$query = "DELETE  FROM #__ccnewsletter_subscribers";
				$database->setQuery( $query );
				$database->query();
		}
 		$xml = $xml->document;
		$i = 0;

		foreach( $xml->subscriber as $file )
		{
		/*	echo $xml->subscriber[$i]->name[0]->data();
			echo " - " . $xml->subscriber[$i]->email[0]->data();
			echo " - " . $xml->subscriber[$i]->confirmed[0]->data();
			echo " - " . $xml->subscriber[$i]->subscribe_date[0]->data();

			echo "<br/>";
		*/

			$query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email='".$xml->subscriber[$i]->email[0]->data()."'";
			$database->setquery($query);
			$count = $database->loadResult();
			if($count<1)
			{
				$query = "INSERT INTO #__ccnewsletter_subscribers values ('', ".$database->Quote($xml->subscriber[$i]->name[0]->data()).", ".$database->Quote($xml->subscriber[$i]->email[0]->data()).", '0', ".$database->Quote($xml->subscriber[$i]->confirmed[0]->data()).", ".$database->Quote($xml->subscriber[$i]->subscribe_date[0]->data()).", '')";
				$database->setQuery( $query );
				$database->query();
				$msg = JText::_( 'CC_IMPORT_SUCCESSFULLY' );
			}
			$i++;
	 	}
		$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg );
		}
	}

	function importacajoomacsv()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$fieldseparator = ",";
		$lineseparator = "\n";
		$database =& JFactory::getDBO();
		$post	= JRequest::get( 'post' );
		$import_file = JRequest::getVar( 'importfile', '', 'files', 'array' );
		$deletesubsfromfile = JRequest::getVar( 'deletesubsfromfile', 'post', 'string' );
		$csvfile = $import_file['tmp_name'];
		jimport('joomla.filesystem.file');
		$addauto = 0;
		$save = 0;
		$outputfile = "output.sql";
		$format = strtolower(JFile::getExt($import_file['name']));
		if($csvfile=="")
		{
			JError::raiseWarning(100, JText::_('CC_NO_FILE_WARNING'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
	 	elseif($format != "csv")
		{
			$err = true;
			JError::raiseWarning(100, JText::_('CC_ERROR_NOT_CORRECT_FORMAT'));
			$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import');
		}
		else
		{

			if(!file_exists($csvfile))
			{
			    echo "File not found. Make sure you specified the correct path.\n";
			    exit;
			}

			$file = fopen($csvfile,"r");
			if(!$file)
			{
			    echo "Error opening data file.\n";
			    exit;
			}
			$size = filesize($csvfile);
			if(!$size)
			{
			    echo "File is empty.\n";
			    exit;
			}
			$csvcontent = fread($file,$size);
			fclose($file);

			//$import = file_get_contents($path . $filename);
			$import = str_replace(array("\r\n","\r"),"\n",$csvcontent);
			$array = explode("\n", $import);
			if($deletesubsfromfile=="deletesubsfromfile")
			{
				if (sizeof($array) > 0)
				{
					foreach ($array AS $row)
					{
						$row = trim($row);
						$values = explode(',', $row);
						if(count($values) == 4)
						{
						$query = "DELETE  FROM #__ccnewsletter_subscribers";
						$database->setQuery( $query );
						$database->query();
						}
					}
				}
			}

			if (sizeof($array) > 0)
			{
				 	foreach ($array AS $row)
					{
						$row = trim($row);
						if (empty($row))
						{
							continue;
						}
						$values = explode(',', $row);
						if(count($values) != 4)
						{
							JError::raiseWarning(100, JText::_('CC_INVALID_FORMAT'));
							$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import' );
							return;
						}
						$values[0] = trim($values[0]);
						$values[1] = trim($values[1]);

						echo $values[0];
						echo $values[1];
						if ( isset($values[1]) )
						{
							$valid = ccNewsletterControllerimport::validEmail($values[1]);
							if (!$valid) {
								continue;
							}
							else
							{
					 			 $subscribername = addslashes($values[0]);
					 			 $subscriberemail = $values[1];
					 			 $subscriberreceive_html  = (empty($values[2])) ? '0' : '1';
					 			 $subscriberconfirmed = (empty($values[3])) ? '0' : '1';
					 			 $date = date("Y-m-d H:i:s");
					 			 $query = "SELECT count(*) FROM #__ccnewsletter_subscribers WHERE email=".$database->Quote($subscriberemail)."";
								 $database->setquery($query);
								 $count = $database->loadResult();
								if($count<1)
								{
						 			 $query = "INSERT INTO `#__ccnewsletter_subscribers` (`id`,`name` , `email`, `plainText` , `enabled`, `sdate`)  VALUES ('',".$database->Quote($subscribername).",".$database->Quote($subscriberemail).",".$database->Quote($subscriberreceive_html).",".$database->Quote($subscriberconfirmed)." , ".$database->Quote($date).")";
									$database->setQuery($query);
									$database->query();
									$lastid = $database->insertid();
								}
							}
						}
					}
					if($lastid)
					{
						$msg = JText::_( 'CC_IMPORT_SUCCESSFULLY' );
						$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg );
					}
					else
					{
						$msg = JText::_( 'CC_IMPORT_ERROR' );
						$this->setRedirect( 'index.php?option=com_ccnewsletter&controller=import', $msg );
					}
				}
			}
		}
	 function validEmail($email)
	 {
		return preg_match("/^[a-z0-9]([a-z0-9_\-\.])*@([a-z0-9\-]+\.)+[a-z]{2,7}$/i", $email);
	 }
}
?>
