Subversion Repositories cheapmusic

Rev

Rev 129 | Rev 132 | 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
 
127 - 873
    $xh->add_attribute("class", "navbar-text float-right ml-3");
874
    $xh->tag('span');
875
    $xh->tag('span', "Showing ");
876
    $xh->add_attribute("class", "d-block d-md-none");
877
    $xh->tag('span', "<br>");
878
    $xh->tag('span', count(array_filter($_SESSION["resultArr"], function ($entry) { return ($entry['Show'] === true); })) . ' of ' . count($_SESSION["resultArr"]));
879
    $xh->close(); // span
880
 
881
    $xh->close(); // nav
882
    $xh->add_attribute("class", "tab-content mb-3");
883
    $xh->tag('div');
884
    $xh->add_attribute("id", "detailFilter");
885
    $xh->add_attribute("class", "container tab-pane");
886
    $xh->tag('div');
887
    $xh->brnl();
888
    $xh->insert_code(detailResultHeader());
889
    $xh->close(); // div
890
    $xh->close(); // div
891
 
892
    $html = $xh->flush();
893
    //error_log(print_r($html, 1));
894
 
895
    return $html;
66 - 896
}
897
 
65 - 898
// print summary/header on top of listing table
66 - 899
function detailResultHeader() {
127 - 900
    $xh = new Html;
901
    $xh->init($_SESSION["htmlIndent"]);
66 - 902
 
127 - 903
    $xh->add_attribute("id", "detailFilterForm");
904
    $xh->tag('form');
905
    $xh->insert_code(inputSessionTab());
906
    $xh->insert_code(inputNonce());
907
    $xh->add_attribute("class", "card-group");
908
    $xh->tag('div');
66 - 909
 
910
    // Condition
911
    if (isset($_SESSION['AdditionalFilterCounters']['Condition'])) {
127 - 912
        $xh->add_attribute("class", "card m-2");
913
        $xh->tag('div');
914
        $xh->add_attribute("class", "card-header font-weight-bold");
915
        $xh->tag('div', "Condition");
916
        $xh->add_attribute("class", "card-body");
917
        $xh->tag('div');
918
 
66 - 919
        $cnt = count($_SESSION['AdditionalFilterCounters']['Condition']);
920
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
127 - 921
            $xh->add_attribute("class", "form-check");
922
            $xh->tag('div');
923
            $xh->add_attribute("class", "form-check-label");
924
            $xh->tag('label');
925
            $xh->add_attribute("name", "filterCondition[]");
926
            $xh->add_attribute("type", "checkbox");
927
            $xh->add_attribute("value", $key);
928
            $xh->add_attribute("class", "form-check-input");
929
            if ($value) $xh->add_attribute("checked", "");
930
            if ($cnt < 1) $xh->add_attribute("disabled", "");
931
            $xh->single_tag('input');
932
            $xh->tag('span', $key);
933
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
934
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['Condition'][$key]);
935
            $xh->close(); // label
936
            $xh->close(); // div
66 - 937
        }
127 - 938
 
939
        $xh->close(); // div
940
        $xh->close(); // div
13 - 941
    }
66 - 942
 
943
    // Media Type
944
    if (isset($_SESSION['AdditionalFilterCounters']['MediaType'])) {
127 - 945
        $xh->add_attribute("class", "card m-2");
946
        $xh->tag('div');
947
        $xh->add_attribute("class", "card-header font-weight-bold");
948
        $xh->tag('div', "Media Type");
949
        $xh->add_attribute("class", "card-body");
950
        $xh->tag('div');
951
 
66 - 952
        $cnt = count($_SESSION['AdditionalFilterCounters']['MediaType']);
953
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
127 - 954
            $xh->add_attribute("class", "form-check");
955
            $xh->tag('div');
956
            $xh->add_attribute("class", "form-check-label");
957
            $xh->tag('label');
958
            $xh->add_attribute("name", "filterMediaType[]");
959
            $xh->add_attribute("type", "checkbox");
960
            $xh->add_attribute("value", $key);
961
            $xh->add_attribute("class", "form-check-input");
962
            if ($value) $xh->add_attribute("checked", "");
963
            if ($cnt < 1) $xh->add_attribute("disabled", "");
964
            $xh->single_tag('input');
965
            $xh->add_attribute("class",getMediaIconClass($key, "material-text"));
966
            $xh->tag('i', getMediaIconAlias($key));
967
            $xh->tag('span', getMediaIconText($key));
968
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
969
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['MediaType'][$key]);
970
            $xh->close(); // label
971
            $xh->close(); // div
66 - 972
        }
127 - 973
 
974
        $xh->close(); // div
975
        $xh->close(); // div
65 - 976
    }
59 - 977
 
66 - 978
    // Merchant
979
    if (isset($_SESSION['AdditionalFilterCounters']['Merchant'])) {
127 - 980
        $xh->add_attribute("class", "card m-2");
981
        $xh->tag('div');
982
        $xh->add_attribute("class", "card-header font-weight-bold");
983
        $xh->tag('div', "Merchant");
984
        $xh->add_attribute("class", "card-body");
985
        $xh->tag('div');
986
 
66 - 987
        $cnt = count($_SESSION['AdditionalFilterCounters']['Merchant']);
988
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
127 - 989
            $xh->add_attribute("class", "form-check");
990
            $xh->tag('div');
991
            $xh->add_attribute("class", "form-check-label");
992
            $xh->tag('label');
993
            $xh->add_attribute("name", "filterMerchant[]");
994
            $xh->add_attribute("type", "checkbox");
995
            $xh->add_attribute("value", $key);
996
            $xh->add_attribute("class", "form-check-input");
997
            if ($value) $xh->add_attribute("checked", "");
998
            if ($cnt < 1) $xh->add_attribute("disabled", "");
999
            $xh->single_tag('input');
1000
            $xh->tag('span', $key);
1001
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
1002
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['Merchant'][$key]);
1003
            $xh->close(); // label
