<?php
/**
 * Class Campaign
 *
 * Common interface for all third party applications related with campaign.
 * List of third party applications included :
 * 1) MailChimp
 * 2) ExactTarget
 * 3) ConstantContact
 * 4) CampaignMonitor
 *
 * @todo exactTarget functionality not tested
 * @author Nikhil Ben Kuruvilla <nikhil_ben@ispg.in>
 * @package Oorjit Products
 * @license Please read 'copyright.txt', proprietary License
 * @copyright Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.
 * @version Campaign.class.PHP, v 1.0 2011/06/14 20:52:11 
 */
class Campaign {

	private $campaign;
	private $apiKey;
	private $userName;
	private $password;
	private $apiClientID;
	private $confirmationEmail;
	private $wsdl = "https://webservice.exacttarget.com/etframework.wsdl";
	private $partnerAPI = "http://exacttarget.com/wsdl/partnerAPI";
	private $mailChimpSite = 'http://mailchimp.com';
	private $mailChimp = FALSE;
	private $constantContact = FALSE;
	private $exactTarget = FALSE;
	private $campaignMonitor = FALSE;

	/**
	 * function __construct
	 *
	 * @param array $settings
	 */
	public function __construct($settings) {
		$this -> apiKey = $settings['api_key'];
		$this -> userName = $settings['user_name'];
		$this -> password = $settings['password'];
		$this -> campaign = $settings['campaign'];
		$this -> apiClientID = $settings['api_client_id'];
		$this -> confirmationEmail = isset($settings['confirmation_email']) ? $settings['confirmation_email']  : '';
		$this -> newsletterListID = $settings['newsletter_list_id'];
		$this -> setObjects();
	}

	/**
	 * function setObjects
	 *
	 * Creates objects..
	 */
	private function setObjects() {
		if ($this -> campaign == "mail_chimp") {
			$this -> mailChimp = TRUE;
			$this -> setCampaign();
			$this -> objMailChimp = new MCAPI($this -> apiKey);
		} elseif ($this -> campaign == "constant_contact") {
			$this -> constantContact = TRUE;
			$this -> setCampaign();
			$this -> objConstantContact = new cc($this -> userName, $this -> password, $this -> apiKey);
			$this -> objConstantContactUtility = new CC_Campaign($this -> userName, $this -> password, $this -> apiKey);
		} elseif ($this -> campaign == "exact_target") {
			$this -> exactTarget = TRUE;
			$this -> setCampaign();
			$client = new ExactTargetSoapClient($this -> wsdl, array('trace' => 1));
		} elseif ($this -> campaign == "campaign_monitor") {
			$this -> campaignMonitor = TRUE;
			$this -> setCampaign();
			$this -> objCampaignMonitorList = new CS_REST_Clients($this -> apiClientID, $this -> apiKey);
		}
	}

	/**
	 * function setCampaign
	 *
	 * @access private
	 * @return include required class file
	 */
	private function setCampaign() {
		if ($this -> mailChimp == TRUE) {
			$mailer_class_file = __LIBRARY_PATH . '/campaign/mail_chimp/MCAPI.class.php';
		} elseif ($this -> constantContact == TRUE) {
			$mailer_class_file = __LIBRARY_PATH . '/campaign/constant_contact/cc_class.php';
			$mailer_class_file_2 = __LIBRARY_PATH . '/campaign/constant_contact/cc_utility_class.php';
			if (file_exists($mailer_class_file_2)) {
				include_once ($mailer_class_file_2);
			}
		} elseif ($this -> campaignMonitor == TRUE) {
			$mailer_class_file = __LIBRARY_PATH . '/campaign/campaign_monitor/csrest_clients.php';
			$mailer_class_file_2 = __LIBRARY_PATH . '/campaign/campaign_monitor/csrest_subscribers.php';
			$mailer_class_file_3 = __LIBRARY_PATH . '/campaign/campaign_monitor/csrest_lists.php';
			$mailer_class_file_4 = __LIBRARY_PATH . '/campaign/campaign_monitor/csrest_campaigns.php';
// EXTD MAIL START			
			$mailer_class_file_5 = __LIBRARY_PATH . '/campaign/campaign_monitor/csrest_segments.php';
// EXTD MAIL END			
			if (file_exists($mailer_class_file_2)) {
				include_once ($mailer_class_file_2);
			}
			if (file_exists($mailer_class_file_3)) {
				include_once ($mailer_class_file_3);
			}
			if (file_exists($mailer_class_file_4)) {
				include_once ($mailer_class_file_4);
			}
// EXTD MAIL START		
			if (file_exists($mailer_class_file_5)) {
				include_once ($mailer_class_file_5);
			}
// EXTD MAIL END						
		} elseif ($this -> exactTarget == TRUE) {
			$mailer_class_file = __LIBRARY_PATH . '/campaign/exact_target/exacttarget_soap_client.php';
		}

		if (file_exists($mailer_class_file)) {
			include_once ($mailer_class_file);
		} else {
			return false;
		}
	}

