Subversion Repositories cheapmusic

Rev

Rev 137 | Rev 141 | 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
138 - 1112
function sanitizeInput($str) {
1113
    $str = trim(preg_replace('/[\t\n\r\s]+/', ' ', $str));
1114
    $str = stripslashes($str);
1115
    $str = htmlspecialchars($str);
1116
    return $str;
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
138 - 1183
function initSessionVariables($systemConf) {
65 - 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
    ));
138 - 1214
    $_SESSION["htmlIndent"] = (!empty($systemConf["htmlIndent"]) ? intval($systemConf["htmlIndent"]) : 0);
1215
    $_SESSION["gtmId"] = (empty($systemConf["gtmId"]) ? "" : $systemConf["gtmId"]);
1216
    $_SESSION["nonce"] = NonceUtil::generate($systemConf["nonce_secret"], 1800);
1217
    initSV("mode", SIMPLE_SEARCH);
5 - 1218
}
1219
 
14 - 1220
function md5SearchTerm() {
1221
    $data = array();
1222
    $data['cond'] = $_SESSION['filterCondition'];
1223
    $data['type'] = $_SESSION['filterMediaType'];
17 - 1224
    $data['buyer'] = $_SESSION['buyer'];
65 - 1225
    $data['term'] = array(
1226
        $_SESSION['searchTerm']
1227
    );
14 - 1228
 
65 - 1229
    return (md5(json_encode($data)));
14 - 1230
}
1231
 
65 - 1232
// check POST value, return true if set and false if not
1233
function checkPV($var) {
1234
    if (isset($_POST[$var])) {
1235
        return (true);
1236
    }
1 - 1237
 
65 - 1238
    return (false);
5 - 1239
}
1240
 
65 - 1241
// get POST or GET value, return empty if not set
1242
function getPGV($var) {
1243
    if (isset($_POST[$var])) {
1244
        return ($_POST[$var]);
1245
    }
1246
    else if (isset($_GET[$var])) {
1247
        return ($_GET[$var]);
1248
    }
14 - 1249
 
65 - 1250
    return ("");
14 - 1251
}
1252
 