1004
            $xh->close(); // div
66 - 1005
        }
127 - 1006
 
1007
        $xh->close(); // div
1008
        $xh->close(); // div
66 - 1009
    }
1 - 1010
 
66 - 1011
    // Shipping From
1012
    if (isset($_SESSION['AdditionalFilterCounters']['ShippingFrom'])) {
127 - 1013
        $xh->add_attribute("class", "card m-2");
1014
        $xh->tag('div');
1015
        $xh->add_attribute("class", "card-header font-weight-bold");
1016
        $xh->tag('div', "Shipping From");
1017
        $xh->add_attribute("class", "card-body");
1018
        $xh->tag('div');
1019
 
66 - 1020
        $cnt = count($_SESSION['AdditionalFilterCounters']['ShippingFrom']);
1021
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
127 - 1022
            $xh->add_attribute("class", "form-check");
1023
            $xh->tag('div');
1024
            $xh->add_attribute("class", "form-check-label");
1025
            $xh->tag('label');
1026
 
1027
            $xh->add_attribute("name", "filterShipFrom[]");
1028
            $xh->add_attribute("type", "checkbox");
1029
            $xh->add_attribute("value", $key);
1030
            $xh->add_attribute("class", "form-check-input");
1031
            if ($value) $xh->add_attribute("checked", "");
1032
            if ($cnt < 1) $xh->add_attribute("disabled", "");
1033
            $xh->single_tag('input');
1034
 
1035
            $xh->add_attribute("class", "img-fluid lazyload");
1036
            $xh->add_attribute("title", "Ships from " . getCountry($key));
1037
            $xh->add_attribute("data-toggle", "tooltip");
1038
            $xh->add_attribute("data-delay", "200");
1039
            $xh->add_attribute("src",PIXEL);
1040
            $xh->add_attribute("data-src", timeStampUrl("images/flags/" . $key . ".png"));
1041
            $xh->add_attribute("alt", getCountry($key) . " Flag");
1042
            $xh->single_tag('img');
1043
 
1044
            $xh->add_attribute("class", "badge badge-pill badge-dark ml-2");
1045
            $xh->tag('span', $_SESSION['AdditionalFilterCounters']['ShippingFrom'][$key]);
1046
 
1047
            $xh->close(); // label
1048
            $xh->close(); // div
66 - 1049
        }
127 - 1050
 
1051
        $xh->close(); // div
1052
        $xh->close(); // div
66 - 1053
    }
1054
 
127 - 1055
    $xh->close(); // div
1056
    $xh->add_attribute("class", "p-2");
1057
    $xh->tag('div');
1058
    $xh->add_attribute("type", "submit");
1059
    $xh->add_attribute("class", "btn btn-success detailFilterButton");
1060
    $xh->add_attribute("name", "submit");
1061
    $xh->add_attribute("value", "Apply");
1062
    $xh->tag('button', "Apply");
1063
    $xh->add_attribute("type", "submit");
1064
    $xh->add_attribute("class", "btn btn-danger detailFilterButton");
1065
    $xh->add_attribute("name", "submit");
1066
    $xh->add_attribute("value", "Reset");
1067
    $xh->tag('button', "Reset");
1068
    $xh->close(); // div
1069
    $xh->close(); // form
66 - 1070
 
127 - 1071
    $html = $xh->flush();
1072
    //error_log(print_r($html, 1));
1073
 
1074
    return $html;
5 - 1075
}
1 - 1076
 
65 - 1077
// compare price for sort low to high
1078
function compare_price($a, $b) {
1079
    return strnatcmp($a['ConvertedTotalPrice'], $b['ConvertedTotalPrice']);
5 - 1080
}
13 - 1081
 
65 - 1082
// print monetary values with correct symbol and thousands/decimal delimiters
1083
function print_monetary($num, $curr) {
1084
    if ($curr == "USD") {
1085
        return ("$" . number_format($num, 2, '.', ','));
1086
    }
1087
    else if ($curr == "CAD") {
1088
        return ("C $" . number_format($num, 2, '.', ','));
1089
    }
1090
    else if ($curr == "EUR") {
1091
        return (number_format($num, 2, ',', '.') . "&euro;");
1092
    }
1093
    else if ($curr == "GBP") {
1094
        return ("&pound;" . number_format($num, 2, '.', ','));
1095
    }
1096
    else if ($curr == "AUD") {
1097
        return ("AU $" . number_format($num, 2, '.', ','));
1098
    }
1 - 1099
 
65 - 1100
    return ($curr . " " . number_format($num, 2, '.', ','));
5 - 1101
}
1 - 1102
 
65 - 1103
// find lowest used / new prices
66 - 1104
function findLowestCondition($condition) {
65 - 1105
    foreach ($_SESSION["resultArr"] as $row) {
1106
        if (!$row["Show"]) {
1107
            continue;
1108
        }
1 - 1109
 
66 - 1110
        if ($condition == $row["Condition"]) {
65 - 1111
            return ($row["ConvertedTotalPrice"]);
1112
        }
1113
    }
5 - 1114
 
65 - 1115
    return (0);
5 - 1116
}
1117
 
65 - 1118
// find lowest cd, record, digital and book prices
66 - 1119
function findLowestMediaType($mediaType) {
65 - 1120
    foreach ($_SESSION["resultArr"] as $row) {
1121
        if (!$row["Show"]) {
1122
            continue;
1123
        }
20 - 1124
 
66 - 1125
        if ($mediaType == $row["MediaType"]) {
65 - 1126
            return ($row["ConvertedTotalPrice"]);
1127
        }
1128
    }
20 - 1129
 
65 - 1130
    return (0);
20 - 1131
}
1132
 