	/**
	 * function subscribe
	 *
	 * Add email to a particular list upon subscription
	 * by the user. A confirmation mail will be sent upon accepting
	 * the user will be succesfully added to the list.
	 *
	 * @category MailChimp
	 * @category ConstantContact
	 * @category CampaignMonitor
	 * @category ExactTarget
	 * @param integer $list_id, id of the email list
	 * @param varchar $email, email of the subscriber
	 * @param array $param
	 * @return bool True/False
	 */
	public function subscribe($list_id, $email, $param = '') 
	{
		if ($this -> mailChimp == TRUE) 
		{
// EXTD MAIL START			
			if(count($param['subcribedTypes']))
			{
				$subcribedTypes		=	implode(',',$param['subcribedTypes']);
				return $this->objMailChimp->listSubscribe($list_id, $email, array(
																				 'GROUPINGS' =>	array(
																									 array(
																										  'name'=>'Product Types',
																										  'groups'=>$subcribedTypes
																										  ),
																										  array(
																										  'name'=>'Language',
																										  'groups'=>$param['language']
																										  )
																									 )
																				  ));
			}
			else
			{
				//if(count($param['language']) && $list_id!=$this->newsletterListID)
				if(count($param['language']))
				{
				return 	 $this->objMailChimp->listSubscribe($list_id, $email, array(
																				 'GROUPINGS' =>	array(
																										  array(
																										  'name'=>'Language',
																										  'groups'=>$param['language']
																										  )
																									 )
																				  ));
				}
				else
				{
				 return $this->objMailChimp->listSubscribe($list_id, $email,array(website => $this->mailChimpSite));
				}
				
			}
// EXTD MAIL END	

		
			
		} 
		elseif ($this -> constantContact == TRUE) 
		{
			return $this -> objConstantContact -> create_contact($email, $list_id);
		} 
		elseif ($this -> campaignMonitor == TRUE) 
		{
// EXTD MAIL START			
			$this->objCampaignMonitorSubscribe = new CS_REST_Subscribers($list_id, $this -> apiKey);
			if(count($param['subcribedTypes']) || count($param['language']))
			{ 
			if(count($param['subcribedTypes']))
			{
				foreach ($param['subcribedTypes'] as $subcribedType) 
				{
					$customFields[]		=	array(
												  'Key' => 'ProductType',
												  'Value' => $subcribedType
												  );
				}
			}
			if(count($param['language']))
			{
				$customFields[]		=	array(
												  'Key' => 'Language',
												  'Value' => $param['language']
												  );	
			}
				
				
				
				return $this -> objCampaignMonitorSubscribe -> add(array('EmailAddress' => $email, 'Name' => NULL, 'CustomFields' => $customFields, 'Resubscribe' => true));
			}
			else
			{
				return $this -> objCampaignMonitorSubscribe -> add(array('EmailAddress' => $email, 'Name' => NULL, 'Resubscribe' => true));
			}
// EXTD MAIL END				
			
		} elseif ($this -> exactTarget == TRUE) {
			try {
				$client -> username = $this -> userName;
				$client -> password = $this -> password;

				$subscriber = new ExactTarget_Subscriber();
				$subscriber -> EmailAddress = $email;
				$subscriber -> SubscriberKey = $email;

				$cl = new ExactTarget_ClientID();
				$cl -> ID = 123;
				$subscriber -> Client = $cl;
				$subscriber -> Lists = array();

				$list = new ExactTarget_SubscriberList();
				$list -> ID = "12345";

				$so = new ExactTarget_SaveOption();
				$so -> PropertyName = "*";
				$so -> SaveAction = ExactTarget_SaveAction::UpdateAdd;
				$soe = new SoapVar($so, SOAP_ENC_OBJECT, 'SaveOption', $this -> partnerAPI);
				$opts = new ExactTarget_UpdateOptions();
				$opts -> SaveOptions = array($soe);
				$object = new SoapVar($subscriber, SOAP_ENC_OBJECT, 'Subscriber', $this -> partnerAPI);

				$request = new ExactTarget_CreateRequest();
				$request -> Options = $opts;
				$request -> Objects = array($object);
				var_dump($request);
				$results = $client -> Create($request);
				return $results;
			} catch (SoapFault $e) {
				return $e;
			}
		} else {
			return FALSE;
		}
	}

	/**
	 * function getList
	 *
	 * Get the whole list..
	 *
	 * @category MailChimp
	 * @category ConstantContact
	 * @category CampaignMonitor
	 * @category ExactTarget
	 * @return array campaign list
	 */
	public function getList() {
		if ($this -> mailChimp == TRUE) {
			return $this -> objMailChimp -> lists();
		} elseif ($this -> constantContact == TRUE) {
			return $this -> objConstantContact -> getList();
		} elseif ($this -> campaignMonitor == TRUE) {
			return $this -> objCampaignMonitorList -> get_lists();
		} elseif ($this -> exactTarget == TRUE) {
			try {

				/* Set username and password here */
				$client -> username = $this -> userName;
				$client -> password = $this -> password;

				$rr = new ExactTarget_RetrieveRequest();
				$rr -> ObjectType = "List";
				$rr -> Properties = array();
				$rr -> Properties[] = "ID";
				$rr -> Properties[] = "List.ListName";
				$rr -> Options = NULL;

				$rrm = new ExactTarget_RetrieveRequestMsg();
				$rrm -> RetrieveRequest = $rr;

				$results = $client -> Retrieve($rrm);
				return $results;
			} catch (SoapFault $e) {
				return $e;
			}
		}
	}

	/**
	 * function createList
	 *
	 * Creates a list based on city..
	 *
	 * @package constantContact
	 * @package campaignMonitor
	 * @return listID
	 */
	public function createList($listName, $param = '') {
		if ($this -> campaignMonitor == TRUE) {
			$this -> objCampaignCreateList = new CS_REST_Lists(NULL, $this->apiKey);
			
			return $this ->objCampaignCreateList->create($param['clientID'], array('Title' => $listName, 'UnsubscribePage' => NULL, 'ConfirmedOptIn' => false, 'ConfirmationSuccessPage' => NULL));
			
		} elseif ($this -> constantContact == TRUE) {
			return $this -> objConstantContact -> create_list($listName);
		}
	}

	/**
	 * function updateList
	 *
	 * Updates a list based on listID..
	 *
	 * @package constantContact
	 * @package campaignMonitor
	 * @return listID
	 */
	public function updateList($listID, $listName) {
		if ($this -> campaignMonitor == TRUE) {
			$this -> objCampaignCreateList = new CS_REST_Lists($listID, $this -> apiKey);
			return $this -> objCampaignCreateList -> update(array('Title' => $listName, 'UnsubscribePage' => NULL, 'ConfirmedOptIn' => false, 'ConfirmationSuccessPage' => NULL));
		} elseif ($this -> constantContact == TRUE) {
			return $this -> objConstantContact -> update_list($listID, $listName);
		}
	}