65 - 1253
function saveSearchResult() {
1254
    $conn = MySessionHandler::getDBSessionId();
13 - 1255
 
65 - 1256
    $access = mysqli_real_escape_string($conn, time());
1257
    // BUGBUG
1258
    //  country
1259
    //  currency
1260
    $zip = mysqli_real_escape_string($conn, $_SESSION['buyer']['Zip']);
1261
    $condNew = $_SESSION['filterCondition']['New'] ? 'Y' : 'N';
1262
    $condUsed = $_SESSION['filterCondition']['Used'] ? 'Y' : 'N';
1263
    $mediaCD = $_SESSION['filterMediaType']['CD'] ? 'Y' : 'N';
1264
    $mediaRecord = $_SESSION['filterMediaType']['Record'] ? 'Y' : 'N';
1265
    $mediaDigital = $_SESSION['filterMediaType']['Digital'] ? 'Y' : 'N';
1266
    $mediaBook = $_SESSION['filterMediaType']['Book'] ? 'Y' : 'N';
138 - 1267
    $searchTerm = mysqli_real_escape_string($conn, $_SESSION['searchTerm']);
1268
 
1269
    $arr = [];
1270
    $advSearchTerm = null;
1271
    if (!empty($_SESSION["advSearch"]["Title"])) {
1272
        $arr[] = "t:" . $_SESSION["advSearch"]["Title"];
1273
    }
1274
    if (!empty($_SESSION["advSearch"]["Artist"])) {
1275
        $arr[] = "a:" . $_SESSION["advSearch"]["Artist"];
1276
    }
1277
    if (!empty($_SESSION["advSearch"]["Track"])) {
1278
        $arr[] = "tr:" . $_SESSION["advSearch"]["Track"];
1279
    }
1280
    if (!empty($_SESSION["advSearch"]["Barcode"])) {
1281
        $arr[] = "b:" . $_SESSION["advSearch"]["Barcode"];
1282
    }
1283
    if (!empty($_SESSION["advSearch"]["Format"])) {
1284
        $arr[] = "f:" . $_SESSION["advSearch"]["Format"];
1285
    }
1286
    if (!empty($_SESSION["advSearch"]["Catno"])) {
1287
        $arr[] = "c:" . $_SESSION["advSearch"]["Catno"];
1288
    }
1289
    if (!empty($_SESSION["advSearch"]["Label"])) {
1290
        $arr[] = "l:" . $_SESSION["advSearch"]["Label"];
1291
    }
1292
    if (!empty($_SESSION["advSearch"]["Country"])) {
1293
        $arr[] = "co:" . $_SESSION["advSearch"]["Country"];
1294
    }
1295
    if (!empty($_SESSION["advSearch"]["Year"])) {
1296
        $arr[] = "y:" . $_SESSION["advSearch"]["Year"];
1297
    }
1298
    $advSearchTerm = (empty($arr) ? 'NULL' : mysqli_real_escape_string($conn, join('|', $arr)));
1299
 
65 - 1300
    $lowNew = floatval($_SESSION['lowestPrice']['New']);
1301
    $lowUsed = floatval($_SESSION['lowestPrice']['Used']);
116 - 1302
    $lowCD = floatval($_SESSION['lowestPrice']['CD']);
1303
    $lowRecord = floatval($_SESSION['lowestPrice']['Record']);
65 - 1304
    $lowDigital = floatval($_SESSION['lowestPrice']['Digital']);
1305
    $lowBook = floatval($_SESSION['lowestPrice']['Book']);
1306
    $count = count($_SESSION['resultArr']);
1307
    $userId = (empty($_SESSION['sessData']['userID']) ? 'NULL' : $_SESSION['sessData']['userID']);
96 - 1308
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
8 - 1309
 
65 - 1310
    $sql = "INSERT
20 - 1311
                INTO searches
138 - 1312
                (sessId, access, ip, zip, condNew, condUsed, mediaCD, mediaRecord, mediaDigital, mediaBook, searchTerm, advSearchTerm, lowNew, lowUsed, lowCD, lowRecord, lowDigital, lowBook, count, userId)
1313
                VALUES ('" . session_id() . "', '$access', '$ip', '$zip', '$condNew', '$condUsed', '$mediaCD', '$mediaRecord', '$mediaDigital', '$mediaBook', '$searchTerm', '$advSearchTerm', $lowNew, $lowUsed, $lowCD, $lowRecord, $lowDigital, $lowBook, $count, $userId)";
8 - 1314
 
65 - 1315
    if (!($result = mysqli_query($conn, $sql))) {
1316
        error_log("MySQL Write Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1317
    }
13 - 1318
 
129 - 1319
 
1320
    return(mysqli_insert_id($conn));
65 - 1321
}
13 - 1322
 
17 - 1323
function getUrl($url, $userAgent = null) {
1324
    $ch = curl_init();
1325
 
1326
    // Set request header with language and charset
1327
    $header = array(
1328
        "Accept-Language: en-US,en;q=0.5",
1329
        "Accept-Charset: UTF-8,*;q=0.5"
1330
    );
1331
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1332
 
1333
    // Set optional user-agent
1334
    if ($userAgent) {
1335
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1336
    }
1337
 
1338
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1339
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1340
    curl_setopt($ch, CURLOPT_HEADER, 0);
84 - 1341
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1342
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
17 - 1343
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1344
    curl_setopt($ch, CURLOPT_URL, $url);
1345
    $response = curl_exec($ch);
1346
    if ($response === false) {
20 - 1347
        error_log('Curl Request Error: ' . curl_error($ch) . ' (' . curl_errno($ch) . ')');
1348
        error_log('Url: ' . $url);
17 - 1349
        $response = '';
1350
    }
23 - 1351
 
17 - 1352
    curl_close($ch);
1353
 
1354
    return $response;
1355
}
1356
 
129 - 1357
function getMultiUrl($urls, $userAgent = null) {
1358
    $multi = curl_multi_init();
1359
    $channels = [];
1360
    $response = [];
1361
    // Set request header with language and charset
1362
    $header = array(
1363
        "Accept-Language: en-US,en;q=0.5",
1364
        "Accept-Charset: UTF-8,*;q=0.5"
1365
    );
137 - 1366
 
129 - 1367
    // Loop through the URLs, create curl-handles
1368
    // and attach the handles to our multi-request
1369
    foreach ($urls as $url) {
1370
        $ch = curl_init();
1371
 
1372
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1373
 
1374
        // Set optional user-agent
1375
        if ($userAgent) {
1376
            curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1377
        }
1378
 
1379
        curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1380
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1381
        curl_setopt($ch, CURLOPT_HEADER, 0);
1382
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1383
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
1384
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1385
        curl_setopt($ch, CURLOPT_URL, $url);
137 - 1386
 
129 - 1387
        curl_multi_add_handle($multi, $ch);
137 - 1388
 
129 - 1389
        $channels[$url] = $ch;
1390
    }
137 - 1391
 
129 - 1392
    // While we're still active, execute curl
1393
    $active = null;
1394
    do {
1395
        $mrc = curl_multi_exec($multi, $active);
1396
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
137 - 1397
 
129 - 1398
    while ($active && $mrc == CURLM_OK) {
1399
        // Wait for activity on any curl-connection
1400
        if (curl_multi_select($multi) == -1) {
1401
            continue;
1402
        }
137 - 1403
 
138 - 1404
        // Continue to exec until curl is ready to give us more data
129 - 1405
        do {
1406
            $mrc = curl_multi_exec($multi, $active);
1407
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1408
    }
137 - 1409
 
129 - 1410
    // Loop through the channels and retrieve the received
1411
    // content, then remove the handle from the multi-handle
1412
    foreach ($channels as $url => $channel) {
1413
        $response[$url] = curl_multi_getcontent($channel);
1414
        if ($response[$url] === false) {
1415
            error_log('Curl Request Error: ' . curl_error($channel) . ' (' . curl_errno($channel) . ')');
1416
            error_log('Url: ' . $url);
1417
            $response[$url] = '';
1418
        }
1419
        curl_multi_remove_handle($multi, $channel);
1420
    }
137 - 1421
 
129 - 1422
    // Close the multi-handle and return our results
1423
    curl_multi_close($multi);
1424
 
1425
    return($response);
1426
}
1427
 
20 - 1428
// Retrieve search history for current session id
14 - 1429
function getSearchHistory() {
127 - 1430
    $xh = new Html;
1431
    $xh->init($_SESSION["htmlIndent"]);
1432
 
138 - 1433
    $sql = "select searchTerm, advSearchTerm, max(access) from searches where sessId = '" . session_id() . "'";
38 - 1434
    if (!empty($_SESSION['sessData']['userID'])) {
1435
        $sql .= " or userID = '" . $_SESSION['sessData']['userID'] . "'";
1436
    }
138 - 1437
    $sql .= " group by searchTerm order by max(access) desc, searchTerm limit 0,30;";
14 - 1438
    $conn = MySessionHandler::getDBSessionId();
1439
 
20 - 1440
    if ($result = mysqli_query($conn, $sql)) {
1441
        if (mysqli_num_rows($result) > 0) {
65 - 1442
            while ($row = mysqli_fetch_assoc($result)) {
138 - 1443
                $xh->add_attribute("value", $row["advSearchTerm"] ? "*ADV*" . $row["advSearchTerm"] : $row["searchTerm"]);
1444
                $xh->tag("option", $row["searchTerm"]);
20 - 1445
            }
14 - 1446
        }
1447
    }
65 - 1448
    else if (mysqli_errno($conn)) {
1449
        error_log("MySQL Read Searches SQL: " . $sql);
1450
        error_log("MySQL Read Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1451
    }
14 - 1452
 
127 - 1453
    $html = $xh->flush();
1454
    //error_log(print_r($html, 1));
1455
 
1456
    return $html;
14 - 1457
}
1458
 
41 - 1459
// Retrieve coupons codes
1460
function getCouponCodes() {
1461
    $lastAdvertiser = "";
1462
 
127 - 1463
    $xh = new Html;
1464
    $xh->init($_SESSION["htmlIndent"]);
1465
 
41 - 1466
    if (!isLoggedIn()) {
127 - 1467
        $xh->add_attribute("class", "container bg-warning text-center py-3");
1468
        $xh->tag('div');
1469
            $xh->add_attribute("class", "display-6");
1470
            $xh->tag('p');
1471
                $xh->add_attribute("class", "material-icons");
1472
                $xh->tag('i', "error_outline");
1473
                $xh->tag('span', " Please login to your Find Cheap Music account in order to see the coupons.");
1474
            $xh->close(); // p
1475
        $xh->close(); // div
1476
 
1477
        $html = $xh->flush();
1478
       //error_log(print_r($html, 1));
1479
 
1480
        return $html;
41 - 1481
    }
1482
 
65 - 1483
    $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 - 1484
    $conn = MySessionHandler::getDBSessionId();
1485
 
1486
    if ($result = mysqli_query($conn, $sql)) {
1487
        if (mysqli_num_rows($result) > 0) {
127 - 1488
            $xh->add_attribute("class", "container py-4 border bg-light");
134 - 1489
            $xh->add_attribute("id", "couponList");
127 - 1490
            $xh->tag('div');
65 - 1491
            while ($row = mysqli_fetch_assoc($result)) {
1492
                if ($row["advertiser"] != $lastAdvertiser) {
41 - 1493
                    if (!empty($lastAdvertiser)) {
127 - 1494
                        $xh->close(); // ul
41 - 1495
                    }
127 - 1496
                    $xh->add_attribute("class", "text-center mt-3 mb-1");
1497
                    $xh->tag('h2', $row["advertiser"]);
1498
                    $xh->add_attribute("class", "list-group");
1499
                    $xh->tag('ul');
41 - 1500
                    $lastAdvertiser = $row["advertiser"];
1501
                }
51 - 1502
                if (!empty($row["url"])) {
127 - 1503
                    $xh->add_attribute("class", "list-group-item");
1504
                    $xh->tag('li');
134 - 1505
                        $xh->add_attribute("class", "btn btn-link text-left coupon-link");
127 - 1506
                        $xh->add_attribute("target", "_blank");
1507
                        $xh->add_attribute("href", htmlentities($row["url"]));
1508
                        $xh->add_attribute("rel", "nofollow noreferrer noopener");
134 - 1509
                        $xh->add_attribute("data-advertiser", $row["advertiser"]);
127 - 1510
                        $xh->tag('a');
1511
                            $str = '<strong>' . $row["description"] . '</strong> until ' . $row["enddate"];
1512
                            if (!empty($row["couponcode"])) {
1513
                                $str .= ' (Use Coupon Code "' . $row["couponcode"] . '")';
1514
                            }
1515
                            if (!empty($row["pixel"])) {
1516
                                $xh->add_attribute("class", "border-0 lazyload");
1517
                                $xh->add_attribute("src",PIXEL);
1518
                                $xh->add_attribute("data-src", htmlentities($row["pixel"]));
1519
                                $xh->add_attribute("width", "1");
1520
                                $xh->add_attribute("height", "1");
1521
                                $xh->add_attribute("alt", $row["advertiser"] . " Coupon");
1522
                                $xh->single_tag('img');
1523
                            }
1524
                            $xh->tag('span', $str);
1525
                        $xh->close(); // a
1526
                    $xh->close(); // li
41 - 1527
                }
1528
            }
137 - 1529
 
127 - 1530
            if (!empty($lastAdvertiser)) {
1531
                $xh->close(); // ul
1532
            }
134 - 1533
 
1534
    $xh->add_attribute("nonce", base64_encode($_SESSION["nonce"]));
1535
    $xh->tag('script');
137 - 1536
        $str  = my_trim('document.addEventListener("DOMContentLoaded", function() {');
1537
        $str .= my_trim('    document.getElementById("couponList").addEventListener("click", function(event) {');
1538
        $str .= my_trim('        e = event.target.closest("a");');
1539
        $str .= my_trim('        if (e && e.classList.contains("coupon-link")) {');
1540
        $str .= my_trim('            window.dataLayer.push({ "event" : "trackEvent", "eventCategory" : "Coupon", "eventAction" : "Click", "eventLabel" : e.getAttribute("data-advertiser")});');
1541
        $str .= my_trim('        }');
1542
        $str .= my_trim('    });');
1543
        $str .= my_trim('});');
134 - 1544
    $xh->insert_code($str);
1545
    $xh->close(); // script
1546
 
127 - 1547
            $xh->close(); // div
41 - 1548
        }
65 - 1549
    }
1550
    else if (mysqli_errno($conn)) {
127 - 1551
        $xh->add_attribute("class", "container bg-info text-center py-3");
1552
        $xh->tag('div');
1553
            $xh->add_attribute("class", "display-6");
1554
            $xh->tag('p');
1555
                $xh->add_attribute("class", "material-icons");
1556
                $xh->tag('i', "loyalty");
1557
                $xh->tag('span', " No Coupons available at the moment...");
1558
            $xh->close(); // p
1559
        $xh->close(); // div
41 - 1560
    }
1561
 
127 - 1562
    $html = $xh->flush();
1563
    //error_log(print_r($html, 1));
1564
 
1565
    return $html;
41 - 1566
}
1567
 
14 - 1568
// Delete left over progressbar files older than 2 days
1569
function cleanupPbFiles() {
84 - 1570
    $files = glob("../MyFiles/tmp/pb*.txt");
65 - 1571
    $now = time();
14 - 1572
    foreach ($files as $file) {
1573
        if (is_file($file)) {
1574
            if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days and older
1575
                unlink($file);
1576
            }
65 - 1577
        }
14 - 1578
    }
1579
}
1580
 
1581
// Update progressbar file for a session
129 - 1582
function updatePbFile($flag = false, $desc = null) {
1583
    static $max_pb = 10; // max progressbar steps
22 - 1584
    static $current = 0;
129 - 1585
    static $lastTime = 0;
1586
    static $startTime = 0;
1587
    static $timers = [];
23 - 1588
 
22 - 1589
    if ($flag) {
129 - 1590
        if ($desc == "Start") {
1591
            $current = 0;
1592
            $timers = [];
1593
            $startTime = $lastTime = microtime(true);
1594
        } else if (strpos($desc, "End:") === 0) {
1595
            $nowTime = microtime(true);
1596
            $timers["Total"] = intval(($nowTime - $startTime) * 1000);
1597
            $pieces = explode(":", $desc);
1598
            savePbTimers($timers, $pieces[1]);
1599
        }
65 - 1600
    }
1601
    else {
22 - 1602
        ++$current;
129 - 1603
        $nowTime = microtime(true);
1604
        $diffTime = $nowTime - $lastTime;
1605
        $lastTime = $nowTime;
1606
        $timers[$desc] = intval($diffTime * 1000);
1607
   }
22 - 1608
 
1609
    if ($current > $max_pb) {
1610
        error_log("max_pb $max_pb is too small, current step is $current. Adjust tools.php (updatePbFile).");
1611
        $max_pb = $current;
1612
    }
65 - 1613
    $filename = session_id() . "_" . MySessionHandler::getSessionTab();
14 - 1614
    $arr_content = array();
1615
 
20 - 1616
    $percent = intval($current / $max_pb * 100);
14 - 1617
 
1618
    $arr_content['percent'] = $percent;
1619
    $arr_content['message'] = $current . " search(es) processed.";
84 - 1620
    $file = "../MyFiles/tmp/pb_" . $filename . ".txt";
14 - 1621
 
77 - 1622
    if ($percent >= 100) {
1623
        @unlink($file);
1624
    } else {
1625
        file_put_contents($file, json_encode($arr_content));
1626
    }
14 - 1627
}
20 - 1628
 
1629
// Linkshare / CJ Affiliate csv dump
1630
function ls_cj_csv($fields) {
1631
    static $fh = null;
1632
    $delimiter = ',';
1633
    $enclosure = '"';
1634
    $mysql_null = false;
1635
 
1636
    if (!$fh) {
1637
        $fh = fopen("ls_cj.csv", "a+");
1638
    }
1639
 
1640
    $delimiter_esc = preg_quote($delimiter, '/');
1641
    $enclosure_esc = preg_quote($enclosure, '/');
1642
 
1643
    $output = array();
1644
    foreach ($fields as $field) {
1645
        if ($field === null && $mysql_null) {
1646
            $output[] = 'NULL';
1647
            continue;
1648
        }
1649
 
65 - 1650
        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure) : $field;
20 - 1651
    }
1652
 
1653
    fwrite($fh, join($delimiter, $output) . "\n");
1654
}
35 - 1655
 
1656
// Login in check
1657
function isLoggedIn() {
65 - 1658
    return (!empty($_SESSION['sessData']['userLoggedIn']) && !empty($_SESSION['sessData']['userID'])) ? true : false;
35 - 1659
}
1660
 
1661
// unset all login system session data
1662
function unsetSessData() {
1663
    unset($_SESSION['sessData']['userLoggedIn']);
1664
    unset($_SESSION['sessData']['userID']);
1665
    unset($_SESSION['sessData']['loginType']);
36 - 1666
}
1667
 
1668
// get user image name
1669
function getUserImage($userData) {
1670
    if (empty($userData) || empty($userData['picture'])) {
109 - 1671
        return 'login/assets/images/default.png';
36 - 1672
    }
38 - 1673
 
36 - 1674
    $httpPos = strpos($userData['picture'], 'http');
1675
    if ($httpPos === false) {
65 - 1676
        return 'login/' . UPLOAD_PATH . 'profile_picture/' . $userData['picture'];
36 - 1677
    }
1678
 
1679
    return $userData['picture'];
38 - 1680
}
39 - 1681
 
1682
function startsWith($haystack, $needle) {
1683
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
1684
}
1685
 
1686
function endsWith($haystack, $needle) {
1687
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
45 - 1688
}
50 - 1689
 
1690
function displayBarcode($barcode) {
1691
    $barcode = trim(preg_replace("/[^0-9]/", "", $barcode));
1692
    $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
1693
 
1694
    if ($barcodeType == "UPC" && strlen($barcode) == 12) {
1695
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 5) . "-" . substr($barcode, 6, 5) . "-" . substr($barcode, 11, 1);
65 - 1696
    }
1697
    else if (($barcodeType == "EAN" || $barcodeType == "ISBN") && strlen($barcode) == 13) {
50 - 1698
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 6) . "-" . substr($barcode, 7, 6);
65 - 1699
    }
1700
    else if ($barcodeType == "EAN" && strlen($barcode) == 14) {
50 - 1701
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 2) . "-" . substr($barcode, 3, 5) . "-" . substr($barcode, 8, 5) . "-" . substr($barcode, 13, 1);
65 - 1702
    }