65 - 1133
// find lowest non-zero double value in array
1134
function minNotNull(Array $values) {
1135
    return min(array_diff(array_map('doubleval', $values) , array(
1136
 
1137
    )));
13 - 1138
}
11 - 1139
 
65 - 1140
// apply exchange rates
1141
function applyExchangeRates($arr) {
1142
    foreach ($arr as & $value) {
1143
        $value["ConvertedPrice"] = $value["Price"];
1144
        $value["ConvertedShippingCost"] = $value["ShippingCost"];
1 - 1145
 
65 - 1146
        if ($_SESSION["buyer"]["Currency"] != $value["Currency"]) {
1147
            $value["ConvertedPrice"] = number_format($value["Price"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["Currency"]) , 2, '.', '');
1148
        }
1 - 1149
 
65 - 1150
        if ($_SESSION["buyer"]["Currency"] != $value["ShippingCurrency"]) {
1151
            $value["ConvertedShippingCost"] = number_format($value["ShippingCost"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["ShippingCurrency"]) , 2, '.', '');
1152
        }
1 - 1153
 
65 - 1154
        $value["ConvertedTotalPrice"] = number_format($value["ConvertedPrice"] + $value["ConvertedShippingCost"], 2, '.', '');
1155
    }
5 - 1156
 
65 - 1157
    return ($arr);
5 - 1158
}
1159
 
36 - 1160
// sanitize user input
65 - 1161
function sanitizeInput($data) {
1162
    $data = trim(preg_replace('/[\t\n\r\s]+/', ' ', $data));
1163
    $data = stripslashes($data);
1164
    $data = htmlspecialchars($data);
1165
    return $data;
5 - 1166
}
1 - 1167
 
52 - 1168
// sanitize user input (plus delete apostrophe)
1169
function sanitizeInput2($data) {
65 - 1170
    $data = trim(preg_replace('/[\t\n\r\s\']+/', ' ', $data));
1171
    $data = stripslashes($data);
1172
    $data = htmlspecialchars($data, ENT_QUOTES | ENT_HTML5);
1173
    return $data;
52 - 1174
}
1175
 
14 - 1176
// convert certain utf-8 characters to ascii
1177
function cleanString($str) {
1178
    $utf8 = array(
65 - 1179
        '/[áàâãªä]/u' => 'a',
1180
        '/[ÁÀÂÃÄ]/u' => 'A',
1181
        '/[ÍÌÎÏ]/u' => 'I',
1182
        '/[íìîï]/u' => 'i',
1183
        '/[éèêë]/u' => 'e',
1184
        '/[ÉÈÊË]/u' => 'E',
1185
        '/[óòôõºö]/u' => 'o',
1186
        '/[ÓÒÔÕÖ]/u' => 'O',
1187
        '/[úùûü]/u' => 'u',
1188
        '/[ÚÙÛÜ]/u' => 'U',
1189
        '/ç/' => 'c',
1190
        '/Ç/' => 'C',
1191
        '/ñ/' => 'n',
1192
        '/Ñ/' => 'N',
1193
        '/–/' => '-', // UTF-8 hyphen to "normal" hyphen
1194
        '/[’‘‹›‚]/u' => ' ', // Literally a single quote
1195
        '/[“”«»„]/u' => ' ', // Double quote
1196
        '/ /' => ' ', // nonbreaking space (equiv. to 0x160)
66 - 1197
 
14 - 1198
    );
1199
 
65 - 1200
    return preg_replace(array_keys($utf8) , array_values($utf8) , $str);
14 - 1201
}
1202
 
1203
// Clean the search string
1204
function searchFriendlyString($str) {
1205
    $str = strip_tags($str);
1206
    $str = stripslashes($str);
1207
    $str = cleanString($str);
65 - 1208
    $str = str_replace(array(
1209
        "[",
1210
        "]",
1211
        "<",
1212
        ">",
1213
        "(",
1214
        ")",
1215
        " - ",
1216
        " & ",
1217
        " / "
1218
    ) , " ", $str); // eliminate single '-', '&', '/' and brackets
1219
    $str = trim(preg_replace('/[\t\n\r\s]+/', ' ', $str)); // delete extra whitespaces
14 - 1220
    return ucwords($str);
1221
}
1222
 
65 - 1223
// get a SESSION value, return empty string if not set
1224
function getSV($var) {
1225
    if (!isset($_SESSION[$var])) {
1226
        return ('');
1227
    }
1 - 1228
 
65 - 1229
    return ($_SESSION[$var]);
5 - 1230
}
1231
 
65 - 1232
// initialize a SESSION value if not set
1233
function initSV($var, $value) {
1234
    if (!isset($_SESSION[$var])) {
1235
        $_SESSION[$var] = $value;
1236
    }
5 - 1237
}
1 - 1238
 
65 - 1239
// initialize sessions variables
1240
function initSessionVariables() {
1241
    initSV("resultArr", []);
1242
    initSV("barcode", array(
1243
        "Type" => "",
1244
        "Value" => ""
1245
    ));
1246
    initSV("buyer", array(
1247
        "Country" => "United States",
1248
        "Currency" => "USD",
1249
        "Zip" => ""
1250
    ));
1251
    initSV("filterCondition", array(
1252
        "New" => true,
1253
        "Used" => true
1254
    ));
1255
    initSV("filterMediaType", array(
1256
        "CD" => true,
1257
        "Record" => true,
1258
        "Digital" => true,
1259
        "Book" => true
1260
    ));
1261
    initSV("currentLayout", "TableView");
1262
    initSV("lowestPrice", array(
1263
        "Used" => 0.00,
1264
        "New" => 0.00,
1265
        "CD" => 0.00,
1266
        "Record" => 0.00,
1267
        "Digital" => 0.00,
1268
        "Book" => "0.00",
1269
        "All" => 0.00
1270
    ));
5 - 1271
}
1272
 
