<?php

/**

 * This file contains the base class for all addons to do their work.

 * Addons must extend this class as it contains basic functionality they will require.

 *

 * @package Interspire_Addons, FEEDBACKLOOP

 */



/**

 * Addons_add_addon_installer

 * This is the base class for all addons to work off.

 * It handles:

 * - installing & uninstalling addons

 * - enabling & disabling addons

 * - running addons

 * - finding/loading addons including their language data_files and description.xml data_files

 *

 * The description.xml file is used by the calling code to work out

 * - the name of the addon

 * - a short description

 * - the current version number

 * - the author

 * - license details 

 *

 * @uses Interspire_Addons_Exception, Addons_add_addon_installer

 */

if (!class_exists('Interspire_Addons', false)) {require_once(dirname(dirname(__FILE__)) . '/interspire_addons.php');}

require_once (dirname(__FILE__) . '/language/language.php');

class Addons_feedbackloop extends Interspire_Addons{

    private $AddonName = "feedbackloop";

	

	//Enable Feedback Loop

	public function Enable(){

		try {

			$status = parent::Enable();

		} catch (Interspire_Addons_Exception $e) {

			throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());

		}

		return true;

	}



	//Disable Feedback Loop

	public function Disable(){

		try {

			$status = parent::Disable();

		} catch (Interspire_Addons_Exception $e) {

			throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());

		}

		return true;

	}

	

	//Installation of feedbackloop

	public function Install(){

		$tables = $sequences = array();

    	if (!$this->isEnabled("add_addon_installer")){throw new Interspire_Addons_Exception("ERROR: Telesys: Additional Addon Installer is required", Interspire_Addons_Exception::AddonDoesntExist);}else{$this->Process("add_addon_installer", "GetApi", "add_addon_installer")->install($this->AddonName);}

		$this->db->StartTransaction();

		require dirname(__FILE__) . '/schema.' . SENDSTUDIO_DATABASE_TYPE . '.php';

		foreach ($queries as $query) {

			$qry = str_replace('%%TABLEPREFIX%%', $this->db->TablePrefix, $query);

			$qry_result = $this->db->Query($qry);

			if (!$qry_result) {

				$this->db->RollbackTransaction();

				throw new Interspire_Addons_Exception("There was a problem running query " . $qry . ": " . $this->db->GetErrorMsg(), Interspire_Addons_Exception::DatabaseError);

			}

		}

		$this->enabled = true;

		$this->configured = true;

        try {

			$status = parent::Install();

		} catch (Interspire_Addons_Exception $e) {

			$this->db->RollbackTransaction();

			throw new Exception("ERROR: failed install addon {$this->GetId()} " . $e->getMessage());

		}

		$this->db->CommitTransaction();

		$qry_result = $this->db->Query ( "SELECT method FROM " . SENDSTUDIO_TABLEPREFIX . "feedbackloop LIMIT 1" );

		if (!$qry_result){

			$qry_result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "feedbackloop` ADD `method` INT( 11 ) NOT NULL DEFAULT '1'" );

		}

		$qry_result = $this->db->Query ( "SELECT feedbackloop FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers LIMIT 1" );

		if (!$qry_result){

			$qry_result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "list_subscribers` ADD `feedbackloop` INT( 11 ) NOT NULL DEFAULT '0'" );

		}

		$qry_result = $this->db->Query ( "SELECT feedbackloop FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe LIMIT 1" );

		if (!$qry_result){

			$qry_result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe` ADD `feedbackloop` INT( 11 ) NOT NULL DEFAULT '0'" );

		}

		$qry_result = $this->db->Query ( "SELECT feedbackloop FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters LIMIT 1" );

		if (!$qry_result){

			$qry_result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_newsletters` ADD `feedbackloop` INT( 11 ) NOT NULL DEFAULT '0'" );

		}

		return true;

	}

	

	//Default Action on feedback Loop

	public function Admin_Action_Default(){

		$db = IEM::getDatabase();

		$query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "feedbackloop";

		$qry_result = $db->Query($query);

		$common_array=array();

		$api=$this->GetApi();

		$method_label=array("None","Normal","Email","Unsubscribe Link");

		while ($qry_row = $db->Fetch($qry_result)) {

			$nexus=$api->link_up($qry_row);

			$qry_row['status']=$nexus['error'];

			$qry_row['complaints']=$api->numberof_feedbackloop($nexus);

			$qry_row['type']=($qry_row['type']==1)?"IMAP":"POP3";

			$qry_row['method_label']=$method_label[$qry_row['method']];

			$common_array[]=$qry_row;

			$api->unlink_up($nexus);

		}

		$this->template_system->Assign('FlashMessages',GetFlashMessages(),false);

		$this->template_system->assign('qry_result',$common_array);

		$this->template_system->ParseTemplate('feedbacklooptmpl');

	}



	//Administrator Action on feedback loop add

	public function Admin_Action_Add(){

		$db = IEM::getDatabase();

		$api=$this->GetApi();

		if ($_SERVER['REQUEST_METHOD']=="POST"){

			if (!empty($_POST['feedbackloop_test'])){

				$data=array(

				'name'=>$_POST['feedbackloop_name'],

				'hostname'=>trim($_POST['feedbackloop_hostname']),

				'username'=>$_POST['feedbackloop_username'],

				'password'=>$_POST['feedbackloop_password'],

				'port'=>$_POST['feedbackloop_port'],

				'type'=>$_POST['feedbackloop_type'],

				'method'=>$_POST['feedbackloop_method'],

				'uid'=>$_POST['feedbackloop_uid'],

				'advanced'=>$_POST['feedbackloop_advanced'],

				);

				$qry_res=$api->link_up($data);

				if ($qry_res['error']){

					FlashMessage("Mail Server nexus Failed: ".$qry_res['error'],SS_FLASH_MSG_ERROR);

				}else{

					FlashMessage("Mail Server logged succesfully!, <b>".$api->numberof_feedbackloop($qry_res)."</b> complaints to runspam",SS_FLASH_MSG_SUCCESS);

				}

				$this->template_system->Assign('FlashMessages',GetFlashMessages(),false);

				$this->template_system->assign('do',$_POST['feedbackloop_do']);

				$this->template_system->assign('value',$data);

				$this->template_system->ParseTemplate('feedbackloop_add');

				return;

			}

			if ($_POST['feedbackloop_do']=="update"){

				$api->update($_POST);

				$na=$this->db->NumAffected();

				FlashMessage(GetLang("Addon_feedbackloop_Updated"),SS_FLASH_MSG_SUCCESS,"index.php?Page=Addons&Addon=feedbackloop");

			}else{

				if ($api->add($_POST)){

					FlashMessage(GetLang("Addon_feedbackloop_New_Added"),SS_FLASH_MSG_SUCCESS,"index.php?Page=Addons&Addon=feedbackloop");

				}else{

					FlashMessage(GetLang("Addon_feedbackloop_New_Added_Error"),SS_FLASH_MSG_ERROR,"index.php?Page=Addons&Addon=feedbackloop");

				}

			}

		}else{

			$id=(!empty($_GET['id']))?$_GET['id']:0;

			$f=$api->feedbackloop_details($id,true);

			if ($id!=0 && $f['exist']==false){

				FlashMessage(GetLang("Addon_feedbackloop_Not_Found"),SS_FLASH_MSG_ERROR,"index.php?Page=Addons&Addon=feedbackloop");

			}

			$this->template_system->assign('do',($f['exist']==false)?"add":"update");

			$this->template_system->assign('value',$f['data']);

			$this->template_system->ParseTemplate('feedbackloop_add');

		}

	}

	

	//Admin Action on Run Spam Feedback Loop

	public function Admin_Action_Runspam(){

		$id=(!empty($_GET['id']))?$_GET['id']:0;

		$api=$this->GetApi();

		$f=$api->feedbackloop_details($id,true);

		if ($id!=0 && $f['exist']==false){

			FlashMessage(GetLang("Addon_feedbackloop_Not_Found"),SS_FLASH_MSG_ERROR,"index.php?Page=Addons&Addon=feedbackloop");

		}else{

			$con=$api->link_up($f['data']);

			$total=$api->numberof_feedbackloop($con);

			$pinfo=$api->runspam($con,20);

			$api->unlink_up($con);

			FlashMessage(sprintf(GetLang("Addon_feedbackloop_Processed"),$pinfo['runspamed'],$total),SS_FLASH_MSG_SUCCESS);

			$this->template_system->assign('value',$f['data']);

			$this->template_system->Assign('FlashMessages',GetFlashMessages(),false);

			$this->template_system->ParseTemplate('feedbackloop_runspam');

		}

	}



	//Admin Action on Delete Feedback Loop

	public function Admin_Action_Delete(){

		$db = IEM::getDatabase();

		$api=$this->GetApi();

		$id=(!empty($_GET['id']))?$_GET['id']:0;

		$f=$api->feedbackloop_details($id,true);

		if ($id!=0 && $f['exist']==false){

			FlashMessage(GetLang("Addon_feedbackloop_Not_Found"),SS_FLASH_MSG_ERROR,"index.php?Page=Addons&Addon=feedbackloop");

		}else{

			$api->delete($id);

			FlashMessage(GetLang("Addon_feedbackloop_Deleted"),SS_FLASH_MSG_SUCCESS,"index.php?Page=Addons&Addon=feedbackloop");

		}

	}

	

	//Admin Action on Export Feedback Loop

	public function Admin_Action_Export(){

	    $statid=(isset($_GET['statid']))?(int)$_GET['statid']:0;

	    $query="SELECT b.emailaddress, b.feedbackloop, b.unsubscribed FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe a LEFT JOIN " . SENDSTUDIO_TABLEPREFIX . "list_subscribers b ON a.subscriberid=b.subscriberid WHERE a.statid={$statid} AND a.feedbackloop=1 GROUP BY a.subscriberid";

	    $qry_result = $this->db->Query($query);

	    $filename="complaints_in_stat_{$statid}.csv";

	    header("Cache-Control: must-revalidate");

		header("Pragma: must-revalidate");

		header("Content-type: application/vnd.ms-excel");		

		header ( 'Content-Disposition: attachment; filename="' . $filename . '"' );

	    while ($qry_row=$this->db->Fetch($qry_result)){

	        echo $qry_row['emailaddress'].PHP_EOL;

	    }

	}



	//Admin Action on Export Feedback Loop List

    public function Admin_Action_ExportList(){

	    $listid=(isset($_GET['listid']))?(int)$_GET['listid']:0;

	    $query="SELECT b.emailaddress, b.feedbackloop, b.unsubscribed FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe a LEFT JOIN " . SENDSTUDIO_TABLEPREFIX . "list_subscribers b ON a.subscriberid=b.subscriberid WHERE a.listid={$listid} AND a.feedbackloop=1 GROUP BY a.subscriberid";

	    $qry_result = $this->db->Query($query);

	    $filename="complaints_in_contact_list_{$listid}.csv";

	    header("Cache-Control: must-revalidate");

		header("Pragma: must-revalidate");

		header("Content-type: application/vnd.ms-excel");		

		header ( 'Content-Disposition: attachment; filename="' . $filename . '"' );

	    while ($qry_row=$this->db->Fetch($qry_result)){

	        echo $qry_row['emailaddress'].PHP_EOL;

	    }

	}



	//Admin Action on Edit (By default call Add)

	public function Admin_Action_Edit(){

		$this->Admin_Action_Add();

	}



	//Admin Action on Manage Feedback Loop

	public function Admin_Action_Manager(){

		$this->template_system->ParseTemplate('feedbacklooptmpl');

	}



	//Get Event Listeners

	function GetEventListeners(){

		$my_file = '{%IEM_ADDONS_PATH%}/feedbackloop/feedbackloop.php';

		$listeners = array();

		$listeners[] =

			array (

				'eventname' => 'IEM_SENDSTUDIOFUNCTIONS_GENERATEMENULINKS',

				'trigger_details' => array (

					'Addons_feedbackloop',

					'SetMenuItems',

				),

				'trigger_file' => $my_file

			);

		$listeners[] =

			array (

				'eventname' => 'IEM_USERAPI_GETPERMISSIONTYPES',

				'trigger_details' => array (

					'Interspire_Addons',

					'GetAddonPermissions',

				),

				'trigger_file' => $my_file

			);

		return $listeners;

	}



	//Set Menu Items in Loop

	static function SetMenuItems(EventData_IEM_SENDSTUDIOFUNCTIONS_GENERATEMENULINKS $data){

		$user = &GetUser();

		$self = new self;

		$menuItems = $data->data;

		$menuItems['contactlist_button'][]=array (

					'text' => "Feedback Loops",

					'link' => $self->admin_url . '',

					'image' => '../addons/feedbackloop/images/feedbackloop_tool.gif',

					'show' => $user->isAdmin(),

					'description' => GetLang('Addon_feedbackloop_Menu_Description'),

		);



		$data->data = $menuItems;

	}



	//Satting Permission

	static function RegisterAddonPermissions(){

		return;

	}



	//Get Main Feedback Loop API

    protected function GetApi($api = 'Feedbackloop'){

        $api = (is_array($api)) ? $api[0] : $api;

        $path = $this->addon_base_directory . $this->addon_id . '/oops/' . strtolower($api) . '.php';

        if (! is_file($path)) {

            return false;

        }

        require_once $path;

        $class = $api . '_API';

        $api = new $class();

        $api->template_system=$this->template_system;

        return $api;

    }

	

	//Uninstall feedback Loop

	public function UnInstall(){

		$tables = $sequences = array();

    	if (!$this->isEnabled("add_addon_installer")){throw new Interspire_Addons_Exception("ERROR: The Addon (Main Addons Installer) is required", Interspire_Addons_Exception::AddonDoesntExist);}else{$this->Process("add_addon_installer", "GetApi", "add_addon_installer")->uninstall($this->AddonName);}

		$this->db->StartTransaction();

		try {

			$this->Disable();

		} catch (Interspire_Addons_Exception $e) {

			$this->db->RollbackTransaction();

			throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());

		}

		require dirname(__FILE__) . '/schema.' . SENDSTUDIO_DATABASE_TYPE . '.php';

	    try {

			$status = parent::UnInstall();

		} catch (Interspire_Addons_Exception $e) {

			$this->db->RollbackTransaction();

			throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());

		}

		$this->db->CommitTransaction();

		return true;

	}

	

	

}