Subversion Repositories cheapmusic

Rev

Rev 130 | Rev 133 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 - 1
<?php
93 - 2
use Fuse\Fuse;
65 - 3
include_once ('php/clsLibGTIN.php');
4
include_once ('php/exchangeRates.php');
5
include_once ('php/countryCodes.php');
6
include_once ('php/constants.php');
7
include_once ('php/ebay.php');
8
include_once ('php/discogs.php');
9
include_once ('php/linkshare.php');
10
include_once ('php/cjaffiliate.php');
11
include_once ('php/walmart.php');
12
include_once ('php/itunes.php');
81 - 13
include_once ('php/amazon.php');
91 - 14
include_once ('php/amazon_scrape.php');
83 - 15
include_once ('php/impact.php');
99 - 16
include_once ('php/sessions_db.php');
116 - 17
include_once ('php/media.php');
127 - 18
include_once ('php/class.html.php');
19
include_once ('php/htmlTools.php');
1 - 20
 
20 - 21
error_reporting(E_ALL);
22
 
65 - 23
// search
5 - 24
function performSearch() {
14 - 25
    $currentMd5SearchTerm = md5SearchTerm();
116 - 26
    if (isset($_SESSION['md5LastSearch']) && $currentMd5SearchTerm == $_SESSION['md5LastSearch']) {
14 - 27
        return;
28
    }
29
    $_SESSION['md5LastSearch'] = $currentMd5SearchTerm;
30
 
81 - 31
    $_SESSION["barcode"]["Type"] = clsLibGTIN::GTINCheck($_SESSION["searchTerm"], false, 1);
32
    $_SESSION["barcode"]["Value"] = clsLibGTIN::GTINCheck($_SESSION["searchTerm"]);
33
 
129 - 34
    updatePbFile(true, "Start");
22 - 35
 
107 - 36
    getGeoLocation();
37
 
81 - 38
    findDiscogsMaster($_SESSION["searchTerm"]);
129 - 39
    updatePbFile(false, "Discogs");
81 - 40
 
65 - 41
    $_SESSION["resultArr"] = [];
99 - 42
    expireSearchCache();
65 - 43
    $_SESSION["resultArr"] = searchAll($_SESSION["searchTerm"]);
93 - 44
 
99 - 45
    verifyResultArr();
93 - 46
 
65 - 47
    $_SESSION["resultArr"] = applySearchFilter($_SESSION["resultArr"]);
5 - 48
 
65 - 49
    //echo "<pre>";print_r($_SESSION["resultArr"]);echo "</pre>";
66 - 50
    $_SESSION["lowestPrice"]["Used"] = findLowestCondition("Used");
51
    $_SESSION["lowestPrice"]["New"] = findLowestCondition("New");
52
    $_SESSION["lowestPrice"]["CD"] = findLowestMediaType("CD");
53
    $_SESSION["lowestPrice"]["Record"] = findLowestMediaType("Record");
54
    $_SESSION["lowestPrice"]["Digital"] = findLowestMediaType("Digital");
55
    $_SESSION["lowestPrice"]["Book"] = findLowestMediaType("Book");
65 - 56
    $_SESSION["lowestPrice"]["All"] = 0.00;
57
    if (array_sum($_SESSION["lowestPrice"]) > 0) {
58
        $_SESSION["lowestPrice"]["All"] = minNotNull($_SESSION["lowestPrice"]);
59
    }
13 - 60
 
129 - 61
    $aiVal = saveSearchResult();
62
 
63
    updatePbFile(true, "End:$aiVal");
5 - 64
}
65
 
9 - 66
function resetSessionVars() {
67
    $_SESSION["searchTerm"] = '';
46 - 68
    $_SESSION["discogsTitle"] = '';
69
    $_SESSION["discogsArtist"] = '';
14 - 70
    $_SESSION['md5LastSearch'] = '';
65 - 71
    $_SESSION["barcode"]["Type"] = '';
72
    $_SESSION["barcode"]["Value"] = '';
9 - 73
 
65 - 74
    $_SESSION["resultArr"] = [];
9 - 75
 
65 - 76
    $_SESSION["lowestPrice"]["Used"] = 0.00;
77
    $_SESSION["lowestPrice"]["New"] = 0.00;
78
    $_SESSION["lowestPrice"]["CD"] = 0.00;
79
    $_SESSION["lowestPrice"]["Record"] = 0.00;
80
    $_SESSION["lowestPrice"]["Digital"] = 0.00;
81
    $_SESSION["lowestPrice"]["Book"] = 0.00;
82
    $_SESSION["lowestPrice"]["All"] = 0.00;
9 - 83
}
84
 
65 - 85
// search for items on all sites
72 - 86
function searchAll($searchKey, $batchFlag = false) {
65 - 87
    $arr = [];
88
    if ($_SESSION["filterCondition"]["New"]) {
129 - 89
        get_vendor($arr, 'get_ebay', $searchKey, constant("NEW"));
65 - 90
    }
129 - 91
    if (!$batchFlag) { updatePbFile(false, "eBay New"); }
65 - 92
    if ($_SESSION["filterCondition"]["New"]) {
129 - 93
        get_vendor($arr, 'get_linkshare', $searchKey, constant("NEW"));
65 - 94
    }
129 - 95
    if (!$batchFlag) { updatePbFile(false, "Linkshare"); }
65 - 96
    if ($_SESSION["filterCondition"]["New"]) {
129 - 97
        get_vendor($arr, 'get_cjaffiliate', $searchKey, constant("NEW"));
65 - 98
    }
129 - 99
    if (!$batchFlag) { updatePbFile(false, "CJ Affiliate"); }
65 - 100
    if ($_SESSION["filterCondition"]["New"]) {
129 - 101
        get_vendor($arr, 'get_walmart', $searchKey, constant("NEW"));
65 - 102
    }
129 - 103
    if (!$batchFlag) { updatePbFile(false, "Walmart"); }
65 - 104
    if ($_SESSION["filterCondition"]["New"]) {
129 - 105
        get_vendor($arr, 'get_itunes', $searchKey, constant("NEW"));
65 - 106
    }
129 - 107
    if (!$batchFlag) { updatePbFile(false, "iTunes"); }
17 - 108
 
91 - 109
    $cntArr = count($arr);
129 - 110
    get_vendor($arr, 'get_amazon', $searchKey, constant("NEW"));
111
    if (!$batchFlag) { updatePbFile(false, "Amazon API"); }
91 - 112
    if ($cntArr == count($arr)) {
129 - 113
        get_vendor($arr, 'get_amazon_scrape', $searchKey, constant("NEW"));
91 - 114
    }
129 - 115
    if (!$batchFlag) { updatePbFile(false, "Amazon Scrape"); }
81 - 116
 
129 - 117
    get_vendor($arr, 'get_impact', $searchKey, constant("NEW"));
118
    if (!$batchFlag) { updatePbFile(false, "Impact"); }
83 - 119
 
65 - 120
    if ($_SESSION["filterCondition"]["Used"]) {
129 - 121
        get_vendor($arr, 'get_ebay', $searchKey, constant("USED"));
65 - 122
    }
129 - 123
    if (!$batchFlag) { updatePbFile(false, "eBay Used"); }
17 - 124
 
66 - 125
//echo "<pre>";print_r($arr);echo "</pre";
24 - 126
 
65 - 127
    $arr = applyExchangeRates($arr);
128
    usort($arr, 'compare_price');
5 - 129
 
65 - 130
    return $arr;
5 - 131
}
132
 
20 - 133
// Search and merge
129 - 134
function get_vendor(&$arr, $func, $searchKey, $condition) {
65 - 135
    $arrTemp = $func($searchKey, $condition);
129 - 136
    foreach($arrTemp as $value) {
137
        $arr[] = $value;
138
    }
20 - 139
}
140
 
21 - 141
// delete results from array that do not match the search filters
142
function applySearchFilter($arr) {
66 - 143
    unset($_SESSION['AdditionalFilterCounters']);
144
    unset($_SESSION['AdditionalFilters']);
65 - 145
    foreach ($arr as $key => $row) {
66 - 146
        if (!$_SESSION["filterMediaType"][$row["MediaType"]] || !$_SESSION["filterCondition"][$row["Condition"]]) {
21 - 147
            unset($arr[$key]);
66 - 148
        } else {
149
            if (isset($_SESSION['AdditionalFilterCounters']['Condition']['All'])) {
150
                $_SESSION['AdditionalFilterCounters']['Condition']['All']++;
151
            } else {
152
                $_SESSION['AdditionalFilterCounters']['Condition']['All'] = 1;
153
            }
154
 
155
            if (isset($_SESSION['AdditionalFilterCounters']['Merchant'][$row['Merchant']])) {
156
                $_SESSION['AdditionalFilterCounters']['Merchant'][$row['Merchant']]++;
157
            } else {
158
                $_SESSION['AdditionalFilterCounters']['Merchant'][$row['Merchant']] = 1;
159
                $_SESSION['AdditionalFilters']['Merchant'][$row['Merchant']] = true;
160
            }
161
 
162
            if (!empty($row['SellerName'])) {
163
                if (isset($_SESSION['AdditionalFilterCounters']['Seller'][$row['SellerName']])) {
164
                    $_SESSION['AdditionalFilterCounters']['Seller'][$row['SellerName']]++;
165
                } else {
166
                    $_SESSION['AdditionalFilterCounters']['Seller'][$row['SellerName']] = 1;
167
                    $_SESSION['AdditionalFilters']['Seller'][$row['SellerName']] = true;
168
                }
169
            }
170
 
171
            if (isset($_SESSION['AdditionalFilterCounters']['Condition'][$row['Condition']])) {
172
                $_SESSION['AdditionalFilterCounters']['Condition'][$row['Condition']]++;
173
            } else {
174
                $_SESSION['AdditionalFilterCounters']['Condition'][$row['Condition']] = 1;
175
                $_SESSION['AdditionalFilters']['Condition'][$row['Condition']] = true;
176
            }
177
 
178
            if (isset($_SESSION['AdditionalFilterCounters']['MediaType'][$row['MediaType']])) {
179
                $_SESSION['AdditionalFilterCounters']['MediaType'][$row['MediaType']]++;
180
            } else {
181
                $_SESSION['AdditionalFilterCounters']['MediaType'][$row['MediaType']] = 1;
182
                $_SESSION['AdditionalFilters']['MediaType'][$row['MediaType']] = true;
183
            }
184
 
185
            if (isset($_SESSION['AdditionalFilterCounters']['DetailCondition'][$row['DetailCondition']])) {
186
                $_SESSION['AdditionalFilterCounters']['DetailCondition'][$row['DetailCondition']]++;
187
            } else {
188
                $_SESSION['AdditionalFilterCounters']['DetailCondition'][$row['DetailCondition']] = 1;
189
                $_SESSION['AdditionalFilters']['DetailCondition'][$row['DetailCondition']] = true;
190
            }
191
 
192
            if (isset($_SESSION['AdditionalFilterCounters']['ShippingFrom'][$row['Country']])) {
193
                $_SESSION['AdditionalFilterCounters']['ShippingFrom'][$row['Country']]++;
194
            } else {
195
                $_SESSION['AdditionalFilterCounters']['ShippingFrom'][$row['Country']] = 1;
196
                $_SESSION['AdditionalFilters']['ShippingFrom'][$row['Country']] = true;
197
            }
65 - 198
        }
199
    }
23 - 200
 
66 - 201
    if (isset($_SESSION['AdditionalFilters']['Merchant'])) {
202
        ksort($_SESSION['AdditionalFilters']['Merchant'], SORT_NATURAL | SORT_FLAG_CASE);
203
    }
204
 
205
    if (isset($_SESSION['AdditionalFilters']['Seller'])) {
206
        ksort($_SESSION['AdditionalFilters']['Seller'], SORT_NATURAL | SORT_FLAG_CASE);
207
    }
208
 
209
    if (isset($_SESSION['AdditionalFilters']['Condition'])) {
210
        ksort($_SESSION['AdditionalFilters']['Condition'], SORT_NATURAL | SORT_FLAG_CASE);
211
    }
212
 
213
    if (isset($_SESSION['AdditionalFilters']['DetailCondition'])) {
214
        ksort($_SESSION['AdditionalFilters']['DetailCondition'], SORT_NATURAL | SORT_FLAG_CASE);
215
    }
216
 
217
    if (isset($_SESSION['AdditionalFilters']['ShippingFrom'])) {
218
        ksort($_SESSION['AdditionalFilters']['ShippingFrom'], SORT_NATURAL | SORT_FLAG_CASE);
219
    }
220
 
221
    if (isset($_SESSION['AdditionalFilters']['MediaType'])) {
222
        ksort($_SESSION['AdditionalFilters']['MediaType'], SORT_NATURAL | SORT_FLAG_CASE);
223
    }
224
 
21 - 225
    return $arr;
226
}
227
 
