<?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

 */

define("FEEDBACKLOOP_TYPE","all");



class Feedbackloop_API extends API {

	private $db;

	public $maildir = "INBOX";

	

	//Feedback Loop By default run constructor

	public function __construct() {

		$this->db = IEM::getDatabase ();

	}



	// link up to Feedback Loop Account

	public function link_up($feedbackloop = array()) {

		$common_array = array ();

		$common_array ['type'] = $feedbackloop ['type'];

		$common_array ['method'] = $feedbackloop ['method'];

		if ($feedbackloop ['type'] == 1) {

			imap_timeout(IMAP_READTIMEOUT,10);

			$this->host_string = "{{$feedbackloop['hostname']}:{$feedbackloop['port']}{$feedbackloop['advanced']}}";

			$host = "{{$feedbackloop['hostname']}:{$feedbackloop['port']}{$feedbackloop['advanced']}}{$this->maildir}";

			$mbox = imap_open ( $host, $feedbackloop ['username'], $feedbackloop ['password'] );

			$common_array ['mbox'] = $mbox;

			if (! $mbox) {

				$common_array ['error'] = imap_last_error ();

			} else {

				$common_array ['error'] = false;

			}

		} else {

			$common_array ['error'] = "Unknown error";

		}

		return $common_array;

	}

	

	//un-link between server and Feedback Loop Account

	public function unlink_up($mailinfo) {

		imap_close ( $mailinfo ['mbox'] );

	}



	//Total Number of feedback Loop

	public function numberof_feedbackloop($mailinfo) {

		$total = 0;

		if ($mailinfo ['type'] == 1) {

			$total = (! $mailinfo ['mbox']) ? 0 : imap_num_msg ( $mailinfo ['mbox'] );

		}

		return $total;

	}



	//Run Spam Complaint

	public function runspam_all($limit=5){

	    $feedbackloops=$this->feedbackloop_details();

	    foreach ($feedbackloops as $k=>$v){

	        $imap=$this->link_up($v);

	        $total=$this->numberof_feedbackloop($imap);

	        $runspamed=$this->runspam($imap,$limit);

			$this->unlink_up($imap);

	    }

	}

	

	//Fix cron option