	/**
	 * function unsubscribe
	 *
	 * Unsubscribe user from a particular list
	 *
	 * @package mailChimp
	 * @package campaignMonitor
	 * @param string $listID
	 * @param string $email
	 */
	public function unsubscribe($email, $listID = '') {
		if ($this -> mailChimp == TRUE) {
			return $this -> objMailChimp -> listUnsubscribe($listID, $email);
		} elseif ($this -> campaignMonitor == TRUE) {
			$this -> wrap = new CS_REST_Subscribers($listID, $this -> apiKey);
			return $this -> wrap -> unsubscribe($email);
		} elseif ($this -> constantContact == TRUE) {
			$this -> objConstantContactManage = new CC_Contact($this -> userName, $this -> password, $this -> apiKey);
			return $this -> objConstantContactManage -> removeSubscriber($email);
		}
	}

	/**
	 * function createCampaign
	 *
	 * Creates a new campaign...
	 *
	 * @package mailChimp
	 * @package constantContact
	 * @package CampaignMonitor
	 * @param array $options
	 * @return string campaignID
	 */
	public function createCampaign($options) 
	{
		// some services has 100 char limit for subject & title
		$options['title']		= date('y-m-d H:i:s')." : ". $options['title'];
		$options['subject'] 	= substr($options['subject'], 0, 78);
		$options['title'] 		= substr($options['title'], 0, 78);
		
		
		
		if ($this->mailChimp == TRUE) 
		{
		    foreach($options['list_id'] as $listID)
			{
				$seg 					= array();
				if($options['productTypeKey']!='' && $options['language']!='')
				{
				$resInterestGroups		= $this->objMailChimp->listInterestGroupings($listID);
				if(!$this->objMailChimp->errorCode && count($resInterestGroups) > 0 )
				{
					
					foreach($resInterestGroups as $interestGroup)
					{
						if($interestGroup['name']=='Product Types')
						{
							$interestGroupId			= $interestGroup['id'];	
						}
						if($interestGroup['name']=='Language')
						{
							$interestLanguageGroupId			= $interestGroup['id'];	
						}
					}
					$seg['match']	 		= 'all';
					$seg['conditions'][0]   = array(
													'field'=>'interests-'.$interestGroupId,
													'op'=>'one',
													'value'=>$options['productTypeKey']
													);
					$seg['conditions'][1]   = array(
													'field'=>'interests-'.$interestLanguageGroupId,
													'op'=>'one',
													'value'=>$options['language']
													);
													
				}
				
				}
				else if($options['productTypeKey']=='' && $options['language']!='' && $options['language']!='all')
				{
				$resInterestGroups		= $this->objMailChimp->listInterestGroupings($listID);
				if(!$this->objMailChimp->errorCode && count($resInterestGroups) > 0 )
				{
					
					foreach($resInterestGroups as $interestGroup)
					{
						if($interestGroup['name']=='Language')
						{
							$interestLanguageGroupId			= $interestGroup['id'];	
						}
					}
					$seg['match']	 		= 'all';
					$seg['conditions'][0]   = array(
													'field'=>'interests-'.$interestLanguageGroupId,
													'op'=>'one',
													'value'=>$options['language']
													);
													
				}
				}
				if(count($seg)>0)
				{									
					$result 				= $this->objMailChimp->campaignCreate("regular",  array(
																									'list_id' 		=> $listID, 
																									'subject' 		=> $options['subject'] . '...', 
																									'from_email' 	=> $options['from_email'], 
																									'from_name' 	=> $options['from_name'], 
																									'to_email' 		=> $options['to_email'], 
																									'title' 		=> $options['title'] . '...'
																									), 
																									array(
																										  'html' 	=> $options['content'], 
																										  'text' 	=> $options['content']
																										  ),
																									$seg);	
																									
				}
				else
				{
					$result 				= $this->objMailChimp->campaignCreate("regular",  array(
																									'list_id' 		=> $listID, 
																									'subject' 		=> $options['subject'] . '...', 
																									'from_email' 	=> $options['from_email'], 
																									'from_name' 	=> $options['from_name'], 
																									'to_email' 		=> $options['to_email'], 
																									'title' 		=> $options['title'] . '...'
																									), 
																									array(
																										  'html' 	=> $options['content'], 
																										  'text' 	=> $options['content']
				
																										  ));		
				}
				
			}
																																						
		} 
		elseif ($this -> constantContact == TRUE) 
		{
			$options['content'] = '<html><title></title></head><body>'.$options['content'].'</body></html>';
			$listID = $options['list_id'][0];
			foreach($options['list_id'] as $listID)
			{
				$listIDArray[] = "http://api.constantcontact.com/ws/customers/" . $this -> userName . "/lists/" . $listID;
			}
			// Default list id for constant contact = 1
			if ($listID == NULL) 
			{ 
				$listID = 1;
			}
			$verifiedEmailAddresses = $this -> objConstantContactUtility -> listVerifiedAddresses();
			$campaign = array();
			$campaign["cmp_name"] = $options['title'];
			$campaign["cmp_type"] = "";
			$campaign["cmp_status"] = "";
			$campaign["cmp_date"] = "";
			$campaign["cmp_subject"] = $options['subject'];
			$campaign["cmp_from_name"] = $options['from_name'];
			$campaign["cmp_from_email"] = $verifiedEmailAddresses['email'] . "|".$verifiedEmailAddresses['url'];
			$campaign["cmp_reply_email"] = $verifiedEmailAddresses['email'] . "|".$verifiedEmailAddresses['url'];
			$campaign["cmp_perm_reminder"] = "NO";
			$campaign["cmp_txt_reminder"] = "You're receiving this email because of your relationship with [COMPANY NAME]. Please confirm your continued interest in receiving email from us.";
			$campaign["cmp_as_webpage"] = "YES";
			$campaign["cmp_as_webtxt"] = "Having trouble viewing this email?";
			$campaign["cmp_as_weblink"] = "Click here";
			$campaign["cmp_grt_sal"] = "Dear";
			$campaign["cmp_grt_name"] = "FirstName";
			$campaign["cmp_grt_str"] = "Greetings!";
			$campaign["cmp_org_name"] = $options['from_name'];
			$campaign["cmp_org_addr1"] = $options['from_name'];
			$campaign["cmp_org_addr2"] = $options['address_2'];
			$campaign["cmp_org_addr3"] = "";
			if($options['city']=='')
			{
				$campaign["cmp_org_city"] = "Test City";
			}
			else
			{
				$campaign["cmp_org_city"] = $options['city'];
			}
			$campaign["org_state_us"] = "";
			$campaign["org_state"] = $options['state'];
			$campaign["org_country"] = "ca";
			$campaign["org_zip"] = $options['zip'];
			$campaign["cmp_forward"] = "YES";
			$campaign["cmp_fwd_email"] = "Forward email";
			$campaign["cmp_subscribe"] = "YES";
			$campaign["cmp_sub_link"] = "Subscribe me!";
			$campaign["cmp_mail_type"] = "HTML";
			$campaign["cmp_html_body"] = $options['content'];
			$campaign["cmp_text_body"] = $options['text'];
			$campaign["cmp_style_sheet"] = "";
			$campaign["lists"] = $listIDArray;

			$campaign_id = null;
			//header("Content-Type: text/xml;charset=UTF-8");
			$campaignXML = $this -> objConstantContactUtility -> createXmlOptimized($campaign_id, $campaign);
			//echo $campaignXML;
			/*
			$myFile = "public/test.txt";
			$fh = fopen($myFile, 'w') or die("can't open file");
			fwrite($fh, $campaignXML);
			fclose($fh); exit;
			*/						
			$result = $this -> objConstantContactUtility -> addCampaign($campaignXML);
			
		} 
		elseif($this->campaignMonitor == TRUE) 
		{
			$segmentsIds			= array();
		    foreach($options['list_id'] as $listID)
			{
				$objLists 						= new CS_REST_Lists($listID, $this->apiKey);
				$segments 						= $objLists->get_segments();
				
				if($listID==$this->newsletterListID)
				{
					if($options['language']!='all')
					{
					foreach ($segments->response as $responce)
					{
					if($responce->Title == $options['language'])
					{
						$segmentsIds[0]				= $responce->SegmentID;
					}
					}
					}
				}
				else
				{
				foreach ($segments->response as $responce)
				{
					if($responce->Title == $options['productTypeKey']."-".$options['language'])
					{
						$segmentsIds[]				= $responce->SegmentID;
					}				
				}
				}
				
				
			}
			$this->objCampaignMonitor 		= new CS_REST_Campaigns(NULL, $this->apiKey);
			if(count($segmentsIds) == 0)
			{
				$result 						= $this->objCampaignMonitor->create($this->apiClientID, array(
																												'Subject' 	=> $options['subject'], 
																												'Name' 		=> $options['title'], 
																												'FromName' 	=> $options['from_name'], 
																												'FromEmail' => $options['from_email'], 
																												'ReplyTo' 	=> $options['reply_email'], 
																												'HtmlUrl' 	=> $options['html_url'], 
																												'TextUrl' 	=> $options['text_url'], 
																												'ListIDs' 	=> $options['list_id']
																												));
			}
			else
			{
				
				
				$result 						= $this->objCampaignMonitor->create($this->apiClientID, array(
																												'Subject' 	=> $options['subject'], 
																												'Name' 		=> $options['title'], 
																												'FromName' 	=> $options['from_name'], 
																												'FromEmail' => $options['from_email'], 
																												'ReplyTo' 	=> $options['reply_email'], 
																												'HtmlUrl' 	=> $options['html_url'], 
																												'TextUrl' 	=> $options['text_url'], 
																												'SegmentIDs'=> $segmentsIds 
																												));
																												
																												
			}																												
		}
		$return 				= $this->processResult($result);
		return $return;
	}

