<?php

/*
  MailBeez Automatic Trigger Email Campaigns
  http://www.mailbeez.com

  Copyright (c) 2010 - 2012 MailBeez

  inspired and in parts based on
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
  
  
  V2.7.4
 */

///////////////////////////////////////////////////////////////////////////////
///																																					 //
///                 MailBeez Core file - do not edit                         //
///                                                                          //
///////////////////////////////////////////////////////////////////////////////

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/configbeez.php');

mh_register_module(mh_cfg('MH_MODULE_KEY', 'MAILBEEZ_INSTALLED'), 'service_newsletter2go_api_v2.php');


class config_email_engine extends configbeez
{

// class constructor
    function __construct()
    {
        parent::__construct();
        $this->code = 'config_email_engine';
        $this->module = 'config_email_engine'; // same as folder name
        $this->version = 4.5; // float value
        $this->title = mh_lng('MAILBEEZ_CONFIG_EMAIL_ENGINE_TEXT_TITLE');
        $this->description = mh_lng('MAILBEEZ_CONFIG_EMAIL_ENGINE_TEXT_DESCRIPTION');
        $this->description_image = '../../common/images/icon_system_64.png';
        $this->icon = '../../common/images/icon_system.png';
        $this->removable = false; // can't be removed
        $this->stealth = true; // don't list as an installed module
        $this->display_as_submodule_of = 'config';
        $this->sort_order = 1.3;
        $this->enabled = mh_cfg('MAILBEEZ_MAILHIVE_STATUS') == 'True';
        $this->on_cfg_save_clear_template_c = true;

        $this->admin_action_plugins_path = MH_DIR_CONFIG; // default-path to include admin action plugins from

        $this->admin_action_plugins = 'register_mlbz_ubvx.php';


        if (('Newsletter2Go' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'))) {
            if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION') == 'v1') {
                $this->admin_action_plugins = 'register.php';
            } else {
                $this->admin_action_plugins = 'register_v2.php';
            }
        }


//        $this->admin_action_plugins .= (preg_match('/PHPMailer/', MAILBEEZ_CONFIG_EMAIL_ENGINE) || preg_match('/Newsletter2Go/', MAILBEEZ_CONFIG_EMAIL_ENGINE)) ? 'test.php' : '';
        $this->admin_action_plugins .= (preg_match('/PHPMailer/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'))) ? ';connection.php;test.php' : '';
        $this->admin_action_plugins .= ('mlbz_ubvx' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE') || 'mlbz_hysndr' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) ? ';connection.php;test.php' : '';

        $this->documentation_key = 'config_email_engine'; // leave empty if no documentation available
        $this->documentation_root = 'https://www.mailbeez.com/documentation/installation/config/';

        $this->advanced = true;
        $this->mlbz = true;
        $this->mlbz_advanced = true;
    }

    function config_email_engine()
    {
        self::__construct();
    }

// class methods

    function getAudience()
    {
        return false;
    }

    function check()
    {
        return true;
    }

    function remove()
    {
        return false;
    }

    // installation methods

