Subversion Repositories cheapmusic

Rev

Rev 153 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
72 - 1
<?php
73 - 2
use PHPMailer\PHPMailer\PHPMailer;
3
use PHPMailer\PHPMailer\Exception;
4
 
121 - 5
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/hosting.php');
72 - 6
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/sessions_db.php');
7
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/cryptor.php');
8
include_once ($_SERVER['DOCUMENT_ROOT'] . "/php/vendors.php");
9
include_once ($_SERVER['DOCUMENT_ROOT'] . '/php/tools.php');
121 - 10
include_once ($_SERVER['DOCUMENT_ROOT'] . "/php/NonceUtil.php");
72 - 11
 
153 - 12
$configFile = parse_ini_file(FCM_CONFIGFILE, true);
72 - 13
$crypt = Cryptor::getInstance($configFile['cryptor']);
14
$tmpSessionTab = (isset($_POST["sessionTab"]) && $_POST["sessionTab"] > 0 ? $_POST["sessionTab"] : null);
15
$handler = MySessionHandler::getInstance($tmpSessionTab, $configFile['mysqli']);
16
$vendors = Vendors::getInstance();
83 - 17
Vendors::setAllVendors($configFile, $vendors);
73 - 18
$loginConfig = $configFile['login'];
121 - 19
$systemConf = $configFile['system'];
72 - 20
unset($configFile);
21
 
120 - 22
session_set_cookie_params(604800, '/', '.findcheapmusic.com', true, true);
72 - 23
session_set_save_handler($handler, true);
24
if (!empty($_COOKIE['PHPSESSID'])) {
25
    session_id($_COOKIE['PHPSESSID']);
26
}
27
@session_start();
28
 
138 - 29
initSessionVariables($systemConf);
121 - 30
 
74 - 31
wlLog("Start");
72 - 32
$sent = processWishlist();
74 - 33
wlLog("End (Sent " . $sent . " emails)");
72 - 34
exit (0);
35
 
36
 
37
 
38
 