	/**
	 * function scheduleCampaign
	 *
	 * Schedules an existing campaign...
	 *
	 * @subpackage mailChimp
	 * @subpackage constantContact
	 * @subpackage campaignMonitor
	 * @param string $campaign_id
	 * @param string $schedule_time
	 * @return boolean true on success
	 */
	public function scheduleCampaign($campaign_id, $schedule_time, $timeZone = '') {
		if ($this -> mailChimp == TRUE) {
			$schedule_time = date('Y-m-d H:i:s', strtotime($this -> processTimeZone($timeZone),strtotime($schedule_time)));
			$result = $this -> objMailChimp -> campaignSchedule($campaign_id, $schedule_time);
		} elseif ($this -> campaignMonitor == TRUE) {
			$this -> objCampaignMonitor = new CS_REST_Campaigns($campaign_id, $this -> apiKey);
			$result = $this -> objCampaignMonitor -> send(array('ConfirmationEmail' => $this -> confirmationEmail, 'SendDate' => $schedule_time));
		} elseif ($this -> constantContact == TRUE) {

			unset($this -> objConstantContact);
			$mailer_class_file_3 = __LIBRARY_PATH . '/campaign/constant_contact/Schedule.php';

			include_once ($mailer_class_file_3);
			
			$schedule_time = date('Y-m-d H:i:s.u', strtotime($this -> processTimeZone($timeZone),strtotime($schedule_time)));
			$schedule_time=substr_replace($schedule_time,"T",10,1);
			$schedule_time=substr_replace($schedule_time,"Z",23,3);
			
			$this -> ObjSchedule = new Schedule();
			$result = $this -> ObjSchedule -> scheduleCampaign($campaign_id, $schedule_time, array('userName' => $this -> userName, 'password' => $this -> password, 'apiKey' => $this -> apiKey));

		}
		$return = $this -> processResult($result);
		return $return;
	}

	/**
	 * function deleteList
	 *
	 * Delete an existing list..
	 * NOT CURRENTLY USED IN THIS APPLICATION
	 *
	 * @package campaignMonitor
	 * @param string $listID
	 */
	public function deleteList($listID) {
		if ($this -> campaignMonitor == TRUE) {
			$this -> wrap = new CS_REST_Lists($listID, $this -> apiKey);
			return $result = $this -> wrap -> delete();
		}
	}

