<?php

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

  Copyright (c) 2010, 2011 MailBeez

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

  Released under the GNU General Public License
 */

/*

  abstraction layer for email-engine

  v2.7.6

 */

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

mh_define('MH_EMAIL_ENGINE_LOGFILE', MH_DIR_FS_LOGS . 'email_failed.log');


if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_BUGFIX_1') == 'True') {
    $GLOBALS['mailbeez_bugfix_1_pattern'] = array();
    $GLOBALS['mailbeez_bugfix_1_replace'] = array();

    $GLOBALS['mailbeez_bugfix_1_pattern'][0] = '/\..php/';
    $GLOBALS['mailbeez_bugfix_1_replace'][0] = '.php';

    $GLOBALS['mailbeez_bugfix_1_pattern'][1] = '/\..png/';
    $GLOBALS['mailbeez_bugfix_1_replace'][1] = '.png';

    $GLOBALS['mailbeez_bugfix_1_pattern'][2] = '/\..jpeg/';
    $GLOBALS['mailbeez_bugfix_1_replace'][2] = '.jpeg';

    $GLOBALS['mailbeez_bugfix_1_pattern'][3] = '/\..jpg/';
    $GLOBALS['mailbeez_bugfix_1_replace'][3] = '.jpg';

    $GLOBALS['mailbeez_bugfix_1_pattern'][4] = '/\..gif/';
    $GLOBALS['mailbeez_bugfix_1_replace'][4] = '.gif';

}

switch (MH_PLATFORM) {
    case 'oscommerce':
    case 'creloaded':
    case 'digistore':
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/oscommerce/emailMB.php');
        break;
    case 'zencart':
        break;
    case 'xtc':
    case 'gambio':
    case 'mercari':
        break;
    default:
        echo 'platform not supported';
}