1703
    else {
50 - 1704
        return $barcode;
1705
    }
52 - 1706
}
93 - 1707
 
1708
// fuzzy search to verify titles are relevant
1709
function verifyResultArr() {
1710
    require_once ('php/Fuse/Bitap/Bitap.php');
1711
    require_once ('php/Fuse/Bitap/matched_indices.php');
1712
    require_once ('php/Fuse/Bitap/pattern_alphabet.php');
1713
    require_once ('php/Fuse/Bitap/regex_search.php');
1714
    require_once ('php/Fuse/Bitap/score.php');
1715
    require_once ('php/Fuse/Bitap/search.php');
1716
    require_once ('php/Fuse/Helpers/deep_value.php');
1717
    require_once ('php/Fuse/Helpers/is_list.php');
1718
    require_once ('php/Fuse/Fuse.php');
1719
 
137 - 1720
    if (!empty($_SESSION["advSearch"]["Barcode"]) || empty($_SESSION["resultArr"]) || empty($_SESSION["searchTerm"])) {
93 - 1721
        return;
1722
    }
1723
 
1724
    $options = [
1725
      'shouldSort' => false,
1726
    //  'tokenize' => true,
1727
    //  'matchAllTokens' => true,
1728
    //  'findAllMatches' => true,
1729
      'includeScore' => true,
1730
      'includeMatches' => true,
1731
      'threshold' => 0.6,
1732
      'location' => 0,
1733
      'distance' => 100,
1734
      'minMatchCharLength' => 5,
1735
      'keys' => [ "Title" ]
1736
    ];
1737
 
1738
    $fuse = new Fuse($_SESSION["resultArr"], $options);
1739
    $result = $fuse->search($_SESSION["searchTerm"]);
1740
 
1741
    $_SESSION["resultArr"] = [];
1742
    foreach($result as $r) {
97 - 1743
        $r['item']['score'] = (!empty($r['score']) ? $r['score'] : 0);
1744
        $r['item']['indices'] = (!empty($r['matches'][0]['indices']) ? $r['matches'][0]['indices'] : []);
93 - 1745
        $_SESSION['resultArr'][] = $r['item'];
1746
    }
1747
 
1748
    /* debug start
1749
    $lines = [];
1750
    foreach($_SESSION['resultArr'] as $r) {
1751
        $p = 0;
1752
        $t = '';
1753
        foreach($r['indices'] as $ind) {
1754
            if ($p < $ind[0]) {
1755
                $t .= substr($r['Title'], $p, $ind[0] - $p);
1756
            }
1757
            $t .= "<b>" . substr($r['Title'], $ind[0], $ind[1] - $ind[0] + 1) . "</b>";
1758
            $p = $ind[1] + 1;
1759
        }
1760
        if ($p < strlen($r['Title'])) {
1761
            $t .= substr($r['Title'], $p);
1762
        }
1763
        $lines[] = array ('score' => $r['score'], 'title' => $t);
1764
    }
1765
 
1766
    usort($lines, 'compare_score');
1767
    echo "<p>";
1768
    foreach($lines as $l) {
1769
        echo $l['score'] . ": " . $l['title'] . "<br/>";
1770
    }
1771
    echo "</p>";
1772
    debug end */
1773
}
1774
 
