<?php

define("FBL_DOMAINS", "all");
define("FBL_DELETE_UNKNOWN", true);

class Fbl_API extends API {

    private $instance = NULL;
    private $db = NULL;
    
    public $mails_to_delete = array();
    public $folder = "INBOX";
    public $link = NULL;

    public function __construct() {
        $this->db = IEM::getdatabase();
    }

    public function connect($fbl=array()) {
        $r = array();
        $r["type"] = $fbl["type"];
        $r["method"] = $fbl["method"];
        if( $fbl["type"] == 1 ) {
            imap_timeout(IMAP_READTIMEOUT, 10);
            $this->host_string = "{" . $fbl["hostname"] . ":" . $fbl["port"] . $fbl["advanced"] . "}";
            $host = "{" . $fbl["hostname"] . ":" . $fbl["port"] . $fbl["advanced"] . "}" . $this->folder;
            $mbox = imap_open($host, $fbl["username"], $fbl["password"]);
            $this->link = $mbox;
            $r["mbox"] = $mbox;
            if( !$mbox ) {
                $r["error"] = imap_last_error();
            }
            else {
                $r["error"] = false;
            }

        }
        else {
            $r["error"] = "Unknown error";
        }

        return $r;
    }

    public function disconnect($link) {
        imap_close($link["mbox"]);
    }

    public function count_fbl($link) {
        $t = 0;
        if( $link["type"] == 1 ) {
            $t = !$link["mbox"] ? 0 : imap_num_msg($link["mbox"]);
        }

        return $t;
    }

    public function process_all($limit=500) {
        $fbls = $this->fbl_details();
        foreach( $fbls as $k => $v ) {
            $imap = $this->connect($v);
            $total = $this->count_fbl($imap);
            $processed = $this->process($imap, $limit);
            $this->disconnect($imap);
        }
    }

    public function fix() {
        $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters";
        $result = $this->db->Query($query);
        while( $row = $this->db->Fetch($result) ) {
            $query = "SELECT COUNT(DISTINCT subscriberid) as total FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe WHERE `statid`='" . $row["statid"] . "' AND fbl='1'";
            $rt = $this->db->Query($query);
            $r = $this->db->Fetch($rt);
            $fbls = $r["total"];
            $qun = "UPDATE " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters SET fbl=" . $fbls . " WHERE `statid`='" . trim($row["statid"]) . "'";
            $this->db->Query($qun);
            $this->log("Fixing: " . $row["statid"] . " with " . $fbls);
        }
    }

    public function fbl_details($id=false, $blank=false) {
        if( !$id && !$blank ) {
            $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "fbl";
            $q = $this->db->Query($query);
            $data = array();
            while( $row = $this->db->Fetch($q) ) {
                $data[] = $row;
            }

            return $data;
        }

        $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "fbl WHERE uid='" . $this->db->Quote($id) . "'";
        $result = $this->db->Query($query);
        $r = $this->db->Fetch($result);
        $data = $r ? $r : array( "port" => 143 , "advanced" => "/imap/novalidate-cert" );
        return array( "exist" => $r ? true : false , "data" => $data );
    }

    public function add($data) {
        $port = is_numeric($data["fbl_port"]) ? $data["fbl_port"] : $data["type"] == 1 ? 143 : 995;
        $advanced_default = "/imap/novalidate-cert";
        $method = is_numeric($data["fbl_method"]) ? $data["fbl_method"] : 1;
        $result = $this->db->InsertQuery("fbl", array( "name" => $data["fbl_name"] , "hostname" => $data["fbl_hostname"] , "username" => $data["fbl_username"] , "password" => $data["fbl_password"] , "port" => $port , "type" => !empty( $data["fbl_type"] ) ? $data["fbl_type"] : 1 , "advanced" => !empty( $data["fbl_advanced"] ) ? $data["fbl_advanced"] : $advanced_default , "method" => $method ));
        return $result;
    }

    public function update($data) {
        $port = is_numeric($data["fbl_port"]) ? $data["fbl_port"] : $data["type"] == 1 ? 143 : 995;
        $advanced_default = "/imap/novalidate-cert";
        $uid = is_numeric($data["fbl_uid"]) ? $data["fbl_uid"] : 0;
        $method = is_numeric($data["fbl_method"]) ? $data["fbl_method"] : 1;
        $result = $this->db->UpdateQuery("fbl", array( "name" => $data["fbl_name"] , "hostname" => $data["fbl_hostname"] , "username" => $data["fbl_username"] , "password" => $data["fbl_password"] , "port" => $port , "type" => !empty( $data["fbl_type"] ) ? $data["fbl_type"] : 1 , "advanced" => !empty( $data["fbl_advanced"] ) ? $data["fbl_advanced"] : $advanced_default , "method" => $method ), "`uid`=" . $uid);
        return $result;
    }

