Rev 153 | Blame | Compare with Previous | Last modification | View Log | RSS feed
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/hosting.php');
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/sessions_db.php');
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/cryptor.php');
include_once ($_SERVER['DOCUMENT_ROOT'] . "/php/vendors.php");
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/tools.php');
include_once ($_SERVER['DOCUMENT_ROOT'] . "/php/NonceUtil.php");
$configFile = parse_ini_file(FCM_CONFIGFILE, true);
$crypt = Cryptor::getInstance($configFile['cryptor']);
$tmpSessionTab = (isset($_POST["sessionTab"]) && $_POST["sessionTab"] > 0 ? $_POST["sessionTab"] : null);
$handler = MySessionHandler::getInstance($tmpSessionTab, $configFile['mysqli']);
$vendors = Vendors::getInstance();
Vendors::setAllVendors($configFile, $vendors);
$loginConfig = $configFile['login'];
$systemConf = $configFile['system'];
unset($configFile);
session_set_cookie_params(604800, '/', '.findcheapmusic.com', true, true);
session_set_save_handler($handler, true);
if (!empty($_COOKIE['PHPSESSID'])) {
session_id($_COOKIE['PHPSESSID']);
}
@session_start();
initSessionVariables($systemConf);
wlLog("Start");
$sent = processWishlist();
wlLog("End (Sent " . $sent . " emails)");
exit (0);
function processWishlist() {
global $wlFreqHoursArr;
global $wlFreqArr;
$lastUid = -1;
$lastCount = 0;
$totalSent = 0;
$xh = new Html;
$xh->init($_SESSION["htmlIndent"]);
$xhtoc = new Html;
$xhtoc->init($_SESSION["htmlIndent"]);
$toc = '';
$prefix = 0;
$conn = MySessionHandler::getDBSessionId();
$sql = "SELECT w.id, w.uid, w.barcode, w.title, w.artist, w.cond, w.format, w.currency, w.price, w.checked, u.wlEmailFlag
FROM wishlist w
JOIN users u ON w.uid = u.id
WHERE w.price > 0.00 and u.wlEmailFlag = '1'
ORDER BY uid;";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($wl = mysqli_fetch_assoc($result)) {
if ($lastUid != $wl['uid']) {
if ($lastUid != '-1' && $lastCount > 0) {
wlLog("Email User (" . $user['id'] . "): TOC Count: " . $lastCount);
updateUserCheckedDate($user['id']);
++$totalSent;
emailWishlistResults($user, $toc);
storeWishlistResults($user, $xh, $xhtoc);
$xh->reset();
$xh->init();
$xhtoc->reset();
$xhtoc->init();
$toc = '';
$prefix = 0;
}
$user = getUser($wl['uid']);
wlLog("Begin User (" . $user['id'] . "/" . $user['email'] . "/" . $wlFreqArr[$user['wlFreq']] . "): Last Check: " . ($user['wlChecked'] > 0 ? date(("Y-m-d h:i:s"), $user['wlChecked']):"Never"));
$_SESSION['buyer']['Zip'] = $user['zip'];
$lastCount = 0;
}
$lastUid = $wl['uid'];
$diff = (time() - $user['wlChecked']) / 3600;
if ($diff > $wlFreqHoursArr[$user['wlFreq']]) {
if (!empty($wl['barcode'])) {
$_SESSION["advSearch"]["Title"] = $wl['barcode'];
$_SESSION["searchTerm"] = $wl['barcode'];
} else {
$_SESSION["searchTerm"] = trim($wl['artist'] . " " . $wl['title']);
$_SESSION["advSearch"]["Title"] = $wl['title'];
$_SESSION["advSearch"]["Artist"] = $wl['artist'];
}
$_SESSION["prefix"] = ++$prefix;
$arr = searchAll(true);
$arr = filterWishlistResults($arr, $wl);
updateWishlistCheckedDate($wl['id']);
if (!empty($arr)) {
++$lastCount;
$toc .= formatResults($arr, $wl, $lastCount, $xh, $xhtoc);
}
}
}
if ($lastCount > 0) {
wlLog("Email User (" . $user['id'] . "): TOC Count: " . $lastCount);
updateUserCheckedDate($user['id']);
++$totalSent;
emailWishlistResults($user, $toc);
storeWishlistResults($user, $xh, $xhtoc);
}
}
}
else if (mysqli_errno($conn)) {
error_log("MySQL Read Wishlist SQL: " . $sql);
error_log("MySQL Read Wishlist Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
}
return $totalSent;
}
function filterWishlistResults($arr, $wl) {
foreach ($arr as $key => $row) {
if ($wl['cond'] != 'Any' && $row["Condition"] != $wl['cond']) {
unset($arr[$key]);
}
if ($wl['format'] != 'Any' && $row["MediaType"] != $wl['format']) {
unset($arr[$key]);
}
if ($row["ConvertedTotalPrice"] > $wl['price']) {
unset($arr[$key]);
}
}
return $arr;
}
function formatResults($arr, $wl, $cnt, &$xh, &$xhtoc) {
$toc = "<li>" . htmlentities($wl["artist"]) . " - " . htmlentities($wl["title"]) . " (" . count($arr) . ")</li>";
$xhtoc->tag('li');
$xhtoc->add_attribute("href", "#jump_" . $cnt);
$xhtoc->tag('a', htmlentities($wl["artist"]) . " - " . htmlentities($wl["title"]));
$xhtoc->add_attribute("class", "badge badge-pill badge-dark ml-2");
$xhtoc->tag('span', count($arr));
$xhtoc->close(); // li
$xh->add_attribute("id", "jump_" . $cnt);
$xh->add_attribute("class", "bg-info p-1");
$xh->tag('h3', $cnt . ") " . htmlentities($wl["artist"]) . " - " . htmlentities($wl["title"]));
$xh->tag('p', "Condition: " . $wl["cond"] . " | Format: " . $wl["format"] . " | Price Cap: " . print_monetary($wl["price"], $wl["currency"]));
$xh->insert_code(buildTable($arr, $cnt));
$xh->add_attribute("class", "btn btn-info mb-5");
$xh->add_attribute("role", "button");
$xh->add_attribute("href", "#toc");
$xh->add_attribute("data-toggle", "tooltip");
$xh->add_attribute("title", "Table of Contents");
$xh->add_attribute("aria-label", "Go to table of contents");
$xh->tag('a');
$xh->add_attribute("class", "material-icons");
$xh->tag('i', "arrow_upward");
$xh->close(); // a
return ($toc);
}
function updateWishlistCheckedDate($id) {
$nul = 'NULL';
$conn = MySessionHandler::getDBSessionId();
$checked = mysqli_real_escape_string($conn, time());
$sql = "UPDATE wishlist
SET checked = '$checked'
WHERE id = '$id'";
if ($result = mysqli_query($conn, $sql)) {
return 0;
}
else {
error_log("MySQL Update Wishlist SQL: " . $sql);
error_log("MySQL Update Wishlist Error: " . mysqli_error($conn) . " (" . $error . ")");
return -1;
}
return -1;
}
function getUser($uid) {
$conn = MySessionHandler::getDBSessionId();
$sql = "SELECT id, first_name, last_name, email, zip, wlEmailFlag, wlFreq, wlChecked
FROM users
WHERE id = '$uid'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
return $row;
}
}
else if (mysqli_errno($conn)) {
error_log("MySQL Read Users SQL: " . $sql);
error_log("MySQL Read Users Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
}
return [];
}
function updateUserCheckedDate($uid) {
$nul = 'NULL';
$conn = MySessionHandler::getDBSessionId();
$checked = mysqli_real_escape_string($conn, time());
$sql = "UPDATE users
SET wlChecked = '$checked'
WHERE id = '$uid'";
if ($result = mysqli_query($conn, $sql)) {
return 0;
}
else {
error_log("MySQL Update Users SQL: " . $sql);
error_log("MySQL Update Users Error: " . mysqli_error($conn) . " (" . $error . ")");
return -1;
}
return -1;
}
function PHPMailer_Init() {
// Include PHPMailer library files
require_once 'login/includes/PHPMailer/Exception.php';
require_once 'login/includes/PHPMailer/PHPMailer.php';
require_once 'login/includes/PHPMailer/SMTP.php';
$mail = new PHPMailer;
return $mail;
}
function emailWishlistResults($user, $toc) {
global $loginConfig;
global $wlFreqArr;
$to = trim($user["email"]);
$unsubscribeUrl = "https://" . $_SERVER["SERVER_NAME"] . "/index.php?submit=unsubscribe&id=" . $user["id"] . "&email=" . $to;
$subject = "Wishlist Price Checks | " . $loginConfig['SITE_NAME'];
$mailContent = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Find Cheap Music Wishlist Price Checks</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<table cellpadding="0" cellspacing="0" border="0" width="100%" style="border-radius:6px;background-color:#ffffff;padding-top:15px;border-collapse:separate">
<tbody>
<tr>
<td style="color:#616471;font-weight:400;text-align:left;line-height:190%;padding-top:15px;padding-right:40px;padding-bottom:30px;padding-left:40px;font-size:15px">
<h1 style="font-weight:500;font-size:22px;letter-spacing:-1px;line-height:115%;margin:18px 0 0;padding:0;text-align:left;color:#3c7bb6">Wishlist Price Checks</h1>
<br/>
Hi ' . $user["first_name"] . ',<br/>This is your ' . strtolower($wlFreqArr[$user["wlFreq"]]) . ' wishlist price check email from <a href="https://' . $_SERVER["SERVER_NAME"] . '/index.php">Find Cheap Music</a>. The price monitor found matching listings for the following wishlist entries:.
<ol>' . $toc . '</ol>
Please login to your account at <a href="https://' . $_SERVER["SERVER_NAME"] . '/index.php">Find Cheap Music</a> and navigate to the wishlist.
<br/>We look forward to serving you,<br/><strong>' . $loginConfig['SITE_NAME'] . ' Team</strong>
<br/><p style="font-style: italic;font-weight: 300;">You subscribed to this periodic email with email address ' . $to . '. Click <a href="' . $unsubscribeUrl . '">here</a> to unsubscribe from further emails. You can reinstate the emails at any time by setting the option \'Email Price Checks\' for your account at <a href="https://' . $_SERVER["SERVER_NAME"] . '/index.php">Find Cheap Music</a> back to \'Yes\'.</p>
</td>
</tr>
</tbody>
</table>
</body>
</html>';
$mailContentText = "This email contains the periodic price checks for your wishlist in HTML fornmat. Please login to your account at https://" . $_SERVER["SERVER_NAME"] . "/index.php and navigate to the wishlist.\r\n\r\n";
$mailContentText .= "\r\nWe look forward to serving you,\r\n" . $loginConfig['SITE_NAME'] . " Team";
if ($loginConfig['SMTP'] == true) {
$mail = PHPMailer_Init();
// SMTP configuration
$mail->isSMTP();
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->WordWrap = 80;
$mail->Host = $loginConfig['SMTP_HOST'];
$mail->SMTPAuth = true;
$mail->Username = $loginConfig['SMTP_USERNAME'];
$mail->Password = $loginConfig['SMTP_PASSWORD'];
$mail->SMTPSecure = $loginConfig['SMTP_SECURE'];
$mail->Port = $loginConfig['SMTP_PORT'];
$mail->addCustomHeader("List-Unsubscribe-Post", "List-Unsubscribe=One-Click");
$mail->addCustomHeader("List-Unsubscribe", "<" . $unsubscribeUrl . ">");
$mail->setFrom($loginConfig['SENDER_EMAIL'], $loginConfig['SENDER_NAME']);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->isHTML(true);
$mail->Body = $mailContent;
$mail->AltBody = $mailContentText;
$mail->DKIM_domain = $loginConfig['DKIM_DOMAIN'];
$mail->DKIM_private = $_SERVER['DOCUMENT_ROOT'] . $loginConfig['DKIM_PRIVATE'];
$mail->DKIM_selector = $loginConfig['DKIM_SELECTOR'];
$mail->DKIM_passphrase = $loginConfig['DKIM_PASSPHRASE'];
$mail->DKIM_identity = $mail->From;
$mail->DKIM_copyHeaderFields = false;
$mail->DKIM_extraHeaders = ['List-Unsubscribe', 'List-Help'];
//$mail->SMTPDebug = 2; // bugbug
// Send email
if (!$mail->send()) {
error_log('Mailer error: ' . $mail->ErrorInfo);
}
}
else {
//set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
//additional headers
$headers .= 'From: ' . $loginConfig['SENDER_NAME'] . '<' . $loginConfig['SENDER_EMAIL'] . '>' . "\r\n";
//send email
mail($to, $subject, $mailContent, $headers);
}
}
function storeWishlistResults($user, &$xh, &$xhtoc) {
$conn = MySessionHandler::getDBSessionId();
$created = mysqli_real_escape_string($conn, time());
$xhdb = new Html;
$xhdb->init($_SESSION["htmlIndent"]);
$xhdb->add_attribute("class", "container bg-info p-2 mb-5");
$xhdb->tag('div');
$xhdb->add_attribute("id", "toc");
$xhdb->tag('h2', "Table of Contents:");
$xhdb->tag('ol');
$html = $xhtoc->flush();
//error_log(print_r($html, 1));
$xhdb->insert_code($html);
$xhdb->close(); // ol
$xhdb->close(); // div
$html = $xh->flush();
//error_log(print_r($html, 1));
$xhdb->insert_code($html);
$html = $xhdb->flush();
//error_log(print_r($html, 1));
$data = base64_encode(gzencode($html));
$ip = inet_pton($_SERVER['REMOTE_ADDR']);
$sql = "INSERT INTO pricemonitor (userId, created, ip, data)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
created = ?, ip = ?, data = ?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ddssdss', $user['id'], $created, $ip, $data, $created, $ip, $data);
if ($result = mysqli_stmt_execute($stmt)) {
return 0;
}
else {
error_log("MySQL Update Users SQL: " . $sql);
error_log("MySQL Update Users Error: " . mysqli_error($conn) . " (" . $error . ")");
return -1;
}
mysqli_stmt_close($stmt);
return -1;
}
function wlLog($msg) {
if ($fh = fopen(FCM_WLLOGFILE, "a")) {
$date = new DateTime();
$date = $date->format("Y-m-d h:i:s");
fwrite($fh, $date . " " . $msg . PHP_EOL);
fclose($fh);
}
}