	/**
	 * function createNewsLetter
	 *
	 * NOTE : DEPRECATED, NOT CURRENTLY USED (USE createCampaign() INSTEAD)
	 *
	 * @package campaignMonitor
	 * @param array $options
	 * @return type
	 */
	public function createNewsLetter($options) {
		if ($this -> campaignMonitor == TRUE) {
			//commented for the following for sending newsletter only to newsletter subscribers insted of all city subscribers.
			/*$listID = $this -> getList();
			$i = 0;
			foreach ($listID->response as $campaignListID) {
				$options['list_id'][$i] = $campaignListID -> ListID;
				$i++;
			}*/
			return $this -> createCampaign($options);
		}
	}

	/**
	 * getUnsubscriberList
	 * 
	 * Get unsubscribed users for synchronisation. Only supports campaignMonitor and
	 * mailChimp. constantContact as of now doesnt have featyre to get unsubscribed users list.
	 * 
	 * @param string $campaignListID
	 * @return array $result
	 */
	public function getUnsubscriberList($campaignListID) {
		if ($this -> campaignMonitor == TRUE) {
			$this -> wrap = new CS_REST_Lists($campaignListID, $this -> apiKey);
			$dateLimit = date('Y-m-d', strtotime('-2 days'));
			$result = $this -> wrap -> get_unsubscribed_subscribers($dateLimit);
		} elseif ($this -> mailChimp == TRUE) {
			$result = $this -> objMailChimp -> listMembers($campaignListID, 'unsubscribed');
		}
		return $result;
	}
	
		/**
	 * getsubscriberList
	 * 
	 * Get unsubscribed users for synchronisation. Only supports campaignMonitor and
	 * mailChimp. constantContact as of now doesnt have featyre to get unsubscribed users list.
	 * 
	 * @param string $campaignListID
	 * @return array $result
	 */
	public function getSubscriberList($campaignListID) {
		if ($this -> campaignMonitor == TRUE) {
			$this -> wrap = new CS_REST_Lists($campaignListID, $this -> apiKey);
			$dateLimit = date('Y-m-d', strtotime('-2 days'));
			$result = $this -> wrap -> get_subscribers($dateLimit);
		} elseif ($this -> mailChimp == TRUE) {
			$result = $this -> objMailChimp -> listMembers($campaignListID, 'subscribed');
		}
		return $result;
	}
	
	/**
	 * processResult
	 * 
	 * Processes results and return message, response on campaaign create/Schedule
	 * actions. used for constantContact, campaignMonitor and mailChimp.
	 * 
	 * @param array $result
	 * @return array $return
	 */
	private function processResult($result) 
	{
		$campaignRespose 			= new Campaign_Response();
		if($this->mailChimp == TRUE) 
		{
			/* For debugging */
			$campaignResponse->Message 				= str_replace('"','\'',$this->objMailChimp->errorMessage);
			$campaignResponse->Code 				= $this->objMailChimp->errorCode;
			if ($campaignResponse->Code) 
			{
				$return['response']				= $campaignResponse;
			} 
			else 
			{
				$return['response'] 			= $result;
			}
			if ($result) 
			{
				$return['status'] = 'success';
			} 
			else 
			{
				$return['status'] = 'failed';
			}
		} 
		elseif($this->campaignMonitor == TRUE) 
		{
			if ($result->was_successful()) 
			{
				$return['status'] 		= 'success';
				
			} 
			else 
			{
				$result->response->Message			= json_encode($result->response->Message);
				$result->response->Message 		    = str_replace('"','\'',$result->response->Message);			
				$return['status'] = 'failed';
			}
			$return['response'] 	= $result->response;
			
		} 
		elseif ($this -> constantContact == TRUE) 
		{
			if ($result == 1) {
				$campaign = $this -> objConstantContactUtility -> getCampaigns('DRAFT');
				$id = array();
				$i = 0;

				foreach ($campaign['items'] as $value) {
					$id[$i] = $value['id'];
					$i++;
				}

				$return['response'] = $id[0];
				$return['status'] = 'success';
			} elseif ($result == 201 || $result == 200) {//Campaign Scheduled succesfully
				$return['status'] = 'success';

			} elseif ($result >= 400) {// Probably campaign created as draft, but cannot be scheduled succesfully
				$campaignResponse -> Message = "Campaign created in draft, but cannot be scheduled !";
				$campaignResponse -> Code = 400;
				$return['status'] = 'failed';
				$return['response'] = $campaignResponse;

			} else {
				$campaignResponse -> Message = "Campaign cannot be created ! ";
				$campaignResponse -> Code = 400;
				$return['status'] = 'failed';
				$return['response'] = $campaignResponse;
			}
		}

		return $return;
	}

