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

/*

  v2.7

 */

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

/* -------------------------------------------------------------------------------------
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */


function mh_php_mail($sender_email_address,
                     $sender_email_name,
                     $from_email_address,
                     $from_email_name,
                     $to_email_address,
                     $to_name,
                     $forwarding_to,
                     $reply_address,
                     $reply_address_name,
                     $path_to_attachement,
                     $path_to_more_attachements,
                     $email_subject,
                     $message_body_html,
                     $message_body_plain,
                     $mail,
                     $testConnection = false)
{
    $error_msg_id = -1;

    switch (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) {
        case 'PHPMailer':
        case 'mlbz_ubvx':

            $phpmailer_path = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/PHPMailer_6_latest/';
            if (version_compare(phpversion(), '5.5.0', '>')) {
                if (!class_exists('\PHPMailer\PHPMailer\PHPMailer')) {
                    $phpmailer_path = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/PHPMailer_6_latest/';
                    require_once($phpmailer_path . 'src/PHPMailer.php');
                    require_once($phpmailer_path . 'src/SMTP.php');
                    require_once($phpmailer_path . 'src/Exception.php');
                }
                $php_mailer = new \PHPMailer\PHPMailer\PHPMailer();
            } else {
                // legacy support
                $phpmailer_path = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/PHPMailer_5_latest/';
                require_once($phpmailer_path . 'mailbeez.class.phpmailer.php');
                $php_mailer = new MH_PHPMailer();
            }

            $php_mailer->Timeout = 30;


            if (mh_cfg('MAILBEEZ_SMTP_DISABLE_SSL_VERIFICATION') == 'True') {
                // https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#php-56-certificate-verification-failure
                $php_mailer->SMTPOptions = array(
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    )
                );
            }

            if (mh_session('language') == 'german') {
                $php_mailer->SetLanguage("de", $phpmailer_path . 'language/');
            } else {
                $php_mailer->SetLanguage("en", $phpmailer_path . 'language/');
            }


            // convert all characters to given charset
            if (stristr(mh_session('language_charset'), '8859')) {
                $email_subject = str_replace('€', 'Eur', $email_subject);
                $message_body_html = str_replace('€', 'Eur', $message_body_html);
                $message_body_plain = str_replace('€', 'Eur', $message_body_plain);

                $email_subject = mh_fix_utf8(ForceUTF8_Encoding::toISO8859(($email_subject)));
                $message_body_html = mh_fix_utf8(ForceUTF8_Encoding::toISO8859(($message_body_html)));
                $message_body_plain = mh_fix_utf8(ForceUTF8_Encoding::toISO8859(($message_body_plain)));
            }
            break;
        default:
            return array('message_id' => $error_msg_id, 'error' => 'unknown engine: ' . mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'));
            break;
    }

    if ($sender_email_address != '') {
        //$php_mailer->Sender = '"' . $sender_email_name . '" <' . $sender_email_address . '>';
        $php_mailer->Sender = $sender_email_address;
    }

    // V2.6.3
    // todo: make configurable
    // $php_mailer->CharSet = '';


    $php_mailer->XMailer = 'mailbeez.com Version ' . mh_cfg('MAILBEEZ_VERSION');

    $php_mailer->SMTPDebug = (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_DEBUG_MODE') == 'True' || mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_MLBZ_DEBUG_MODE') == 'True') ? true : false;

    $php_mailer->MessageID = $mail['email_message_id'];

    $php_mailer->DKIM_selector = mh_cfg('MAILBEEZ_DKIM_SELECTOR');

    /**
     * Used with DKIM DNS Resource Record
     * optional, in format of email address 'you@yourdomain.com'
     * @var string
     */
    $php_mailer->DKIM_identity = mh_cfg('MAILBEEZ_DKIM_IDENTIY');

    /**
     * Used with DKIM DNS Resource Record
     * @var string
     */
    $php_mailer->DKIM_passphrase = mh_cfg('MAILBEEZ_DKIM_PASSPHRASE');

    /**
     * Used with DKIM DNS Resource Record
     * optional, in format of email address 'you@yourdomain.com'
     * @var string
     */
    $php_mailer->DKIM_domain = mh_cfg('MAILBEEZ_DKIM_DOMAIN');

    /**
     * Used with DKIM DNS Resource Record
     * optional, in format of email address 'you@yourdomain.com'
     * @var string
     */
    $php_mailer->DKIM_private = mh_cfg('MAILBEEZ_DKIM_PRIVATE');


    $php_mailer->CharSet = mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET');

    // information for reporting abuse
    // https://www.cs.tut.fi/~jkorpela/headers.html#X-Abuse-Info
    $php_mailer->addCustomHeader('X-Abuse-Info', mh_cfg('MAILBEEZ_SMTP_ABUSE_INFO'));

    // X-Report	Information about reporting abuse
    // https://www.cs.tut.fi/~jkorpela/headers.html#X-Report
    $php_mailer->addCustomHeader('X-Report', mh_cfg('MAILBEEZ_SMTP_ABUSE_INFO'));


    // according to F. Gadegast powerweb.de
    $php_mailer->addCustomHeader('X-Abuse', mh_cfg('MAILBEEZ_SMTP_ABUSE_EMAIL_ADDRESS'));

    // https://www.cs.tut.fi/~jkorpela/headers.html#X-Report-Abuse-To
    $php_mailer->addCustomHeader('X-Report-Abuse-To', mh_cfg('MAILBEEZ_SMTP_ABUSE_EMAIL_ADDRESS'));

    // E-mail address for reporting abuse
    // https://www.cs.tut.fi/~jkorpela/headers.html#Abuse-Reports-To
    $php_mailer->addCustomHeader('Abuse-Reports-To', mh_cfg('MAILBEEZ_SMTP_ABUSE_EMAIL_ADDRESS'));

    // An E-mail address for sending complaints on the adequacy of the Usenet message
    // https://www.cs.tut.fi/~jkorpela/headers.html#X-Complaints-To
    $php_mailer->addCustomHeader('X-Complaints-To', mh_cfg('MAILBEEZ_SMTP_ABUSE_EMAIL_ADDRESS'));

    // List unsubscribe
    $php_mailer->addCustomHeader('List-Unsubscribe', '<' . $mail['list_unsubscribe_post'] . '>');
    $php_mailer->addCustomHeader('List-Unsubscribe-Post', 'List-Unsubscribe=One-Click');


    if (mh_cfg('MAILBEEZ_EMAIL_TRANSPORT') == 'smtp') {
        $php_mailer->IsSMTP();
        $php_mailer->SMTPKeepAlive = true; // set mailer to use SMTP
        $php_mailer->SMTPAuth = (mh_cfg('MAILBEEZ_SMTP_AUTH') == 'True') ? true : false; // turn on SMTP authentication true/false
        $php_mailer->Username = mh_cfg('MAILBEEZ_SMTP_USERNAME'); // SMTP username
        $php_mailer->Password = mh_cfg('MAILBEEZ_SMTP_PASSWORD'); // SMTP password
        $php_mailer->Host = mh_cfg('MAILBEEZ_SMTP_MAIN_SERVER') . ';' . mh_cfg('MAILBEEZ_SMTP_BACKUP_SERVER'); // specify main and backup server "smtp1.example.com;smtp2.example.com"

        $php_mailer->SMTPSecure = (mh_cfg('MAILBEEZ_SMTP_SECURE') == 'none') ? '' : mh_cfg('MAILBEEZ_SMTP_SECURE'); // sets the prefix to the servier
        $php_mailer->Port = mh_cfg('MAILBEEZ_SMTP_PORT'); // set the SMTP port for the server

    }

