# Modified 07/15/2013 by Plugin Review Network
# ------------------------------------------------
# License and copyright:
# See license.txt for license information.
# ------------------------------------------------
if (!function_exists('add_action')) {
    die;
}
# MOD to include WP table prefix
global $table_prefix;
$infrespconfig = $table_prefix . 'InfResp_config';
# Does the config table exist?
$query = "SHOW TABLES LIKE '" . $infrespconfig . "'";
$result = mysql_query($query) or die("Invalid query: " . mysql_error());
if (mysql_num_rows($result) == 0) {
    # No, the defs are not installed!
    $wpdefs = dirname(__FILE__) . "/wp-defs.sql";
    $contents = GrabFile($wpdefs);
    # MOD to include WP table prefix
    $contents = str_ireplace('InfResp', $table_prefix . 'InfResp', $contents);
    if ($contents == FALSE) {
        die("Could not find the wp-defs.sql file!\n");
    }
    # Process the defs file.
    preg_match_all('/-- Start command --(.*?)-- End command --/ims', $contents, $queries);
    for ($i = 0; $i < sizeof($queries[1]); $i++) {
        $query = $queries[1][$i];
        # echo nl2br($query) . "<br>\n";
        $result = mysql_query($query) or die("Invalid query: " . nl2br(mysql_error()));
    }
}
function SendMessageTemplate($filename = "", $to_address = "", $from_address = "", $SubscriberID = "")
{
    global $Responder_ID, $siteURL, $ResponderDirectory;
    global $MySQL_server, $MySQL_user, $MySQL_password, $MySQL_database;
    global $DB_LinkID, $charset, $cop, $newline, $blahtest, $table_prefix;
    global $DB_TimeJoined, $DB_Real_TimeJoined, $DB_SubscriberID;
    global $DB_EmailAddress, $DB_LastActivity, $DB_FirstName;
    global $DB_LastName, $CanReceiveHTML;
    global $DB_IPaddy, $DB_ReferralSource, $DB_UniqueCode;
    global $DB_ResponderName, $DB_OwnerEmail, $DB_MsgSub;
    global $DB_OwnerName, $DB_ReplyToEmail, $DB_ResponderDesc;
    global $DB_OptInRedir, $DB_OptOutRedir, $DB_OptInDisplay, $DB_OptOutDisplay;
    if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
        $newline = "\r\n";
    } elseif (strtoupper(substr(PHP_OS, 0, 3) == 'MAC')) {
        $newline = "\r";
    } else {
        $newline = PHP_EOL;
    }
    if ($filename == "") {
        die("Message template error!<br>\n");
    }
    $pathinfo = pathinfo($filename);
    $htmlfilename = $customfilename = $pathinfo['basename'];
    # MOD 1.6.0: to allow for HTML template locations
    $htmlfilename = str_replace(".txt", ".html", $htmlfilename);
    $customhtmlfilename = str_replace(".html", "." . $Responder_ID . ".html", $htmlfilename);
    $customlocations = array();
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'templates/infinity-responder/', $customhtmlfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'irmessages/', $customhtmlfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', '/', $customhtmlfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'templates/infinity-responder/', $htmlfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'irmessages/', $htmlfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', '/', $htmlfilename);
    $customlocations[] = dirname(__FILE__) . '/' . $htmlfilename;
    $customlocations = apply_filters('inf_resp_template_hierarchy_html', $customlocations);
    if (count($customlocations) > 0) {
        foreach ($customlocations as $customlocation) {
            if (file_exists($customlocation)) {
                $htmlfilename = $customlocation;
            }
        }
    }
    # MOD 1.6.0: to allow for text template locations
    $customfilename = str_replace(".txt", "." . $Responder_ID . ".txt", $customfilename);
    $customlocations = array();
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'templates/infinity-responder/', $customfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'irmessages/', $customfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', '/', $customfilename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'templates/infinity-responder/', $filename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', 'irmessages/', $filename);
    $customlocations[] = get_stylesheet_directory() . str_replace('templates/messages/', '/', $filename);
    $customlocations[] = dirname(__FILE__) . '/' . $htmlfilename;
    $customlocations = apply_filters('inf_resp_template_hierarchy_text', $customlocations);
    if (count($customlocations) > 0) {
        foreach ($customlocations as $customlocation) {
            if (file_exists($customlocation)) {
                $filename = $customlocation;
            }
        }
    }
    $file_contents = GrabFile($filename);
    if ($file_contents == FALSE) {
        die("Template {$filename} not found!<br>\n");
    }
    # Separate the subject
    preg_match("/<SUBJ>(.*?)<\\/SUBJ>/ims", $file_contents, $matches);
    $MessageInfo['Subject'] = $Send_Subject = $matches[1];
    # Seperate the message
    preg_match("/<MSG>(.*?)<\\/MSG>/ims", $file_contents, $matches);
    $DB_MsgBodyText = trim($matches[1]);
    # MOD 1.6.0: do similar for HTML template if it was found
    if ($htmlfilename != $pathinfo['basename']) {
        $file_contents = GrabFile($hmtlfilename);
        if ($file_contents == FALSE) {
            die("Template {$filename} not found!<br>\n");
        }
        if (stristr($file_contents, '<SUBJ>') && stristr($file_contents, '</SUBJ>') && stristr($file_contents, '<MSG>') && stristr($file_contents, '</MSG>')) {
            # Separate the subject
            preg_match("/<SUBJ>(.*?)<\\/SUBJ>/ims", $file_contents, $matches);
            $MessageInfo['Subject'] = $Send_Subject = $matches[1];
            # Seperate the message
            preg_match("/<MSG>(.*?)<\\/MSG>/ims", $file_contents, $matches);
            $DB_MsgBodyHTML = trim($matches[1]);
        } else {
            $DB_MsgBodyHTML = $file_contents;
        }
    } else {
        # Generate the HTML message
        $DB_MsgBodyHTML = nl2br($DB_MsgBodyText);
    }
    if ($DB_SubscriberID != "") {
        $SubscriberInfo = GetSubscriberInfo($DB_SubscriberID);
    }
    if ($SubscriberID != "") {
        $SubscriberInfo = GetSubscriberInfo($SubscriberID);
    }
    if ($SubscriberInfo['UniqueCode'] != "") {
        $DB_UniqueCode = $SubscriberInfo['UniqueCode'];
    }
    # Generate codes and links
    $cop = checkit();
    $subcode = "s" . $DB_UniqueCode;
    $unsubcode = "u" . $DB_UniqueCode;
    # MOD sub links to Wordpress Plugin Handling
    // $sub_conf_link   = $siteURL.$ResponderDirectory."/s.php?c=$subcode";
    // $unsub_conf_link = $siteURL.$ResponderDirectory."/s.php?c=$unsubcode";
    // $unsub_link      = $siteURL.$ResponderDirectory."/s.php?c=$unsubcode";
    $sub_conf_link = $siteURL . "/?infresp=s&c={$subcode}";
    $unsub_conf_link = $siteURL . "/?infresp=s&c={$unsubcode}";
    $unsub_link = $siteURL . "/?infresp=s&c={$unsubcode}";
    $UnsubURL = $unsub_link;
    # Replace unsub and sub/unsub conf links
    $DB_MsgBodyText = preg_replace('/%sub_conf_url%/i', $sub_conf_link, $DB_MsgBodyText);
    $DB_MsgBodyText = preg_replace('/%unsub_conf_url%/i', $unsub_conf_link, $DB_MsgBodyText);
    $DB_MsgBodyText = preg_replace('/%unsub_url%/i', $unsub_link, $DB_MsgBodyText);
    $DB_MsgBodyHTML = preg_replace('/%sub_conf_url%/i', "<A HREF=\"{$sub_conf_link}\">{$sub_conf_link}</A>", $DB_MsgBodyHTML);
    $DB_MsgBodyHTML = preg_replace('/%unsub_conf_url%/i', "<A HREF=\"{$unsub_conf_link}\">{$unsub_conf_link}</A>", $DB_MsgBodyHTML);
    $DB_MsgBodyHTML = preg_replace('/%unsub_url%/i', "<A HREF=\"{$unsub_link}\">{$unsub_link}</A>", $DB_MsgBodyHTML);
    # Process tags
    $MessageInfo['ResponderID'] = $Responder_ID;
    $MessageInfo['BodyText'] = $DB_MsgBodyText;
    $MessageInfo['BodyHTML'] = $DB_MsgBodyHTML;
    $message = ProcessMessageTags($MessageInfo, $SubscriberInfo);
    $DB_MsgBodyText = $message['BodyText'];
    $DB_MsgBodyHTML = $message['BodyHTML'];
    $Send_Subject = $message['Subject'];
    # Set another from
    if (!isEmpty($from_address)) {
        $DB_ReplyToEmail = $from_address;
    }
    # Set another to
    if (!isEmpty($to_address)) {
        $DB_EmailAddress = $to_address;
    }
    # Generate the headers
    $Message_Body = "";
    $Message_Headers = "Return-Path: <" . $DB_ReplyToEmail . ">{$newline}";
    # $Message_Headers .= "Return-Receipt-To: <" . $DB_ReplyToEmail . ">$newline";
    $Message_Headers .= "Envelope-to: {$DB_EmailAddress}{$newline}";
    $Message_Headers .= "From: {$DB_OwnerName} <" . $DB_ReplyToEmail . ">{$newline}";
    # $Message_Headers .= "Date: " . date('D\, j F Y H:i:s O') . "$newline";
    $Message_Headers .= "Date: " . date('r') . "{$newline}";
    $Message_Headers .= "Reply-To: {$DB_ReplyToEmail}{$newline}";
    $Message_Headers .= "Sender-IP: " . $_SERVER["SERVER_ADDR"] . $newline;
    $Message_Headers .= "MIME-Version: 1.0{$newline}";
    $Message_Headers .= "Priority: normal{$newline}";
    $Message_Headers .= "X-Mailer: WP Infinity Responder{$newline}";
    # Generate the body
    if (get_option('inf_resp_mailer') != 'wp_mail') {
        if ($CanReceiveHTML == 1) {
            $boundary = md5(time()) . rand(1000, 9999);
            $Message_Headers .= "Content-Type: multipart/alternative; {$newline}            boundary=\"{$boundary}\"{$newline}";
            $Message_Body .= "This is a multi-part message in MIME format.{$newline}{$newline}";
            $Message_Body .= "--" . $boundary . $newline;
            $Message_Body .= "Content-type: text/plain; charset={$charset}{$newline}";
            $Message_Body .= "Content-Transfer-Encoding: 8bit" . $newline;
            $Message_Body .= "Content-Disposition: inline{$newline}{$newline}";
            $Message_Body .= $DB_MsgBodyText . $newline . $newline;
            $Message_Body .= "--" . $boundary . $newline;
            $Message_Body .= "Content-type: text/html; charset={$charset}{$newline}";
            $Message_Body .= "Content-Transfer-Encoding: 8bit" . $newline;
            $Message_Body .= "Content-Disposition: inline{$newline}{$newline}";
            $Message_Body .= $DB_MsgBodyHTML . $newline . $newline;
        } else {
            $Message_Headers .= "Content-type: text/plain; charset={$charset}{$newline}";
            $Message_Headers .= "Content-Transfer-Encoding: 8bit" . $newline;
            $Message_Body = $DB_MsgBodyText . $newline;
        }
    }
    # Final filtering
    $Send_Subject = stripnl(str_replace("|", "", $Send_Subject));
    $Message_Body = str_replace("|", "", $Message_Body);
    $Message_Headers = str_replace("|", "", $Message_Headers);
    $Message_Body = utf8_decode($Message_Body);
    # Send the mail
    // echo "Addy: $DB_EmailAddress <br>\n";
    // echo "Subj: $Send_Subject <br>\n";
    // echo "Head: $Message_Headers <br>\n";
    # MOD for sending message via wp_mail /phpmailer
    if (get_option('inf_resp_mailer') == 'wp_mail') {
        add_option('inf_resp_owner_email', $DB_OwnerEmail);
        update_option('inf_resp_owner_email', $DB_OwnerEmail);
        add_option('inf_resp_owner_name', $DB_OwnerName);
        update_option('inf_resp_owner_name', $DB_OwnerName);
        add_filter('wp_mail_from', 'inf_resp_from_email', 100);
        add_filter('wp_mail_from_name', 'inf_resp_from_name', 100);
        // echo "Can Receive HTML? ".$CanReceiveHTML."<br>";
        if ($CanReceiveHTML == 1) {
            // echo "Text Body: <textarea>$DB_MsgBodyText</textarea><br>\n";
            // echo "HTML Body: <textarea>$DB_MsgBodyHTML</textarea><br>\n";
            // echo "---------------------------<br>\n";
            add_option('inf_resp_alt_body', $DB_MsgBodyText);
            update_option('inf_resp_alt_body', $DB_MsgBodyText);
            add_action('phpmailer_init', 'inf_resp_set_alt_body');
            add_action('phpmailer_init', 'inf_resp_set_word_wrap');
            $result = wp_mail($DB_EmailAddress, $Send_Subject, $DB_MsgBodyHTML, $Message_Headers, false);
        } else {
            // echo "Text Body: <textarea>$DB_MsgBodyText</textarea><br>\n";
            // echo "---------------------------<br>\n";
            add_action('phpmailer_init', 'inf_resp_set_word_wrap');
            $result = wp_mail($DB_EmailAddress, $Send_Subject, $DB_MsgBodyText, $Message_Headers, false);
        }
        if (!$result) {
            echo "Message sending by wp_mail failed!<br>";
            $result = mail($DB_EmailAddress, $Send_Subject, $Message_Body, $Message_Headers, "-f {$DB_ReplyToEmail}");
            if (!$result) {
                echo "Message sending by mail failed also!<br>";
                echo "Email: " . $DB_EmailAddress . "<br>";
                echo "Subject: " . $Send_Subject . "<br>";
                echo "Headers: " . $Message_Headers . "<br>";
            }
        }
    } else {
        // echo "Body: <textarea>$Message_Body </textarea><br>\n";
        // echo "---------------------------<br>\n";
        $result = mail($DB_EmailAddress, $Send_Subject, $Message_Body, $Message_Headers, "-f {$DB_ReplyToEmail}");
    }
    # Update the activity row
    $Set_LastActivity = time();
    $infrespsubscribers = $table_prefix . 'InfResp_subscribers';
    $query = "UPDATE " . $infrespsubscribers . " SET LastActivity = '{$Set_LastActivity}' WHERE SubscriberID = '{$DB_SubscriberID}'";
    $DB_result = mysql_query($query, $DB_LinkID) or die("Invalid query: " . mysql_error());
    # Head on back
    return $result;
}