66 - 228
// filter view result table $_SESSION["resultArr"] for detailed filter selection
229
function detailFilterResults($selArr) {
67 - 230
    if (!empty($selArr['filterCondition'])) {
231
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
232
            $_SESSION['AdditionalFilters']['Condition'][$key] = false;
233
        }
234
        if (!is_array($selArr['filterCondition'])) { $selArr['filterCondition'] = [ $selArr['filterCondition'] ];}
235
        foreach($selArr['filterCondition'] as $value) {
236
            $_SESSION['AdditionalFilters']['Condition'][$value] = true;
237
        }
238
    } else {
68 - 239
        $selArr['filterCondition'] = [];
77 - 240
        if (!empty($_SESSION['AdditionalFilters']['Condition'])) {
241
            foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
242
                if ($value) {
243
                    $selArr['filterCondition'][] = $key;
244
                }
68 - 245
            }
246
        }
66 - 247
    }
248
 
67 - 249
    if (!empty($selArr['filterMediaType'])) {
250
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
251
            $_SESSION['AdditionalFilters']['MediaType'][$key] = false;
252
        }
253
        if (!is_array($selArr['filterMediaType'])) { $selArr['filterMediaType'] = [ $selArr['filterMediaType'] ];}
254
        foreach($selArr['filterMediaType'] as $value) {
255
            $_SESSION['AdditionalFilters']['MediaType'][$value] = true;
256
        }
257
    } else {
68 - 258
        $selArr['filterMediaType'] = [];
77 - 259
        if (!empty($_SESSION['AdditionalFilters']['MediaType'])) {
260
            foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
261
                if ($value) {
262
                    $selArr['filterMediaType'][] = $key;
263
                }
68 - 264
            }
265
        }
66 - 266
    }
267
 
67 - 268
    if (!empty($selArr['filterShipFrom'])) {
269
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
270
            $_SESSION['AdditionalFilters']['ShippingFrom'][$key] = false;
271
        }
272
        if (!is_array($selArr['filterShipFrom'])) { $selArr['filterShipFrom'] = [ $selArr['filterShipFrom'] ];}
273
        foreach($selArr['filterShipFrom'] as $value) {
274
            $_SESSION['AdditionalFilters']['ShippingFrom'][$value] = true;
275
        }
276
    } else {
68 - 277
        $selArr['filterShipFrom'] = [];
77 - 278
        if (!empty($_SESSION['AdditionalFilters']['ShippingFrom'])) {
279
            foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
280
                if ($value) {
281
                    $selArr['filterShipFrom'][] = $key;
282
                }
68 - 283
            }
284
        }
66 - 285
    }
286
 
67 - 287
    if (!empty($selArr['filterMerchant'])) {
288
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
289
            $_SESSION['AdditionalFilters']['Merchant'][$key] = false;
290
        }
291
        if (!is_array($selArr['filterMerchant'])) { $selArr['filterMerchant'] = [ $selArr['filterMerchant'] ];}
292
        foreach($selArr['filterMerchant'] as $value) {
293
            $_SESSION['AdditionalFilters']['Merchant'][$value] = true;
294
        }
295
    } else {
68 - 296
        $selArr['filterMerchant'] = [];
77 - 297
        if (!empty($_SESSION['AdditionalFilters']['Merchant'])) {
298
            foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
299
                if ($value) {
300
                    $selArr['filterMerchant'][] = $key;
301
                }
68 - 302
            }
303
        }
66 - 304
    }
305
 
306
    foreach ($_SESSION["resultArr"] as & $row) {
307
        $row["Show"] = true;
308
 
309
        if (!in_array($row["Condition"], $selArr['filterCondition']) ||
310
            !in_array($row["MediaType"], $selArr['filterMediaType']) ||
311
            !in_array($row["Merchant"], $selArr['filterMerchant']) ||
312
            !in_array($row["Country"], $selArr['filterShipFrom'])) {
313
            $row["Show"] = false;
314
        }
315
    }
316
}
317
 
318
function resetDetailFilter() {
319
    if (isset($_SESSION['AdditionalFilters']['Merchant'])) {
320
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $field) {
321
            $_SESSION['AdditionalFilters']['Merchant'][$key] = true;
322
        }
323
    }
324
 
325
    if (isset($_SESSION['AdditionalFilters']['Seller'])) {
326
        foreach($_SESSION['AdditionalFilters']['Seller'] as $key => $field) {
327
            $_SESSION['AdditionalFilters']['Seller'][$key] = true;
328
        }
329
    }
330
 
331
    if (isset($_SESSION['AdditionalFilters']['Condition'])) {
332
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $field) {
333
            $_SESSION['AdditionalFilters']['Condition'][$key] = true;
334
        }
335
    }
336
 
337
    if (isset($_SESSION['AdditionalFilters']['DetailCondition'])) {
338
        foreach($_SESSION['AdditionalFilters']['DetailCondition'] as $key => $field) {
339
            $_SESSION['AdditionalFilters']['DetailCondition'][$key] = true;
340
        }
341
    }
342
 
343
    if (isset($_SESSION['AdditionalFilters']['ShippingFrom'])) {
344
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $field) {
345
            $_SESSION['AdditionalFilters']['ShippingFrom'][$key] = true;
346
        }
347
    }
348
 
349
    if (isset($_SESSION['AdditionalFilters']['MediaType'])) {
350
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $field) {
351
            $_SESSION['AdditionalFilters']['MediaType'][$key] = true;
352
        }
353
    }
107 - 354
 
66 - 355
    foreach ($_SESSION["resultArr"] as & $row) {
356
        $row["Show"] = true;
357
    }
358
}
359
 
65 - 360
// print result table or card deck
59 - 361
function printResult() {
362
    if ($_SESSION["currentLayout"] == 'TableView') {
78 - 363
        return buildTable($_SESSION["resultArr"]);
65 - 364
    }
365
    else /* CardView */ {
78 - 366
        return buildCardDeck($_SESSION["resultArr"]);
59 - 367
    }
368
}
369
 