14 - 1273
function md5SearchTerm() {
1274
    $data = array();
1275
    $data['cond'] = $_SESSION['filterCondition'];
1276
    $data['type'] = $_SESSION['filterMediaType'];
17 - 1277
    $data['buyer'] = $_SESSION['buyer'];
65 - 1278
    $data['term'] = array(
1279
        $_SESSION['searchTerm']
1280
    );
14 - 1281
 
65 - 1282
    return (md5(json_encode($data)));
14 - 1283
}
1284
 
65 - 1285
// check POST value, return true if set and false if not
1286
function checkPV($var) {
1287
    if (isset($_POST[$var])) {
1288
        return (true);
1289
    }
1 - 1290
 
65 - 1291
    return (false);
5 - 1292
}
1293
 
65 - 1294
// get POST or GET value, return empty if not set
1295
function getPGV($var) {
1296
    if (isset($_POST[$var])) {
1297
        return ($_POST[$var]);
1298
    }
1299
    else if (isset($_GET[$var])) {
1300
        return ($_GET[$var]);
1301
    }
14 - 1302
 
65 - 1303
    return ("");
14 - 1304
}
1305
 
65 - 1306
function saveSearchResult() {
1307
    $conn = MySessionHandler::getDBSessionId();
13 - 1308
 
65 - 1309
    $access = mysqli_real_escape_string($conn, time());
1310
    // BUGBUG
1311
    //  country
1312
    //  currency
1313
    $zip = mysqli_real_escape_string($conn, $_SESSION['buyer']['Zip']);
1314
    $condNew = $_SESSION['filterCondition']['New'] ? 'Y' : 'N';
1315
    $condUsed = $_SESSION['filterCondition']['Used'] ? 'Y' : 'N';
1316
    $mediaCD = $_SESSION['filterMediaType']['CD'] ? 'Y' : 'N';
1317
    $mediaRecord = $_SESSION['filterMediaType']['Record'] ? 'Y' : 'N';
1318
    $mediaDigital = $_SESSION['filterMediaType']['Digital'] ? 'Y' : 'N';
1319
    $mediaBook = $_SESSION['filterMediaType']['Book'] ? 'Y' : 'N';
1320
    $data = mysqli_real_escape_string($conn, $_SESSION['searchTerm']);
1321
    $lowNew = floatval($_SESSION['lowestPrice']['New']);
1322
    $lowUsed = floatval($_SESSION['lowestPrice']['Used']);
116 - 1323
    $lowCD = floatval($_SESSION['lowestPrice']['CD']);
1324
    $lowRecord = floatval($_SESSION['lowestPrice']['Record']);
65 - 1325
    $lowDigital = floatval($_SESSION['lowestPrice']['Digital']);
1326
    $lowBook = floatval($_SESSION['lowestPrice']['Book']);
1327
    $count = count($_SESSION['resultArr']);
1328
    $userId = (empty($_SESSION['sessData']['userID']) ? 'NULL' : $_SESSION['sessData']['userID']);
96 - 1329
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
8 - 1330
 
65 - 1331
    $sql = "INSERT
20 - 1332
                INTO searches
116 - 1333
                (sessId, access, ip, zip, condNew, condUsed, mediaCD, mediaRecord, mediaDigital, mediaBook, data, lowNew, lowUsed, lowCD, lowRecord, lowDigital, lowBook, count, userId)
1334
                VALUES ('" . session_id() . "', '$access', '$ip', '$zip', '$condNew', '$condUsed', '$mediaCD', '$mediaRecord', '$mediaDigital', '$mediaBook', '$data', $lowNew, $lowUsed, $lowCD, $lowRecord, $lowDigital, $lowBook, $count, $userId)";
8 - 1335
 
65 - 1336
    if (!($result = mysqli_query($conn, $sql))) {
1337
        error_log("MySQL Write Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1338
    }
13 - 1339
 
129 - 1340
 
1341
    return(mysqli_insert_id($conn));
65 - 1342
}
13 - 1343
 
17 - 1344
function getUrl($url, $userAgent = null) {
1345
    $ch = curl_init();
1346
 
1347
    // Set request header with language and charset
1348
    $header = array(
1349
        "Accept-Language: en-US,en;q=0.5",
1350
        "Accept-Charset: UTF-8,*;q=0.5"
1351
    );
1352
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1353
 
1354
    // Set optional user-agent
1355
    if ($userAgent) {
1356
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1357
    }
1358
 
1359
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1360
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1361
    curl_setopt($ch, CURLOPT_HEADER, 0);
84 - 1362
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1363
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
17 - 1364
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1365
    curl_setopt($ch, CURLOPT_URL, $url);
1366
    $response = curl_exec($ch);
1367
    if ($response === false) {
20 - 1368
        error_log('Curl Request Error: ' . curl_error($ch) . ' (' . curl_errno($ch) . ')');
1369
        error_log('Url: ' . $url);
17 - 1370
        $response = '';
1371
    }
23 - 1372
 
17 - 1373
    curl_close($ch);
1374
 
1375
    return $response;
1376
}
1377
 
129 - 1378
function getMultiUrl($urls, $userAgent = null) {
1379
    $multi = curl_multi_init();
1380
    $channels = [];
1381
    $response = [];
1382
    // Set request header with language and charset
1383
    $header = array(
1384
        "Accept-Language: en-US,en;q=0.5",
1385
        "Accept-Charset: UTF-8,*;q=0.5"
1386
    );
1387
 
1388
    // Loop through the URLs, create curl-handles
1389
    // and attach the handles to our multi-request
1390
    foreach ($urls as $url) {
1391
        $ch = curl_init();
1392
 
1393
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1394
 
1395
        // Set optional user-agent
1396
        if ($userAgent) {
1397
            curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1398
        }
1399
 
1400
        curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1401
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1402
        curl_setopt($ch, CURLOPT_HEADER, 0);
1403
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1404
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
1405
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1406
        curl_setopt($ch, CURLOPT_URL, $url);
1407
 
1408
        curl_multi_add_handle($multi, $ch);
1409
 
1410
        $channels[$url] = $ch;
1411
    }
1412
 
1413
    // While we're still active, execute curl
1414
    $active = null;
1415
    do {
1416
        $mrc = curl_multi_exec($multi, $active);
1417
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1418
 
1419
    while ($active && $mrc == CURLM_OK) {
1420
        // Wait for activity on any curl-connection
1421
        if (curl_multi_select($multi) == -1) {
1422
            continue;
1423
        }
1424
 
1425
        // Continue to exec until curl is ready to
1426
        // give us more data
1427
        do {
1428
            $mrc = curl_multi_exec($multi, $active);
1429
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1430
    }
1431
 
1432
    // Loop through the channels and retrieve the received
1433
    // content, then remove the handle from the multi-handle
1434
    foreach ($channels as $url => $channel) {
1435
        $response[$url] = curl_multi_getcontent($channel);
1436
        if ($response[$url] === false) {
1437
            error_log('Curl Request Error: ' . curl_error($channel) . ' (' . curl_errno($channel) . ')');
1438
            error_log('Url: ' . $url);
1439
            $response[$url] = '';
1440
        }
1441
        curl_multi_remove_handle($multi, $channel);
1442
    }
1443
 
1444
    // Close the multi-handle and return our results
1445
    curl_multi_close($multi);
1446
 
1447
    return($response);
1448
}
1449
 
20 - 1450
// Retrieve search history for current session id
14 - 1451
function getSearchHistory() {
127 - 1452
    $xh = new Html;
1453
    $xh->init($_SESSION["htmlIndent"]);
1454
 
38 - 1455
    $sql = "select data, max(access) from searches where sessId = '" . session_id() . "'";
1456
    if (!empty($_SESSION['sessData']['userID'])) {
1457
        $sql .= " or userID = '" . $_SESSION['sessData']['userID'] . "'";
1458
    }
1459
    $sql .= " group by data order by max(access) desc, data limit 0,30;";
14 - 1460
    $conn = MySessionHandler::getDBSessionId();
1461
 
20 - 1462
    if ($result = mysqli_query($conn, $sql)) {
1463
        if (mysqli_num_rows($result) > 0) {
65 - 1464
            while ($row = mysqli_fetch_assoc($result)) {
127 - 1465
                $xh->tag("option", $row["data"]);
20 - 1466
            }
14 - 1467
        }
1468
    }
65 - 1469
    else if (mysqli_errno($conn)) {
1470
        error_log("MySQL Read Searches SQL: " . $sql);
1471
        error_log("MySQL Read Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1472
    }
14 - 1473
 
127 - 1474
    $html = $xh->flush();
1475
    //error_log(print_r($html, 1));
1476
 
1477
    return $html;
14 - 1478
}
1479
 
41 - 1480
// Retrieve coupons codes
1481
function getCouponCodes() {
1482
    $lastAdvertiser = "";
1483
 
127 - 1484
    $xh = new Html;
1485
    $xh->init($_SESSION["htmlIndent"]);
1486
 
41 - 1487
    if (!isLoggedIn()) {
127 - 1488
        $xh->add_attribute("class", "container bg-warning text-center py-3");
1489
        $xh->tag('div');
1490
            $xh->add_attribute("class", "display-6");
1491
            $xh->tag('p');
1492
                $xh->add_attribute("class", "material-icons");
1493
                $xh->tag('i', "error_outline");
1494
                $xh->tag('span', " Please login to your Find Cheap Music account in order to see the coupons.");
1495
            $xh->close(); // p
1496
        $xh->close(); // div
1497
 
1498
        $html = $xh->flush();
1499
       //error_log(print_r($html, 1));
1500
 
1501
        return $html;
41 - 1502
    }
1503
 
65 - 1504
    $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 - 1505
    $conn = MySessionHandler::getDBSessionId();
1506
 
1507
    if ($result = mysqli_query($conn, $sql)) {
1508
        if (mysqli_num_rows($result) > 0) {
127 - 1509
            $xh->add_attribute("class", "container py-4 border bg-light");
1510
            $xh->tag('div');
65 - 1511
            while ($row = mysqli_fetch_assoc($result)) {
1512
                if ($row["advertiser"] != $lastAdvertiser) {
41 - 1513
                    if (!empty($lastAdvertiser)) {
127 - 1514
                        $xh->close(); // ul
41 - 1515
                    }
127 - 1516
                    $xh->add_attribute("class", "text-center mt-3 mb-1");
1517
                    $xh->tag('h2', $row["advertiser"]);
1518
                    $xh->add_attribute("class", "list-group");
1519
                    $xh->tag('ul');
41 - 1520
                    $lastAdvertiser = $row["advertiser"];
1521
                }
51 - 1522
                if (!empty($row["url"])) {
127 - 1523
                    $xh->add_attribute("class", "list-group-item");
1524
                    $xh->tag('li');
1525
                        $xh->add_attribute("class", "btn btn-link text-left");
1526
                        $xh->add_attribute("target", "_blank");
1527
                        $xh->add_attribute("href", htmlentities($row["url"]));
1528
                        $xh->add_attribute("rel", "nofollow noreferrer noopener");
1529
                        $xh->tag('a');
1530
                            $str = '<strong>' . $row["description"] . '</strong> until ' . $row["enddate"];
1531
                            if (!empty($row["couponcode"])) {
1532
                                $str .= ' (Use Coupon Code "' . $row["couponcode"] . '")';
1533
                            }
1534
                            if (!empty($row["pixel"])) {
1535
                                $xh->add_attribute("class", "border-0 lazyload");
1536
                                $xh->add_attribute("src",PIXEL);
1537
                                $xh->add_attribute("data-src", htmlentities($row["pixel"]));
1538
                                $xh->add_attribute("width", "1");
1539
                                $xh->add_attribute("height", "1");
1540
                                $xh->add_attribute("alt", $row["advertiser"] . " Coupon");
1541
                                $xh->single_tag('img');
1542
                            }
1543
                            $xh->tag('span', $str);
1544
                        $xh->close(); // a
1545
                    $xh->close(); // li
41 - 1546
                }
1547
            }
127 - 1548
 
1549
            if (!empty($lastAdvertiser)) {
1550
                $xh->close(); // ul
1551
            }
1552
            $xh->close(); // div
41 - 1553
        }
65 - 1554
    }
1555
    else if (mysqli_errno($conn)) {
127 - 1556
        $xh->add_attribute("class", "container bg-info text-center py-3");
1557
        $xh->tag('div');
1558
            $xh->add_attribute("class", "display-6");
1559
            $xh->tag('p');
1560
                $xh->add_attribute("class", "material-icons");
1561
                $xh->tag('i', "loyalty");
1562
                $xh->tag('span', " No Coupons available at the moment...");
1563
            $xh->close(); // p
1564
        $xh->close(); // div
41 - 1565
    }
1566
 
127 - 1567
    $html = $xh->flush();
1568
    //error_log(print_r($html, 1));
1569
 
1570
    return $html;
41 - 1571
}
1572
 
14 - 1573
// Delete left over progressbar files older than 2 days
1574
function cleanupPbFiles() {
84 - 1575
    $files = glob("../MyFiles/tmp/pb*.txt");
65 - 1576
    $now = time();
14 - 1577
    foreach ($files as $file) {
1578
        if (is_file($file)) {
1579
            if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days and older
1580
                unlink($file);
1581
            }
65 - 1582
        }
14 - 1583
    }
1584
}
1585
 
1586
// Update progressbar file for a session
129 - 1587
function updatePbFile($flag = false, $desc = null) {
1588
    static $max_pb = 10; // max progressbar steps
22 - 1589
    static $current = 0;
129 - 1590
    static $lastTime = 0;
1591
    static $startTime = 0;
1592
    static $timers = [];
23 - 1593
 
22 - 1594
    if ($flag) {
129 - 1595
        if ($desc == "Start") {
1596
            $current = 0;
1597
            $timers = [];
1598
            $startTime = $lastTime = microtime(true);
1599
        } else if (strpos($desc, "End:") === 0) {
1600
            $nowTime = microtime(true);
1601
            $timers["Total"] = intval(($nowTime - $startTime) * 1000);
1602
            $pieces = explode(":", $desc);
1603
            savePbTimers($timers, $pieces[1]);
1604
        }
65 - 1605
    }
1606
    else {
22 - 1607
        ++$current;
129 - 1608
        $nowTime = microtime(true);
1609
        $diffTime = $nowTime - $lastTime;
1610
        $lastTime = $nowTime;
1611
        $timers[$desc] = intval($diffTime * 1000);
1612
   }
22 - 1613
 
1614
    if ($current > $max_pb) {
1615
        error_log("max_pb $max_pb is too small, current step is $current. Adjust tools.php (updatePbFile).");
1616
        $max_pb = $current;
1617
    }
65 - 1618
    $filename = session_id() . "_" . MySessionHandler::getSessionTab();
14 - 1619
    $arr_content = array();
1620
 
20 - 1621
    $percent = intval($current / $max_pb * 100);
14 - 1622
 
1623
    $arr_content['percent'] = $percent;
1624
    $arr_content['message'] = $current . " search(es) processed.";
84 - 1625
    $file = "../MyFiles/tmp/pb_" . $filename . ".txt";
14 - 1626
 
77 - 1627
    if ($percent >= 100) {
1628
        @unlink($file);
1629
    } else {
1630
        file_put_contents($file, json_encode($arr_content));
1631
    }
14 - 1632
}
20 - 1633
 
1634
// Linkshare / CJ Affiliate csv dump
1635
function ls_cj_csv($fields) {
1636
    static $fh = null;
1637
    $delimiter = ',';
1638
    $enclosure = '"';
1639
    $mysql_null = false;
1640
 
1641
    if (!$fh) {
1642
        $fh = fopen("ls_cj.csv", "a+");
1643
    }
1644
 
1645
    $delimiter_esc = preg_quote($delimiter, '/');
1646
    $enclosure_esc = preg_quote($enclosure, '/');
1647
 
1648
    $output = array();
1649
    foreach ($fields as $field) {
1650
        if ($field === null && $mysql_null) {
1651
            $output[] = 'NULL';
1652
            continue;
1653
        }
1654
 
65 - 1655
        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure) : $field;
20 - 1656
    }
1657
 
1658
    fwrite($fh, join($delimiter, $output) . "\n");
1659
}
35 - 1660
 
1661
// Login in check
1662
function isLoggedIn() {
65 - 1663
    return (!empty($_SESSION['sessData']['userLoggedIn']) && !empty($_SESSION['sessData']['userID'])) ? true : false;
35 - 1664
}
1665
 
1666
// unset all login system session data
1667
function unsetSessData() {
1668
    unset($_SESSION['sessData']['userLoggedIn']);
1669
    unset($_SESSION['sessData']['userID']);
1670
    unset($_SESSION['sessData']['loginType']);
36 - 1671
}
1672
 
1673
// get user image name
1674
function getUserImage($userData) {
1675
    if (empty($userData) || empty($userData['picture'])) {
109 - 1676
        return 'login/assets/images/default.png';
36 - 1677
    }
38 - 1678
 
36 - 1679
    $httpPos = strpos($userData['picture'], 'http');
1680
    if ($httpPos === false) {
65 - 1681
        return 'login/' . UPLOAD_PATH . 'profile_picture/' . $userData['picture'];
36 - 1682
    }
1683
 
1684
    return $userData['picture'];
38 - 1685
}
39 - 1686
 
1687
function startsWith($haystack, $needle) {
1688
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
1689
}
1690
 
1691
function endsWith($haystack, $needle) {
1692
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
45 - 1693
}
50 - 1694
 
1695
function displayBarcode($barcode) {
1696
    $barcode = trim(preg_replace("/[^0-9]/", "", $barcode));
1697
    $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
1698
 
1699
    if ($barcodeType == "UPC" && strlen($barcode) == 12) {
1700
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 5) . "-" . substr($barcode, 6, 5) . "-" . substr($barcode, 11, 1);
65 - 1701
    }
1702
    else if (($barcodeType == "EAN" || $barcodeType == "ISBN") && strlen($barcode) == 13) {
50 - 1703
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 6) . "-" . substr($barcode, 7, 6);
65 - 1704
    }
1705
    else if ($barcodeType == "EAN" && strlen($barcode) == 14) {
50 - 1706
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 2) . "-" . substr($barcode, 3, 5) . "-" . substr($barcode, 8, 5) . "-" . substr($barcode, 13, 1);
65 - 1707
    }
