<?php
//
// Copyright (c) 2008-2017 Nagios Enterprises, LLC. All rights reserved.
//

require_once(dirname(__FILE__) . '/phpmailer/PHPMailerAutoload.php');

////////////////////////////////////////////////////////////////////////
// EMAIL FUNCTIONS
////////////////////////////////////////////////////////////////////////

// sends a sime text email message
/**
 * @param      $opts
 * @param null $debug
 *
 * @return bool
 * @throws Exception
 * @throws phpmailerException
 */
function send_email($opts, &$debug_msg = null, $referer = "") {

    // make sure we have what we need
    if (!isset($opts["from"]))
        return false;
    if (!isset($opts["to"]))
        return false;
    if (!isset($opts["subject"]))
        return false;
    if (!isset($opts["message"]))
        return false;

    // get mail options
    $mailmethod = get_option("mail_method");
    
    $fromaddress = get_option("mail_from");
    if (empty($fromaddress))
        $fromaddress = 'root@localhost';

    $smtphost = get_option("smtp_host");
    $smtpport = get_option("smtp_port");
    $smtpusername = get_option("smtp_username");
    $smtppassword = get_option("smtp_password");
    $smtpsecurity = get_option("smtp_security");

    // instantiate phpmailer
    $mail = new PHPMailer();

    // Set Char set to UTF-8 for internationalization
    $mail->CharSet = 'UTF-8';

    // use global from address instead of one specified by user
    $address_parts = parse_email_address($fromaddress);
    $mail->SetFrom($address_parts[0]["email"], $address_parts[0]["name"]);
    $mail->AddReplyTo($address_parts[0]["email"], $address_parts[0]["name"]);

    // to address(es)
    $addresses = parse_email_address($opts["to"]);

    foreach ($addresses as $address) {
        $mail->AddAddress($address["email"], $address["name"]);
    }

    $mail->Subject = mb_convert_encoding($opts["subject"], "UTF-8", "auto");

    // add html <br> tags to newlines for mail readers in HTML mode
    $opts["message"] = nl2br($opts["message"]);

    //convert to UTF to account for special chars
    $opts["message"] = mb_convert_encoding($opts["message"], "UTF-8", "auto");

    // text body
    $mail->MsgHTML($opts["message"]);
    $mail->IsHTML(true);
    
    if (isset($opts["high_priority"]) && $opts["high_priority"] == 1) {

        // For most clients expecting the Priority header:
        // 1 = High, 2 = Medium, 3 = Low
        $mail->Priority = 1;

        // MS Outlook custom header
        // May set to "Urgent" or "Highest" rather than "High"
        $mail->AddCustomHeader("X-MSMail-Priority: High");

        // Not sure if Priority will also set the Importance header:
        $mail->AddCustomHeader("Importance: High"); 
    }

    // see if there is an attachment
    if (isset($opts["attachment"])) {

        // multiple files
        if (is_array($opts["attachment"])) {
            foreach ($opts["attachment"] as $aopt) {
                $mail->AddAttachment($aopt[0], $aopt[1]);
            }
        } 
        else // single file
            $mail->AddAttachment($opts["attachment"]);
    }

    // use SMTP method?
    if ($mailmethod == "smtp") {

        $debuginfo = "method=smtp";

        $mail->IsSMTP();
        $mail->Host = $smtphost;
        $mail->Port = intval($smtpport);

        $debuginfo .= ";host=$smtphost";
        $debuginfo .= ";port=$smtpport";

        // use SMTP Auth
        if (!empty($smtpusername)) {
            $debuginfo .= ";smtpauth=true";
            $mail->SMTPAuth = true;
            $mail->Username = $smtpusername;
            $mail->Password = $smtppassword;
        }

        // optionally use TLS or SSL
        if ($smtpsecurity == "tls") {
            $mail->SMTPSecure = "tls";
            $debuginfo .= ";security=tls";
        } else if ($smtpsecurity == "ssl") {
            $mail->SMTPSecure = "ssl";
            $debuginfo .= ";security=ssl";
        } else {
            $mail->SMTPSecure = false;
            $mail->SMTPAutoTLS = false;
            $debuginfo .= ";security=none";
        }
    } 
    else { // mail method
        $debuginfo = "method=sendmail";
    }

    if ($referer == "") {
        $refer_string = ", Referer: Unknown";
    } else {
        $refer_string = ", Referer: " . $referer;
    }

    // send it!
    if (!$mail->Send()) {

        $debug_msg = "Email failed! " . $mail->ErrorInfo . "({$debuginfo}) {$refer_string}";
        log_error(LOG_TYPE_APPLICATION, $debug_msg);
        return false;

    } else {

        $debug_msg = "Email sent! ({$debuginfo}) {$refer_string}";
        log_info(LOG_TYPE_APPLICATION, $debug_msg);
        return true;
    }

}


/**
 * @param $a
 *
 * @return array
 */
function parse_email_address($a)
{

    $results = array();

    $addresses = explode(",", $a);
    foreach ($addresses as $address) {

        $newa = array(
            "name" => "",
            "email" => "",
        );

        $parts = explode("<", $address);

        // just the address
        if (count($parts) == 1) {
            $newa["email"] = trim($parts[0]);
        } else {
            $newa["name"] = trim($parts[0]);
            $parts = explode(">", $parts[1]);
            $newa["email"] = trim($parts[0]);
        }

        $results[] = $newa;
    }


    return $results;
}