    function keys()
    {

        $keys_array = array('MAILBEEZ_CONFIG_EMAIL_ENGINE', 'MAILBEEZ_CONFIG_EMAIL_ENCODE_SUBJECT', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING' /* 'MAILBEEZ_EMAIL_TRANSPORT', */);


        if (MH_PLATFORM == 'zencart') {
            $keys_array = array_merge(array('MAILBEEZ_MAILHIVE_ZENCART_OVERRIDE'), $keys_array);
        }

        if (mh_get('action') && ('Newsletter2Go' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'))) {

            if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION') == 'v1') {
                if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_DEBUG_MODE') == 'True') {
                    $keys_n2g = array('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY');
                } else {
                    $keys_n2g = array('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY');
                }
            } else {
                if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_DEBUG_MODE') == 'True') {
                    $keys_n2g = array('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_AUTH_KEY', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_ACCESS_TOKEN', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_REFRESH_TOKEN', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_SECRET', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_LIST_ID', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_CAMPAIGN_DATA');

                } else {
                    $keys_n2g = array();

                }
            }

            if ('Newsletter2Go' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) {
                $keys_n2g = array_merge(array('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_DEBUG_MODE'), $keys_n2g);
            }
            $keys_array = array_merge($keys_array, $keys_n2g);

        }

        $keys_smtp = array('MAILBEEZ_CONFIG_EMAIL_ENGINE_DEBUG_MODE',
            'MAILBEEZ_SMTP_USERNAME', 'MAILBEEZ_SMTP_SENDER', 'MAILBEEZ_SMTP_PASSWORD', 'MAILBEEZ_SMTP_MAIN_SERVER', 'MAILBEEZ_SMTP_BACKUP_SERVER', 'MAILBEEZ_SMTP_AUTH', 'MAILBEEZ_SMTP_SECURE', 'MAILBEEZ_SMTP_PORT', 'MAILBEEZ_ADD_HEADER_REPLY_TO', 'MAILBEEZ_SMTP_ABUSE_INFO', 'MAILBEEZ_SMTP_ABUSE_EMAIL_ADDRESS', 'MAILBEEZ_SMTP_DISABLE_SSL_VERIFICATION');

        if (mh_get('action') && (preg_match('/PHPMailer/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')))) {
            $keys_array = array_merge($keys_array, $keys_smtp);
            $keys_array = array_merge($keys_array, array('MAILBEEZ_EMAIL_USE_TXT_ONLY', 'MAILBEEZ_CONFIG_EMAIL_ENGINE_WORDWRAP' /*, 'MAILBEEZ_SENDMAIL_PATH' */));

            if (!version_compare(PHP_VERSION, '5.0.0', '<')) {
                // requires PHP 5
                $keys_array = array_merge($keys_array, array('MAILBEEZ_DKIM_SELECTOR', 'MAILBEEZ_DKIM_IDENTIY', 'MAILBEEZ_DKIM_PASSPHRASE', 'MAILBEEZ_DKIM_DOMAIN', 'MAILBEEZ_DKIM_PRIVATE'));
            }
        }

        $keys_array = array_merge($keys_array, array('MAILBEEZ_CONFIG_EMAIL_BUGFIX_1'));

        $mailbeezEmailEngine = strtolower((string)mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'));
        if (mh_get('action') && (($mailbeezEmailEngine == 'mlbz_ubvx') || ($mailbeezEmailEngine == 'mlbz_hysndr'))) {
            if ($mailbeezEmailEngine == 'mlbz_hysndr') {
                $credential_keys = array('MAILBEEZ_MLBZ_HYSNDR_USERNAME', 'MAILBEEZ_MLBZ_HYSNDR_PASSWORD');
            } else {
                $credential_keys = array('MAILBEEZ_MLBZ_UBVX_USERNAME', 'MAILBEEZ_MLBZ_UBVX_PASSWORD');
            }
            $keys_mlbz_ubvx = array_merge($credential_keys, array(
                'MAILBEEZ_CONFIG_EMAIL_ENGINE_MLBZ_DEBUG_MODE',
                'MAILBEEZ_SMTP_SENDER',
                'MAILBEEZ_MLBZ_BOUNCE_SOFT_DAYS',
                'MAILBEEZ_MLBZ_BOUNCE_SOFT_HARD_COUNT',
                'MAILBEEZ_MLBZ_BOUNCE_SOFT_HARD_COUNT_DAYS',
            ));

            $keys_array = array_merge($keys_array, $keys_mlbz_ubvx);
        }
        return $keys_array;
    }

    function install()
    {
        return false;
    }

    function show_engine_name($engine_id)
    {
        $mapping = array('Shop' => 'Shop', 'mlbz_ubvx' => 'MailBeez.Email V4', 'mlbz_hysndr' => 'MailBeez.Email V5', 'PHPMailer' => 'SMTP', 'Newsletter2Go' => 'Newsletter2Go');
        return '<b><i>' . $mapping[$engine_id] . '</i></b> ';
    }

    static function deleteEmailErrors()
    {
        $sql = "delete from " . TABLE_MAILBEEZ_TRACKING . " where message_id=-1 or message_id=-42";
        return mh_db_query($sql);
    }