65 - 370
// build HTML table from array
78 - 371
function buildTable($arr) {
86 - 372
    global $buyItNowTooltip;
127 - 373
 
374
    $xh = new Html;
375
    $xh->init($_SESSION["htmlIndent"]);
376
 
78 - 377
    if (count($arr) > 0) {
127 - 378
        $xh->add_attribute("class", "table");
379
        $xh->tag('div');
380
        $xh->add_attribute("class", "table table-striped table-condensed table-hover small");
130 - 381
        $xh->add_attribute("id", "storeOfferTable");
127 - 382
        $xh->tag('table');
383
        $xh->add_attribute("class", "thead-dark table-header-sticky");
384
        $xh->tag('thead');
385
        $xh->tag('tr');
17 - 386
 
127 - 387
        $xh->tag('th', "Image");
388
        $xh->add_attribute("class", "text-left");
389
        $xh->tag('th', "Title / Merchant");
390
        $xh->tag('th', "Condition");
391
        $xh->add_attribute("class", "hide-small");
392
        $xh->tag('th', "Price");
393
        $xh->add_attribute("class", "hide-small");
394
        $xh->tag('th', "S/H");
395
        $xh->tag('th', "Total");
396
        $xh->add_attribute("class", "hide-extra-small");
397
        $xh->tag('th', "");
398
 
399
        $xh->close(); // tr
400
        $xh->close(); // thead
401
 
402
        $xh->tag('tbody');
403
 
78 - 404
        foreach ($arr as $row) {
65 - 405
            if (!$row["Show"]) {
406
                continue;
407
            }
1 - 408
 
59 - 409
            $title = $row["Title"];
410
            if (mb_strlen($row["Title"], 'UTF-8') > MAXTITLELENGTH) {
65 - 411
                $title = mb_substr($row["Title"], 0, MAXTITLELENGTH, 'UTF-8') . '...';
59 - 412
            }
124 - 413
            $title = htmlentities($title);
5 - 414
 
127 - 415
            $xh->add_attribute("class", "border");
130 - 416
            $xh->add_attribute("data-url", $row["URL"]);
417
            $xh->add_attribute("data-merchant", $row["Merchant"]);
127 - 418
            $xh->tag('tr');
13 - 419
 
9 - 420
            // Image
127 - 421
            $xh->tag('td');
422
            $xh->add_attribute("href", htmlentities($row["URL"]));
423
            $xh->add_attribute("target", "_blank");
424
            $xh->add_attribute("rel", "sponsored noreferrer noopener");
425
            $xh->add_attribute("data-toggle", "tooltip");
426
            $xh->add_attribute("title", $buyItNowTooltip);
427
            $xh->tag('a');
130 - 428
            $xh->add_attribute("class", "affiliate-link img-fluid result-table-image lazyload");
127 - 429
            $xh->add_attribute("src",PIXEL);
430
            $xh->add_attribute("data-src", htmlentities($row["Image"]));
431
            $xh->add_attribute("alt", "Item Image");
432
            $xh->single_tag('img');
433
            $xh->close(); // a
434
            $xh->close(); // td
1 - 435
 
9 - 436
            // Title / Merchant
127 - 437
            $xh->add_attribute("class", "text-left");
438
            $xh->tag('td');
439
            $xh->add_attribute("class", "font-weight-bold");
440
            $xh->tag('span');
130 - 441
            $xh->add_attribute("class", "affiliate-link");
127 - 442
            $xh->add_attribute("href", htmlentities($row["URL"]));
443
            $xh->add_attribute("target", "_blank");
444
            $xh->add_attribute("rel", "sponsored noreferrer noopener");
445
            $xh->add_attribute("data-toggle", "tooltip");
446
            $xh->add_attribute("title",$buyItNowTooltip);
447
            $xh->tag('a', $title);
448
            $xh->close(); // span
449
            $xh->brnl();
450
            $xh->brnl();
451
            $xh->add_attribute("class", "font-weight-bold");
452
            $xh->tag('span', htmlentities($row["Merchant"]));
65 - 453
            if ($row["FeedbackScore"] != - 1) {
127 - 454
                $xh->brnl();
455
                $xh->add_attribute("class", "hide-extra-small");
456
                $xh->tag('span', htmlentities($row["SellerName"]) . " (" . number_format($row["FeedbackScore"], 0, "", ", ") . " / " . $row["FeedbackPercent"] . "%)");
65 - 457
            }
458
            else if (!empty($row["SellerName"])) {
127 - 459
                $xh->brnl();
460
                $xh->add_attribute("class", "hide-extra-small");
461
                $xh->tag('span', htmlentities($row["SellerName"]));
65 - 462
            }
463
            if (!empty($row["TimeLeft"])) {
127 - 464
                $xh->brnl();
465
                $xh->tag('span', $row["TimeLeft"]);
65 - 466
            }
127 - 467
            $xh->close(); // td
1 - 468
 
9 - 469
            // Condition
127 - 470
            $xh->add_attribute("class", "text-center");
471
            $xh->tag('td');
472
            $xh->add_attribute("class", "font-weight-bold");
473
            $xh->tag('span', $row["DetailCondition"]);
474
            $xh->brnl();
475
            $xh->brnl();
476
            $xh->add_attribute("class",getMediaIconClass($row["MediaType"], "media-icon"));
477
            $xh->add_attribute("title",getMediaIconText($row["MediaType"]));
478
            $xh->add_attribute("data-toggle", "tooltip");
479
            $xh->add_attribute("data-placement", "right");
480
            $xh->add_attribute("data-delay", "200");
481
            $xh->tag('i', getMediaIconAlias($row["MediaType"]));
482
            $xh->close(); // td
5 - 483
 
9 - 484
            // Price
127 - 485
            $str = print_monetary($row["Price"], $row["Currency"]);
65 - 486
            if ($row["Currency"] != $_SESSION["buyer"]["Currency"]) {
487
                $str .= "<br/>&asymp; " . print_monetary($row["ConvertedPrice"], $_SESSION["buyer"]["Currency"]);
488
            }
489
            if ($row["BestOffer"] == "true") {
490
                $str .= "<br>Best Offer Accepted";
491
            }
127 - 492
            $xh->add_attribute("class", "hide-small");
493
            $xh->tag('td', $str);
1 - 494
 
9 - 495
            // Shipping and Handling Cost
127 - 496
            $str = "";
65 - 497
            if ($row["ShippingCost"] == 0.00) {
498
                $str .= "Free Shipping";
499
            }
500
            else {
501
                $str .= print_monetary($row["ShippingCost"], $row["ShippingCurrency"]);
81 - 502
                if ($row["ShippingEstimated"]) {
503
                    $str .= "*";
504
                }
65 - 505
            }
506
            if ($row["ShippingCost"] > 0.00 && $row["ShippingCurrency"] != $_SESSION["buyer"]["Currency"]) {
507
                $str .= "<br/>&asymp; " . print_monetary($row["ConvertedShippingCost"], $_SESSION["buyer"]["Currency"]);
508
            }
24 - 509
            if ($row["HandlingTime"] > 0) {
510
                $str .= "<br>Handling Time " . $row["HandlingTime"] . " day" . ($row["HandlingTime"] > 1 ? "s" : "");
511
            }
512
            if ($row["ShippingCost"] > 0.00 && $row["FreeShippingCap"] > 0) {
513
                $str .= "<br>Free Shipping over " . print_monetary($row["FreeShippingCap"], $_SESSION["buyer"]["Currency"]);
514
            }
127 - 515
            $str .= "<br/>";
516
            $xh->add_attribute("class", "hide-small");
517
            $xh->tag('td');
518
            $xh->tag('span', $str);
519
            $xh->add_attribute("class", "img-fluid lazyload");
520
            $xh->add_attribute("title", "Ships from " . getCountry($row["Country"]));
521
            $xh->add_attribute("data-toggle", "tooltip");
522
            $xh->add_attribute("data-placement", "right");
523
            $xh->add_attribute("data-delay", "200");
524
            $xh->add_attribute("src",PIXEL);
525
            $xh->add_attribute("data-src", timeStampUrl("images/flags/" . $row["Country"] . ".png"));
526
            $xh->add_attribute("alt", getCountry($row["Country"]) . " Flag");
527
            $xh->single_tag('img');
528
            $xh->close(); // td
1 - 529
 
9 - 530
            // Total Price
127 - 531
            $xh->add_attribute("class", "font-weight-bolder");
532
            $xh->tag('td', print_monetary($row["ConvertedTotalPrice"], $_SESSION["buyer"]["Currency"]));
1 - 533
 
9 - 534
            // Link
54 - 535
            if ($row["Merchant"] == "iTunes") {
66 - 536
                if ($row["MediaType"] == "Digital") {
127 - 537
                    $linkImage = timeStampUrl("images/US-UK_Apple_Music_Badge_RGB.svg");
65 - 538
                }
539
                else {
127 - 540
                    $linkImage = timeStampUrl("images/US_UK_Apple_Books_Badge_Get_RGB_071818.svg");
54 - 541
                }
127 - 542
                $class = "btn";
543
                $altText = "iTunes Badge";
81 - 544
            } else if (strpos($row["Merchant"], "eBay") !== false) {
127 - 545
                $class = "btn";
546
                $altText = "eBay Store";
547
                $linkImage = timeStampUrl("images/ebay-right-now.gif");
81 - 548
            } else if (strpos($row["Merchant"], "Amazon") !== false) {
127 - 549
                $class = "btn";
550
                $altText = "Amazon Store";
551
                $linkImage = timeStampUrl("images/amazon-buy3.gif");
81 - 552
            } else {
127 - 553
                $class = "btn btn-success";
554
                $altText = "";
555
                $linkImage = "";
54 - 556
            }
127 - 557
            $xh->add_attribute("class", "hide-extra-small text-center");
558
            $xh->tag('td');
130 - 559
            $xh->add_attribute("class", $class);
127 - 560
            $xh->add_attribute("title", $buyItNowTooltip);
561
            $xh->add_attribute("aria-label", "Go to store");
562
            $xh->add_attribute("data-toggle", "tooltip");
563
            $xh->add_attribute("role", "button");
130 - 564
            $xh->add_attribute("href", htmlentities($row["URL"]));
127 - 565
            $xh->add_attribute("target", "_blank");
566
            $xh->add_attribute("rel", "sponsored noreferrer noopener");
567
            $xh->tag('a');
568
            if (empty($linkImage)) {
130 - 569
                $xh->add_attribute("class", "affiliate-link material-icons md-36");
127 - 570
                $xh->tag('i', "store");
571
            } else {
130 - 572
                $xh->add_attribute("class", "affiliate-link lazyload");
573
                $xh->add_attribute("src", PIXEL);
127 - 574
                $xh->add_attribute("data-src", $linkImage);
130 - 575
                $xh->add_attribute("alt", $altText);
127 - 576
                $xh->single_tag('img');
577
            }
578
            $xh->close(); // a
579
            $xh->close(); // td
1 - 580
 
127 - 581
            $xh->close(); // tr
9 - 582
        }
17 - 583
 
127 - 584
        $xh->close(); // tbody
585
 
586
        $xh->add_attribute("class", "text-right");
587
        $xh->tag('tfoot');
588
        $xh->add_attribute("class", "border");
589
        $xh->tag('tr');
590
        $xh->add_attribute("class", "font-italic");
591
        $xh->add_attribute("colspan", "7");
592
        $xh->tag('td', "Prices retrieved on " . gmdate("Y-m-d H:i") . " UTC<br>Daily exchange rates update");
593
        $xh->close(); // tr
594
        $xh->close(); // tfoot
595
        $xh->close(); // table
130 - 596
 
597
        $xh->add_attribute("nonce", base64_encode($_SESSION["nonce"]));
598
        $xh->tag('script');
599
            $str  = trim('document.addEventListener("DOMContentLoaded", function() {');
600
            $str .= trim('    document.getElementById("storeOfferTable").addEventListener("click", function(event) {');
601
            $str .= trim('        if (event.target.classList.contains("affiliate-link")) {');
602
            $str .= trim('            var url = event.target.closest("tr").getAttribute("data-url");');
603
            $str .= trim('            var merchant = event.target.closest("tr").getAttribute("data-merchant");');
604
            $str .= trim('            window.dataLayer.push({ "event" :  "trackEvent",  "eventCategory" :  "Affiliate",  "eventAction" :  "Click",  "eventLabel" :  merchant});');
605
            $str .= trim('            saveTransfer(url);');
606
            $str .= trim('        }');
607
            $str .= trim('    });');
608
            $str .= trim('});');
609
        $xh->insert_code($str);
610
        $xh->close(); // script
611
 
127 - 612
        $xh->close(); // div
613
 
614
        $html = $xh->flush();
615
        //error_log(print_r($html, 1));
65 - 616
    }
617
    else {
127 - 618
        $html = printNoResultsWarning();
9 - 619
    }
1 - 620
 
127 - 621
    return ($html);
59 - 622
}
1 - 623
 