	/**
	 * batchSubscribe
	 *
	 * @param string $listID
	 * @param array $batch
	 */
	public function batchSubscribe($listID, $emailIDs) {
		if ($this -> campaignMonitor == TRUE) {
			$this -> objCampaignMonitorSubscribe = new CS_REST_Subscribers($listID, $this -> apiKey);
			$batch = $this -> campaignMonitorArrayFormat($emailIDs);
			
			$res= $this -> objCampaignMonitorSubscribe -> import($batch, "true");
			return $res;
			
		} elseif ($this -> mailChimp == TRUE) {
			$batch = $this -> mailChimpArrayFormat($emailIDs);
			$batchSubscribe = $this -> objMailChimp -> listBatchSubscribe($listID, $batch, "false");
			// For debugging result only

			 //return $this -> batchSubscribeDebug($this -> objMailChimp, $batchSubscribe);

			 

			 return $batchSubscribe;

		} elseif ($this -> constantContact == TRUE) {
			
			$batch = $this -> constantContactArrayFormat($emailIDs);
			$listIDArray[0] = $listID;
			$batchSubscribe = $this -> objConstantContact -> create_contacts($batch,$listIDArray);

		}

	}

// EXTD MAIL START	
	/**
	 * mailChimpArrayFormat
	 *
	 * @param array $emailIDs
	 * @return array $batch
	 */
	private function mailChimpArrayFormat($emailIDs) 
	{
		// MAILCHIMP CUSTOM FORMATING OF ARRAY
		foreach ($emailIDs as $emailID) 
		{
			if($emailID['subcribedTypes'])
			{
			$batch[] = array(
							'EMAIL'		 => $emailID['subscEmailID'], 
							'EMAIL_TYPE' => 'html',
							'GROUPINGS'	 =>	array(
												 array(
													  'name'=>'Product Types',
													  'groups'=>$emailID['subcribedTypes']
													  ),
													  array(
													  'name'=>'Language',
													  'groups'=>$emailID['LanguageLCIDstring']
													  )
													  
												 )
						    );
			}
			else
			{
							$batch[] = array(
							'EMAIL'		 => $emailID['subscEmailID'], 
							'EMAIL_TYPE' => 'html',
							'GROUPINGS'	 =>	array(
													  array(
													  'name'=>'Language',
													  'groups'=>$emailID['LanguageLCIDstring']
													  )
													  
												 )
						    );	
			}
		}
		//print('<pre>'.print_r($batch,1).'<pre>');
		return $batch;
	}
// EXTD MAIL END
	/**
	 * campaignMonitorArrayFormat
	 *
	 * @param array $emailIDs
	 * @return array $batch
	 */
	private function campaignMonitorArrayFormat($emailIDs) 
	{
		// CAMPAIGN MONITOR CUSTOM FORMATING OF ARRAY
		foreach ($emailIDs as $emailID) 
		{
			$customFields			=	array();
			$allSubcribedTypes		=	array();
			if($emailID['subcribedTypes'] != '')
			{
				$allSubcribedTypes		=	explode(',',$emailID['subcribedTypes']);
				foreach ($allSubcribedTypes as $subcribedType) 
				{
					$customFields[]		=	array(
												  'Key' => 'ProductType',
												  'Value' => $subcribedType
												  );
				}
				
				$customFields[]		=	array(
												  'Key' => 'Language',
												  'Value' => $emailID['LanguageLCIDstring']
												  );
				
				
				
				$batch[] = array('EmailAddress' => $emailID['subscEmailID'],'CustomFields' => $customFields);
			}
			
			else
			{	
			$customFields[]		=	array(
												  'Key' => 'Language',
												  'Value' => $emailID['LanguageLCIDstring']
												  );		
				$batch[] = array('EmailAddress' => $emailID['subscEmailID'],'CustomFields' => $customFields);
			}
		}
		return $batch;
	}
	
				/**
	 * constantcontact ArrayFormat
	 *
	 * @param array $emailIDs
	 * @return array $batch
	 */
	private function constantContactArrayFormat($emailIDs) 
	{
		// CAMPAIGN MONITOR CUSTOM FORMATING OF ARRAY
		foreach ($emailIDs as $emailID) 
		{	
			$batch[] = array('Email Address' => $emailID['subscEmailID'],'First Name' => NULL,'Last Name' => NULL);
		}
		return $batch;
	}

	/**
	 * batchSubscribeDebug
	 *
	 * MailChimp batch Subscribe mode debugging
	 *
	 * @param object $api
	 * @param array $vals
	 */
	private function batchSubscribeDebug($api, $vals) {

		// FOR MAIL CHIMP ONLY
		if ($api -> errorCode) {
			echo "Batch Subscribe failed!\n";
			echo "code:" . $api -> errorCode . "\n";
			echo "msg :" . $api -> errorMessage . "\n";
		} else {
			echo "added:   " . $vals['add_count'] . "\n";
			echo "updated: " . $vals['update_count'] . "\n";
			echo "errors:  " . $vals['error_count'] . "\n";
			foreach ($vals['errors'] as $val) {
				echo $val['email_address'] . " failed\n";
				echo "code:" . $val['code'] . "\n";
				echo "msg :" . $val['message'] . "\n";
			}
		}
		exit ;
	}
	
	/**
	 * checkContact
	 * 
	 * Checks for a contact is present in constantContact
	 * 
	 * @param string $emailID
	 * @return array
	 */
	public function checkContact($emailID) {
		return $this -> objConstantContact -> query_contacts($emailID);
	}

	/**
	 * updateSubscription
	 * 
	 * Updates an already existing subscriber to a new list. Only used 
	 * for constantContact.
	 * 
	 * @param integer $id, user ID
	 * @param string $email, user Email
	 * @param array $lists, whole list to which user is allready subscribed + new lists
	 */
	public function updateSubscription($id, $email, $lists) {
		return $this -> objConstantContact -> update_contact($id, $email, $lists);
	}


	/**
	 * getContactDetails
	 * 
	 * Get all contact details based on contactID or user Email. Currently used for
	 * campaignMonitor and constantContact.
	 * 
	 * @param integer $contactID
	 * @param string $email
	 * @return array
	 */
	public function getContactDetails($contactID = '', $email = '') {
		if ($this -> campaignMonitor == TRUE) {
			return $this -> objCampaignMonitorList -> get($email);
		} elseif ($this -> constantContact == TRUE) {
			return $this -> objConstantContact -> get_contact($contactID);
		}
	}
	
	
	/**
	 * processTimeZone
	 * 
	 * To resolve TimeZone issues with mailChimp.
	 * 
	 * @uses scheduleCampaign()
	 * @param string $tz, +05:30
	 * @return string $tzString, '-05 hours 30 minutes'
	 */
	private function processTimeZone($tz) {
		$sign = $tz[0];
		$tz = str_replace($sign,"",$tz);
		$string = explode(":", $tz);

		if ($sign == "+") {
			$tzString = "-";
		} else if($sign == "-") {
			$tzString = "+";
			$string[0] = $string[0] + 1; // ADDS +1 HOUR
		}
		
		$tzString .=  $string[0]." hours ".$string[1]." minutes";
		
		return $tzString;
	}

	/**
	 * debug
	 *
	 * FOR DEBUGGING PURPOSE ONLY
	 *
	 * @param $value
	 */
	public function debug($value) {
		echo "<pre>";
		var_dump($value);
		exit ;
	}
// EXTD MAIL START	
/*
	 * function createList Cutome fields
	 *
	 * Creates custome fields based on List Id..
	 *@package campaignMonitor
*/
	public function createListCustomeFields($cityCampaignListID,$fields) 
	{
		if ($this->campaignMonitor == TRUE) 
		{
			$this->objCampaignCreateList 	= 	new CS_REST_Lists($cityCampaignListID, $this->apiKey); 
			$rtn1 							= 	$this->objCampaignCreateList->create_custom_field($fields);
		} 
	}

/*
	 * function createList Segments
	 *
	 *@package campaignMonitor	 
	 * Creates Segments based on List Id..
	 array(
     *             'Title' => The title of the new segment
     *             'Rules' => array(
     *                 array(
     *                     'Subject' => The subject of this rule
     *                     'Clauses' => array<string> The specific clauses for this rule
     *                 )
     *             )
     *         )
*/

