Subversion Repositories cheapmusic

Rev

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