	public function cronfix(){

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

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

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

    	    $query = "SELECT COUNT(DISTINCT subscriberid) as total FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe WHERE `statid`='{$qry_row['statid']}'";

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

    		$common_array = $this->db->Fetch ( $qry_resultset );

    		$feedbackloops=$common_array['total'];

    	    $this->log("Fixing: {$qry_row['statid']} with {$feedbackloops}");

    	}

	}



	//Feedback Loop Details

	public function feedbackloop_details($id=false, $blank = false) {

	    if (!$id){

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

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

	        $data=array();

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

    		    $data[]=$qry_row;

    		}

    		return $data;

	    }else{

            $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "feedbackloop WHERE uid='" . $this->db->Quote ( $id ) . "'";

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

    		$common_array = $this->db->Fetch ( $qry_result );

    		$data = ($common_array) ? $common_array : array ('port' => 143, 'advanced' => '/imap/novalidate-cert' );

    		return array ("exist" => ($common_array) ? true : false, "data" => $data );

	    }

	}



	//Add New Feedback Loop

	public function add($data) {

		$port = is_numeric ( $data ['feedbackloop_port'] ) ? $data ['feedbackloop_port'] : (($data ['type'] == 1) ? 143 : 995);

		$advanced_default = "/imap/novalidate-cert";

		$method = is_numeric ( $data ['feedbackloop_method'] ) ? $data ['feedbackloop_method'] : 1;

		$qry_result = $this->db->InsertQuery ( "feedbackloop", array ('name' => $data ['feedbackloop_name'], 'hostname' => $data ['feedbackloop_hostname'], 'username' => $data ['feedbackloop_username'], 'password' => $data ['feedbackloop_password'], 'port' => $port, 'type' => (! empty ( $data ['feedbackloop_type'] )) ? $data ['feedbackloop_type'] : 1, 'advanced' => (! empty ( $data ['feedbackloop_advanced'] )) ? $data ['feedbackloop_advanced'] : $advanced_default, 'method'=> $method ) );

		return $qry_result;

	}



	//Update existing Feedback Loop

	public function update($data) {

		$port = (is_numeric ( $data ['feedbackloop_port'] )) ? $data ['feedbackloop_port'] : (($data ['type'] == 1) ? 143 : 995);

		$advanced_default = "/imap/novalidate-cert";

		$uid = is_numeric ( $data ['feedbackloop_uid'] ) ? $data ['feedbackloop_uid'] : 0;

		$method = is_numeric ( $data ['feedbackloop_method'] ) ? $data ['feedbackloop_method'] : 1;

		$qry_result = $this->db->UpdateQuery ( "feedbackloop", array ('name' => $data ['feedbackloop_name'], 'hostname' => $data ['feedbackloop_hostname'], 'username' => $data ['feedbackloop_username'], 'password' => $data ['feedbackloop_password'], 'port' => $port, 'type' => (! empty ( $data ['feedbackloop_type'] )) ? $data ['feedbackloop_type'] : 1, 'advanced' => (! empty ( $data ['feedbackloop_advanced'] )) ? $data ['feedbackloop_advanced'] : $advanced_default , 'method'=> $method), "`uid`=" . $uid );

		return $qry_result;

	}



	//Delete Existing Feedback Loop

	public function delete($id) {

		return $this->db->DeleteQuery ( "feedbackloop", "WHERE `uid`=" . $id, 1 );

	}



	//Run SPAM Complaints

	public function runspam($mailinfo, $interval = 100) {

		$info = array ();

		$delete=array();

		$head=$this->head($mailinfo,$interval);

		$this->log($head);

		$info ['head'] = $head;

		foreach ( $head as $key => $value ){

			if ($value['feedbackloop']){

    			$utd = @$value ['X-Mailer-RecptId'];

    			$ltd = @$value ['X-Mailer-LID'];

    			$sid = @$value ['X-Mailer-SID'];

    			$data=array();

    			$data['recipient_id']=$utd;

    			$data['list_id']=$ltd;

    			$data['stat_id']=$sid;

    			$data['recipient_ip']=@$value ['X-Mailer-IP'];

				if (FEEDBACKLOOP_TYPE == "all") {

					$subscriber_ids=explode(",",$data['recipient_id']);

					foreach ($subscriber_ids as $k=>$v){

						$nd = $data;

						$subscribers_lists=explode(",",$data['list_id']);

						foreach ($subscribers_lists as $l => $w){

							$nd['list_id']=(int)$w;

							if ($this->isset_subscriber($v,$nd['list_id'])){

							    $delete[]=$value['msg'];

								if (!$this->already_unsubscribed($v,$nd['list_id'])){

									$subscribers_stat=($nd['stat_id'])?array($nd['stat_id']):$this->get_stats_from_listid($nd['list_id']);

									$this->remove_from_list($w,$v);

									foreach ($subscribers_stat as $m => $o){

										$nd['stat_id']=(int)$o;

										$this->save_in_feedbackloop_table($nd);

										$this->remove_from_stats($w,$v,$nd['stat_id'],$data ['recipient_ip']);

									}

								}else {

								    if (!$this->already_unsubscribed($v,$nd['list_id'],true)){

    								    $subscribers_stat=($nd['stat_id'])?array($nd['stat_id']):$this->get_stats_from_listid($nd['list_id']);

    								    $this->remove_from_list($w,$v,true);

    									foreach ($subscribers_stat as $m => $o){

    										$nd['stat_id']=(int)$o;

    										$this->save_in_feedbackloop_table($nd);

    										$this->remove_from_stats($w,$v,$nd['stat_id'],$data ['recipient_ip']);

    									}

								    }else{

								        $subscribers_stat=($nd['stat_id'])?array($nd['stat_id']):$this->get_stats_from_listid($nd['list_id']);

    									foreach ($subscribers_stat as $m => $o){

    										$nd['stat_id']=(int)$o;

    										$this->remove_from_stats($w,$v,$nd['stat_id'],$data ['recipient_ip'],true);

    									}

								    }

								}

							}else{

							    $this->log("Skipping: ".print_r($nd,true));

							}

						}

					}

				}

			}

		}

		$info ['runspamed'] = count($delete);

		$this->delete_runspamed($mailinfo,$delete);

		return $info;

	}

	

	//Remove Contact from List

	public function remove_from_list($listid,$subscriberid,$unsubscribed=false){

	    if(!$unsubscribed){

	        $this->log("Unsubscribing NEW from listid: {$listid} , subscriberid:{$subscriberid}");

	        $qun="UPDATE ".SENDSTUDIO_TABLEPREFIX."lists SET unsubscribecount=unsubscribecount + 1 , subscribecount=subscribecount - 1 WHERE `listid`='" . trim ( $listid ) . "'";

	        $this->db->Query ( $qun );

    		$this->db->UpdateQuery ( "list_subscribers", array ("feedbackloop"=>1,"unsubscribed" => $this->db->Quote ( time () ), "unsubscribeconfirmed" => 1 ), "`subscriberid`='". trim ( $subscriberid ) . "' AND `listid`='" .trim ( $listid ) ."'"  );	

	    }else{

	        $this->log("Unsubscribing UPDATED from listid: {$listid} , subscriberid:{$subscriberid}");

	        $this->db->UpdateQuery ( "list_subscribers", array ("feedbackloop"=>1), "`subscriberid`='". trim ( $subscriberid ) . "' AND `listid`='" .trim ( $listid ) ."'"  );

	    }

	}



	//Remove contact from Stats

    public function remove_from_stats($listid,$subscriberid,$statid,$ip,$unsubscribed=false){

	    if (!$unsubscribed){

	        $this->log("Stats-Newsletter Added to statid: {$statid}, listid: {$listid} , subscriberid:{$subscriberid}");

	        $this->db->DeleteQuery ( "list_subscribers_unsubscribe", "WHERE `subscriberid`='" . trim ( $subscriberid ) . "' AND `listid`='" . trim ( $listid ) ."' AND `statid`='".trim($statid)."'" );

    		$und = array ("feedbackloop"=>1,"subscriberid" => $this->db->Quote ( trim ( $subscriberid ) ), "unsubscribetime" => $this->db->Quote ( time () ), "listid" => $this->db->Quote ( trim ( $listid ) ), "unsubscribeip" => $ip, "unsubscriberequesttime" => $this->db->Quote ( time () ), "statid" => $this->db->Quote ( trim ( $statid ) ), "unsubscribearea" => $this->db->Quote ( "n" ) );

    		$common_array=$this->db->InsertQuery ( "list_subscribers_unsubscribe", $und );

    		$qun="UPDATE ".SENDSTUDIO_TABLEPREFIX."stats_newsletters SET unsubscribecount=unsubscribecount + 1 , feedbackloop=feedbackloop + 1 WHERE `statid`='" . trim ( $statid ) . "'";

            $this->db->Query ( $qun );

	    }else{

	        $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe WHERE `subscriberid`='" . trim ( $subscriberid ) . "' AND `listid`='" . trim ( $listid ) ."' AND `statid`='".trim($statid)."'";

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

    		$common_array = $this->db->Fetch ( $qry_result );

    		if (!$common_array){

    		    $this->log("Stats-Newsletter Deletes/Added to statid: {$statid}, listid: {$listid} , subscriberid:{$subscriberid}");

    		    $this->db->DeleteQuery ( "list_subscribers_unsubscribe", "WHERE `subscriberid`='" . trim ( $subscriberid ) . "' AND `listid`='" . trim ( $listid ) ."' AND `statid`='".trim($statid)."'" );

        		$und = array ("feedbackloop"=>1,"subscriberid" => $this->db->Quote ( trim ( $subscriberid ) ), "unsubscribetime" => $this->db->Quote ( time () ), "listid" => $this->db->Quote ( trim ( $listid ) ), "unsubscribeip" => $ip, "unsubscriberequesttime" => $this->db->Quote ( time () ), "statid" => $this->db->Quote ( trim ( $statid ) ), "unsubscribearea" => $this->db->Quote ( "n" ) );

        		$common_array=$this->db->InsertQuery ( "list_subscribers_unsubscribe", $und );

        		$qun="UPDATE ".SENDSTUDIO_TABLEPREFIX."stats_newsletters SET unsubscribecount=unsubscribecount + 1 , feedbackloop=feedbackloop + 1 WHERE `statid`='" . trim ( $statid ) . "'";

                $this->db->Query ( $qun );

    		}

	    }

	}



	//Destroy Feedback Loop

	public function destroy(){

	    $qun="UPDATE ".SENDSTUDIO_TABLEPREFIX."stats_newsletters SET feedbackloop=0";

    	$this->db->Query ( $qun );

    	$qun="DELETE FROM ".SENDSTUDIO_TABLEPREFIX."list_subscribers_unsubscribe WHERE feedbackloop=1";

    	$this->db->Query ( $qun );

	}



	//Save Feedback Loop Query

	public function save_in_feedbackloop_table($data){

	    $qry_result = $this->db->InsertQuery ("feedbackloop_mails", $data );

	}



	//Set Subscriber check

	public function isset_subscriber($id,$listid){

		$common_array=$this->db->Fetch ( $this->db->Query ("SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers WHERE subscriberid=" . $this->db->Quote ( trim ( $id ) ) . " AND listid=" . $this->db->Quote ( trim ( $listid ) ) . " LIMIT 1") );

		return ($common_array)?true:false;

	}



	//Get List Id

	public function get_stats_from_listid($listid){

		$q="SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletter_lists WHERE listid='".$this->db->Quote ( $listid )."'";

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

		$stid=array();

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

			$stid[]=$qry_row['statid'];

		}

		return $stid;

	}



	//If Already Unsubscribed

	public function already_unsubscribed($id,$listid,$feedbackloop=false){

	    $feedbackloop=($feedbackloop==true)?"AND feedbackloop=1":"";

		$q="SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers WHERE subscriberid=" . $this->db->Quote ( trim ( $id ) ) . " AND listid=" . $this->db->Quote ( trim ( $listid ) ) . " AND unsubscribeconfirmed=1 {$feedbackloop}";

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

		$common_array = $this->db->Fetch ( $qry_result );

		return ($common_array)?true:false;

	}



	//Get feedbackloop Total Stats

	public function get_feedbackloop_total_from_stat($statid){

		$q="SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters WHERE statid=" . $this->db->Quote ( trim ( $statid ) ) . " LIMIT 1";

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

		$common_array = $this->db->Fetch ( $qry_result );

		return ($common_array)?$common_array['feedbackloop']:0;

	}



	//Get Feedbackloop Total From list

    public function get_feedbackloop_total_from_list($listid){

		$q="SELECT COUNT(*) as total FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe WHERE listid=" . $this->db->Quote ( trim ( $listid ) ) . " AND feedbackloop=1 GROUP BY subscriberid";

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

		$t=array();

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

		    $t[]=$common_array;

		}

		return count($t);

	}



	//Extract Email from

	public function extract_emails_from($string) {

		preg_match_all ( "/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches );

		return @$matches [0] [0];

	}



	//Extract Header

	public function head($mailinfo, $interval = 100) {

		$tm = $this->numberof_feedbackloop ( $mailinfo );

		$tm = ($interval < $tm) ? $interval : $tm;

		$headd = array ();

		if (!$mailinfo['mbox']){return $headd;}

		if ($mailinfo ['type'] == 1) {

			for($i = 1; $i <= $tm; $i ++) {

			    $header=$this->header_from_mail($mailinfo,$i);

			    $headd[]=$header;

			}

		}

		return $headd;

	}



	//Extract Log

	public function log($data){

	    if (IEM_CLI_MODE){

	        echo PHP_EOL.print_r($data,true).PHP_EOL;

	    }

	}



	//delete Run Spam

	public function delete_runspamed($mailinfo,$runspamed=array()){

	    $maildirs = imap_list($mailinfo['mbox'], $this->host_string, "*");

	    $this->log("Mails to Delete");

	    $this->log($runspamed);

	    $this->log($maildirs);

	    $mboxname="Trash";

	    foreach ($runspamed as $k=>$v){

            $common_array=imap_delete($mailinfo['mbox'],$v);

            $this->log($common_array);

            $this->log(imap_last_error());

		}

		imap_expunge ( $mailinfo['mbox'] );

	}

	

	//Delete Header from mail

	public function header_from_mail($mailinfo,$mn){

	    $data=array('feedbackloop'=>false,'msg'=>$mn);

	    $subscriberid=false;

	    $sp=$this->retrive_mailinfo_one($mailinfo,$mn);

	    if ($sp['subscriberid']){

	        return $this->createdata_from_subscriberid($sp,$mn);

	    }

	    $sp=$this->retrive_mailinfotwo($mailinfo,$mn,$sp['x-header']);

	    if ($sp['subscriberid']){

	        return $this->createdata_from_subscriberid($sp,$mn);

	    }

	    $sp=$this->retrive_mailinfothree($mailinfo,$mn,$sp['x-header']);

	    if ($sp['subscriberid']){

	        return $this->createdata_from_subscriberid($sp,$mn);

	    }

	    $sp=$this->retrive_mailinfoforth($mailinfo,$mn,$sp['x-header']);



	    if ($sp['subscriberid']){

	        return $this->createdata_from_subscriberid($sp,$mn);

	    }

	    $sp=$this->retrive_mailinfofive($mailinfo,$mn,$sp['x-header']);

	    if ($sp['subscriberid']){

	        return $this->createdata_from_subscriberid($sp,$mn);

	    }

	    return $data;

	}



	// Get mail info

	public function retrive_mailinfo_one($mailinfo,$mn,$xheader=array()){

	    $qry_result=array();

	    $a=explode ( "\n", @imap_fetchbody ( $mailinfo['mbox'], $mn, 0 ));

	    $xheader=array();

	    foreach($a as $k=>$v){

	        if (@eregi ( "^X-", $v )) {

				@eregi ( "^([^:]*): (.*)", $v, $arg );

				$xheader [$arg [1]] = $arg [2];

			}

	        $uu=$this->textdata_to_subscriber($v);

	        if ($uu['subscriberid']){

	            return array_merge(array('x-header'=>$xheader),$uu);

	        }

	    }

	    return array('x-header'=>$xheader,'subscriberid'=>false);

	}

	//Get Mail Info Second

	public function retrive_mailinfotwo($mailinfo,$mn,$xheader=array()){

	    $qry_result=array();

	    $a=explode ( "\n", @imap_fetchbody ( $mailinfo['mbox'], $mn, 1 ));

	    $xheader=array_merge(array(),$xheader);

	    foreach($a as $k=>$v){

	        if (@eregi ( "^X-", $v )) {

				@eregi ( "^([^:]*): (.*)", $v, $arg );

				$xheader [$arg [1]] = $arg [2];

			}

	        $uu=$this->textdata_to_subscriber($v);

	        if ($uu['subscriberid']){

	            return array_merge(array('x-header'=>$xheader),$uu);

	        }

	    }

	    return array('x-header'=>$xheader,'subscriberid'=>false);

	}



	//Retrive Mail Info third

    public function retrive_mailinfothree($mailinfo,$mn,$xheader=array()){

	    $qry_result=array();

	    $a=explode ( "\n", @imap_fetchbody ( $mailinfo['mbox'], $mn, 2 ));

	    $xheader=array_merge(array(),$xheader);

	    foreach($a as $k=>$v){

	        if (@eregi ( "^X-", $v )) {

				@eregi ( "^([^:]*): (.*)", $v, $arg );

				$xheader [$arg [1]] = $arg [2];

			}

	        $uu=$this->textdata_to_subscriber($v);

	        if ($uu['subscriberid']){

	            return array_merge(array('x-header'=>$xheader),$uu);

	        }

	    }

	    return array('x-header'=>$xheader,'subscriberid'=>false);

	}



	//Retrive mail info forth

    public function retrive_mailinfoforth($mailinfo,$mn,$xheader=array()){

	    $qry_result=array();

	    $a=explode ( "\n", @imap_fetchbody ( $mailinfo['mbox'], $mn, "2.3" ));

	    $xheader=array_merge(array(),$xheader);

	    foreach($a as $k=>$v){

	        if (@eregi ( "^X-", $v )) {

				@eregi ( "^([^:]*): (.*)", $v, $arg );

				$xheader [$arg [1]] = $arg [2];

			}

	        $uu=$this->textdata_to_subscriber($v);

	        if ($uu['subscriberid']){

	            return array_merge(array('x-header'=>$xheader),$uu);

	        }

	    }

	    return array('x-header'=>$xheader,'subscriberid'=>false);

	}



	//Retrive mail info five

    public function retrive_mailinfofive($mailinfo,$mn,$xheader=array()){

	    $qry_result=array();

	    $a=explode ( "\n", @imap_fetchbody ( $mailinfo['mbox'], $mn, 3 ));

	    $xheader=array_merge(array(),$xheader);

	    foreach($a as $k=>$v){

	        if (@eregi ( "^X-", $v )) {

				@eregi ( "^([^:]*): (.*)", $v, $arg );

				$xheader [$arg [1]] = $arg [2];

			}

	        $uu=$this->textdata_to_subscriber($v);

	        if ($uu['subscriberid']){

	            return array_merge(array('x-header'=>$xheader),$uu);

	        }

	    }

	    return array('x-header'=>$xheader,'subscriberid'=>false);

	}



	//Get text to subscriber

	public function textdata_to_subscriber($str){

	    $uri="unsubscribe\.php";

	    $qry_result=false;

	    if (preg_match("/{$uri}/",$str)) {

	        $url=parse_url(str_replace(array("<",">"),array("",""),trim($str)));

	        $var=false;

	        parse_str($url['query'],$var);

	    	$subscriberid=(int)$var['M'];

	    	$statid=(int)$var['N'];

	    	$confirmed=$var['C'];

	    	$listid=$var['L'];

	    	return array("subscriberid"=>$subscriberid,"statid"=>$statid,"confirmed"=>$confirmed,"listid"=>$listid);

	    }

	    return array('subscriberid'=>false);	    

	}



	//Crate data from subscriber id

	public function createdata_from_subscriberid($data,$mn){

	    $subscriberid=$data['subscriberid'];

		$db = IEM::getDatabase();

		$query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers WHERE subscriberid='".$db->Quote ( $subscriberid )."'";

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

		$sid=array();

		$lid=array();

		$stid=array();

		$qry_resultset=false;

		$email="";

		if ($data['subscriberid'] && $data['listid'] && $data['statid']){

		    $data['msg']=$mn;

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

    			$email=$qry_row['emailaddress'];

    		}

		    $data['X-Mailer-LID']=$data['listid'];

    		$data['X-Mailer-RecptId']=$data['subscriberid'];

    		$data['X-Mailer-SID']=$data['statid'];

    		$data['X-Apparently-To']=$email;

    		$data['feedbackloop']=true;

		}else{

		    $data=array("feedbackloop"=>false,'raw-x-header'=>$data['x-header'],'msg'=>$mn);

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

    			$sid[]=$qry_row['subscriberid'];

    			$lid[]=$qry_row['listid'];

    			$qry_resultset=true;

    			$email=$qry_row['emailaddress'];

    		}

    		if (!$qry_resultset){

    		    return $data;

    		}

    		$sid=(count($sid)>0)?$sid:array(0);

    		$lid=(count($lid)>0)?$lid:array(0);

    		foreach ($lid as $k=>$v){

    			$q="SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletter_lists WHERE listid='".$db->Quote ( $v )."'";

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

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

    				$stid[]=$qry_row['statid'];

    			}

    		}

    		$stid=(count($stid)>0)?$stid:array(0);

    		$data['X-Mailer-LID']=implode(",",$lid);

    		$data['X-Mailer-RecptId']=implode(",",$sid);

    		$data['X-Mailer-SID']=implode(",",$stid);

    		$data['X-Apparently-To']=$email;

    		$data['feedbackloop']=true;

		}

		return $data;

	}



	//Create from next

	public function assemble_from_next(&$data,$from){

		$data['From']=$this->extract_emails_from($from);

		$db = IEM::getDatabase();

		$query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers WHERE emailaddress='".$db->Quote ( $data['From'] )."'";

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

		$sid=array();

		$lid=array();

		$stid=array();

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

			$sid[]=$qry_row['subscriberid'];

			$lid[]=$qry_row['listid'];

		}



		$sid=(count($sid)>0)?$sid:array(0);

		$lid=(count($lid)>0)?$lid:array(0);

		foreach ($lid as $k=>$v){

			$q="SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletter_lists WHERE listid='".$db->Quote ( $v )."'";

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

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

				$stid[]=$qry_row['statid'];

			}

		}

		$stid=(count($stid)>0)?$stid:array(0);

		$data['X-Mailer-LID']=implode(",",$lid);

		$data['X-Mailer-RecptId']=implode(",",$sid);

		$data['X-Mailer-SID']=implode(",",$stid);

	}



	public function count_in_stat($statid){

		return 0;

	}

}