// switch between systems
function mh_sendEmail($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt, $is_copy = false)
{
    $result = false;

    if (mh_cfg('MAILBEEZ_MAILHIVE_STATUS') == 'False') {
        return false;
    }

    if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_BUGFIX_1') == 'True') {
        // try to fix that wired '..' issue
        // where e.g. file.php becomes file..php, image.png becomes image..png
        // could be already in the generated output (not very likely)

        $output_content_html = preg_replace($GLOBALS['mailbeez_bugfix_1_pattern'], $GLOBALS['mailbeez_bugfix_1_replace'], $output_content_html);
    }


    // final check for valid content

    if (str_replace(MAILBEEZ_SIMULATION_TAG, '', $output_subject) == '' || $output_content_html == '') {

        $error_msg = 'sending cancelled due to empty subject or html body';

        $msg = "*****\n";
        $msg .= "$error_msg\n";
//        $msg .= '$mail (' . sizeof($mail) . '): ' . var_export($mail, true);
        $msg .= '$output_subject: ' . $output_subject . "\n";
        $msg .= '$output_content_html: ' . $output_content_html . "\n";
        $msg .= '$mail (' . sizeof($mail) . ')' . "\n";

        mh_email_failed_log($msg);
        return array('message_id' => -1, 'stop' => 1, 'error' => $error_msg);
    }

    $uniq_id = uniqid();
    if (!empty($mail->Hostname)) {
        $serverhostname = $mail->Hostname;
    } elseif (isset($_SERVER['SERVER_NAME'])) {
        $serverhostname = $_SERVER['SERVER_NAME'];
    } else {
        $serverhostname = 'localhost.localdomain';
    }


    // message-id for tracking open / click
    $mail['message_id'] = (isset($mail['message_id'])) ? $mail['message_id'] : sprintf("%s", $uniq_id);
    // message id for PHPMailer bouncehandling
    $mail['email_message_id'] = (isset($mail['email_message_id'])) ? $mail['email_message_id'] : sprintf("<mb.%s@%s>", $uniq_id, $serverhostname);

    if (!isset($mail['mailengine']) && preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) && (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION') == 'v2')) {
        // avoid N2Go V2 thumbnail builder to open tracking image
        // {{recipient.id}} will not be parsed in when generating thumbnail
        $output_content_html = str_replace(MAILBEEZ_TRACKER_OPEN_PARAM . MAILBEEZ_MESSAGE_ID_TOKEN, MAILBEEZ_TRACKER_OPEN_PARAM . MAILBEEZ_MESSAGE_ID_TOKEN . "&n2go_rid={{recipient.id}}", $output_content_html);
    }

    // parse message-id into email
    $output_content_html = str_replace(MAILBEEZ_MESSAGE_ID_TOKEN, $mail['message_id'], $output_content_html);
    $output_content_txt = str_replace(MAILBEEZ_MESSAGE_ID_TOKEN, $mail['message_id'], $output_content_txt);


    // allow to set from fields
    $from = (isset($mail['mailbeez_from_email']) && $mail['mailbeez_from_email'] != '') ? $mail['mailbeez_from_email'] : $from;
    $from_name = (isset($mail['mailbeez_from_name']) && $mail['mailbeez_from_name'] != '') ? $mail['mailbeez_from_name'] : $from_name;


    // dynamically set mailengine
    if (isset($mail['mailengine'])) {
        // use specified email engine
        $args = func_get_args();
        $args[0]['message_id'] = $mail['message_id'];
        $args[0]['email_message_id'] = $mail['email_message_id'];

        if (preg_match('/->/', $mail['mailengine'])) {
            // e.g. 'configbeez->mymodule->myMailEngine'
            $class_method = explode('->', $mail['mailengine']);
            if (!is_object(${$class_method[1]})) {
                include_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . '' . $class_method[0] . '/' . $class_method[1] . '.php');
                ${$class_method[1]} = new $class_method[1]();
            }
            call_user_func(array(${$class_method[1]}, $class_method[2]), makeValuesReferenced($args));

            $result = array('message_id' => $mail['message_id']);
        } elseif (function_exists($mail['mailengine'])) {
            call_user_func_array($mail['mailengine'], makeValuesReferenced($args));
            $result = array('message_id' => $mail['message_id']);
        } else {
            unset($mail['mailengine']);
            $result = mh_sendEmail($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt);
        }
    } else {

        if (preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'))) {
            mh_load_modules_language_files(MH_DIR_CONFIG, 'config_email_engine_n2g', MH_FILE_EXTENSION);

            $forwarding_to = (isset($mail['forwarding_to'])) ? $mail['forwarding_to'] : '';
            if ($forwarding_to != '') {
                echo 'ERROR: BCC not supported, please configure MailBeez to send through SMTP in MailBeez > Configuration > Email Engine';
                mh_exit();
            }

            if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION') == 'v1') {

                require_once(MH_DIR_CONFIG . 'config_email_engine_n2g/classes/newsletter2go.class.php');

                try {
                    $nl2go = new newsletter2go(mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY'));

                    $params = array(
                        'to' => $email_address,
                        'from' => $from_name . ' <' . $from . '>',
                        'subject' => mh_smart_force_utf8($output_subject),
                        'text' => mh_smart_force_utf8($output_content_txt),
                        'html' => mh_smart_force_utf8($output_content_html),
                        'debug' => '',
                        'ref' => $mail['current_module'] . '-' . $mail['iteration'],
                        'date' => '',
                        'reply' => '',
                        'linktracking' => '',
                        'opentracking' => ''
                    );

                    $result_n2go = $nl2go->sendEmail($params);

                    // 430 not allowed to send yet
                    // 402 Not enough credits

                    if ($result_n2go['status'] == 200) {
                        // OK
                        $result = array('message_id' => $mail['message_id']);
                    } elseif ($result_n2go['status'] == 430) {
                        $result = array('message_id' => -10, '_error_msg' => '<div style="border: 1px solid red; background-color: #fff; padding: 10px; margin: 10px">' . mh_lng('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_REG_STATUS') . '</div>', 'stop' => 1, 'error' => MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_REG_STATUS);
                    } elseif ($result_n2go['status'] == 402) {
                        $result = array('message_id' => -10, '_error_msg' => '<div style="border: 1px solid red; background-color: #fff; padding: 10px; margin: 10px">' . mh_lng('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_REG_STATUS_CREDITS') . '</div>', 'stop' => 1, 'error' => $result_n2go['reason']);
                    } else {
                        $result = array('message_id' => -10, '_error_msg' => '<div style="border: 1px solid red; background-color: #fff; padding: 10px; margin: 10px">Newsletter2Go Error: ' . $result_n2go['reason'] . '</div>', 'stop' => 1, 'error' => $result_n2go['reason']);
                    }

                    mh_free($nl2go);
                    //  [success] => 1 [value] => [status] => 200 [reason] => OK
                } catch (Exception $e) {
                    print_r($e->getMessage());
                    mh_exit();
                }
            } else {

                require_once(MH_DIR_CONFIG . 'config_email_engine_n2g/classes/newsletter2go_v2.class.php');

                $campaignName = $mail['module_iteration'];
                $replyEmail = null;
                $replyName = null;
                $result_n2go = array();
                try {
                    $nl2go = NL2GO\Api::getInstance();
                    $result_n2go = $nl2go->postSendMailBeez($campaignName, mh_smart_force_utf8($output_subject), mh_smart_force_utf8($output_content_html), $email_address, mh_smart_force_utf8($mail['firstname'] . ' ' . $mail['lastname']), $from, mh_smart_force_utf8($from_name), $replyEmail, mh_smart_force_utf8($replyName));
                } catch (Exception $e) {
                    print_r($e->getMessage());
                    mh_exit();

                }

                if ($result_n2go->status == 201) {
                    // OK
                    $result = array('message_id' => $mail['message_id']);
                } elseif ($result_n2go->code == 10031) {
                    $result = array('message_id' => -10, '_error_msg' => '<div style="border: 1px solid red; background-color: #fff; padding: 10px; margin: 10px">' . mh_lng('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_REG_STATUS') . '</div>', 'stop' => 1, 'error' => MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_REG_STATUS);
                } elseif ($result_n2go->code == 10048) {
                    $result = array('message_id' => -10, '_error_msg' => '<div style="border: 1px solid red; background-color: #fff; padding: 10px; margin: 10px">' . mh_lng('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_REG_STATUS_CREDITS') . '</div>', 'stop' => 1, 'error' => $result_n2go->errorMessage);
                } else {
                    $result = array('message_id' => -10, '_error_msg' => '<div style="border: 1px solid red; background-color: #fff; padding: 10px; margin: 10px">Newsletter2Go Error: ' . $result_n2go->errorMessage . '<br>' . print_r($result_n2go->moreInfo, true) . '</div>', 'stop' => 1, 'error' => $result_n2go->errorMessage);
                }
            }

        } elseif (
            (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE') == 'mlbz_ubvx') ||
            preg_match('/PHPMailer/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'))
        ) {

            require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/email_engine_php_mailer.php');

            $forwarding_to = (isset($mail['forwarding_to'])) ? $mail['forwarding_to'] : '';
            $path_to_attachement = '';
            $path_to_more_attachements = '';

            if (mh_cfg('MAILBEEZ_FROM_OVERRIDE') == 'True') {
                $from = mh_cfg('MAILBEEZ_FROM_ADDRESS');
                $from_name = mh_cfg('MAILBEEZ_FROM_ADDRESS_NAME');
            }


            if (mh_cfg('MAILBEEZ_ADD_HEADER_REPLY_TO') == 'True') {
                // reply_to added
                $reply_address = $from;
                $reply_address_name = $from_name;
            } else {
                // no reply-to added
                $reply_address = '';
                $reply_address_name = '';
            }


            //
            // $reply_address = (MAILBEEZ_REPLY_TO_ADDRESS == '') ? '' : MAILBEEZ_REPLY_TO_ADDRESS;
            // $reply_address_name = (MAILBEEZ_REPLY_TO_ADDRESS_NAME == '') ? '' : MAILBEEZ_REPLY_TO_ADDRESS_NAME;

            // set sender for bouncehandling
            // the email appears to be send from $from (also for reply), but bounces to $sender
            $sender = $from;
            $sender_name = $from_name;
            if (mh_cfg('MAILBEEZ_BOUNCEHIVE_STATUS') == 'True') {
                $sender = mh_cfg('MAILBEEZ_SENDER_ADDRESS');
                $sender_name = mh_cfg('MAILBEEZ_SENDER_ADDRESS_NAME');
            }

            $result = mh_php_mail($sender,
                $sender_name,
                $from,
                $from_name,
                $email_address,
                $mail['firstname'] . ' ' . $mail['lastname'],
                $forwarding_to,
                $reply_address,
                $reply_address_name,
                $path_to_attachement,
                $path_to_more_attachements,
                $output_subject,
                $output_content_html,
                $output_content_txt,
                $mail);
        } else {
            // default mailengine by platform
            switch (MH_PLATFORM) {
                case 'oscommerce':
                case 'creloaded':
                case 'digistore':
                    $result = osc_sendEmail($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt);
                    break;
                case 'mercari':
                    $result = mercari_sendEmail($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt);
                    break;
                case 'zencart':
                    $result = zencart_sendEmail($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt);
                    break;
                case 'xtc':
                case 'gambio':
                    $result = xtc_sendEmail($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt);
                    break;
                default:
                    $result = false;
                    echo 'platform not supported';
            }
        }
    }


    if (!$is_copy) {
        if ($result && $result['message_id'] > 0) {
            mh_archive_email($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt);
        }
    }

    return $result;
}


