Subversion Repositories cheapmusic

Rev

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