1708
    else {
50 - 1709
        return $barcode;
1710
    }
52 - 1711
}
93 - 1712
 
1713
// fuzzy search to verify titles are relevant
1714
function verifyResultArr() {
1715
    require_once ('php/Fuse/Bitap/Bitap.php');
1716
    require_once ('php/Fuse/Bitap/matched_indices.php');
1717
    require_once ('php/Fuse/Bitap/pattern_alphabet.php');
1718
    require_once ('php/Fuse/Bitap/regex_search.php');
1719
    require_once ('php/Fuse/Bitap/score.php');
1720
    require_once ('php/Fuse/Bitap/search.php');
1721
    require_once ('php/Fuse/Helpers/deep_value.php');
1722
    require_once ('php/Fuse/Helpers/is_list.php');
1723
    require_once ('php/Fuse/Fuse.php');
1724
 
1725
    if (!empty($_SESSION["barcode"]["Value"]) || empty($_SESSION["resultArr"])) {
1726
        return;
1727
    }
1728
 
1729
    $options = [
1730
      'shouldSort' => false,
1731
    //  'tokenize' => true,
1732
    //  'matchAllTokens' => true,
1733
    //  'findAllMatches' => true,
1734
      'includeScore' => true,
1735
      'includeMatches' => true,
1736
      'threshold' => 0.6,
1737
      'location' => 0,
1738
      'distance' => 100,
1739
      'minMatchCharLength' => 5,
1740
      'keys' => [ "Title" ]
1741
    ];
1742
 
1743
    $fuse = new Fuse($_SESSION["resultArr"], $options);
1744
    $result = $fuse->search($_SESSION["searchTerm"]);
1745
 
1746
    $_SESSION["resultArr"] = [];
1747
    foreach($result as $r) {
97 - 1748
        $r['item']['score'] = (!empty($r['score']) ? $r['score'] : 0);
1749
        $r['item']['indices'] = (!empty($r['matches'][0]['indices']) ? $r['matches'][0]['indices'] : []);
93 - 1750
        $_SESSION['resultArr'][] = $r['item'];
1751
    }
1752
 
1753
    /* debug start
1754
    $lines = [];
1755
    foreach($_SESSION['resultArr'] as $r) {
1756
        $p = 0;
1757
        $t = '';
1758
        foreach($r['indices'] as $ind) {
1759
            if ($p < $ind[0]) {
1760
                $t .= substr($r['Title'], $p, $ind[0] - $p);
1761
            }
1762
            $t .= "<b>" . substr($r['Title'], $ind[0], $ind[1] - $ind[0] + 1) . "</b>";
1763
            $p = $ind[1] + 1;
1764
        }
1765
        if ($p < strlen($r['Title'])) {
1766
            $t .= substr($r['Title'], $p);
1767
        }
1768
        $lines[] = array ('score' => $r['score'], 'title' => $t);
1769
    }
1770
 
1771
    usort($lines, 'compare_score');
1772
    echo "<p>";
1773
    foreach($lines as $l) {
1774
        echo $l['score'] . ": " . $l['title'] . "<br/>";
1775
    }
1776
    echo "</p>";
1777
    debug end */
1778
}
1779
 