65 - 624
// build HTML card deck from array
78 - 625
function buildCardDeck($arr) {
86 - 626
    global $buyItNowTooltip;
66 - 627
 
127 - 628
    $xh = new Html;
629
    $xh->init($_SESSION["htmlIndent"]);
630
 
78 - 631
    if (count($arr) > 0) {
127 - 632
        $xh->add_attribute("class", "card-deck small");
130 - 633
        $xh->add_attribute("id", "storeOfferCards");
127 - 634
        $xh->tag('div');
59 - 635
 
78 - 636
        foreach ($arr as $row) {
65 - 637
            if (!$row["Show"]) {
638
                continue;
639
            }
59 - 640
 
124 - 641
            $href = "href=\"" . htmlentities($row["URL"]) . "\" target=\"_blank\" rel=\"sponsored noreferrer noopener\"";
59 - 642
            $title = $row["Title"];
643
            if (mb_strlen($row["Title"], 'UTF-8') > MAXTITLELENGTH) {
65 - 644
                $title = mb_substr($row["Title"], 0, MAXTITLELENGTH, 'UTF-8') . '...';
59 - 645
            }
124 - 646
            $title = htmlentities($title);
59 - 647
 
127 - 648
            $xh->add_attribute("class", "card m-2 shadow mx-auto result-card");
130 - 649
            $xh->add_attribute("data-url", $row["URL"]);
650
            $xh->add_attribute("data-merchant", $row["Merchant"]);
127 - 651
            $xh->tag('div');
59 - 652
 
653
            // Image
127 - 654
              $xh->add_attribute("class", "p-0 m-0 text-center");
655
              $xh->add_attribute("href", htmlentities($row["URL"]));
656
              $xh->add_attribute("target", "_blank");
657
              $xh->add_attribute("rel", "sponsored noreferrer noopener");
658
              $xh->add_attribute("data-toggle", "tooltip");
659
              $xh->add_attribute("title", $buyItNowTooltip);
660
              $xh->tag('a');
130 - 661
                $xh->add_attribute("class", "affiliate-link p-0 m-0 responsive-image result-card-image lazyload");
662
                $xh->add_attribute("src", PIXEL);
127 - 663
                $xh->add_attribute("data-src", htmlentities($row["Image"]));
664
                $xh->add_attribute("alt", $title . " Item Image");
665
                $xh->single_tag('img');
666
              $xh->close(); // a
59 - 667
 
127 - 668
              $xh->add_attribute("class", "card-body d-flex flex-column");
669
              $xh->tag('div');
670
 
59 - 671
            // Title / Merchant
127 - 672
              $xh->add_attribute("class", "card-title font-weight-bold");
673
              $xh->tag('p');
130 - 674
                $xh->add_attribute("class", "affiliate-link");
127 - 675
                $xh->add_attribute("href", htmlentities($row["URL"]));
676
                $xh->add_attribute("target", "_blank");
677
                $xh->add_attribute("rel", "sponsored noreferrer noopener");
678
                $xh->add_attribute("data-toggle", "tooltip");
679
                $xh->add_attribute("title", $buyItNowTooltip);
680
                $xh->tag('a', $title);
681
              $xh->close(); // p
682
              $xh->add_attribute("class", "card-text mt-auto");
683
              $xh->tag('div');
684
                $xh->add_attribute("class", "font-weight-bold");
685
                $xh->tag('span', htmlentities($row["Merchant"]));
686
                $xh->brnl();
59 - 687
 
66 - 688
            // Condition / MediaType
127 - 689
                $xh->tag('span', $row["DetailCondition"]);
690
                $xh->add_attribute("class", getMediaIconClass($row["MediaType"], "media-icon float-right"));
691
                $xh->add_attribute("title", getMediaIconText($row["MediaType"]));
692
                $xh->add_attribute("data-toggle", "tooltip");
693
                $xh->add_attribute("data-placement", "right");
694
                $xh->add_attribute("data-delay", "200");
695
                $xh->tag('i', getMediaIconAlias($row["MediaType"]));
696
                $xh->brnl();
59 - 697
 
698
            // Total Price
127 - 699
                $xh->add_attribute("class", "font-weight-bolder");
700
                $xh->tag('span', print_monetary($row["ConvertedTotalPrice"], $_SESSION["buyer"]["Currency"]));
701
            $xh->close(); // div
59 - 702
 
127 - 703
            $xh->close(); // div
59 - 704
 
705
            // Link / Ships from Flag
127 - 706
            $xh->add_attribute("class", "card-footer");
707
            $xh->tag('div');
708
            $xh->add_attribute("class", "row");
709
            $xh->tag('div');
710
            $xh->add_attribute("class", "col-9");
711
            $xh->tag('div');
59 - 712
            if ($row["Merchant"] == "iTunes") {
66 - 713
                if ($row["MediaType"] == "Digital") {
127 - 714
                    $linkImage = timeStampUrl("images/US-UK_Apple_Music_Badge_RGB.svg");
65 - 715
                }
716
                else {
127 - 717
                    $linkImage = timeStampUrl("images/US_UK_Apple_Books_Badge_Get_RGB_071818.svg");
59 - 718
                }
127 - 719
                $class = "btn p-0 m-0";
720
                $altText = "iTunes Badge";
81 - 721
            } else if (strpos($row["Merchant"], "eBay") !== false) {
127 - 722
                $class = "btn p-0 m-0";
723
                $altText = "eBay Store";
724
                $linkImage = timeStampUrl("images/ebay-right-now.gif");
81 - 725
            } else if (strpos($row["Merchant"], "Amazon") !== false) {
127 - 726
                $class = "btn p-0 m-0";
727
                $altText = "Amazon Store";
728
                $linkImage = timeStampUrl("images/amazon-buy3.gif");
729
            } else {
730
                $class = "btn btn-success m-0";
731
                $altText = "";
732
                $linkImage = "";
65 - 733
            }
127 - 734
 
130 - 735
            $xh->add_attribute("class", "affiliate-link " . $class);
127 - 736
            $xh->add_attribute("title", $buyItNowTooltip);
737
            $xh->add_attribute("aria-label", "Go to store");
738
            $xh->add_attribute("data-toggle", "tooltip");
739
            $xh->add_attribute("role", "button");
740
            $xh->add_attribute("href",htmlentities($row["URL"]));
741
            $xh->add_attribute("target", "_blank");
742
            $xh->add_attribute("rel", "sponsored noreferrer noopener");
743
            $xh->tag('a');
744
            if (empty($linkImage)) {
130 - 745
                $xh->add_attribute("class", "affiliate-link material-icons md-36");
127 - 746
                $xh->tag('i', "store");
747
            } else {
130 - 748
                $xh->add_attribute("class", $class . " affiliate-link img-fluid p-0 m-0 lazyload");
127 - 749
                $xh->add_attribute("src",PIXEL);
750
                $xh->add_attribute("data-src", $linkImage);
751
                $xh->add_attribute("alt",$altText);
752
                $xh->single_tag('img');
59 - 753
            }
127 - 754
            $xh->close(); // a
755
            $xh->close(); // div
756
            $xh->add_attribute("class", "col-3");
757
            $xh->tag('div');
758
              $xh->add_attribute("class", "float-right lazyload");
759
              $xh->add_attribute("title", "Ships from " . getCountry($row["Country"]));
760
              $xh->add_attribute("data-toggle", "tooltip");
761
              $xh->add_attribute("data-placement", "right");
762
              $xh->add_attribute("data-delay", "200");
763
              $xh->add_attribute("src",PIXEL);
764
              $xh->add_attribute("data-src", timeStampUrl("images/flags/" . $row["Country"] . ".png"));
765
              $xh->add_attribute("alt", getCountry($row["Country"]) . " Flag");
766
              $xh->single_tag('img');
767
            $xh->close(); // div
768
            $xh->close(); // div
769
            $xh->close(); // div
59 - 770
 
127 - 771
            $xh->close(); // div
59 - 772
        }
773
 
127 - 774
        $xh->close(); // div
775
 
130 - 776
        $xh->add_attribute("nonce", base64_encode($_SESSION["nonce"]));
777
        $xh->tag('script');
778
            $str  = trim('document.addEventListener("DOMContentLoaded", function() {');
779
            $str .= trim('    document.getElementById("storeOfferCards").addEventListener("click", function(event) {');
780
            $str .= trim('        if (event.target.classList.contains("affiliate-link")) {');
781
            $str .= trim('            var url = event.target.closest(".card").getAttribute("data-url");');
782
            $str .= trim('            var merchant = event.target.closest(".card").getAttribute("data-merchant");');
783
            $str .= trim('            window.dataLayer.push({ "event" :  "trackEvent",  "eventCategory" :  "Affiliate",  "eventAction" :  "Click",  "eventLabel" :  merchant});');
784
            $str .= trim('            saveTransfer(url);');
785
            $str .= trim('        }');
786
            $str .= trim('    });');
787
            $str .= trim('});');
788
        $xh->insert_code($str);
789
        $xh->close(); // script
790
 
127 - 791
        $xh->add_attribute("class", "py-2 text-right");
792
        $xh->tag('div');
793
        $xh->add_attribute("class", "py-2 font-italic");
794
        $xh->tag('p', "Prices retrieved on " . gmdate("Y-m-d H:i") . " UTC<br>Daily exchange rates update");
795
        $xh->close(); // div
796
 
797
        $html = $xh->flush();
65 - 798
    }
799
    else {
127 - 800
        $html = printNoResultsWarning();
59 - 801
    }
802
 
127 - 803
    //error_log(print_r($html, 1));
5 - 804
 
127 - 805
    return $html;
59 - 806
}
807
 
66 - 808
function printResultHeader() {
127 - 809
    $xh = new Html;
810
    $xh->init($_SESSION["htmlIndent"]);
811
    $xh->add_attribute("class", "navbar bg-dark mt-2 pb-0");
812
    $xh->tag('nav');
813
    $str = "";
113 - 814
    if ($_SESSION["lowestPrice"]["New"] > 0) {
815
        $str .= 'New from ' . print_monetary($_SESSION["lowestPrice"]["New"], $_SESSION["buyer"]["Currency"]);
816
    }
817
    if ($_SESSION["lowestPrice"]["New"] > 0 && $_SESSION["lowestPrice"]["Used"] > 0) {
818
        $str .= '<br>';
819
    }
820
    if ($_SESSION["lowestPrice"]["Used"] > 0) {
821
        $str .= 'Used from ' . print_monetary($_SESSION["lowestPrice"]["Used"], $_SESSION["buyer"]["Currency"]);
822
    }
127 - 823
    $xh->add_attribute("class", "mr-3");
824
    $xh->tag('span', $str);
825
    $xh->add_attribute("class", "nav nav-tabs ml-3");
826
    $xh->tag('ul');
827
    $xh->add_attribute("class", "nav-item border-0");
828
    $xh->tag('li');
829
    $xh->add_attribute("id", "detailTab");
830
    $xh->add_attribute("class", "nav-link active bg-white");
831
    $xh->add_attribute("href", "#detailFilter");
832
    $xh->tag('a');
833
    $xh->tag('span', "Filter");
834
    $xh->add_attribute("id", "detailTabArrow");
835
    $xh->tag('span');
836
    $xh->add_attribute("class", "material-icons material-text");
837
    $xh->tag('i', "expand_more");
838
    $xh->close(); // span
839
    $xh->close(); // a
840
    $xh->close(); // li
841
    $xh->close(); // ul
842
    $xh->add_attribute("class", "ml-auto");
843
    $xh->tag('span');
107 - 844
    if ($_SESSION["currentLayout"] == 'CardView') {
127 - 845
        $xh->add_attribute("id", "resultViewToggle");
846
        $xh->add_attribute("name", "submit");
847
        $xh->add_attribute("value", "TableView");
848
        $xh->add_attribute("type", "submit");
849
        $xh->add_attribute("class", "btn btn-sm btn-rounded filterButton btn-info p-0 m-0 active");
850
        $xh->add_attribute("data-toggle", "tooltip");
851
        $xh->add_attribute("title", "Table View");
852
        $xh->add_attribute("aria-label", "Switch to Table View");
853
        $xh->tag('button');
854
        $xh->add_attribute("class", "material-icons md-36");
855
        $xh->tag('i', "view_list");
856
        $xh->close(); // button
107 - 857
    } else {
127 - 858
        $xh->add_attribute("id", "resultViewToggle");
859
        $xh->add_attribute("name", "submit");
860
        $xh->add_attribute("value", "CardView");
861
        $xh->add_attribute("type", "submit");
862
        $xh->add_attribute("class", "btn btn-sm btn-rounded filterButton btn-info p-0 m-0 active");
863
        $xh->add_attribute("data-toggle", "tooltip");
864
        $xh->add_attribute("title", "Card View");
865
        $xh->add_attribute("aria-label", "Switch To Card View");
866
        $xh->tag('button');
867
        $xh->add_attribute("class", "material-icons md-36");
868
        $xh->tag('i', "view_module");
869
        $xh->close(); // button
107 - 870
    }
127 - 871
    $xh->close(); // span
66 - 872
 
132 - 873
    $xh->add_attribute("nonce", base64_encode($_SESSION["nonce"]));
874
    $xh->tag('script');
875
        $str  = trim('document.addEventListener("DOMContentLoaded", function() {');
876
        $str .= trim('    document.getElementById("resultViewToggle").addEventListener("click", function(event) {');
877
        $str .= trim('        window.dataLayer.push({ "event" : "trackEvent", "eventCategory" : "Result View", "eventAction" : "Toggle", "eventLabel" : "' . ($_SESSION["currentLayout"] == "CardView" ? "Table View" : "Card View") . '"});');
878
        $str .= trim('    });');
879
        $str .= trim('});');
880
    $xh->insert_code($str);
881
    $xh->close(); // script
882
 
127 - 883
    $xh->add_attribute("class", "navbar-text float-right ml-3");
884
    $xh->tag('span');
885
    $xh->tag('span', "Showing ");
886
    $xh->add_attribute("class", "d-block d-md-none");
887
    $xh->tag('span', "<br>");
888
    $xh->tag('span', count(array_filter($_SESSION["resultArr"], function ($entry) { return ($entry['Show'] === true); })) . ' of ' . count($_SESSION["resultArr"]));
889
    $xh->close(); // span
890
 
891
    $xh->close(); // nav
892
    $xh->add_attribute("class", "tab-content mb-3");
893
    $xh->tag('div');
894
    $xh->add_attribute("id", "detailFilter");
895
    $xh->add_attribute("class", "container tab-pane");
896
    $xh->tag('div');
897
    $xh->brnl();
898
    $xh->insert_code(detailResultHeader());
899
    $xh->close(); // div
900
    $xh->close(); // div
901
 
902
    $html = $xh->flush();
903
    //error_log(print_r($html, 1));
904
 
905
    return $html;
66 - 906
}
907
 