// <mailbeez_protected>

    if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE') == 'mlbz_ubvx') {
        $php_mailer->IsSMTP();
        $php_mailer->SMTPKeepAlive = true; // set mailer to use SMTP
        $php_mailer->SMTPAuth = true; // turn on SMTP authentication true/false
        $php_mailer->AuthType = 'LOGIN';
        $php_mailer->Username = mh_cfg('MAILBEEZ_MLBZ_UBVX_USERNAME'); // SMTP username
        $php_mailer->Password = mh_cfg('MAILBEEZ_MLBZ_UBVX_PASSWORD'); // SMTP password
        $php_mailer->Host = 'smtp-api.ubivox.com'; // specify main and backup server "smtp1.example.com;smtp2.example.com"
        $php_mailer->SMTPSecure = 'tls'; // sets the prefix to the server
        $php_mailer->Port = 587; // set the SMTP port for the server
    }

// </mailbeez_protected>


    if (mh_cfg('MAILBEEZ_EMAIL_TRANSPORT') == 'sendmail') { // set mailer to use sendmail
        $php_mailer->IsSendmail();
        $php_mailer->Sendmail = mh_cfg('MAILBEEZ_SENDMAIL_PATH');
    }

    if (mh_cfg('MAILBEEZ_EMAIL_TRANSPORT') == 'mail') {
        $php_mailer->IsMail();
    }

    if (MH_PLATFORM == 'zencart') {
        // zencart does a & -> &amp; in zen_href_link for html & txt and for text only a &amp; -> & in zen_mail()
        while (strstr($message_body_plain, '&amp;')) $message_body_plain = str_replace('&amp;', '&', $message_body_plain);
    }
    $message_body_plain = str_replace('<br />', " \n", $message_body_plain);
    $message_body_plain = strip_tags($message_body_plain);

    if (mh_cfg('MAILBEEZ_EMAIL_USE_TXT_ONLY') != 'True' && $message_body_html != '') {
        $php_mailer->IsHTML(true);
        $php_mailer->Body = $message_body_html;
        $php_mailer->AltBody = $message_body_plain;
    } else {
        $php_mailer->IsHTML(false);
        $php_mailer->Body = $message_body_plain;
    }


    $php_mailer->From = $from_email_address;
    $php_mailer->FromName = $from_email_name;

    $php_mailer->AddAddress($to_email_address, $to_name);

    if ($forwarding_to != '')
        $php_mailer->AddBCC($forwarding_to);

    if ($reply_address != '') {
        $php_mailer->AddReplyTo($reply_address, $reply_address_name);
    }

    $php_mailer->WordWrap = mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_WORDWRAP');

    if ($path_to_attachement != '') {
        $php_mailer->AddAttachment($path_to_attachement);
    }

    if ($path_to_more_attachements != '') {
        $php_mailer->AddAttachment($path_to_more_attachements);
    }

    $php_mailer->Subject = $email_subject;

    if ($testConnection) {
        return $php_mailer->smtpConnect();
    }


    if (!$php_mailer->Send()) {
        echo "Email could not be sent<p>";
        echo "Mailer Error: " . htmlentities($php_mailer->ErrorInfo);
        if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE') == 'mlbz_ubvx') {
//            require_once(MH_DIR_CONFIG . 'config_bouncehive/common/functions.php');
//            trackBounceByAddress($to_email_address);
            //this error is a correct identification for bounces
            $error_msg_id = -42; // email address is marked as bounced

//            return array('message_id' => $error_msg_id,
//                '_error_msg' => '<div style="border: 1px solid red; background-color: #fff; padding: 10px; margin: 10px">MailBeez.Email: The email-address is invalid and rejected for sending or has bounced previously. The address will be marked as hard bounced.</div>', 'error' => $php_mailer->ErrorInfo);
        }
        return array('message_id' => $error_msg_id, 'error' => $php_mailer->ErrorInfo);
    }

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