	public function createSegments($cityCampaignListID,$segment_details) 
	{
		if ($this->campaignMonitor == TRUE) 
		{
			$this->objCampaignCreateSegment = new CS_REST_Segments(NULL, $this->apiKey);
			$rtn1 		= 	$this->objCampaignCreateSegment->create($cityCampaignListID,$segment_details);
		} 
	}	
	
/*
	 * function Update Custom field
	 *
	 * @package campaignMonitor	 
	 * Update Custom field based on cityCampaignListID and email
	 * @uses thirdPartyUpdateCustomField() in thirdPartyMailModel
	 * @email subscribersEmail
	 * @subscribedListID listID	 
	 * @subscriptionProductTypes Subscribed ProductTypesKey array 	 	 
*/

	public function updateCustomField($email,$subscribedListID,$subscriptionProductTypes = '',$languageLCIDstring='')
	{
					
		if($this->campaignMonitor == TRUE) 
		{	
			$this->objCampaignMonitorSubscribe		= new CS_REST_Subscribers($subscribedListID, $this->apiKey);
			
			$this->objCampaignMonitorSubscribe->update($email, array(
																	 'CustomFields' => array(
																							 array(
																								  'Key' => 'ProductType',
																								  'Value' => '',
																								  "Clear" => true
																								  )
																							),
																	 'Resubscribe' => true
																	));
			/*
			if($subscriptionProductTypes != '' && count($subscriptionProductTypes) > 0)
			{
				$this->objCampaignMonitorSubscribe->update($email, array(
																	 'CustomFields' => array(
																							 array(
																								  'Key' => 'Language',
																								  'Value' => '',
																								  "Clear" => true
																								  )  
																							),
																	 'Resubscribe' => true
																	));	
			}
			*/														
																	
			if($subscriptionProductTypes != '' && count($subscriptionProductTypes) > 0)
			{
				foreach ($subscriptionProductTypes as $subcribedType) 
				{
					$customFields[]		=	array(
												  'Key' => 'ProductType',
												  'Value' => $subcribedType
												  );
				}
				/*
				$customFields[]		=	array(
												  'Key' => 'Language',
												  'Value' => $languageLCIDstring
												  );
				*/								  
				$result = $this->objCampaignMonitorSubscribe->update($email,array(
																	 	'CustomFields' => $customFields,
																	 	'Resubscribe' => true
																		));	
				
			
			}
			
			
		}
		else if($this->mailChimp == TRUE)
		{
		    if(count($subscriptionProductTypes))
			{
				$subcribedTypes		=	implode(',',$subscriptionProductTypes);
				return $this->objMailChimp->listUpdateMember($subscribedListID, $email, array(
																							 'GROUPINGS' =>	array(
																												 array(
																													  'name'=>'Product Types',
																													  'groups'=>$subcribedTypes
																													  )
																												 )
																							 ));
		   }
		   return false;
		}																											   
	}	
	
//added by Lijo For multi language	
	
	
	public function getSegmentDetails($SegmentID) {

		if ($this -> campaignMonitor == TRUE) {
			$this -> objCampaignCreateSegment = new CS_REST_Segments($SegmentID, $this -> apiKey);
			return $rtn1 = $this->objCampaignCreateSegment->get();
		} 

	}

	 /* function to get list of segments of a list

	 *
	 */

	public function get_segments($cityCampaignListID) {

		if ($this -> campaignMonitor == TRUE) {

			$this -> objCampaignCreateList = new CS_REST_Lists($cityCampaignListID, $this -> apiKey);

					$result= $this->objCampaignCreateList->get_segments();

		
		   $return = $this->processResult($result);
			
			return $result;
		} 

	}
	
	/* function to get list of custom fields of a list

	 *
	 */
	 //@usage Campagain monitor
	public function get_custom_fields($cityCampaignListID) {
		if ($this -> campaignMonitor == TRUE) {
			$this -> objCampaignCreateList = new CS_REST_Lists($cityCampaignListID, $this -> apiKey);
			$result= $this->objCampaignCreateList->get_custom_fields();
		    //$return = $this->processResult($result);
			return $result;
		} 

	}
	
	  /**
	  *@usage Campagain monitor
     * Updates the optios for the given multi-optioned custom field
     * @param string $key The personalisation tag of the field to update
     * @param array<string> $new_options The set of options to add to the custom field
     * @param boolean $keep_existing Whether to remove any existing options not contained in $new_options
     * @access public
     * @return CS_REST_Wrapper_Result A successful response will be empty
     */
	
	function update_field_options($cityCampaignListID,$key,$option) {
		if ($this -> campaignMonitor == TRUE) {
			$this -> objCampaignCreateList = new CS_REST_Lists($cityCampaignListID, $this -> apiKey);
			$result= $this->objCampaignCreateList->update_field_options($key, $option, 1);
		    //$return = $this->processResult($result);
			return $result;
		
		}
	}
	
	
	 /** Delete a single Interest Group - if the last group for a list is deleted, this will also turn groups for the list off.
     *@Usage Mail_Chimp
     * @section List Related
     * @example xml-rpc_listInterestGroupDel.php
     * 
     * @param string $id the list id to connect to. Get by calling lists()
     * @param string $group_name the interest group to delete
     * @return bool true if the request succeeds, otherwise an error will be thrown
     */
    function listInterestGroupDel($id, $group_name) {
		if($this->mailChimp == TRUE)
		{
			$res = $this->objMailChimp->listInterestGroupDel($id, $group_name);	
		}
		
	}
	
	
	
