Subversion Repositories cheapmusic

Rev

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