    public function delete($id) {
        return $this->db->DeleteQuery("fbl", "WHERE `uid`=" . $id, 1);
    }

    public function process($link, $interval=100) {
        $info = array();
        $delete = array();
        $head = $this->head($link, $interval);
        $info["head"] = $head;
        foreach( $head as $key => $value ) {
            if( $value["fbl"] ) {
                $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["host"] = $value["host"];
                $data["recipient_ip"] = $value["X-Mailer-IP"];
                if( FBL_DOMAINS == "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->unsubscribe_from_list($w, $v);
                                    foreach( $subscribers_stat as $m => $o ) {
                                        $nd["stat_id"] = (int) ($o);
                                        $this->save_in_fbl_table($nd);
                                        $this->unsubscribe_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->unsubscribe_from_list($w, $v, true);
                                        foreach( $subscribers_stat as $m => $o ) {
                                            $nd["stat_id"] = (int) ($o);
                                            $this->save_in_fbl_table($nd);
                                            $this->unsubscribe_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->unsubscribe_from_stats($w, $v, $nd["stat_id"], $data["recipient_ip"], true);
                                    }
                                }
                            }
                            else {
                                $this->log("Skipping !isset user: " . print_r($nd, true));
                            }
                        }
                    }
                }
            }
        }

        $info["processed"] = count($delete);
        $this->delete_processed($link, $delete);
        return $info;
    }

    public function unsubscribe_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( "fbl" => 1 , "unsubscribed" => $this->db->Quote(time()) , "unsubscribeconfirmed" => 1 ), "`subscriberid`='" . trim($subscriberid) . "' AND `listid`='" . trim($listid) . "'");
            return NULL;
        }

        $this->log("Unsubscribing UPDATED from listid: " . $listid . " , subscriberid:" . $subscriberid);
        $this->db->UpdateQuery("list_subscribers", array( "fbl" => 1 ), "`subscriberid`='" . trim($subscriberid) . "' AND `listid`='" . trim($listid) . "'");
    }

    public function unsubscribe_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( "fbl" => 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") );
            $r = $this->db->InsertQuery("list_subscribers_unsubscribe", $und);
            $qun = "UPDATE " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters SET unsubscribecount=unsubscribecount + 1 , fbl=fbl + 1 WHERE `statid`='" . trim($statid) . "'";
            $this->db->Query($qun);
            return NULL;
        }
        $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe WHERE `subscriberid`='" . trim($subscriberid) . "' AND `listid`='" . trim($listid) . "' AND `statid`='" . trim($statid) . "'";
        $result = $this->db->Query($query);
        $r = $this->db->Fetch($result);
        if( !$r ) {
            $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( "fbl" => 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") );
            $r = $this->db->InsertQuery("list_subscribers_unsubscribe", $und);
            $qun = "UPDATE " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters SET unsubscribecount=unsubscribecount + 1 , fbl=fbl + 1 WHERE `statid`='" . trim($statid) . "'";
            $this->db->Query($qun);
        }
    }

    public function flush() {
        $qun = "UPDATE " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters SET fbl=0";
        $this->db->Query($qun);
        $qun = "DELETE FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe WHERE fbl=1";
        $this->db->Query($qun);
    }

    public function save_in_fbl_table($data) {
        $result = $this->db->InsertQuery("fbl_mails", $data);
    }

    public function isset_subscriber($subscriberid, $listid) {
        $r = $this->db->Fetch($this->db->Query("SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers WHERE subscriberid=" . $this->db->Quote(trim($subscriberid)) . " AND listid=" . $this->db->Quote(trim($listid)) . " LIMIT 1"));
        return $r ? true : false;
    }

    public function get_stats_from_listid($listid) {
        $q = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletter_lists WHERE listid='" . $this->db->Quote($listid) . "'";
        $result = $this->db->Query($q);
        $stid = array();
        while( $row = $this->db->Fetch($result) ) {
            $stid[] = $row["statid"];
        }

        return $stid;
    }

    public function already_unsubscribed($id, $listid, $fbl=false) {
        $fbl = $fbl == true ? "AND fbl=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 " . $fbl;
        $result = $this->db->Query($q);
        $r = $this->db->Fetch($result);
        return $r ? true : false;
    }

    public function get_fbl_count_from_stat($statid) {
        $q = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletters WHERE statid=" . $this->db->Quote(trim($statid)) . " LIMIT 1";
        $result = $this->db->Query($q);
        $r = $this->db->Fetch($result);
        return ( $r ? $r["fbl"] : 0 );
    }

    public function get_fbl_count_from_list($listid) {
        $q = "SELECT COUNT(*) as total FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers_unsubscribe WHERE listid=" . $this->db->Quote(trim($listid)) . " AND fbl=1 GROUP BY subscriberid";
        $result = $this->db->Query($q);
        $t = array();
        while( $r = $this->db->Fetch($result) ) {
            $t[] = $r;
        }

        return count($t);
    }

    public function extract_emails_from($string) {
        preg_match_all("/[\\._a-zA-Z0-9-]+@[\\._a-zA-Z0-9-]+/i", $string, $matches);
        return $matches[0][0];
    }

    public function head($link, $interval=100) {
        $tm = $this->count_fbl($link);
        $tm = $interval < $tm ? $interval : $tm;
        $headd = array();
        if( !$link["mbox"] ) {
            return $headd;
        }

        if( $link["type"] == 1 ) {
            $i = 1;
            while( $i <= $tm ) {
                echo PHP_EOL . "Getting head from: " . $i . PHP_EOL;
                $header = $this->header_from_mail($link, $i);

                $headd[] = $header;
                ++$i;
            }
        }

        return $headd;
    }

    public function log($data) {
        if( IEM_CLI_MODE ) {
            echo PHP_EOL . print_r($data, true) . PHP_EOL;
        }

    }

    public function delete_processed($link, $processed=array(  )) {
        $folders = imap_list($link["mbox"], $this->host_string, "*");
        $this->log("Mails to Delete");
        $this->log($processed);
        $this->log($folders);
        $mboxname = "Trash";
        $ttd = count($processed);
        $i = 1;
        foreach( $processed as $k => $v ) {
            $r = imap_delete($link["mbox"], $v);
            $this->log("[" . $i . "/" . $ttd . "] Deleted: " . (!$r ? "ERROR " . imap_last_error() : "SUCCESS"));
            ++$i;
        }
        imap_expunge($link["mbox"]);
    }

    public function header_from_mail($link, $mn) {
        $data = array( "fbl" => false , "msg" => $mn , "status" => "none" );
        $subscriberid = false;
        $sp = $this->get_sp_0($link, $mn);

        if( $sp["subscriberid"]) {
            return $this->assemble_from_subscriberid($sp, $mn);
        }

        $sp = $this->get_sp0($link, $mn);
        if( $sp["subscriberid"] ) {
            return $this->assemble_from_subscriberid($sp, $mn);
        }

        $sp = $this->get_sp1($link, $mn, $sp["x-header"]);
        if( $sp["subscriberid"] ) {
            return $this->assemble_from_subscriberid($sp, $mn);
        }

        $sp = $this->get_sp2($link, $mn, $sp["x-header"]);
        if( $sp["subscriberid"] ) {
            return $this->assemble_from_subscriberid($sp, $mn);
        }

        $sp = $this->get_sp3($link, $mn, $sp["x-header"]);
        if( $sp["subscriberid"] ) {
            return $this->assemble_from_subscriberid($sp, $mn);
        }

        $sp = $this->get_sp4($link, $mn, $sp["x-header"]);
        if( $sp["subscriberid"] ) {
            return $this->assemble_from_subscriberid($sp, $mn);
        }

        $body = $this->get_body($mn);
        return $data;
    }

    public function get_body($mn) {
        return imap_body($this->link, $mn);
    }

    public function get_sp_0($link, $mn, $xheader=array(  )) {
        $result = array();
        $a = explode("\n", @imap_body($link["mbox"], $mn));
        $xheader = array();
        foreach( $a as $k => $v ) {
            if( @eregi("^X-", $v) ) {
                @eregi("^([^:]*): (.*)", $v, $arg);
                $xheader[$arg[1]] = $arg[2];
            }

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

            if (!array_key_exists('subscriberid', $xheader) && $uu["subscriberid"]) {
                $xheader = array_merge($xheader, $uu);
            }

            if (array_key_exists('host', $xheader))
            {        
                if (!empty($uu['host']))
                {
                    $xheader['host'] = $uu["host"];
                }
            }
        }

        return $xheader;
    }

    public function get_sp0($link, $mn, $xheader=array(  )) {
        $result = array();
        $a = explode("\n", @imap_fetchbody($link["mbox"], $mn, 0));
        $xheader = array();
        foreach( $a as $k => $v ) {
            if( @eregi("^X-", $v) ) {
                @eregi("^([^:]*): (.*)", $v, $arg);
                $xheader[$arg[1]] = $arg[2];
            }

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

            if (!array_key_exists('subscriberid', $xheader) && $uu["subscriberid"]) {
                $xheader = array_merge($xheader, $uu);
            }

            if (array_key_exists('host', $xheader))
            {        
                if (!empty($uu['host']))
                {
                    $xheader['host'] = $uu["host"];
                }
            }
        }

        return $xheader;
    }

    public function get_sp1($link, $mn, $xheader=array()) {
        $result = array();
        $a = explode("\n", @imap_fetchbody($link["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->string_to_subscriberid($v); 

            if (!array_key_exists('subscriberid', $xheader) && $uu["subscriberid"]) {
                $xheader = array_merge($xheader, $uu);
            }

            if (array_key_exists('host', $xheader))
            {        
                if (!empty($uu['host']))
                {
                    $xheader['host'] = $uu["host"];
                }
            }
        }

        return $xheader;
    }

    public function get_sp2($link, $mn, $xheader=array(  )) {
        $result = array();
        $a = explode("\n", @imap_fetchbody($link["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->string_to_subscriberid($v); 

            if (!array_key_exists('subscriberid', $xheader) && $uu["subscriberid"]) {
                $xheader = array_merge($xheader, $uu);
            }

            if (array_key_exists('host', $xheader))
            {        
                if (!empty($uu['host']))
                {
                    $xheader['host'] = $uu["host"];
                }
            }
        }

        return $xheader;
    }

    public function get_sp3($link, $mn, $xheader=array(  )) {
        $result = array();
        $a = explode("\n", @imap_fetchbody($link["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->string_to_subscriberid($v); 

            if (!array_key_exists('subscriberid', $xheader) && $uu["subscriberid"]) {
                $xheader = array_merge($xheader, $uu);
            }

            if (array_key_exists('host', $xheader))
            {        
                if (!empty($uu['host']))
                {
                    $xheader['host'] = $uu["host"];
                }
            }
        }

        return $xheader;
    }

    public function get_sp4($link, $mn, $xheader=array(  )) {
        $result = array();
        $a = explode("\n", @imap_fetchbody($link["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->string_to_subscriberid($v); 

            if (!array_key_exists('subscriberid', $xheader) && $uu["subscriberid"]) {
                $xheader = array_merge($xheader, $uu);
            }

            if (array_key_exists('host', $xheader))
            {        
                if (!empty($uu['host']))
                {
                    $xheader['host'] = $uu["host"];
                }
            }
        }

        return $xheader;
    }

    public function string_to_subscriberid($str) {
        $uri = "unsubscribe\\.php";
        $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( "host" => trim($str) , "subscriberid" => $subscriberid , "statid" => $statid , "confirmed" => $confirmed , "listid" => $listid );
        }

        return array( "subscriberid" => false );
    }

    public function assemble_from_subscriberid($data, $mn) {
        $subscriberid = $data["subscriberid"];
        $db = IEM::getdatabase();
        $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers WHERE subscriberid='" . $db->Quote($subscriberid) . "'";
        $result = $db->Query($query);
        $sid = array();
        $lid = array();
        $stid = array();
        $rt = false;
        $email = "";

        if( $data["subscriberid"] && $data["listid"] && $data["statid"] ) {
            $data["msg"] = $mn;
            while( $row = $db->Fetch($result) ) {
                $email = $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["fbl"] = true;
        }
        else {
            $data = array( "fbl" => false , "raw-x-header" => $data["x-header"] , "msg" => $mn );
            while( $row = $db->Fetch($result) ) {
                $sid[] = $row["subscriberid"];
                $lid[] = $row["listid"];
                $rt = true;
                $email = $row["emailaddress"];
            }
            if( !$rt ) {
                return $data;
            }

            $sid = 0 < count($sid) ? $sid : array( 0 );
            $lid = 0 < count($lid) ? $lid : array( 0 );
            foreach( $lid as $k => $v ) {
                $q = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletter_lists WHERE listid='" . $db->Quote($v) . "'";
                $result = $db->Query($q);
                if( $row = $db->Fetch($result) ) {
                    $stid[] = $row["statid"];
                }
            }

            $stid = 0 < count($stid) ? $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["fbl"] = true;
        }

        return $data;
    }

    public function assemble_from_3(&$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"]) . "'";
        $result = $db->Query($query);
        $sid = array();
        $lid = array();
        $stid = array();
        while( $row = $db->Fetch($result) ) {
            $sid[] = $row["subscriberid"];
            $lid[] = $row["listid"];
        }

        $sid = 0 < count($sid) ? $sid : array( 0 );
        $lid = 0 < count($lid) ? $lid : array( 0 );
        foreach( $lid as $k => $v ) {
            $q = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "stats_newsletter_lists WHERE listid='" . $db->Quote($v) . "'";
            $result = $db->Query($q);
            while( $row = $db->Fetch($result) ) {
                $stid[] = $row["statid"];
            }
        }

        $stid = 0 < count($stid) ? $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;
    }
}

?>