<?php

defined('_MAILING') or die('Restricted access');

$recipientmail = isset($_POST['recipientmail']) ? $_POST['recipientmail'] : '';
$recipientname = isset($_POST['recipientname']) ? $_POST['recipientname'] : '';
$recipientwebsite = isset($_POST['recipientwebsite']) ? $_POST['recipientwebsite'] : '';
$recipientcomment = isset($_POST['recipientcomment']) ? $_POST['recipientcomment'] : '';
$f01 = isset($_POST['f01']) ? $_POST['f01'] : '';
$f02 = isset($_POST['f02']) ? $_POST['f02'] : '';
$f03 = isset($_POST['f03']) ? $_POST['f03'] : '';
$tags = isset($_POST['tags']) ? $_POST['tags'] : 0 ;
$redirectto = isset($_POST['redirectto']) ? $_POST['redirectto'] : '';
$dbloptin = isset($_POST['dbloptin']) ? $_POST['dbloptin'] : '';
$subscriptionFormToken = isset($_POST['subscriptionFormToken']) ? $_POST['subscriptionFormToken'] : '';

// check CSRF registering form token
if ($subscriptionFormToken != Settings::$subscriptionFormToken) {
    die('Invalid CSRF token');
}

/*
$recipientmail = filter_var($recipientmail, FILTER_SANITIZE_EMAIL);
if (filter_var($recipientmail, FILTER_VALIDATE_EMAIL) === false) {
    die(Settings::$subscribeErrorMessage);
}
*/
$pattern = "/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/i";
if (!preg_match($pattern, $recipientmail)) {
    die(Settings::$subscribeErrorMessage);
}

// get subscriber ip address
$ip = $_SERVER["REMOTE_ADDR"];

// get blacklist for checking
$result = $db->query(" select * from ".PREF."_blacklist ");

// check malicious entries
foreach ($result as $row) {
    // 1 - domain
    // 2 - ip
    if ($row['type'] == 1) {
        if (strpos($recipientmail, $row['value']) !== false) {
            die('not allowed 1' . $_SERVER["REMOTE_ADDR"]);
        }
    } else {
        if ($ip == $row['value']) {
            die('not allowed 2');
        }
    }
}

$recipientname = $app->clearSQL($recipientname);
$recipientwebsite = $app->clearSQL($recipientwebsite);
$recipientcomment = $app->clearSQL($recipientcomment);

// in case of header double end of line problems when email is sending thru different servers
$eol = $app->getSystemEOL();