65 - 908
// print summary/header on top of listing table
66 - 909
function detailResultHeader() {
127 - 910
    $xh = new Html;
911
    $xh->init($_SESSION["htmlIndent"]);
66 - 912
 
127 - 913
    $xh->add_attribute("id", "detailFilterForm");
914
    $xh->tag('form');
915
    $xh->insert_code(inputSessionTab());
916
    $xh->insert_code(inputNonce());
917
    $xh->add_attribute("class", "card-group");
918
    $xh->tag('div');
66 - 919
 
920
    // Condition
921
    if (isset($_SESSION['AdditionalFilterCounters']['Condition'])) {
127 - 922
        $xh->add_attribute("class", "card m-2");
923
        $xh->tag('div');
924
        $xh->add_attribute("class", "card-header font-weight-bold");
925
        $xh->tag('div', "Condition");
926
        $xh->add_attribute("class", "card-body");
927
        $xh->tag('div');
928
 
66 - 929
        $cnt = count($_SESSION['AdditionalFilterCounters']['Condition']);
930
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
127 - 931
            $xh->add_attribute("class", "form-check");
932
            $xh->tag('div');
933
            $xh->add_attribute("class", "form-check-label");
934
            $xh->tag('label');
935
            $xh->add_attribute("name", "filterCondition[]");
936
            $xh->add_attribute("type", "checkbox");
937
            $xh->add_attribute("value", $key);
938
            $xh->add_attribute("class", "form-check-input");
939
            if ($value) $xh->add_attribute("checked", "");
940
            if ($cnt < 1) $xh->add_attribute("disabled", "");
941
            $xh->single_tag('input');
942
            $xh->tag('span', $key);
943
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
944
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['Condition'][$key]);
945
            $xh->close(); // label
946
            $xh->close(); // div
66 - 947
        }
127 - 948
 
949
        $xh->close(); // div
950
        $xh->close(); // div
13 - 951
    }
66 - 952
 
953
    // Media Type
954
    if (isset($_SESSION['AdditionalFilterCounters']['MediaType'])) {
127 - 955
        $xh->add_attribute("class", "card m-2");
956
        $xh->tag('div');
957
        $xh->add_attribute("class", "card-header font-weight-bold");
958
        $xh->tag('div', "Media Type");
959
        $xh->add_attribute("class", "card-body");
960
        $xh->tag('div');
961
 
66 - 962
        $cnt = count($_SESSION['AdditionalFilterCounters']['MediaType']);
963
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
127 - 964
            $xh->add_attribute("class", "form-check");
965
            $xh->tag('div');
966
            $xh->add_attribute("class", "form-check-label");
967
            $xh->tag('label');
968
            $xh->add_attribute("name", "filterMediaType[]");
969
            $xh->add_attribute("type", "checkbox");
970
            $xh->add_attribute("value", $key);
971
            $xh->add_attribute("class", "form-check-input");
972
            if ($value) $xh->add_attribute("checked", "");
973
            if ($cnt < 1) $xh->add_attribute("disabled", "");
974
            $xh->single_tag('input');
975
            $xh->add_attribute("class",getMediaIconClass($key, "material-text"));
976
            $xh->tag('i', getMediaIconAlias($key));
977
            $xh->tag('span', getMediaIconText($key));
978
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
979
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['MediaType'][$key]);
980
            $xh->close(); // label
981
            $xh->close(); // div
66 - 982
        }
127 - 983
 
984
        $xh->close(); // div
985
        $xh->close(); // div
65 - 986
    }
59 - 987
 
66 - 988
    // Merchant
989
    if (isset($_SESSION['AdditionalFilterCounters']['Merchant'])) {
127 - 990
        $xh->add_attribute("class", "card m-2");
991
        $xh->tag('div');
992
        $xh->add_attribute("class", "card-header font-weight-bold");
993
        $xh->tag('div', "Merchant");
994
        $xh->add_attribute("class", "card-body");
995
        $xh->tag('div');
996
 
66 - 997
        $cnt = count($_SESSION['AdditionalFilterCounters']['Merchant']);
998
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
127 - 999
            $xh->add_attribute("class", "form-check");
1000
            $xh->tag('div');
1001
            $xh->add_attribute("class", "form-check-label");
1002
            $xh->tag('label');
1003
            $xh->add_attribute("name", "filterMerchant[]");
1004
            $xh->add_attribute("type", "checkbox");
1005
            $xh->add_attribute("value", $key);
1006
            $xh->add_attribute("class", "form-check-input");
1007
            if ($value) $xh->add_attribute("checked", "");
1008
            if ($cnt < 1) $xh->add_attribute("disabled", "");
1009
            $xh->single_tag('input');
1010
            $xh->tag('span', $key);
1011
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
1012
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['Merchant'][$key]);
1013
            $xh->close(); // label
1014
            $xh->close(); // div
66 - 1015
        }
127 - 1016
 
1017
        $xh->close(); // div
1018
        $xh->close(); // div
66 - 1019
    }
1 - 1020
 
66 - 1021
    // Shipping From
1022
    if (isset($_SESSION['AdditionalFilterCounters']['ShippingFrom'])) {
127 - 1023
        $xh->add_attribute("class", "card m-2");
1024
        $xh->tag('div');
1025
        $xh->add_attribute("class", "card-header font-weight-bold");
1026
        $xh->tag('div', "Shipping From");
1027
        $xh->add_attribute("class", "card-body");
1028
        $xh->tag('div');
1029
 
66 - 1030
        $cnt = count($_SESSION['AdditionalFilterCounters']['ShippingFrom']);
1031
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
127 - 1032
            $xh->add_attribute("class", "form-check");
1033
            $xh->tag('div');
1034
            $xh->add_attribute("class", "form-check-label");
1035
            $xh->tag('label');
1036
 
1037
            $xh->add_attribute("name", "filterShipFrom[]");
1038
            $xh->add_attribute("type", "checkbox");
1039
            $xh->add_attribute("value", $key);
1040
            $xh->add_attribute("class", "form-check-input");
1041
            if ($value) $xh->add_attribute("checked", "");
1042
            if ($cnt < 1) $xh->add_attribute("disabled", "");
1043
            $xh->single_tag('input');
1044
 
1045
            $xh->add_attribute("class", "img-fluid lazyload");
1046
            $xh->add_attribute("title", "Ships from " . getCountry($key));
1047
            $xh->add_attribute("data-toggle", "tooltip");
1048
            $xh->add_attribute("data-delay", "200");
1049
            $xh->add_attribute("src",PIXEL);
1050
            $xh->add_attribute("data-src", timeStampUrl("images/flags/" . $key . ".png"));
1051
            $xh->add_attribute("alt", getCountry($key) . " Flag");
1052
            $xh->single_tag('img');
1053
 
1054
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
1055
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['ShippingFrom'][$key]);
1056
 
1057
            $xh->close(); // label
1058
            $xh->close(); // div
66 - 1059
        }
127 - 1060
 
1061
        $xh->close(); // div
1062
        $xh->close(); // div
66 - 1063
    }
1064
 
127 - 1065
    $xh->close(); // div
1066
    $xh->add_attribute("class", "p-2");
1067
    $xh->tag('div');
1068
    $xh->add_attribute("type", "submit");
1069
    $xh->add_attribute("class", "btn btn-success detailFilterButton");
1070
    $xh->add_attribute("name", "submit");
1071
    $xh->add_attribute("value", "Apply");
1072
    $xh->tag('button', "Apply");
1073
    $xh->add_attribute("type", "submit");
1074
    $xh->add_attribute("class", "btn btn-danger detailFilterButton");
1075
    $xh->add_attribute("name", "submit");
1076
    $xh->add_attribute("value", "Reset");
1077
    $xh->tag('button', "Reset");
1078
    $xh->close(); // div
1079
    $xh->close(); // form
66 - 1080
 
127 - 1081
    $html = $xh->flush();
1082
    //error_log(print_r($html, 1));
1083
 
1084
    return $html;
5 - 1085
}
1 - 1086
 
65 - 1087
// compare price for sort low to high
1088
function compare_price($a, $b) {
1089
    return strnatcmp($a['ConvertedTotalPrice'], $b['ConvertedTotalPrice']);
5 - 1090
}
13 - 1091
 
65 - 1092
// print monetary values with correct symbol and thousands/decimal delimiters
1093
function print_monetary($num, $curr) {
1094
    if ($curr == "USD") {
1095
        return ("$" . number_format($num, 2, '.', ','));
1096
    }
1097
    else if ($curr == "CAD") {
1098
        return ("C $" . number_format($num, 2, '.', ','));
1099
    }
1100
    else if ($curr == "EUR") {
1101
        return (number_format($num, 2, ',', '.') . "&euro;");
1102
    }
1103
    else if ($curr == "GBP") {
1104
        return ("&pound;" . number_format($num, 2, '.', ','));
1105
    }
1106
    else if ($curr == "AUD") {
1107
        return ("AU $" . number_format($num, 2, '.', ','));
1108
    }
1 - 1109
 
65 - 1110
    return ($curr . " " . number_format($num, 2, '.', ','));
5 - 1111
}
1 - 1112
 
65 - 1113
// find lowest used / new prices
66 - 1114
function findLowestCondition($condition) {
65 - 1115
    foreach ($_SESSION["resultArr"] as $row) {
1116
        if (!$row["Show"]) {
1117
            continue;
1118
        }
1 - 1119
 
66 - 1120
        if ($condition == $row["Condition"]) {
65 - 1121
            return ($row["ConvertedTotalPrice"]);
1122
        }
1123
    }
5 - 1124
 
65 - 1125
    return (0);
5 - 1126
}
1127
 
65 - 1128
// find lowest cd, record, digital and book prices
66 - 1129
function findLowestMediaType($mediaType) {
65 - 1130
    foreach ($_SESSION["resultArr"] as $row) {
1131
        if (!$row["Show"]) {
1132
            continue;
1133
        }
20 - 1134
 
66 - 1135
        if ($mediaType == $row["MediaType"]) {
65 - 1136
            return ($row["ConvertedTotalPrice"]);
1137
        }
1138
    }
20 - 1139
 
65 - 1140
    return (0);
20 - 1141
}
1142
 