1775
// compare score for sort low to high
1776
function compare_score($a, $b) {
1777
    return ($a['score'] > $b['score']);
1778
}
96 - 1779
 
1780
function my_error_log($msg) {
1781
    error_log("[" . date("d-M-Y H:m:s") . "] " . $msg . PHP_EOL, 3, $_SERVER['DOCUMENT_ROOT'] . "/../MyFiles/logs/my_php_error.log");
1782
}
99 - 1783
 
129 - 1784
function savePbTimers($timers, $id) {
1785
    $conn = MySessionHandler::getDBSessionId();
1786
 
1787
    $sql = "INSERT
1788
                INTO searchPerformance
1789
                (id, Discogs, eBay_New, Linkshare, CJ_Affiliate, Walmart, iTunes, Amazon_API, Amazon_Scrape, Impact, eBay_Used, Total)
1790
                VALUES ($id, " . $timers['Discogs'] . ",
1791
" . $timers['eBay New'] . ",
1792
" . $timers['Linkshare'] . ",
1793
" . $timers['CJ Affiliate'] . ",
1794
" . $timers['Walmart'] . ",
1795
" . $timers['iTunes'] . ",
1796
" . $timers['Amazon API'] . ",
1797
" . $timers['Amazon Scrape'] . ",
1798
" . $timers['Impact'] . ",
1799
" . $timers['eBay Used'] . ",
1800
" . $timers['Total'] . ")";
1801
 
1802
    if (!($result = mysqli_query($conn, $sql))) {
1803
        error_log("MySQL Write SearchPerformance Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1804
    }
1805
 
1806
    return $result;
1807
}
1808
 
99 - 1809
function saveSearchCache($vendor, $query, $subquery, $text) {
1810
    $conn = MySessionHandler::getDBSessionId();
1811
 
1812
    $created = mysqli_real_escape_string($conn, time());
1813
    $v = mysqli_real_escape_string($conn, $vendor);
1814
    $q = mysqli_real_escape_string($conn, $query);
1815
    $s = mysqli_real_escape_string($conn, $subquery);
1816
    $r = base64_encode(gzencode($text));
1817
 
1818
    $sql = "INSERT
1819
                INTO searchCache
1820
                (created, vendor, query, subquery, result)
110 - 1821
                VALUES ('$created', '$v', '$q', '$s', '$r')
1822
                ON DUPLICATE KEY UPDATE result = '$r'";
99 - 1823
 
1824
    if (!($result = mysqli_query($conn, $sql))) {
1825
        error_log("MySQL Write SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1826
    }
1827
 
1828
    return $result;
1829
}
1830
 
1831
 
1832
function expireSearchCache() {
1833
    $conn = MySessionHandler::getDBSessionId();
1834
    $t = MySessionHandler::getDBExpirationTime();
1835
 
1836
    $expired = mysqli_real_escape_string($conn, time() - $t);
1837
 
1838
    $sql = "DELETE
1839
                FROM searchCache
1840
                WHERE created < $expired";
1841
 
1842
    if (!($result = mysqli_query($conn, $sql))) {
1843
        error_log("MySQL Delete SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1844
    }
1845
}
1846
 
1847
function getSearchCache($vendor, $query, $subquery) {
1848
    $conn = MySessionHandler::getDBSessionId();
1849
 
1850
    $v = mysqli_real_escape_string($conn, $vendor);
1851
    $q = mysqli_real_escape_string($conn, $query);
1852
    $s = mysqli_real_escape_string($conn, $subquery);
1853
    $sql = "select result from searchCache where vendor = '$v' and query = '$q' and subquery = '$s'";
1854
 
1855
    if ($result = mysqli_query($conn, $sql)) {
1856
        if (mysqli_num_rows($result) == 1) {
1857
            if ($row = mysqli_fetch_assoc($result)) {
1858
                return gzdecode(base64_decode($row["result"]));
1859
            }
1860
        }
1861
    }
1862
    else if (mysqli_errno($conn)) {
1863
        error_log("MySQL Read SearchCache SQL: " . $sql);
1864
        error_log("MySQL Read SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1865
    }
1866
 
1867
    return false;
104 - 1868
}
107 - 1869
 
1870
 
1871
function getGeoLocation() {
1872
    if (!empty($_SESSION['buyer']['Zip']) || empty($_SERVER['REMOTE_ADDR'])) {
1873
        return;
1874
    }
1875
 
1876
    $conn = MySessionHandler::getDBSessionId();
1877
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
1878
 
1879
    $sql = "select zip from geoLocation where ip = '$ip'";
1880
 
1881
    if ($result = mysqli_query($conn, $sql)) {
1882
        if (mysqli_num_rows($result) == 1) {
1883
            if ($row = mysqli_fetch_assoc($result)) {
1884
                $_SESSION['buyer']['Zip'] = $row["zip"];
1885
                return;
1886
            }
1887
        }
1888
    }
1889
    else if (mysqli_errno($conn)) {
1890
        error_log("MySQL Read geoLocation SQL: " . $sql);
1891
        error_log("MySQL Read geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1892
    }
1893
 
1894
    $vendors = Vendors::getInstance();
1895
    $config = $vendors->getVendor(Vendors::IPAPI);
1896
    $key = $config['KEY'];
1897
 
1898
    $loc = file_get_contents("http://api.ipapi.com/api/" . $_SERVER['REMOTE_ADDR'] . "?access_key=" . $key);
1899
    if ($loc == false) {
1900
        return;
1901
    }
1902
 
1903
    $json = json_decode($loc);
1904
    if (!empty($json->error)) {
1905
        error_log("geoLocation Error: " . $json->error->info . " (" . $json->error->code . " | " . $json->error->type . ")");
1906
        return;
1907
    }
1908
 
1909
    $created = mysqli_real_escape_string($conn, time());
1910
    $countryCode = mysqli_real_escape_string($conn, $json->{'country_code'});
1911
    $zip = mysqli_real_escape_string($conn, $json->zip);
1912
    $language = mysqli_real_escape_string($conn, $json->location->languages[0]->code);
1913
    $is_eu = mysqli_real_escape_string($conn, $json->location->{'is_eu'} ? '1' : '0');
1914
 
1915
    $sql = "INSERT
1916
                INTO geoLocation
1917
                (ip, created, countryCode, zip, language, is_eu)
1918
                VALUES ('$ip', $created, '$countryCode', '$zip', '$language', '$is_eu')";
1919
 
1920
    if (!($result = mysqli_query($conn, $sql))) {
1921
        error_log("MySQL Write geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1922
    }
1923
}
1924
 
1925
function timeStampUrl($file) {
121 - 1926
    if (@file_exists($file)) {
109 - 1927
        return $file . "?" . filemtime($file);
1928
    }
127 - 1929
 
109 - 1930
    return $file;
108 - 1931
}
137 - 1932
 
1933
function my_trim($str) {
1934
    return (trim($str) . ($_SESSION["htmlIndent"] > 0 ? "\n" : ""));
1935
}
1936
 
1937
function buildDiscogsSearchTerm() {
138 - 1938
    if ($_SERVER["REQUEST_METHOD"] == "POST" || $_SERVER["REQUEST_METHOD"] == "GET") {
1939
        unset($_SESSION["advSearch"]);
1940
        $_SESSION["searchTerm"] = "";
1941
    }
137 - 1942
 
1943
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
1944
        if ($_POST["submitBtn"] == "Search") {
138 - 1945
            if (empty($_POST['searchTerm'])) {
1946
                return;
1947
            }
1948
 
1949
            if (strpos($_POST['searchTerm'], "*ADV*") === 0) {
1950
                $_SESSION["advSearch"] = [];
1951
                $_SESSION["searchTerm"] = "";
1952
                $arr = explode('|', substr($_POST['searchTerm'], 5));
1953
                foreach ($arr as $crit) {
1954
                    $s = explode(':', $crit);
1955
                    $_SESSION["searchTerm"] .= " " . $s[1];
137 - 1956
 
138 - 1957
                    if ($s[0] === "t") {
1958
                        $_SESSION["advSearch"]["Title"] = $s[1];
1959
                    }
1960
                    if ($s[0] === "a") {
1961
                        $_SESSION["advSearch"]["Artist"] = $s[1];
1962
                    }
1963
                    if ($s[0] === "tr") {
1964
                        $_SESSION["advSearch"]["Track"] = $s[1];
1965
                    }
1966
                    if ($s[0] === "b") {
1967
                        $_SESSION["advSearch"]["Barcode"] = $s[1];
1968
                    }
1969
                    if ($s[0] === "f") {
1970
                        $_SESSION["advSearch"]["Format"] = $s[1];
1971
                    }
1972
                    if ($s[0] === "c") {
1973
                        $_SESSION["advSearch"]["Catno"] = $s[1];
1974
                    }
1975
                    if ($s[0] === "l") {
1976
                        $_SESSION["advSearch"]["Label"] = $s[1];
1977
                    }
1978
                    if ($s[0] === "co") {
1979
                        $_SESSION["advSearch"]["Country"] = $s[1];
1980
                    }
1981
                    if ($s[0] === "y") {
1982
                        $_SESSION["advSearch"]["Year"] = $s[1];
1983
                    }
1984
                }
1985
                $_SESSION["searchTerm"] = trim($_SESSION["searchTerm"]);
1986
            } else {
1987
                $_SESSION["searchTerm"] = searchFriendlyString($_POST['searchTerm']);
1988
 
1989
                $barcodeType = clsLibGTIN::GTINCheck($_SESSION["searchTerm"], false, 1);
1990
                $barcodeValue = clsLibGTIN::GTINCheck($_SESSION["searchTerm"]);
1991
                if (!empty($barcodeType) && !empty($barcodeValue)) {
1992
                    $_SESSION["advSearch"]["Barcode"] = $barcodeValue;
1993
                }
137 - 1994
            }
1995
        } else if ($_POST["submitBtn"] == "advSearch") {
1996
            $_SESSION["searchTerm"] = searchFriendlyString($_POST["searchTerm"]);
1997
            $_SESSION["advSearch"] = [];
1998
            if (!empty($_POST["advTitle"])) {
1999
                $_SESSION["advSearch"]["Title"] = searchFriendlyString($_POST["advTitle"]);
2000
            }
2001
            if (!empty($_POST["advArtist"])) {
2002
                $_SESSION["advSearch"]["Artist"] = searchFriendlyString($_POST["advArtist"]);
2003
            }
2004
            if (!empty($_POST["advTrack"])) {
2005
                $_SESSION["advSearch"]["Track"] = searchFriendlyString($_POST["advTrack"]);
2006
            }
2007
            if (!empty($_POST["advBarcode"])) {
2008
                $_SESSION["advSearch"]["Barcode"] = searchFriendlyString($_POST["advBarcode"]);
2009
            }
2010
            if (!empty($_POST["advFormat"]) && $_POST["advFormat"] != "All") {
2011
                if (in_array($_POST["advFormat"], array("All", "CD", "Vinyl"))) {
2012
                    $_SESSION["advSearch"]["Format"] = $_POST["advFormat"];
2013
                }
2014
            }
2015
            if (!empty($_POST["advCatno"])) {
2016
                $_SESSION["advSearch"]["Catno"] = searchFriendlyString($_POST["advCatno"]);
2017
            }
2018
            if (!empty($_POST["advLabel"])) {
2019
                $_SESSION["advSearch"]["Label"] = searchFriendlyString($_POST["advLabel"]);
2020
            }
2021
            if (!empty($_POST["advCountry"])) {
2022
                $_SESSION["advSearch"]["Country"] = searchFriendlyString($_POST["advCountry"]);
2023
            }
2024
            if (!empty($_POST["advYear"])) {
2025
                $_SESSION["advSearch"]["Year"] = searchFriendlyString($_POST["advYear"]);
2026
            }
2027
        } else if ($_POST["submitBtn"] == "discogsSearch") {
2028
            if (!empty($_POST['discogsBarcode'])) {
2029
                $_SESSION["advSearch"]["Barcode"] = searchFriendlyString($_POST['discogsBarcode']);
2030
                $_SESSION["searchTerm"] = $_SESSION["advSearch"]["Barcode"];
2031
            }
2032
            else {
2033
                if (!empty($_POST['discogsTitle'])) {
2034
                    $_SESSION["advSearch"]["Title"] = searchFriendlyString($_POST['discogsTitle']);
2035
                }
2036
 
2037
                if (!empty($_POST['discogsArtist'])) {
2038
                    $_SESSION["advSearch"]["Artist"] = searchFriendlyString($_POST['discogsArtist']);
2039
                }
2040
 
2041
                $_SESSION["searchTerm"] = trim($_SESSION["advSearch"]["Title"] . " " . $_SESSION["advSearch"]["Artist"]);
2042
            }
2043
        }
2044
    } else if ($_SERVER["REQUEST_METHOD"] == "GET") {
2045
        $_SESSION["searchTerm"] = searchFriendlyString($_GET["q"] ?? "");
138 - 2046
 
2047
        $barcodeType = clsLibGTIN::GTINCheck($_SESSION["searchTerm"], false, 1);
2048
        $barcodeValue = clsLibGTIN::GTINCheck($_SESSION["searchTerm"]);
2049
        if (!empty($barcodeType) && !empty($barcodeValue)) {
2050
            $_SESSION["advSearch"]["Barcode"] = $barcodeValue;
2051
        }
2052
   }
137 - 2053
}