1780
// compare score for sort low to high
1781
function compare_score($a, $b) {
1782
    return ($a['score'] > $b['score']);
1783
}
96 - 1784
 
1785
function my_error_log($msg) {
1786
    error_log("[" . date("d-M-Y H:m:s") . "] " . $msg . PHP_EOL, 3, $_SERVER['DOCUMENT_ROOT'] . "/../MyFiles/logs/my_php_error.log");
1787
}
99 - 1788
 
129 - 1789
function savePbTimers($timers, $id) {
1790
    $conn = MySessionHandler::getDBSessionId();
1791
 
1792
    $sql = "INSERT
1793
                INTO searchPerformance
1794
                (id, Discogs, eBay_New, Linkshare, CJ_Affiliate, Walmart, iTunes, Amazon_API, Amazon_Scrape, Impact, eBay_Used, Total)
1795
                VALUES ($id, " . $timers['Discogs'] . ",
1796
" . $timers['eBay New'] . ",
1797
" . $timers['Linkshare'] . ",
1798
" . $timers['CJ Affiliate'] . ",
1799
" . $timers['Walmart'] . ",
1800
" . $timers['iTunes'] . ",
1801
" . $timers['Amazon API'] . ",
1802
" . $timers['Amazon Scrape'] . ",
1803
" . $timers['Impact'] . ",
1804
" . $timers['eBay Used'] . ",
1805
" . $timers['Total'] . ")";
1806
 
1807
    if (!($result = mysqli_query($conn, $sql))) {
1808
        error_log("MySQL Write SearchPerformance Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1809
    }
1810
 
1811
    return $result;
1812
}
1813
 
99 - 1814
function saveSearchCache($vendor, $query, $subquery, $text) {
1815
    $conn = MySessionHandler::getDBSessionId();
1816
 
1817
    $created = mysqli_real_escape_string($conn, time());
1818
    $v = mysqli_real_escape_string($conn, $vendor);
1819
    $q = mysqli_real_escape_string($conn, $query);
1820
    $s = mysqli_real_escape_string($conn, $subquery);
1821
    $r = base64_encode(gzencode($text));
1822
 
1823
    $sql = "INSERT
1824
                INTO searchCache
1825
                (created, vendor, query, subquery, result)
110 - 1826
                VALUES ('$created', '$v', '$q', '$s', '$r')
1827
                ON DUPLICATE KEY UPDATE result = '$r'";
99 - 1828
 
1829
    if (!($result = mysqli_query($conn, $sql))) {
1830
        error_log("MySQL Write SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1831
    }
1832
 
1833
    return $result;
1834
}
1835
 
1836
 
1837
function expireSearchCache() {
1838
    $conn = MySessionHandler::getDBSessionId();
1839
    $t = MySessionHandler::getDBExpirationTime();
1840
 
1841
    $expired = mysqli_real_escape_string($conn, time() - $t);
1842
 
1843
    $sql = "DELETE
1844
                FROM searchCache
1845
                WHERE created < $expired";
1846
 
1847
    if (!($result = mysqli_query($conn, $sql))) {
1848
        error_log("MySQL Delete SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1849
    }
1850
}
1851
 
1852
function getSearchCache($vendor, $query, $subquery) {
1853
    $conn = MySessionHandler::getDBSessionId();
1854
 
1855
    $v = mysqli_real_escape_string($conn, $vendor);
1856
    $q = mysqli_real_escape_string($conn, $query);
1857
    $s = mysqli_real_escape_string($conn, $subquery);
1858
    $sql = "select result from searchCache where vendor = '$v' and query = '$q' and subquery = '$s'";
1859
 
1860
    if ($result = mysqli_query($conn, $sql)) {
1861
        if (mysqli_num_rows($result) == 1) {
1862
            if ($row = mysqli_fetch_assoc($result)) {
1863
                return gzdecode(base64_decode($row["result"]));
1864
            }
1865
        }
1866
    }
1867
    else if (mysqli_errno($conn)) {
1868
        error_log("MySQL Read SearchCache SQL: " . $sql);
1869
        error_log("MySQL Read SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1870
    }
1871
 
1872
    return false;
104 - 1873
}
107 - 1874
 
1875
 
1876
function getGeoLocation() {
1877
    if (!empty($_SESSION['buyer']['Zip']) || empty($_SERVER['REMOTE_ADDR'])) {
1878
        return;
1879
    }
1880
 
1881
    $conn = MySessionHandler::getDBSessionId();
1882
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
1883
 
1884
    $sql = "select zip from geoLocation where ip = '$ip'";
1885
 
1886
    if ($result = mysqli_query($conn, $sql)) {
1887
        if (mysqli_num_rows($result) == 1) {
1888
            if ($row = mysqli_fetch_assoc($result)) {
1889
                $_SESSION['buyer']['Zip'] = $row["zip"];
1890
                return;
1891
            }
1892
        }
1893
    }
1894
    else if (mysqli_errno($conn)) {
1895
        error_log("MySQL Read geoLocation SQL: " . $sql);
1896
        error_log("MySQL Read geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1897
    }
1898
 
1899
    $vendors = Vendors::getInstance();
1900
    $config = $vendors->getVendor(Vendors::IPAPI);
1901
    $key = $config['KEY'];
1902
 
1903
    $loc = file_get_contents("http://api.ipapi.com/api/" . $_SERVER['REMOTE_ADDR'] . "?access_key=" . $key);
1904
    if ($loc == false) {
1905
        return;
1906
    }
1907
 
1908
    $json = json_decode($loc);
1909
    if (!empty($json->error)) {
1910
        error_log("geoLocation Error: " . $json->error->info . " (" . $json->error->code . " | " . $json->error->type . ")");
1911
        return;
1912
    }
1913
 
1914
    $created = mysqli_real_escape_string($conn, time());
1915
    $countryCode = mysqli_real_escape_string($conn, $json->{'country_code'});
1916
    $zip = mysqli_real_escape_string($conn, $json->zip);
1917
    $language = mysqli_real_escape_string($conn, $json->location->languages[0]->code);
1918
    $is_eu = mysqli_real_escape_string($conn, $json->location->{'is_eu'} ? '1' : '0');
1919
 
1920
    $sql = "INSERT
1921
                INTO geoLocation
1922
                (ip, created, countryCode, zip, language, is_eu)
1923
                VALUES ('$ip', $created, '$countryCode', '$zip', '$language', '$is_eu')";
1924
 
1925
    if (!($result = mysqli_query($conn, $sql))) {
1926
        error_log("MySQL Write geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1927
    }
1928
}
1929
 
1930
function timeStampUrl($file) {
121 - 1931
    if (@file_exists($file)) {
109 - 1932
        return $file . "?" . filemtime($file);
1933
    }
127 - 1934
 
109 - 1935
    return $file;
108 - 1936
}