65 - 1143
// find lowest non-zero double value in array
1144
function minNotNull(Array $values) {
1145
    return min(array_diff(array_map('doubleval', $values) , array(
1146
 
1147
    )));
13 - 1148
}
11 - 1149
 
65 - 1150
// apply exchange rates
1151
function applyExchangeRates($arr) {
1152
    foreach ($arr as & $value) {
1153
        $value["ConvertedPrice"] = $value["Price"];
1154
        $value["ConvertedShippingCost"] = $value["ShippingCost"];
1 - 1155
 
65 - 1156
        if ($_SESSION["buyer"]["Currency"] != $value["Currency"]) {
1157
            $value["ConvertedPrice"] = number_format($value["Price"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["Currency"]) , 2, '.', '');
1158
        }
1 - 1159
 
65 - 1160
        if ($_SESSION["buyer"]["Currency"] != $value["ShippingCurrency"]) {
1161
            $value["ConvertedShippingCost"] = number_format($value["ShippingCost"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["ShippingCurrency"]) , 2, '.', '');
1162
        }
1 - 1163
 
65 - 1164
        $value["ConvertedTotalPrice"] = number_format($value["ConvertedPrice"] + $value["ConvertedShippingCost"], 2, '.', '');
1165
    }
5 - 1166
 
65 - 1167
    return ($arr);
5 - 1168
}
1169
 
36 - 1170
// sanitize user input
65 - 1171
function sanitizeInput($data) {
1172
    $data = trim(preg_replace('/[\t\n\r\s]+/', ' ', $data));
1173
    $data = stripslashes($data);
1174
    $data = htmlspecialchars($data);
1175
    return $data;
5 - 1176
}
1 - 1177
 
52 - 1178
// sanitize user input (plus delete apostrophe)
1179
function sanitizeInput2($data) {
65 - 1180
    $data = trim(preg_replace('/[\t\n\r\s\']+/', ' ', $data));
1181
    $data = stripslashes($data);
1182
    $data = htmlspecialchars($data, ENT_QUOTES | ENT_HTML5);
1183
    return $data;
52 - 1184
}
1185
 
14 - 1186
// convert certain utf-8 characters to ascii
1187
function cleanString($str) {
1188
    $utf8 = array(
65 - 1189
        '/[áàâãªä]/u' => 'a',
1190
        '/[ÁÀÂÃÄ]/u' => 'A',
1191
        '/[ÍÌÎÏ]/u' => 'I',
1192
        '/[íìîï]/u' => 'i',
1193
        '/[éèêë]/u' => 'e',
1194
        '/[ÉÈÊË]/u' => 'E',
1195
        '/[óòôõºö]/u' => 'o',
1196
        '/[ÓÒÔÕÖ]/u' => 'O',
1197
        '/[úùûü]/u' => 'u',
1198
        '/[ÚÙÛÜ]/u' => 'U',
1199
        '/ç/' => 'c',
1200
        '/Ç/' => 'C',
1201
        '/ñ/' => 'n',
1202
        '/Ñ/' => 'N',
1203
        '/–/' => '-', // UTF-8 hyphen to "normal" hyphen
1204
        '/[’‘‹›‚]/u' => ' ', // Literally a single quote
1205
        '/[“”«»„]/u' => ' ', // Double quote
1206
        '/ /' => ' ', // nonbreaking space (equiv. to 0x160)
66 - 1207
 
14 - 1208
    );
1209
 
65 - 1210
    return preg_replace(array_keys($utf8) , array_values($utf8) , $str);
14 - 1211
}
1212
 
1213
// Clean the search string
1214
function searchFriendlyString($str) {
1215
    $str = strip_tags($str);
1216
    $str = stripslashes($str);
1217
    $str = cleanString($str);
65 - 1218
    $str = str_replace(array(
1219
        "[",
1220
        "]",
1221
        "<",
1222
        ">",
1223
        "(",
1224
        ")",
1225
        " - ",
1226
        " & ",
1227
        " / "
1228
    ) , " ", $str); // eliminate single '-', '&', '/' and brackets
1229
    $str = trim(preg_replace('/[\t\n\r\s]+/', ' ', $str)); // delete extra whitespaces
14 - 1230
    return ucwords($str);
1231
}
1232
 
65 - 1233
// get a SESSION value, return empty string if not set
1234
function getSV($var) {
1235
    if (!isset($_SESSION[$var])) {
1236
        return ('');
1237
    }
1 - 1238
 
65 - 1239
    return ($_SESSION[$var]);
5 - 1240
}
1241
 
65 - 1242
// initialize a SESSION value if not set
1243
function initSV($var, $value) {
1244
    if (!isset($_SESSION[$var])) {
1245
        $_SESSION[$var] = $value;
1246
    }
5 - 1247
}
1 - 1248
 
65 - 1249
// initialize sessions variables
1250
function initSessionVariables() {
1251
    initSV("resultArr", []);
1252
    initSV("barcode", array(
1253
        "Type" => "",
1254
        "Value" => ""
1255
    ));
1256
    initSV("buyer", array(
1257
        "Country" => "United States",
1258
        "Currency" => "USD",
1259
        "Zip" => ""
1260
    ));
1261
    initSV("filterCondition", array(
1262
        "New" => true,
1263
        "Used" => true
1264
    ));
1265
    initSV("filterMediaType", array(
1266
        "CD" => true,
1267
        "Record" => true,
1268
        "Digital" => true,
1269
        "Book" => true
1270
    ));
1271
    initSV("currentLayout", "TableView");
1272
    initSV("lowestPrice", array(
1273
        "Used" => 0.00,
1274
        "New" => 0.00,
1275
        "CD" => 0.00,
1276
        "Record" => 0.00,
1277
        "Digital" => 0.00,
1278
        "Book" => "0.00",
1279
        "All" => 0.00
1280
    ));
5 - 1281
}
1282
 
14 - 1283
function md5SearchTerm() {
1284
    $data = array();
1285
    $data['cond'] = $_SESSION['filterCondition'];
1286
    $data['type'] = $_SESSION['filterMediaType'];
17 - 1287
    $data['buyer'] = $_SESSION['buyer'];
65 - 1288
    $data['term'] = array(
1289
        $_SESSION['searchTerm']
1290
    );
14 - 1291
 
65 - 1292
    return (md5(json_encode($data)));
14 - 1293
}
1294
 
65 - 1295
// check POST value, return true if set and false if not
1296
function checkPV($var) {
1297
    if (isset($_POST[$var])) {
1298
        return (true);
1299
    }
1 - 1300
 
65 - 1301
    return (false);
5 - 1302
}
1303
 
65 - 1304
// get POST or GET value, return empty if not set
1305
function getPGV($var) {
1306
    if (isset($_POST[$var])) {
1307
        return ($_POST[$var]);
1308
    }
1309
    else if (isset($_GET[$var])) {
1310
        return ($_GET[$var]);
1311
    }
14 - 1312
 
65 - 1313
    return ("");
14 - 1314
}
1315
 