	 /** Add a new Interest Grouping - if interest groups for the List are not yet enabled, adding the first
     *  grouping will automatically turn them on.
     *
     * @section List Related
     * @example xml-rpc_listInterestGroupingAdd.php
     *
     * @param string $id the list id to connect to. Get by calling lists()
     * @param string $name the interest grouping to add - grouping names must be unique
     * @param string $type The type of the grouping to add - one of "checkboxes", "hidden", "dropdown", "radio"
     * @param array $groups The lists of initial group names to be added - at least 1 is required and the names must be unique within a grouping. If the number takes you over the 60 group limit, an error will be thrown.
     * @return int the new grouping id if the request succeeds, otherwise an error will be thrown
     */
    function listInterestGroupingAdd($id, $name, $type, $groups) 
	{
	if($this->mailChimp == TRUE)
		{
			$this->objMailChimp->listInterestGroupingAdd($id,$name, $type, $groups);	
		}
	}
	
	function listInterestGroupUpdate($id, $old_name, $new_name) {
		
		if($this->mailChimp == TRUE)
		{
			$this->objMailChimp->listInterestGroupUpdate($id, $old_name, $new_name);	
		}

    }
	
	/**
	 * function createAndActivateWebhook
	 *
	 * Create and activate webhook 
	 *
	 * @package campaignMonitor
	 */
	public function createAndActivateWebhook($listID,$global_http_url) 
	{
		if ($this->campaignMonitor == TRUE) 
		{
			$this->objCampaignCreateList 	= new CS_REST_Lists($listID, $this->apiKey);
			$webhook_result 				= $this->objCampaignCreateList->create_webhook(
																							array(
																							  		'Events' 		=> array(CS_REST_LIST_WEBHOOK_DEACTIVATE,CS_REST_LIST_WEBHOOK_SUBSCRIBE,CS_REST_LIST_WEBHOOK_UPDATE),
																							  		'Url' 			=> $global_http_url.'/subscribe/campaignmonitorwebhook/key/Ph3RwB8qRKGYTE5q/',
																							  		'PayloadFormat' => CS_REST_WEBHOOK_FORMAT_JSON
																						   ));
			if($webhook_result->was_successful()) 
			{
				$this->objCampaignCreateList->activate_webhook($webhook_result->response);
			}	
		} 
	}		
// EXTD MAIL END	

//Email Tracking
public function updateCampaign($currentCampaignId)
{	
	$mailer_class_file = __LIBRARY_PATH . '/campaign/mail_chimp/MCAPI.class.php';
	if (file_exists($mailer_class_file)) {
			include_once ($mailer_class_file);
	}
	$this -> objMailChimp = new MCAPI('b2b47aed7398c52890107d73b13886b3-us4');
	
	$mailer_class_file_4 = __LIBRARY_PATH . '/campaign/campaign_monitor/csrest_campaigns.php';
		if (file_exists($mailer_class_file_4)) {
			include_once ($mailer_class_file_4);
	}
	
	$mailer_class_file = __LIBRARY_PATH . '/campaign/campaign_monitor/csrest_clients.php';
	if (file_exists($mailer_class_file)) {
			include_once ($mailer_class_file);
	}
	
		
		if($this->campaignMonitor == TRUE)
		{
			//echo '<br>==========================================Campagain monitor==============================================<br>';
			
			$this -> objCampaignMonitor = new CS_REST_Campaigns($currentCampaignId, $this -> apiKey);
			$result = $this->objCampaignMonitor->get_summary();
			$return['openCount'] = $result->response->TotalOpened;
			$return['clickCount'] = $result->response->Clicks;
			$return['bounceCount'] = $result->response->Bounced;
			$return['forwardsCount'] = $result->response->Forwards;
			$return['unsubscribedCount'] = $result->response->Unsubscribed;
			$return['uniqueOpenedCount'] = $result->response->UniqueOpened;
			
		}
		else if ($this->mailChimp == TRUE) 
		{
			//echo '<br>========================================Mail Chimp================================================<br>';
			$this -> objMailChimp = new MCAPI($this -> apiKey);
			$result = $this -> objMailChimp ->campaignStats($currentCampaignId);
			$return['openCount'] = $result['opens'];
			$return['clickCount'] = $result['clicks'];
			$return['bounceCount'] = $result['hard_bounces']+$result['soft_bounces'];
			$return['forwardsCount'] = $result['forwards'];
			$return['unsubscribedCount'] = $result['unsubscribes'];
			$return['uniqueOpenedCount'] = $result['unique_opens'];
			
		}
		else if ($this -> constantContact == TRUE) 
		{
			//echo '<pre><br>========================================Constant Contact================================================<br>';
			$result = $this -> objConstantContactUtility -> getCampaignDetails($currentCampaignId);
			$return['openCount'] = $result['Opens'];
			$return['clickCount'] = $result['Clicks'];
			$return['bounceCount'] = $result['Bounces'];
			$return['forwardsCount'] = $result['Forwards'];
			$return['unsubscribedCount'] = $result['OptOuts'];
			$return['uniqueOpenedCount'] = $result['Opens'];
			
		}
		
		return $return;
	
}
//Email track End	

//Function to delete all campagains from campgain monitor [for development]

public function deleteAllCampaign()
{
	
	$sendCamp = $this -> objCampaignMonitorList -> get_campaigns();
	foreach ($sendCamp->response as $sendCampn) 
	{
		$CampaignID		= 	$sendCampn->CampaignID;
		$this -> objCampaignMonitor = new CS_REST_Campaigns($CampaignID, $this -> apiKey);
		$result = $this->objCampaignMonitor->delete();
		
	}
	$sendCamp = $this -> objCampaignMonitorList -> get_drafts();
	foreach ($sendCamp->response as $sendCampn) 
	{
		$CampaignID		= 	$sendCampn->CampaignID;
		$this -> objCampaignMonitor = new CS_REST_Campaigns($CampaignID, $this -> apiKey);
		$result = $this->objCampaignMonitor->delete();
	}
	
}

}





/**
 * class Campaign_Response
 */

class Campaign_Response 
{
	public $Code;
	public $Message;
	public function __set($key, $val) 
	{
		$this->{$key} = $val;
	}
}
?>