    static function ignoreEmailErrors()
    {
        $sql = "update " . TABLE_MAILBEEZ_TRACKING . " set message_id=-2 where message_id=-1";
        return mh_db_query($sql);
    }


    static function trackBounce($data = [])
    {
        // generate def. data');
        if ($data == []) {
            $data['classification'] = 'soft';
            $data['time'] = (string)explode('+', date('c'))[0]; // 2022-1
            $data['reference'] = '';
            $data['address'] = '';
        }

        $bounced_email_address = $data['address'];

        // convert to db date
        $date_bounce = date('Y-m-d H:i:s', strtotime(str_replace("T", " ", $data['time'])));
        $bounce_type = ($data['classification'] == 'hard') ? 'H' : 'S';

        // prepare for email addresses like test'@gmail.com
        $bounced_email_address = mh_db_input($bounced_email_address);

        // check against written hard bounces
        $sql_query_raw = "select id from " . TABLE_MAILBEEZ_BOUNCE . " where bounce_type = 'H' and customers_email = '" . $bounced_email_address . "'";

        $sql_query = mh_db_query($sql_query_raw);

        if (mh_db_num_rows($sql_query) > 0) {
            // hard bounced
            return false;
        }

        // try to match email with mailbeez tracking data
        // find last mail
        $sql_query_raw = "select autoemail_id, module, customers_email, customers_id, bounce_status
                                from " . TABLE_MAILBEEZ_TRACKING . "
                                where customers_email = '" . $bounced_email_address . "'
                                order by autoemail_id DESC
                                limit 1";
        $sql_query = mh_db_query($sql_query_raw);

        // found matching entry
        if (mh_db_num_rows($sql_query) > 0) {
            $query = mh_db_fetch_array($sql_query);
            $bounce_type_checked = self::bounce_analyzer($bounce_type, $query['customers_id']);
            $sql_data_array = array('autoemail_id' => $query['autoemail_id'],
                'customers_email' => $query['customers_email'],
                'customers_id' => $query['customers_id'],
                'module' => $query['module'],
                'date_bounce' => $date_bounce,
                'bounce_type' => $bounce_type_checked,
                'reference' => $data['reference']
            );

            mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);

            /*
            if (mh_get_conf('MAILBEEZ_BOUNCEHIVE_UNSUBSCRIBE') == 'True') {
                mailbeez_bounce_unsubscribe($query['customers_id'], 'H');
            }
            */

            if (mh_cfg('MAILBEEZ_BOUNCEHIVE_MSG_LOG') == 'True') {
                $sql_data_array = array('autoemail_id' => $query['autoemail_id'],
                    'bounce_msg' => 'Mlbz ' . $bounce_type_checked . ' Bounce',
                );
                mh_db_perform(TABLE_MAILBEEZ_BOUNCE_MSG_LOG, $sql_data_array);
            }

            mh_db_query("update " . TABLE_MAILBEEZ_TRACKING . "
                                set bounce_status = '" . $bounce_type_checked . "'
                                where autoemail_id = '" . $query['autoemail_id'] . "'");

            // echo "$bounced_email_address matched to mailbeez email <hr>";
            return true;

        } else {
            // track all other email addresses as well
            $sql_data_array = array('autoemail_id' => -1,
                'customers_email' => $bounced_email_address,
                'customers_id' => -1,
                'module' => 'n/a',
                'date_bounce' => $date_bounce,
                'bounce_type' => $bounce_type
            );

            mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);
            //echo "$bounced_email_address unknown, tracked <hr>";
            return true;

        }

    }


    static function bounce_analyzer($bounce_status, $customers_id)
    {
        if ($bounce_status == 'S') {
            $rawtime = strtotime("-" . (int)mh_cfg('MAILBEEZ_MLBZ_BOUNCE_SOFT_HARD_COUNT_DAYS') . " days");
            $dbdate = date("Ymd", $rawtime);

            // count softbounce in the last MAILBEEZ_MLBZ_BOUNCE_SOFT_HARD_COUNT_DAYS days

            $sql_query_raw = "select count(autoemail_id) as softcnt
                    from " . TABLE_MAILBEEZ_BOUNCE . "
                    where customers_id = '" . $customers_id . "'
                        and bounce_type = 'S'
                        and date_bounce > " . $dbdate . " ";

            $sql_query = mh_db_query($sql_query_raw);

            if (mh_db_num_rows($sql_query) > 0) {
                $query = mh_db_fetch_array($sql_query);
                if ($query['softcnt'] > (int)mh_cfg('MAILBEEZ_MLBZ_BOUNCE_SOFT_HARD_COUNT')) {
                    return 'H';
                }
            }
            return $bounce_status;

        } else {
            return $bounce_status;
        }
    }

    static function bounce_fallback($result, $bounce_status, $true_body)
    {
        $sql_query_raw = "select autoemail_id, module, customers_email, customers_id, bounce_status
                        from " . TABLE_MAILBEEZ_TRACKING . "
                        where customers_email = '" . $result['recipient'] . "'
                            and bounce_status = ''
                        order by autoemail_id DESC
                        limit 1";

        $sql_query = mh_db_query($sql_query_raw);

        if (mh_db_num_rows($sql_query) > 0) {
            $query = mh_db_fetch_array($sql_query);

            $bounce_status_write = mailbeez_analyzer($bounce_status, $query['customers_id']);

            $sql_data_array = array('autoemail_id' => $query['autoemail_id'],
                'customers_email' => $query['customers_email'],
                'customers_id' => $query['customers_id'],
                'module' => $query['module'],
                'date_bounce' => 'now()',
                'bounce_type' => $bounce_status_write
            );

            mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);

            if (mh_cfg('MAILBEEZ_BOUNCEHIVE_UNSUBSCRIBE') == 'True') {
                mailbeez_bounce_unsubscribe($query['customers_id'], $bounce_status_write);
            }

            if (mh_cfg('MAILBEEZ_BOUNCEHIVE_MSG_LOG') == 'True') {
                $sql_data_array = array('autoemail_id' => $query['autoemail_id'],
                    'bounce_msg' => $true_body,
                );
                mh_db_perform(TABLE_MAILBEEZ_BOUNCE_MSG_LOG, $sql_data_array);
            }

            mh_db_query("update " . TABLE_MAILBEEZ_TRACKING . "
                        set bounce_status = '" . $bounce_status_write . "'
                        where autoemail_id = '" . $query['autoemail_id'] . "'");
        } else {
            // add bounce data for unknown mail

            echo "handling bounced on unknown email<hr>";
            $sql_query_raw = "select customers_id, customers_email_address
                            from " . TABLE_CUSTOMERS . "
                            where customers_email_address = '" . $result['recipient'] . "'";

            $sql_query = mh_db_query($sql_query_raw);

            // write for all matching customer ids
            while ($query = mh_db_fetch_array($sql_query)) {
                $sql_data_array = array('autoemail_id' => -1,
                    'customers_email' => $query['customers_email_address'],
                    'customers_id' => $query['customers_id'],
                    'module' => 'n/a',
                    'date_bounce' => 'now()',
                    'bounce_type' => $bounce_status
                );

                mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);


                if (mh_cfg('MAILBEEZ_BOUNCEHIVE_UNSUBSCRIBE') == 'True') {
                    mailbeez_bounce_unsubscribe($query['customers_id'], $bounce_status);
                }

            }
        }
    }

    static function connection_test()
    {

        if (('mlbz_ubvx' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) ||('mlbz_hysndr' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) || (preg_match('/PHPMailer/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')))) {
            // remove output buffering
            ob_start();
            $connectionTest = mh_php_mail('test@mailbeez.com',
                'test',
                'test@mailbeez.com',
                'test',
                'test@mailbeez.com',
                'test',
                '',
                'test@mailbeez.com',
                'test',
                '',
                '',
                'test',
                'test',
                'test',
                array('list_unsubscribe_post' => 'test_list_unsubscribe_post', 'email_message_id' => 'test_email_message_id'),
                true);
            ob_end_clean();
            return $connectionTest;
        }
        return false;
    }

}