65 - 1316
function saveSearchResult() {
1317
    $conn = MySessionHandler::getDBSessionId();
13 - 1318
 
65 - 1319
    $access = mysqli_real_escape_string($conn, time());
1320
    // BUGBUG
1321
    //  country
1322
    //  currency
1323
    $zip = mysqli_real_escape_string($conn, $_SESSION['buyer']['Zip']);
1324
    $condNew = $_SESSION['filterCondition']['New'] ? 'Y' : 'N';
1325
    $condUsed = $_SESSION['filterCondition']['Used'] ? 'Y' : 'N';
1326
    $mediaCD = $_SESSION['filterMediaType']['CD'] ? 'Y' : 'N';
1327
    $mediaRecord = $_SESSION['filterMediaType']['Record'] ? 'Y' : 'N';
1328
    $mediaDigital = $_SESSION['filterMediaType']['Digital'] ? 'Y' : 'N';
1329
    $mediaBook = $_SESSION['filterMediaType']['Book'] ? 'Y' : 'N';
1330
    $data = mysqli_real_escape_string($conn, $_SESSION['searchTerm']);
1331
    $lowNew = floatval($_SESSION['lowestPrice']['New']);
1332
    $lowUsed = floatval($_SESSION['lowestPrice']['Used']);
116 - 1333
    $lowCD = floatval($_SESSION['lowestPrice']['CD']);
1334
    $lowRecord = floatval($_SESSION['lowestPrice']['Record']);
65 - 1335
    $lowDigital = floatval($_SESSION['lowestPrice']['Digital']);
1336
    $lowBook = floatval($_SESSION['lowestPrice']['Book']);
1337
    $count = count($_SESSION['resultArr']);
1338
    $userId = (empty($_SESSION['sessData']['userID']) ? 'NULL' : $_SESSION['sessData']['userID']);
96 - 1339
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
8 - 1340
 
65 - 1341
    $sql = "INSERT
20 - 1342
                INTO searches
116 - 1343
                (sessId, access, ip, zip, condNew, condUsed, mediaCD, mediaRecord, mediaDigital, mediaBook, data, lowNew, lowUsed, lowCD, lowRecord, lowDigital, lowBook, count, userId)
1344
                VALUES ('" . session_id() . "', '$access', '$ip', '$zip', '$condNew', '$condUsed', '$mediaCD', '$mediaRecord', '$mediaDigital', '$mediaBook', '$data', $lowNew, $lowUsed, $lowCD, $lowRecord, $lowDigital, $lowBook, $count, $userId)";
8 - 1345
 
65 - 1346
    if (!($result = mysqli_query($conn, $sql))) {
1347
        error_log("MySQL Write Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1348
    }
13 - 1349
 
129 - 1350
 
1351
    return(mysqli_insert_id($conn));
65 - 1352
}
13 - 1353
 
17 - 1354
function getUrl($url, $userAgent = null) {
1355
    $ch = curl_init();
1356
 
1357
    // Set request header with language and charset
1358
    $header = array(
1359
        "Accept-Language: en-US,en;q=0.5",
1360
        "Accept-Charset: UTF-8,*;q=0.5"
1361
    );
1362
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1363
 
1364
    // Set optional user-agent
1365
    if ($userAgent) {
1366
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1367
    }
1368
 
1369
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1370
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1371
    curl_setopt($ch, CURLOPT_HEADER, 0);
84 - 1372
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1373
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
17 - 1374
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1375
    curl_setopt($ch, CURLOPT_URL, $url);
1376
    $response = curl_exec($ch);
1377
    if ($response === false) {
20 - 1378
        error_log('Curl Request Error: ' . curl_error($ch) . ' (' . curl_errno($ch) . ')');
1379
        error_log('Url: ' . $url);
17 - 1380
        $response = '';
1381
    }
23 - 1382
 
17 - 1383
    curl_close($ch);
1384
 
1385
    return $response;
1386
}
1387
 
129 - 1388
function getMultiUrl($urls, $userAgent = null) {
1389
    $multi = curl_multi_init();
1390
    $channels = [];
1391
    $response = [];
1392
    // Set request header with language and charset
1393
    $header = array(
1394
        "Accept-Language: en-US,en;q=0.5",
1395
        "Accept-Charset: UTF-8,*;q=0.5"
1396
    );
1397
 
1398
    // Loop through the URLs, create curl-handles
1399
    // and attach the handles to our multi-request
1400
    foreach ($urls as $url) {
1401
        $ch = curl_init();
1402
 
1403
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1404
 
1405
        // Set optional user-agent
1406
        if ($userAgent) {
1407
            curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1408
        }
1409
 
1410
        curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1411
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1412
        curl_setopt($ch, CURLOPT_HEADER, 0);
1413
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1414
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
1415
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1416
        curl_setopt($ch, CURLOPT_URL, $url);
1417
 
1418
        curl_multi_add_handle($multi, $ch);
1419
 
1420
        $channels[$url] = $ch;
1421
    }
1422
 
1423
    // While we're still active, execute curl
1424
    $active = null;
1425
    do {
1426
        $mrc = curl_multi_exec($multi, $active);
1427
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1428
 
1429
    while ($active && $mrc == CURLM_OK) {
1430
        // Wait for activity on any curl-connection
1431
        if (curl_multi_select($multi) == -1) {
1432
            continue;
1433
        }
1434
 
1435
        // Continue to exec until curl is ready to
1436
        // give us more data
1437
        do {
1438
            $mrc = curl_multi_exec($multi, $active);
1439
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1440
    }
1441
 
1442
    // Loop through the channels and retrieve the received
1443
    // content, then remove the handle from the multi-handle
1444
    foreach ($channels as $url => $channel) {
1445
        $response[$url] = curl_multi_getcontent($channel);
1446
        if ($response[$url] === false) {
1447
            error_log('Curl Request Error: ' . curl_error($channel) . ' (' . curl_errno($channel) . ')');
1448
            error_log('Url: ' . $url);
1449
            $response[$url] = '';
1450
        }
1451
        curl_multi_remove_handle($multi, $channel);
1452
    }
1453
 
1454
    // Close the multi-handle and return our results
1455
    curl_multi_close($multi);
1456
 
1457
    return($response);
1458
}
1459
 
20 - 1460
// Retrieve search history for current session id
14 - 1461
function getSearchHistory() {
127 - 1462
    $xh = new Html;
1463
    $xh->init($_SESSION["htmlIndent"]);
1464
 
38 - 1465
    $sql = "select data, max(access) from searches where sessId = '" . session_id() . "'";
1466
    if (!empty($_SESSION['sessData']['userID'])) {
1467
        $sql .= " or userID = '" . $_SESSION['sessData']['userID'] . "'";
1468
    }
1469
    $sql .= " group by data order by max(access) desc, data limit 0,30;";
14 - 1470
    $conn = MySessionHandler::getDBSessionId();
1471
 
20 - 1472
    if ($result = mysqli_query($conn, $sql)) {
1473
        if (mysqli_num_rows($result) > 0) {
65 - 1474
            while ($row = mysqli_fetch_assoc($result)) {
127 - 1475
                $xh->tag("option", $row["data"]);
20 - 1476
            }
14 - 1477
        }
1478
    }
65 - 1479
    else if (mysqli_errno($conn)) {
1480
        error_log("MySQL Read Searches SQL: " . $sql);
1481
        error_log("MySQL Read Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1482
    }
14 - 1483
 
127 - 1484
    $html = $xh->flush();
1485
    //error_log(print_r($html, 1));
1486
 
1487
    return $html;
14 - 1488
}
1489
 
41 - 1490
// Retrieve coupons codes
1491
function getCouponCodes() {
1492
    $lastAdvertiser = "";
1493
 
127 - 1494
    $xh = new Html;
1495
    $xh->init($_SESSION["htmlIndent"]);
1496
 
41 - 1497
    if (!isLoggedIn()) {
127 - 1498
        $xh->add_attribute("class", "container bg-warning text-center py-3");
1499
        $xh->tag('div');
1500
            $xh->add_attribute("class", "display-6");
1501
            $xh->tag('p');
1502
                $xh->add_attribute("class", "material-icons");
1503
                $xh->tag('i', "error_outline");
1504
                $xh->tag('span', " Please login to your Find Cheap Music account in order to see the coupons.");
1505
            $xh->close(); // p
1506
        $xh->close(); // div
1507
 
1508
        $html = $xh->flush();
1509
       //error_log(print_r($html, 1));
1510
 
1511
        return $html;
41 - 1512
    }
1513
 
65 - 1514
    $sql = 'select advertiser, date_format(enddate, "%M %e, %Y") as enddate, description, couponcode, url, pixel from coupons where DATE(NOW()) between startdate and enddate group by advertiser, description order by advertiser, id';
41 - 1515
    $conn = MySessionHandler::getDBSessionId();
1516
 
1517
    if ($result = mysqli_query($conn, $sql)) {
1518
        if (mysqli_num_rows($result) > 0) {
127 - 1519
            $xh->add_attribute("class", "container py-4 border bg-light");
1520
            $xh->tag('div');
65 - 1521
            while ($row = mysqli_fetch_assoc($result)) {
1522
                if ($row["advertiser"] != $lastAdvertiser) {
41 - 1523
                    if (!empty($lastAdvertiser)) {
127 - 1524
                        $xh->close(); // ul
41 - 1525
                    }
127 - 1526
                    $xh->add_attribute("class", "text-center mt-3 mb-1");
1527
                    $xh->tag('h2', $row["advertiser"]);
1528
                    $xh->add_attribute("class", "list-group");
1529
                    $xh->tag('ul');
41 - 1530
                    $lastAdvertiser = $row["advertiser"];
1531
                }
51 - 1532
                if (!empty($row["url"])) {
127 - 1533
                    $xh->add_attribute("class", "list-group-item");
1534
                    $xh->tag('li');
1535
                        $xh->add_attribute("class", "btn btn-link text-left");
1536
                        $xh->add_attribute("target", "_blank");
1537
                        $xh->add_attribute("href", htmlentities($row["url"]));
1538
                        $xh->add_attribute("rel", "nofollow noreferrer noopener");
1539
                        $xh->tag('a');
1540
                            $str = '<strong>' . $row["description"] . '</strong> until ' . $row["enddate"];
1541
                            if (!empty($row["couponcode"])) {
1542
                                $str .= ' (Use Coupon Code "' . $row["couponcode"] . '")';
1543
                            }
1544
                            if (!empty($row["pixel"])) {
1545
                                $xh->add_attribute("class", "border-0 lazyload");
1546
                                $xh->add_attribute("src",PIXEL);
1547
                                $xh->add_attribute("data-src", htmlentities($row["pixel"]));
1548
                                $xh->add_attribute("width", "1");
1549
                                $xh->add_attribute("height", "1");
1550
                                $xh->add_attribute("alt", $row["advertiser"] . " Coupon");
1551
                                $xh->single_tag('img');
1552
                            }
1553
                            $xh->tag('span', $str);
1554
                        $xh->close(); // a
1555
                    $xh->close(); // li
41 - 1556
                }
1557
            }
127 - 1558
 
1559
            if (!empty($lastAdvertiser)) {
1560
                $xh->close(); // ul
1561
            }
1562
            $xh->close(); // div
41 - 1563
        }
65 - 1564
    }
1565
    else if (mysqli_errno($conn)) {
127 - 1566
        $xh->add_attribute("class", "container bg-info text-center py-3");
1567
        $xh->tag('div');
1568
            $xh->add_attribute("class", "display-6");
1569
            $xh->tag('p');
1570
                $xh->add_attribute("class", "material-icons");
1571
                $xh->tag('i', "loyalty");
1572
                $xh->tag('span', " No Coupons available at the moment...");
1573
            $xh->close(); // p
1574
        $xh->close(); // div
41 - 1575
    }
1576
 
127 - 1577
    $html = $xh->flush();
1578
    //error_log(print_r($html, 1));
1579
 
1580
    return $html;
41 - 1581
}
1582
 
14 - 1583
// Delete left over progressbar files older than 2 days
1584
function cleanupPbFiles() {
84 - 1585
    $files = glob("../MyFiles/tmp/pb*.txt");
65 - 1586
    $now = time();
14 - 1587
    foreach ($files as $file) {
1588
        if (is_file($file)) {
1589
            if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days and older
1590
                unlink($file);
1591
            }
65 - 1592
        }
14 - 1593
    }
1594
}
1595
 
1596
// Update progressbar file for a session
129 - 1597
function updatePbFile($flag = false, $desc = null) {
1598
    static $max_pb = 10; // max progressbar steps
22 - 1599
    static $current = 0;
129 - 1600
    static $lastTime = 0;
1601
    static $startTime = 0;
1602
    static $timers = [];
23 - 1603
 
22 - 1604
    if ($flag) {
129 - 1605
        if ($desc == "Start") {
1606
            $current = 0;
1607
            $timers = [];
1608
            $startTime = $lastTime = microtime(true);
1609
        } else if (strpos($desc, "End:") === 0) {
1610
            $nowTime = microtime(true);
1611
            $timers["Total"] = intval(($nowTime - $startTime) * 1000);
1612
            $pieces = explode(":", $desc);
1613
            savePbTimers($timers, $pieces[1]);
1614
        }
65 - 1615
    }
1616
    else {
22 - 1617
        ++$current;
129 - 1618
        $nowTime = microtime(true);
1619
        $diffTime = $nowTime - $lastTime;
1620
        $lastTime = $nowTime;
1621
        $timers[$desc] = intval($diffTime * 1000);
1622
   }
22 - 1623
 
1624
    if ($current > $max_pb) {
1625
        error_log("max_pb $max_pb is too small, current step is $current. Adjust tools.php (updatePbFile).");
1626
        $max_pb = $current;
1627
    }
65 - 1628
    $filename = session_id() . "_" . MySessionHandler::getSessionTab();
14 - 1629
    $arr_content = array();
1630
 
20 - 1631
    $percent = intval($current / $max_pb * 100);
14 - 1632
 
1633
    $arr_content['percent'] = $percent;
1634
    $arr_content['message'] = $current . " search(es) processed.";
84 - 1635
    $file = "../MyFiles/tmp/pb_" . $filename . ".txt";
14 - 1636
 
77 - 1637
    if ($percent >= 100) {
1638
        @unlink($file);
1639
    } else {
1640
        file_put_contents($file, json_encode($arr_content));
1641
    }
14 - 1642
}
20 - 1643
 
1644
// Linkshare / CJ Affiliate csv dump
1645
function ls_cj_csv($fields) {
1646
    static $fh = null;
1647
    $delimiter = ',';
1648
    $enclosure = '"';
1649
    $mysql_null = false;
1650
 
1651
    if (!$fh) {
1652
        $fh = fopen("ls_cj.csv", "a+");
1653
    }
1654
 
1655
    $delimiter_esc = preg_quote($delimiter, '/');
1656
    $enclosure_esc = preg_quote($enclosure, '/');
1657
 
1658
    $output = array();
1659
    foreach ($fields as $field) {
1660
        if ($field === null && $mysql_null) {
1661
            $output[] = 'NULL';
1662
            continue;
1663
        }
1664
 
65 - 1665
        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure) : $field;
20 - 1666
    }
1667
 
1668
    fwrite($fh, join($delimiter, $output) . "\n");
1669
}
35 - 1670
 
1671
// Login in check
1672
function isLoggedIn() {
65 - 1673
    return (!empty($_SESSION['sessData']['userLoggedIn']) && !empty($_SESSION['sessData']['userID'])) ? true : false;
35 - 1674
}
1675
 
1676
// unset all login system session data
1677
function unsetSessData() {
1678
    unset($_SESSION['sessData']['userLoggedIn']);
1679
    unset($_SESSION['sessData']['userID']);
1680
    unset($_SESSION['sessData']['loginType']);
36 - 1681
}
1682
 
1683
// get user image name
1684
function getUserImage($userData) {
1685
    if (empty($userData) || empty($userData['picture'])) {
109 - 1686
        return 'login/assets/images/default.png';
36 - 1687
    }
38 - 1688
 
36 - 1689
    $httpPos = strpos($userData['picture'], 'http');
1690
    if ($httpPos === false) {
65 - 1691
        return 'login/' . UPLOAD_PATH . 'profile_picture/' . $userData['picture'];
36 - 1692
    }
1693
 
1694
    return $userData['picture'];
38 - 1695
}
39 - 1696
 
1697
function startsWith($haystack, $needle) {
1698
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
1699
}
1700
 
1701
function endsWith($haystack, $needle) {
1702
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
45 - 1703
}
50 - 1704
 
1705
function displayBarcode($barcode) {
1706
    $barcode = trim(preg_replace("/[^0-9]/", "", $barcode));
1707
    $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
1708
 
1709
    if ($barcodeType == "UPC" && strlen($barcode) == 12) {
1710
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 5) . "-" . substr($barcode, 6, 5) . "-" . substr($barcode, 11, 1);
65 - 1711
    }
1712
    else if (($barcodeType == "EAN" || $barcodeType == "ISBN") && strlen($barcode) == 13) {
50 - 1713
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 6) . "-" . substr($barcode, 7, 6);
65 - 1714
    }
1715
    else if ($barcodeType == "EAN" && strlen($barcode) == 14) {
50 - 1716
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 2) . "-" . substr($barcode, 3, 5) . "-" . substr($barcode, 8, 5) . "-" . substr($barcode, 13, 1);
65 - 1717
    }