if ($dbloptin == '1') {
    // when double opt-in option is enabled
    // send email to subscriber
    // with base64 decoded message
    $subscribeEmailMessage = base64_decode(Settings::$subscribeEmailMessage);
    $subscribeEmailTitle = Settings::$subscribeEmailTitle;
    $confirmationLink = HTTP.'://'.$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'].'?manage=campaign&adata=modify&action=subscribe.confirmed&m='.$recipientmail.'&n='.$recipientname.'&c='.$recipientcomment.'&t='.$tags.'&token='.Settings::$subscriptionEmailToken.'&url='.$recipientwebsite;
    $subscribeEmailMessage = str_replace('{CONFIRM_LINK}', $confirmationLink, $subscribeEmailMessage);
    $subscribeEmailMessage = str_replace('{SUBSCRIBER_EMAIL}', $recipientmail, $subscribeEmailMessage);
    $subscribeEmailMessage = str_replace('{SUBSCRIBER_NAME}', $recipientname, $subscribeEmailMessage);
    $subscribeEmailMessage = str_replace('{SUBSCRIBER_COMMENT}', $recipientcomment, $subscribeEmailMessage);
    $subscribeEmailMessage = str_replace('{SUBSCRIBER_TAGS}', $tags, $subscribeEmailMessage);
    $subscribeEmailMessage = str_replace('{CURRENT_YEAR}', date("Y"), $subscribeEmailMessage);
    $subscribeEmailMessage = str_replace('{CURRENT_MONTH}', date("m"), $subscribeEmailMessage);
    $subscribeEmailMessage = str_replace('{CURRENT_DAY}', date("d"), $subscribeEmailMessage);

    // Define the main headers.
    $header = "MIME-Version: 1.0".$eol;
    $header .= "Content-type: text/html; charset=UTF-8".$eol;
    $header .= "From: ".Settings::$subscribeEmailDescriptionFrom." <".Settings::$subscribeEmailAddressFrom.">".$eol;

    
    
    // use SMTP if choosen and exists
    $id_SMTP = (int)Settings::$serverEmailSenderID;
    if ($id_SMTP == 0) {
        // PHP mail used
        mail($recipientmail, $subscribeEmailTitle, $subscribeEmailMessage, $header);
    } else {
        // SMTP used
        // check if exists SMTP
        $stmt = $db->prepare(" select * from ".PREF."_smtp where id=? ");
        $stmt->bindParam(1, $id_SMTP, PDO::PARAM_INT);
        $stmt->execute();
        $row = $stmt->fetchAll();
        $data = $row[0];
        if ((int)$data['id']){
            
            // SMTP exists
            $host = $data['host'];
            $smtpauth = $data['smtpauth'] == '1' ? true : false ;
            $forcesmtp = $data['forcesmtp'] == '1' ? true : false ;
            $verifypeer = $data['verifypeer'] == '1' ? true : false ;
            $username = $data['username'];
            $login = $data['login'];
            $password = $data['password'];
            $replytomail = $data['replytomail'];
            $replytoname = $data['replytoname'];
            $smtpsecure = $data['smtpsecure'];
            $port = $data['port'];
            $maxlimit = $data['maxlimit'];
            require 'php/PHPMailerAutoload.php';
            $mail = new PHPMailer;
            $mail->CharSet = "UTF-8";
            //$mail->SMTPDebug = 3;
            if (!$verifypeer) {
                $mail->SMTPOptions = array(
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    )
                );
            }
            if ($forcesmtp) {
                $mail->isSMTP();
            }
            $mail->Host = $host;
            $mail->Port = $port;
            $mail->SMTPAuth = $smtpauth;
            $mail->Username = $login;
            $mail->Password = $password;
            $mail->SMTPSecure = $smtpsecure;
            $mail->setFrom($username); // bounce to
            $mail->ClearReplyTos();
            $mail->AddReplyTo($replytomail, $replytoname);
            $mail->From = Settings::$subscribeEmailAddressFrom;
            $mail->FromName = Settings::$subscribeEmailDescriptionFrom;
            $mail->addAddress($recipientmail);
            $mail->isHTML(true);
            $mail->Subject = $subscribeEmailTitle;
            $mail->Body    = "<!DOCTYPE html><html><head><title></title></head><body>".stripslashes($subscribeEmailMessage)."</body>";
            //$mail->AltBody = $message_txt;
            $mail->send();
            
        } else {
            // log if smtp server is not exists but choosen in subscribe widget
            $app->saveLog(" ERROR: SMTP server id:".$id_SMTP." not present ");
            // SMTP not exists, send using PHP mail()
            mail($recipientmail, $subscribeEmailTitle, $subscribeEmailMessage, $header);
        }
    }
    
    
    

} else {
    // or just add a subscriber do the database
    $sql = "
        INSERT INTO ".PREF."_recipient (
            person,
            email,
            comment,
            website,
            f01,
            f02,
            f03
        ) VALUES (
            :recipientname,
            :recipientmail,
            :recipientcomment,
            :recipientwebsite,
            :f01,
            :f02,
            :f03
        )
    ";
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':recipientname', $recipientname, PDO::PARAM_STR);
    $stmt->bindParam(':recipientmail', $recipientmail, PDO::PARAM_STR);
    $stmt->bindParam(':recipientcomment', $recipientcomment, PDO::PARAM_STR);
    $stmt->bindParam(':recipientwebsite', $recipientwebsite, PDO::PARAM_STR);
    $stmt->bindParam(':f01', $f01, PDO::PARAM_STR);
    $stmt->bindParam(':f02', $f02, PDO::PARAM_STR);
    $stmt->bindParam(':f03', $f03, PDO::PARAM_STR);
    $stmt->execute();

    if ($tags != '') {
        $tags = $app->clearSQL($tags);
        $tagsArray = explode(",", $tags);
        $id = $db->lastInsertId();
        foreach ($tagsArray as $tag) {
            $stmt = $db->prepare(" select id from ".PREF."_recipient_tag where name=? ");
            $stmt->bindParam(1, $tag, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetchAll();
            $data = $row[0];
            $id_tag = $data['id'];

            if ($id_tag) {
                $sql = "
                    INSERT INTO ".PREF."_recipient_tag_conn (
                        id_recipient,
                        id_tag
                    ) VALUES (
                        :id_recipient,
                        :id_tag
                    )
                ";
                $stmt = $db->prepare($sql);
                $stmt->bindParam(':id_recipient', $id, PDO::PARAM_STR);    
                $stmt->bindParam(':id_tag', $id_tag, PDO::PARAM_STR);
                $stmt->execute();
            }
        }
    }
    
    // notify admin if needed
    if (Settings::$adminSubscribtionNotify == '1' && Settings::$adminMail != '')  {
        
        // Define the main headers.
        $header = "MIME-Version: 1.0".$eol;
        $header .= "Content-type: text/html; charset=UTF-8".$eol;
        $header .= "From: E-mailer system <".Settings::$subscribeEmailAddressFrom.">".$eol;
        $adminEmailMessage = base64_decode(Settings::$adminEmailMessage);
        $adminEmailMessage = str_replace('{SUBSCRIBER_EMAIL}', $recipientmail, $adminEmailMessage);
        $adminEmailMessage = str_replace('{SUBSCRIBER_NAME}', $recipientname, $adminEmailMessage);
        $adminEmailMessage = str_replace('{SUBSCRIBER_COMMENT}', $recipientcomment, $adminEmailMessage);
        $adminEmailMessage = str_replace('{SUBSCRIBER_WEBSITE}', $recipientwebsite, $adminEmailMessage);
        $adminEmailMessage = str_replace('{SUBSCRIBER_TAGS}', $tags, $adminEmailMessage);
        $adminEmailMessage = str_replace('{CURRENT_YEAR}', date("Y"), $adminEmailMessage);
        $adminEmailMessage = str_replace('{CURRENT_MONTH}', date("m"), $adminEmailMessage);
        $adminEmailMessage = str_replace('{CURRENT_DAY}', date("d"), $adminEmailMessage);
        
        mail(Settings::$adminMail, "E-mailer system", $adminEmailMessage, $header);
    }
    
    
}

// make action after filled subscribtion form

// redirect to posted url
if ($redirectto !='') {
    header("Location: ".$redirectto);
    exit();
}

//do nothing
if (Settings::$afterSubscribe == '0') {
    exit();
}

//show thx message
if (Settings::$afterSubscribe == '1') {
    echo Settings::$afterSubscribeMessage;
    exit();
}

//redirect to settings url
if (Settings::$afterSubscribe == '2') {
    header("Location: ".Settings::$afterSubscribeRedirectTo);
    exit();
}