39
function processWishlist() {
40
    global $wlFreqHoursArr;
74 - 41
    global $wlFreqArr;
72 - 42
    $lastUid = -1;
43
    $lastCount = 0;
44
    $totalSent = 0;
127 - 45
    $xh = new Html;
46
    $xh->init($_SESSION["htmlIndent"]);
47
    $xhtoc = new Html;
48
    $xhtoc->init($_SESSION["htmlIndent"]);
73 - 49
    $toc = '';
121 - 50
    $prefix = 0;
72 - 51
    $conn = MySessionHandler::getDBSessionId();
52
 
74 - 53
    $sql = "SELECT w.id, w.uid, w.barcode, w.title, w.artist, w.cond, w.format, w.currency, w.price, w.checked, u.wlEmailFlag
54
            FROM wishlist w
55
            JOIN users u ON w.uid = u.id
56
            WHERE w.price > 0.00 and u.wlEmailFlag = '1'
57
            ORDER BY uid;";
72 - 58
 
59
    if ($result = mysqli_query($conn, $sql)) {
60
        if (mysqli_num_rows($result) > 0) {
61
            while ($wl = mysqli_fetch_assoc($result)) {
62
                if ($lastUid != $wl['uid']) {
63
                    if ($lastUid != '-1' && $lastCount > 0) {
74 - 64
                        wlLog("Email User (" . $user['id'] . "): TOC Count: " . $lastCount);
73 - 65
                        updateUserCheckedDate($user['id']);
72 - 66
                        ++$totalSent;
78 - 67
                        emailWishlistResults($user, $toc);
127 - 68
                        storeWishlistResults($user, $xh, $xhtoc);
69
                        $xh->reset();
70
                        $xh->init();
71
                        $xhtoc->reset();
72
                        $xhtoc->init();
73 - 73
                        $toc = '';
121 - 74
                        $prefix = 0;
72 - 75
                    }
76
                    $user = getUser($wl['uid']);
74 - 77
                    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"));
72 - 78
                    $_SESSION['buyer']['Zip'] = $user['zip'];
79
                    $lastCount = 0;
80
                }
81
                $lastUid = $wl['uid'];
82
 
74 - 83
                $diff = (time() - $user['wlChecked']) / 3600;
72 - 84
                if ($diff > $wlFreqHoursArr[$user['wlFreq']]) {
85
                    if (!empty($wl['barcode'])) {
137 - 86
                        $_SESSION["advSearch"]["Title"] = $wl['barcode'];
87
                        $_SESSION["searchTerm"] = $wl['barcode'];
72 - 88
                    } else {
137 - 89
                        $_SESSION["searchTerm"] = trim($wl['artist'] . " " . $wl['title']);
90
                        $_SESSION["advSearch"]["Title"] = $wl['title'];
91
                        $_SESSION["advSearch"]["Artist"] = $wl['artist'];
72 - 92
                    }
121 - 93
                    $_SESSION["prefix"] = ++$prefix;
137 - 94
                    $arr = searchAll(true);
72 - 95
                    $arr = filterWishlistResults($arr, $wl);
96
                    updateWishlistCheckedDate($wl['id']);
97
                    if (!empty($arr)) {
98
                        ++$lastCount;
127 - 99
                        $toc .= formatResults($arr, $wl, $lastCount, $xh, $xhtoc);
72 - 100
                    }
101
                }
102
            }
103
 
104
            if ($lastCount > 0) {
74 - 105
                wlLog("Email User (" . $user['id'] . "): TOC Count: " . $lastCount);
73 - 106
                updateUserCheckedDate($user['id']);
72 - 107
                ++$totalSent;
78 - 108
                emailWishlistResults($user, $toc);
127 - 109
                storeWishlistResults($user, $xh, $xhtoc);
72 - 110
            }
111
 
112
        }
113
    }
114
    else if (mysqli_errno($conn)) {
115
        error_log("MySQL Read Wishlist SQL: " . $sql);
116
        error_log("MySQL Read Wishlist Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
117
    }
118
 
119
    return $totalSent;
120
}
121
 
122
function filterWishlistResults($arr, $wl) {
123
    foreach ($arr as $key => $row) {
124
        if ($wl['cond'] != 'Any' && $row["Condition"] != $wl['cond']) {
125
            unset($arr[$key]);
126
        }
73 - 127
 
72 - 128
        if ($wl['format'] != 'Any' && $row["MediaType"] != $wl['format']) {
129
            unset($arr[$key]);
130
        }
73 - 131
 
72 - 132
        if ($row["ConvertedTotalPrice"] > $wl['price']) {
133
            unset($arr[$key]);
134
        }
135
    }
73 - 136
 
72 - 137
    return $arr;
138
}
139
 
127 - 140
function formatResults($arr, $wl, $cnt, &$xh, &$xhtoc) {
141
    $toc = "<li>" . htmlentities($wl["artist"])  . " - " . htmlentities($wl["title"]) . " (" . count($arr) . ")</li>";
72 - 142
 
127 - 143
    $xhtoc->tag('li');
144
        $xhtoc->add_attribute("href", "#jump_" . $cnt);
145
        $xhtoc->tag('a', htmlentities($wl["artist"])  . " - " . htmlentities($wl["title"]));
146
        $xhtoc->add_attribute("class", "badge badge-pill badge-dark ml-2");
147
        $xhtoc->tag('span', count($arr));
148
    $xhtoc->close(); // li
149
 
150
    $xh->add_attribute("id", "jump_" . $cnt);
151
    $xh->add_attribute("class", "bg-info p-1");
152
    $xh->tag('h3', $cnt . ") " . htmlentities($wl["artist"])  . " - " . htmlentities($wl["title"]));
78 - 153
 
127 - 154
    $xh->tag('p', "Condition: " . $wl["cond"] . " | Format: " . $wl["format"]  . " | Price Cap: " . print_monetary($wl["price"], $wl["currency"]));
143 - 155
    $xh->insert_code(buildTable($arr, $cnt));
72 - 156
 
127 - 157
    $xh->add_attribute("class", "btn btn-info mb-5");
158
    $xh->add_attribute("role", "button");
159
    $xh->add_attribute("href", "#toc");
160
    $xh->add_attribute("data-toggle", "tooltip");
161
    $xh->add_attribute("title", "Table of Contents");
162
    $xh->add_attribute("aria-label", "Go to table of contents");
163
    $xh->tag('a');
164
        $xh->add_attribute("class", "material-icons");
165
        $xh->tag('i', "arrow_upward");
166
    $xh->close(); // a
167
 
168
 
169
    return ($toc);
72 - 170
}
171
 
172
function updateWishlistCheckedDate($id) {
173
    $nul = 'NULL';
174
    $conn = MySessionHandler::getDBSessionId();
175
 
176
    $checked = mysqli_real_escape_string($conn, time());
177
 
178
    $sql = "UPDATE wishlist
179
            SET checked = '$checked'
180
            WHERE id = '$id'";
181
 
182
    if ($result = mysqli_query($conn, $sql)) {
183
        return 0;
184
    }
185
    else {
186
        error_log("MySQL Update Wishlist SQL: " . $sql);
187
        error_log("MySQL Update Wishlist Error: " . mysqli_error($conn) . " (" . $error . ")");
188
        return -1;
189
    }
190
 
191
    return -1;
192
}
193
 
194
function getUser($uid) {
195
    $conn = MySessionHandler::getDBSessionId();
196
 
197
    $sql = "SELECT id, first_name, last_name, email, zip, wlEmailFlag, wlFreq, wlChecked
198
            FROM users
199
            WHERE id = '$uid'";
200
 
201
    if ($result = mysqli_query($conn, $sql)) {
202
        if (mysqli_num_rows($result) > 0) {
203
            $row = mysqli_fetch_assoc($result);
204
            return $row;
205
        }
206
    }
207
    else if (mysqli_errno($conn)) {
208
        error_log("MySQL Read Users SQL: " . $sql);
209
        error_log("MySQL Read Users Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
210
    }
211
 
212
    return [];
213
}
214
 
215
function updateUserCheckedDate($uid) {
216
    $nul = 'NULL';
217
    $conn = MySessionHandler::getDBSessionId();
218
 
219
    $checked = mysqli_real_escape_string($conn, time());
220
 
221
    $sql = "UPDATE users
222
            SET wlChecked = '$checked'
223
            WHERE id = '$uid'";
224
 
225
    if ($result = mysqli_query($conn, $sql)) {
226
        return 0;
227
    }
228
    else {
229
        error_log("MySQL Update Users SQL: " . $sql);
230
        error_log("MySQL Update Users Error: " . mysqli_error($conn) . " (" . $error . ")");
231
        return -1;
232
    }
233
 
234
    return -1;
235
}
73 - 236
 
237
function PHPMailer_Init() {
238
    // Include PHPMailer library files
239
    require_once 'login/includes/PHPMailer/Exception.php';
240
    require_once 'login/includes/PHPMailer/PHPMailer.php';
241
    require_once 'login/includes/PHPMailer/SMTP.php';
242
 
243
    $mail = new PHPMailer;
244
 
245
    return $mail;
246
}
247
 
78 - 248
function emailWishlistResults($user, $toc) {
73 - 249
    global $loginConfig;
250
    global $wlFreqArr;
251
 
252
    $to = trim($user["email"]);
74 - 253
    $unsubscribeUrl = "https://" . $_SERVER["SERVER_NAME"] . "/index.php?submit=unsubscribe&amp;id=" . $user["id"] . "&amp;email=" . $to;
73 - 254
    $subject = "Wishlist Price Checks | " . $loginConfig['SITE_NAME'];
74 - 255
    $mailContent = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
256
                    <html xmlns="http://www.w3.org/1999/xhtml">
73 - 257
                    <head>
258
                            <title>Find Cheap Music Wishlist Price Checks</title>
74 - 259
                            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
260
                            <meta name="viewport" content="width=device-width" />
73 - 261
                    </head>
262
                    <body>
74 - 263
                        <table cellpadding="0" cellspacing="0" border="0" width="100%" style="border-radius:6px;background-color:#ffffff;padding-top:15px;border-collapse:separate">
264
	    	                <tbody>
265
                    			<tr>
266
			    	                <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">
267
                        				<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>
268
                	        			<br/>
78 - 269
                		        		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:.
270
                			        	<ol>' . $toc . '</ol>
271
                			        	Please login to your account at <a href="https://' . $_SERVER["SERVER_NAME"] . '/index.php">Find Cheap Music</a> and navigate to the wishlist.
74 - 272
        				                <br/>We look forward to serving you,<br/><strong>' . $loginConfig['SITE_NAME'] . ' Team</strong>
273
                        				<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>
274
                    				</td>
275
                    			</tr>
276
                    		</tbody>
277
                    	</table>
278
                    </body>
279
                    </html>';
73 - 280
 
80 - 281
    $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";
73 - 282
    $mailContentText .= "\r\nWe look forward to serving you,\r\n" . $loginConfig['SITE_NAME'] . " Team";
283
 
284
    if ($loginConfig['SMTP'] == true) {
285
        $mail = PHPMailer_Init();
286
 
287
        // SMTP configuration
288
        $mail->isSMTP();
289
        $mail->CharSet = "text/html; charset=UTF-8;";
290
        $mail->WordWrap = 80;
291
        $mail->Host = $loginConfig['SMTP_HOST'];
292
        $mail->SMTPAuth = true;
293
        $mail->Username = $loginConfig['SMTP_USERNAME'];
294
        $mail->Password = $loginConfig['SMTP_PASSWORD'];
295
        $mail->SMTPSecure = $loginConfig['SMTP_SECURE'];
296
        $mail->Port = $loginConfig['SMTP_PORT'];
297
 
298
        $mail->addCustomHeader("List-Unsubscribe-Post", "List-Unsubscribe=One-Click");
299
        $mail->addCustomHeader("List-Unsubscribe", "<" . $unsubscribeUrl . ">");
300
 
301
        $mail->setFrom($loginConfig['SENDER_EMAIL'], $loginConfig['SENDER_NAME']);
302
 
303
        $mail->addAddress($to);
304
        $mail->Subject = $subject;
305
        $mail->isHTML(true);
306
        $mail->Body = $mailContent;
307
        $mail->AltBody = $mailContentText;
308
 
309
        $mail->DKIM_domain = $loginConfig['DKIM_DOMAIN'];
310
        $mail->DKIM_private = $_SERVER['DOCUMENT_ROOT'] . $loginConfig['DKIM_PRIVATE'];
311
        $mail->DKIM_selector = $loginConfig['DKIM_SELECTOR'];
312
        $mail->DKIM_passphrase = $loginConfig['DKIM_PASSPHRASE'];
313
        $mail->DKIM_identity = $mail->From;
314
        $mail->DKIM_copyHeaderFields = false;
315
        $mail->DKIM_extraHeaders = ['List-Unsubscribe', 'List-Help'];
316
 
317
        //$mail->SMTPDebug = 2; // bugbug
318
 
319
        // Send email
320
        if (!$mail->send()) {
321
            error_log('Mailer error: ' . $mail->ErrorInfo);
322
        }
323
    }
324
    else {
325
        //set content-type header for sending HTML email
326
        $headers = "MIME-Version: 1.0" . "\r\n";
327
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
328
        //additional headers
329
        $headers .= 'From: ' . $loginConfig['SENDER_NAME'] . '<' . $loginConfig['SENDER_EMAIL'] . '>' . "\r\n";
330
        //send email
331
        mail($to, $subject, $mailContent, $headers);
332
    }
333
}
74 - 334
 
127 - 335
function storeWishlistResults($user, &$xh, &$xhtoc) {
78 - 336
    $conn = MySessionHandler::getDBSessionId();
337
 
338
    $created = mysqli_real_escape_string($conn, time());
127 - 339
 
340
    $xhdb = new Html;
341
    $xhdb->init($_SESSION["htmlIndent"]);
342
 
343
    $xhdb->add_attribute("class", "container bg-info p-2 mb-5");
344
    $xhdb->tag('div');
345
        $xhdb->add_attribute("id", "toc");
346
        $xhdb->tag('h2', "Table of Contents:");
347
        $xhdb->tag('ol');
348
            $html = $xhtoc->flush();
349
            //error_log(print_r($html, 1));
350
            $xhdb->insert_code($html);
351
        $xhdb->close(); // ol
352
    $xhdb->close(); // div
353
    $html = $xh->flush();
354
    //error_log(print_r($html, 1));
355
    $xhdb->insert_code($html);
356
 
357
    $html = $xhdb->flush();
358
    //error_log(print_r($html, 1));
359
 
360
    $data = base64_encode(gzencode($html));
96 - 361
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
78 - 362
 
96 - 363
    $sql = "INSERT INTO pricemonitor (userId, created, ip, data)
154 - 364
            VALUES (?, ?, ?, ?)
78 - 365
            ON DUPLICATE KEY UPDATE
154 - 366
            created = ?, ip = ?, data = ?";
367
    $stmt = mysqli_prepare($conn, $sql);
368
    mysqli_stmt_bind_param($stmt, 'ddssdss', $user['id'], $created, $ip, $data, $created, $ip, $data);
78 - 369
 
154 - 370
    if ($result = mysqli_stmt_execute($stmt)) {
78 - 371
        return 0;
372
    }
373
    else {
374
        error_log("MySQL Update Users SQL: " . $sql);
375
        error_log("MySQL Update Users Error: " . mysqli_error($conn) . " (" . $error . ")");
376
        return -1;
377
    }
378
 
154 - 379
    mysqli_stmt_close($stmt);
380
 
78 - 381
    return -1;
382
}
383
 
74 - 384
function wlLog($msg) {
75 - 385
 
154 - 386
    if ($fh = fopen(FCM_WLLOGFILE, "a")) {
76 - 387
        $date = new DateTime();
74 - 388
        $date = $date->format("Y-m-d h:i:s");
389
 
390
        fwrite($fh, $date . " " . $msg . PHP_EOL);
391
 
392
        fclose($fh);
393
    }
80 - 394
}