1718
    else {
50 - 1719
        return $barcode;
1720
    }
52 - 1721
}
93 - 1722
 
1723
// fuzzy search to verify titles are relevant
1724
function verifyResultArr() {
1725
    require_once ('php/Fuse/Bitap/Bitap.php');
1726
    require_once ('php/Fuse/Bitap/matched_indices.php');
1727
    require_once ('php/Fuse/Bitap/pattern_alphabet.php');
1728
    require_once ('php/Fuse/Bitap/regex_search.php');
1729
    require_once ('php/Fuse/Bitap/score.php');
1730
    require_once ('php/Fuse/Bitap/search.php');
1731
    require_once ('php/Fuse/Helpers/deep_value.php');
1732
    require_once ('php/Fuse/Helpers/is_list.php');
1733
    require_once ('php/Fuse/Fuse.php');
1734
 
1735
    if (!empty($_SESSION["barcode"]["Value"]) || empty($_SESSION["resultArr"])) {
1736
        return;
1737
    }
1738
 
1739
    $options = [
1740
      'shouldSort' => false,
1741
    //  'tokenize' => true,
1742
    //  'matchAllTokens' => true,
1743
    //  'findAllMatches' => true,
1744
      'includeScore' => true,
1745
      'includeMatches' => true,
1746
      'threshold' => 0.6,
1747
      'location' => 0,
1748
      'distance' => 100,
1749
      'minMatchCharLength' => 5,
1750
      'keys' => [ "Title" ]
1751
    ];
1752
 
1753
    $fuse = new Fuse($_SESSION["resultArr"], $options);
1754
    $result = $fuse->search($_SESSION["searchTerm"]);
1755
 
1756
    $_SESSION["resultArr"] = [];
1757
    foreach($result as $r) {
97 - 1758
        $r['item']['score'] = (!empty($r['score']) ? $r['score'] : 0);
1759
        $r['item']['indices'] = (!empty($r['matches'][0]['indices']) ? $r['matches'][0]['indices'] : []);
93 - 1760
        $_SESSION['resultArr'][] = $r['item'];
1761
    }
1762
 
1763
    /* debug start
1764
    $lines = [];
1765
    foreach($_SESSION['resultArr'] as $r) {
1766
        $p = 0;
1767
        $t = '';
1768
        foreach($r['indices'] as $ind) {
1769
            if ($p < $ind[0]) {
1770
                $t .= substr($r['Title'], $p, $ind[0] - $p);
1771
            }
1772
            $t .= "<b>" . substr($r['Title'], $ind[0], $ind[1] - $ind[0] + 1) . "</b>";
1773
            $p = $ind[1] + 1;
1774
        }
1775
        if ($p < strlen($r['Title'])) {
1776
            $t .= substr($r['Title'], $p);
1777
        }
1778
        $lines[] = array ('score' => $r['score'], 'title' => $t);
1779
    }
1780
 
1781
    usort($lines, 'compare_score');
1782
    echo "<p>";
1783
    foreach($lines as $l) {
1784
        echo $l['score'] . ": " . $l['title'] . "<br/>";
1785
    }
1786
    echo "</p>";
1787
    debug end */
1788
}
1789
 
1790
// compare score for sort low to high
1791
function compare_score($a, $b) {
1792
    return ($a['score'] > $b['score']);
1793
}
96 - 1794
 
1795
function my_error_log($msg) {
1796
    error_log("[" . date("d-M-Y H:m:s") . "] " . $msg . PHP_EOL, 3, $_SERVER['DOCUMENT_ROOT'] . "/../MyFiles/logs/my_php_error.log");
1797
}
99 - 1798
 
129 - 1799
function savePbTimers($timers, $id) {
1800
    $conn = MySessionHandler::getDBSessionId();
1801
 
1802
    $sql = "INSERT
1803
                INTO searchPerformance
1804
                (id, Discogs, eBay_New, Linkshare, CJ_Affiliate, Walmart, iTunes, Amazon_API, Amazon_Scrape, Impact, eBay_Used, Total)
1805
                VALUES ($id, " . $timers['Discogs'] . ",
1806
" . $timers['eBay New'] . ",
1807
" . $timers['Linkshare'] . ",
1808
" . $timers['CJ Affiliate'] . ",
1809
" . $timers['Walmart'] . ",
1810
" . $timers['iTunes'] . ",
1811
" . $timers['Amazon API'] . ",
1812
" . $timers['Amazon Scrape'] . ",
1813
" . $timers['Impact'] . ",
1814
" . $timers['eBay Used'] . ",
1815
" . $timers['Total'] . ")";
1816
 
1817
    if (!($result = mysqli_query($conn, $sql))) {
1818
        error_log("MySQL Write SearchPerformance Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1819
    }
1820
 
1821
    return $result;
1822
}
1823
 
99 - 1824
function saveSearchCache($vendor, $query, $subquery, $text) {
1825
    $conn = MySessionHandler::getDBSessionId();
1826
 
1827
    $created = mysqli_real_escape_string($conn, time());
1828
    $v = mysqli_real_escape_string($conn, $vendor);
1829
    $q = mysqli_real_escape_string($conn, $query);
1830
    $s = mysqli_real_escape_string($conn, $subquery);
1831
    $r = base64_encode(gzencode($text));
1832
 
1833
    $sql = "INSERT
1834
                INTO searchCache
1835
                (created, vendor, query, subquery, result)
110 - 1836
                VALUES ('$created', '$v', '$q', '$s', '$r')
1837
                ON DUPLICATE KEY UPDATE result = '$r'";
99 - 1838
 
1839
    if (!($result = mysqli_query($conn, $sql))) {
1840
        error_log("MySQL Write SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1841
    }
1842
 
1843
    return $result;
1844
}
1845
 
1846
 
1847
function expireSearchCache() {
1848
    $conn = MySessionHandler::getDBSessionId();
1849
    $t = MySessionHandler::getDBExpirationTime();
1850
 
1851
    $expired = mysqli_real_escape_string($conn, time() - $t);
1852
 
1853
    $sql = "DELETE
1854
                FROM searchCache
1855
                WHERE created < $expired";
1856
 
1857
    if (!($result = mysqli_query($conn, $sql))) {
1858
        error_log("MySQL Delete SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1859
    }
1860
}
1861
 
1862
function getSearchCache($vendor, $query, $subquery) {
1863
    $conn = MySessionHandler::getDBSessionId();
1864
 
1865
    $v = mysqli_real_escape_string($conn, $vendor);
1866
    $q = mysqli_real_escape_string($conn, $query);
1867
    $s = mysqli_real_escape_string($conn, $subquery);
1868
    $sql = "select result from searchCache where vendor = '$v' and query = '$q' and subquery = '$s'";
1869
 
1870
    if ($result = mysqli_query($conn, $sql)) {
1871
        if (mysqli_num_rows($result) == 1) {
1872
            if ($row = mysqli_fetch_assoc($result)) {
1873
                return gzdecode(base64_decode($row["result"]));
1874
            }
1875
        }
1876
    }
1877
    else if (mysqli_errno($conn)) {
1878
        error_log("MySQL Read SearchCache SQL: " . $sql);
1879
        error_log("MySQL Read SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1880
    }
1881
 
1882
    return false;
104 - 1883
}
107 - 1884
 
1885
 
1886
function getGeoLocation() {
1887
    if (!empty($_SESSION['buyer']['Zip']) || empty($_SERVER['REMOTE_ADDR'])) {
1888
        return;
1889
    }
1890
 
1891
    $conn = MySessionHandler::getDBSessionId();
1892
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
1893
 
1894
    $sql = "select zip from geoLocation where ip = '$ip'";
1895
 
1896
    if ($result = mysqli_query($conn, $sql)) {
1897
        if (mysqli_num_rows($result) == 1) {
1898
            if ($row = mysqli_fetch_assoc($result)) {
1899
                $_SESSION['buyer']['Zip'] = $row["zip"];
1900
                return;
1901
            }
1902
        }
1903
    }
1904
    else if (mysqli_errno($conn)) {
1905
        error_log("MySQL Read geoLocation SQL: " . $sql);
1906
        error_log("MySQL Read geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1907
    }
1908
 
1909
    $vendors = Vendors::getInstance();
1910
    $config = $vendors->getVendor(Vendors::IPAPI);
1911
    $key = $config['KEY'];
1912
 
1913
    $loc = file_get_contents("http://api.ipapi.com/api/" . $_SERVER['REMOTE_ADDR'] . "?access_key=" . $key);
1914
    if ($loc == false) {
1915
        return;
1916
    }
1917
 
1918
    $json = json_decode($loc);
1919
    if (!empty($json->error)) {
1920
        error_log("geoLocation Error: " . $json->error->info . " (" . $json->error->code . " | " . $json->error->type . ")");
1921
        return;
1922
    }
1923
 
1924
    $created = mysqli_real_escape_string($conn, time());
1925
    $countryCode = mysqli_real_escape_string($conn, $json->{'country_code'});
1926
    $zip = mysqli_real_escape_string($conn, $json->zip);
1927
    $language = mysqli_real_escape_string($conn, $json->location->languages[0]->code);
1928
    $is_eu = mysqli_real_escape_string($conn, $json->location->{'is_eu'} ? '1' : '0');
1929
 
1930
    $sql = "INSERT
1931
                INTO geoLocation
1932
                (ip, created, countryCode, zip, language, is_eu)
1933
                VALUES ('$ip', $created, '$countryCode', '$zip', '$language', '$is_eu')";
1934
 
1935
    if (!($result = mysqli_query($conn, $sql))) {
1936
        error_log("MySQL Write geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1937
    }
1938
}
1939
 
1940
function timeStampUrl($file) {
121 - 1941
    if (@file_exists($file)) {
109 - 1942
        return $file . "?" . filemtime($file);
1943
    }
127 - 1944
 
109 - 1945
    return $file;
108 - 1946
}