function mh_archive_email($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt)
{
    if (mh_cfg('MAILBEEZ_EMAIL_ARCHIVE_STATUS') == 'True') {
        require_once(MH_DIR_CONFIG . 'config_email_archive.php');
        return config_email_archive::archive($mail, $email_address, $from_name, $from, $output_subject, $output_content_html, $output_content_txt);
    }
    return false;
}


//// only used in case MAILBEEZ_CONFIG_EMAIL_ENGINE is set to "Shop"


// function for osCommerce
if (!function_exists('osc_sendEmail')) {
    function osc_sendEmail($mail, $email_address, $sender_name, $sender, $output_subject, $output_content_html, $output_content_txt)
    {

        $forwarding_to = (isset($mail['forwarding_to'])) ? $mail['forwarding_to'] : '';

        if ($forwarding_to != '') {
            echo 'ERROR: BCC not supported, please configure MailBeez to send through SMTP in MailBeez > Configuration > Email Engine';
            mh_exit();
        }

        $mimemessage = new emailMailBeez(array('X-Mailer: mailbeez.com', 'Return-Path: <' . $sender . '>'));
        // add html and alternative text version
        $mimemessage->add_html($output_content_html, $output_content_txt);
        $mimemessage->build_message(); // encoding -> 76 character linebreak, replacements must be done before

        if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_BUGFIX_1') == 'True') {
            // try to fix that wired '..' issue
            // where e.g. file.php becomes file..php, image.png becomes image..png
            // ..or in the mimeclass (more likely)
            $mimemessage->output = preg_replace($GLOBALS['mailbeez_bugfix_1_pattern'], $GLOBALS['mailbeez_bugfix_1_replace'], $mimemessage->output);
        }
        $mimemessage->send($mail['firstname'] . ' ' . $mail['lastname'], $email_address, $sender_name, $sender, $output_subject, '');

        mh_free($mimemessage);
        return array('message_id' => $mail['message_id']);
    }
}

// function for ZenCart
if (!function_exists('zencart_sendEmail')) {
    function zencart_sendEmail($mail, $email_address, $sender_name, $sender, $output_subject, $output_content_html, $output_content_txt)
    {
        if (mh_cfg('MAILBEEZ_MAILHIVE_ZENCART_OVERRIDE') == 'False') {
            $html_msg = array('EMAIL_SUBJECT' => $output_subject,
                'EMAIL_MESSAGE_HTML' => $output_content_html); // currently complete HTML mail
        } else {
            $html_msg = $output_content_html;
        }

        $forwarding_to = (isset($mail['forwarding_to'])) ? $mail['forwarding_to'] : '';

        if ($forwarding_to != '') {
            echo 'ERROR: BCC not supported, please configure MailBeez to send through SMTP in MailBeez > Configuration > Email Engine';
            mh_exit();
        }

        zen_mail($mail['firstname'] . ' ' . $mail['lastname'], $email_address, $output_subject, $output_content_txt, $sender_name, $sender, $html_msg, 'mailbeez');
        return array('message_id' => $mail['message_id']);
        // email-format is determined by look-up of email-adress in customer base
    }
}

// function for SEO:mercari
if (!function_exists('mercari_sendEmail')) {
    function mercari_sendEmail($mail, $email_address, $sender_name, $sender, $output_subject, $output_content_html, $output_content_txt)
    {
        php_mail($sender, $sender_name, $email_address, $mail['firstname'] . ' ' . $mail['lastname'], '', $sender, $sender_name, '', '', $output_subject, $output_content_html, $output_content_txt);
        return array('message_id' => $mail['message_id']);
    }
}


// function for xtCommerce
if (!function_exists('xtc_sendEmail')) {
    function xtc_sendEmail($mail, $email_address, $sender_name, $sender, $output_subject, $output_content_html, $output_content_txt)
    {
        $forwarding_to = (isset($mail['forwarding_to'])) ? $mail['forwarding_to'] : '';

        $result = xtc_php_mail($sender, $sender_name, $email_address, $mail['firstname'] . ' ' . $mail['lastname'], $forwarding_to, $sender, $sender_name, '', '', $output_subject, $output_content_html, $output_content_txt);


        // todo
        // check result true and handle issue

        return array('message_id' => $mail['message_id']);
    }
}

function mh_email_failed_log($msg)
{
    $filename = MH_EMAIL_ENGINE_LOGFILE;
    $stream = fopen($filename, 'a');
    $string = "[" . date("Y/m/d h:i:s", time()) . "] " . $msg;
    fwrite($stream, $string . PHP_EOL);
    fclose($stream);
}
