Subversion Repositories cheapmusic

Rev

Rev 153 | Rev 156 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 - 1
<?php
93 - 2
use Fuse\Fuse;
65 - 3
include_once ('php/clsLibGTIN.php');
4
include_once ('php/exchangeRates.php');
5
include_once ('php/countryCodes.php');
6
include_once ('php/constants.php');
7
include_once ('php/ebay.php');
8
include_once ('php/discogs.php');
9
include_once ('php/linkshare.php');
10
include_once ('php/cjaffiliate.php');
11
include_once ('php/walmart.php');
12
include_once ('php/itunes.php');
81 - 13
include_once ('php/amazon.php');
91 - 14
include_once ('php/amazon_scrape.php');
83 - 15
include_once ('php/impact.php');
99 - 16
include_once ('php/sessions_db.php');
116 - 17
include_once ('php/media.php');
127 - 18
include_once ('php/class.html.php');
19
include_once ('php/htmlTools.php');
1 - 20
 
20 - 21
error_reporting(E_ALL);
22
 
65 - 23
// search
141 - 24
function performSearch($noDiscogs = false) {
25
    $currentMd5SearchTerm = md5SearchTerm($noDiscogs);
116 - 26
    if (isset($_SESSION['md5LastSearch']) && $currentMd5SearchTerm == $_SESSION['md5LastSearch']) {
14 - 27
        return;
28
    }
29
    $_SESSION['md5LastSearch'] = $currentMd5SearchTerm;
81 - 30
 
129 - 31
    updatePbFile(true, "Start");
22 - 32
 
107 - 33
    getGeoLocation();
34
 
141 - 35
    if ($noDiscogs === false) {
36
        findDiscogsMaster();
37
    }
129 - 38
    updatePbFile(false, "Discogs");
81 - 39
 
65 - 40
    $_SESSION["resultArr"] = [];
99 - 41
    expireSearchCache();
137 - 42
    $_SESSION["resultArr"] = searchAll();
93 - 43
 
99 - 44
    verifyResultArr();
93 - 45
 
65 - 46
    $_SESSION["resultArr"] = applySearchFilter($_SESSION["resultArr"]);
5 - 47
 
65 - 48
    //echo "<pre>";print_r($_SESSION["resultArr"]);echo "</pre>";
66 - 49
    $_SESSION["lowestPrice"]["Used"] = findLowestCondition("Used");
50
    $_SESSION["lowestPrice"]["New"] = findLowestCondition("New");
51
    $_SESSION["lowestPrice"]["CD"] = findLowestMediaType("CD");
52
    $_SESSION["lowestPrice"]["Record"] = findLowestMediaType("Record");
53
    $_SESSION["lowestPrice"]["Digital"] = findLowestMediaType("Digital");
54
    $_SESSION["lowestPrice"]["Book"] = findLowestMediaType("Book");
65 - 55
    $_SESSION["lowestPrice"]["All"] = 0.00;
56
    if (array_sum($_SESSION["lowestPrice"]) > 0) {
57
        $_SESSION["lowestPrice"]["All"] = minNotNull($_SESSION["lowestPrice"]);
58
    }
13 - 59
 
141 - 60
    $aiVal = saveSearchResult($noDiscogs);
137 - 61
 
129 - 62
    updatePbFile(true, "End:$aiVal");
5 - 63
}
64
 
65 - 65
// search for items on all sites
137 - 66
function searchAll($batchFlag = false) {
67
    $searchKey = $_SESSION["searchTerm"];
65 - 68
    $arr = [];
69
    if ($_SESSION["filterCondition"]["New"]) {
129 - 70
        get_vendor($arr, 'get_ebay', $searchKey, constant("NEW"));
65 - 71
    }
129 - 72
    if (!$batchFlag) { updatePbFile(false, "eBay New"); }
65 - 73
    if ($_SESSION["filterCondition"]["New"]) {
129 - 74
        get_vendor($arr, 'get_linkshare', $searchKey, constant("NEW"));
65 - 75
    }
129 - 76
    if (!$batchFlag) { updatePbFile(false, "Linkshare"); }
65 - 77
    if ($_SESSION["filterCondition"]["New"]) {
129 - 78
        get_vendor($arr, 'get_cjaffiliate', $searchKey, constant("NEW"));
65 - 79
    }
129 - 80
    if (!$batchFlag) { updatePbFile(false, "CJ Affiliate"); }
65 - 81
    if ($_SESSION["filterCondition"]["New"]) {
129 - 82
        get_vendor($arr, 'get_walmart', $searchKey, constant("NEW"));
65 - 83
    }
129 - 84
    if (!$batchFlag) { updatePbFile(false, "Walmart"); }
65 - 85
    if ($_SESSION["filterCondition"]["New"]) {
129 - 86
        get_vendor($arr, 'get_itunes', $searchKey, constant("NEW"));
65 - 87
    }
129 - 88
    if (!$batchFlag) { updatePbFile(false, "iTunes"); }
17 - 89
 
91 - 90
    $cntArr = count($arr);
129 - 91
    get_vendor($arr, 'get_amazon', $searchKey, constant("NEW"));
92
    if (!$batchFlag) { updatePbFile(false, "Amazon API"); }
91 - 93
    if ($cntArr == count($arr)) {
129 - 94
        get_vendor($arr, 'get_amazon_scrape', $searchKey, constant("NEW"));
91 - 95
    }
129 - 96
    if (!$batchFlag) { updatePbFile(false, "Amazon Scrape"); }
81 - 97
 
129 - 98
    get_vendor($arr, 'get_impact', $searchKey, constant("NEW"));
99
    if (!$batchFlag) { updatePbFile(false, "Impact"); }
83 - 100
 
65 - 101
    if ($_SESSION["filterCondition"]["Used"]) {
129 - 102
        get_vendor($arr, 'get_ebay', $searchKey, constant("USED"));
65 - 103
    }
129 - 104
    if (!$batchFlag) { updatePbFile(false, "eBay Used"); }
17 - 105
 
66 - 106
//echo "<pre>";print_r($arr);echo "</pre";
24 - 107
 
65 - 108
    $arr = applyExchangeRates($arr);
109
    usort($arr, 'compare_price');
5 - 110
 
65 - 111
    return $arr;
5 - 112
}
113
 
20 - 114
// Search and merge
129 - 115
function get_vendor(&$arr, $func, $searchKey, $condition) {
65 - 116
    $arrTemp = $func($searchKey, $condition);
129 - 117
    foreach($arrTemp as $value) {
118
        $arr[] = $value;
119
    }
20 - 120
}
121
 
21 - 122
// delete results from array that do not match the search filters
123
function applySearchFilter($arr) {
66 - 124
    unset($_SESSION['AdditionalFilterCounters']);
125
    unset($_SESSION['AdditionalFilters']);
65 - 126
    foreach ($arr as $key => $row) {
66 - 127
        if (!$_SESSION["filterMediaType"][$row["MediaType"]] || !$_SESSION["filterCondition"][$row["Condition"]]) {
21 - 128
            unset($arr[$key]);
66 - 129
        } else {
130
            if (isset($_SESSION['AdditionalFilterCounters']['Condition']['All'])) {
131
                $_SESSION['AdditionalFilterCounters']['Condition']['All']++;
132
            } else {
133
                $_SESSION['AdditionalFilterCounters']['Condition']['All'] = 1;
134
            }
135
 
136
            if (isset($_SESSION['AdditionalFilterCounters']['Merchant'][$row['Merchant']])) {
137
                $_SESSION['AdditionalFilterCounters']['Merchant'][$row['Merchant']]++;
138
            } else {
139
                $_SESSION['AdditionalFilterCounters']['Merchant'][$row['Merchant']] = 1;
140
                $_SESSION['AdditionalFilters']['Merchant'][$row['Merchant']] = true;
141
            }
142
 
143
            if (!empty($row['SellerName'])) {
144
                if (isset($_SESSION['AdditionalFilterCounters']['Seller'][$row['SellerName']])) {
145
                    $_SESSION['AdditionalFilterCounters']['Seller'][$row['SellerName']]++;
146
                } else {
147
                    $_SESSION['AdditionalFilterCounters']['Seller'][$row['SellerName']] = 1;
148
                    $_SESSION['AdditionalFilters']['Seller'][$row['SellerName']] = true;
149
                }
150
            }
151
 
152
            if (isset($_SESSION['AdditionalFilterCounters']['Condition'][$row['Condition']])) {
153
                $_SESSION['AdditionalFilterCounters']['Condition'][$row['Condition']]++;
154
            } else {
155
                $_SESSION['AdditionalFilterCounters']['Condition'][$row['Condition']] = 1;
156
                $_SESSION['AdditionalFilters']['Condition'][$row['Condition']] = true;
157
            }
158
 
159
            if (isset($_SESSION['AdditionalFilterCounters']['MediaType'][$row['MediaType']])) {
160
                $_SESSION['AdditionalFilterCounters']['MediaType'][$row['MediaType']]++;
161
            } else {
162
                $_SESSION['AdditionalFilterCounters']['MediaType'][$row['MediaType']] = 1;
163
                $_SESSION['AdditionalFilters']['MediaType'][$row['MediaType']] = true;
164
            }
165
 
166
            if (isset($_SESSION['AdditionalFilterCounters']['DetailCondition'][$row['DetailCondition']])) {
167
                $_SESSION['AdditionalFilterCounters']['DetailCondition'][$row['DetailCondition']]++;
168
            } else {
169
                $_SESSION['AdditionalFilterCounters']['DetailCondition'][$row['DetailCondition']] = 1;
170
                $_SESSION['AdditionalFilters']['DetailCondition'][$row['DetailCondition']] = true;
171
            }
172
 
173
            if (isset($_SESSION['AdditionalFilterCounters']['ShippingFrom'][$row['Country']])) {
174
                $_SESSION['AdditionalFilterCounters']['ShippingFrom'][$row['Country']]++;
175
            } else {
176
                $_SESSION['AdditionalFilterCounters']['ShippingFrom'][$row['Country']] = 1;
177
                $_SESSION['AdditionalFilters']['ShippingFrom'][$row['Country']] = true;
178
            }
65 - 179
        }
180
    }
23 - 181
 
66 - 182
    if (isset($_SESSION['AdditionalFilters']['Merchant'])) {
183
        ksort($_SESSION['AdditionalFilters']['Merchant'], SORT_NATURAL | SORT_FLAG_CASE);
184
    }
185
 
186
    if (isset($_SESSION['AdditionalFilters']['Seller'])) {
187
        ksort($_SESSION['AdditionalFilters']['Seller'], SORT_NATURAL | SORT_FLAG_CASE);
188
    }
189
 
190
    if (isset($_SESSION['AdditionalFilters']['Condition'])) {
191
        ksort($_SESSION['AdditionalFilters']['Condition'], SORT_NATURAL | SORT_FLAG_CASE);
192
    }
193
 
194
    if (isset($_SESSION['AdditionalFilters']['DetailCondition'])) {
195
        ksort($_SESSION['AdditionalFilters']['DetailCondition'], SORT_NATURAL | SORT_FLAG_CASE);
196
    }
197
 
198
    if (isset($_SESSION['AdditionalFilters']['ShippingFrom'])) {
199
        ksort($_SESSION['AdditionalFilters']['ShippingFrom'], SORT_NATURAL | SORT_FLAG_CASE);
200
    }
201
 
202
    if (isset($_SESSION['AdditionalFilters']['MediaType'])) {
203
        ksort($_SESSION['AdditionalFilters']['MediaType'], SORT_NATURAL | SORT_FLAG_CASE);
204
    }
205
 
21 - 206
    return $arr;
207
}
208
 
66 - 209
// filter view result table $_SESSION["resultArr"] for detailed filter selection
210
function detailFilterResults($selArr) {
67 - 211
    if (!empty($selArr['filterCondition'])) {
212
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
213
            $_SESSION['AdditionalFilters']['Condition'][$key] = false;
214
        }
215
        if (!is_array($selArr['filterCondition'])) { $selArr['filterCondition'] = [ $selArr['filterCondition'] ];}
216
        foreach($selArr['filterCondition'] as $value) {
217
            $_SESSION['AdditionalFilters']['Condition'][$value] = true;
218
        }
219
    } else {
68 - 220
        $selArr['filterCondition'] = [];
77 - 221
        if (!empty($_SESSION['AdditionalFilters']['Condition'])) {
222
            foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
223
                if ($value) {
224
                    $selArr['filterCondition'][] = $key;
225
                }
68 - 226
            }
227
        }
66 - 228
    }
229
 
67 - 230
    if (!empty($selArr['filterMediaType'])) {
231
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
232
            $_SESSION['AdditionalFilters']['MediaType'][$key] = false;
233
        }
234
        if (!is_array($selArr['filterMediaType'])) { $selArr['filterMediaType'] = [ $selArr['filterMediaType'] ];}
235
        foreach($selArr['filterMediaType'] as $value) {
236
            $_SESSION['AdditionalFilters']['MediaType'][$value] = true;
237
        }
238
    } else {
68 - 239
        $selArr['filterMediaType'] = [];
77 - 240
        if (!empty($_SESSION['AdditionalFilters']['MediaType'])) {
241
            foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
242
                if ($value) {
243
                    $selArr['filterMediaType'][] = $key;
244
                }
68 - 245
            }
246
        }
66 - 247
    }
248
 
67 - 249
    if (!empty($selArr['filterShipFrom'])) {
250
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
251
            $_SESSION['AdditionalFilters']['ShippingFrom'][$key] = false;
252
        }
253
        if (!is_array($selArr['filterShipFrom'])) { $selArr['filterShipFrom'] = [ $selArr['filterShipFrom'] ];}
254
        foreach($selArr['filterShipFrom'] as $value) {
255
            $_SESSION['AdditionalFilters']['ShippingFrom'][$value] = true;
256
        }
257
    } else {
68 - 258
        $selArr['filterShipFrom'] = [];
77 - 259
        if (!empty($_SESSION['AdditionalFilters']['ShippingFrom'])) {
260
            foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
261
                if ($value) {
262
                    $selArr['filterShipFrom'][] = $key;
263
                }
68 - 264
            }
265
        }
66 - 266
    }
267
 
67 - 268
    if (!empty($selArr['filterMerchant'])) {
269
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
270
            $_SESSION['AdditionalFilters']['Merchant'][$key] = false;
271
        }
272
        if (!is_array($selArr['filterMerchant'])) { $selArr['filterMerchant'] = [ $selArr['filterMerchant'] ];}
273
        foreach($selArr['filterMerchant'] as $value) {
274
            $_SESSION['AdditionalFilters']['Merchant'][$value] = true;
275
        }
276
    } else {
68 - 277
        $selArr['filterMerchant'] = [];
77 - 278
        if (!empty($_SESSION['AdditionalFilters']['Merchant'])) {
279
            foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
280
                if ($value) {
281
                    $selArr['filterMerchant'][] = $key;
282
                }
68 - 283
            }
284
        }
66 - 285
    }
286
 
287
    foreach ($_SESSION["resultArr"] as & $row) {
288
        $row["Show"] = true;
289
 
290
        if (!in_array($row["Condition"], $selArr['filterCondition']) ||
291
            !in_array($row["MediaType"], $selArr['filterMediaType']) ||
292
            !in_array($row["Merchant"], $selArr['filterMerchant']) ||
293
            !in_array($row["Country"], $selArr['filterShipFrom'])) {
294
            $row["Show"] = false;
295
        }
296
    }
297
}
298
 
299
function resetDetailFilter() {
300
    if (isset($_SESSION['AdditionalFilters']['Merchant'])) {
301
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $field) {
302
            $_SESSION['AdditionalFilters']['Merchant'][$key] = true;
303
        }
304
    }
305
 
306
    if (isset($_SESSION['AdditionalFilters']['Seller'])) {
307
        foreach($_SESSION['AdditionalFilters']['Seller'] as $key => $field) {
308
            $_SESSION['AdditionalFilters']['Seller'][$key] = true;
309
        }
310
    }
311
 
312
    if (isset($_SESSION['AdditionalFilters']['Condition'])) {
313
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $field) {
314
            $_SESSION['AdditionalFilters']['Condition'][$key] = true;
315
        }
316
    }
317
 
318
    if (isset($_SESSION['AdditionalFilters']['DetailCondition'])) {
319
        foreach($_SESSION['AdditionalFilters']['DetailCondition'] as $key => $field) {
320
            $_SESSION['AdditionalFilters']['DetailCondition'][$key] = true;
321
        }
322
    }
323
 
324
    if (isset($_SESSION['AdditionalFilters']['ShippingFrom'])) {
325
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $field) {
326
            $_SESSION['AdditionalFilters']['ShippingFrom'][$key] = true;
327
        }
328
    }
329
 
330
    if (isset($_SESSION['AdditionalFilters']['MediaType'])) {
331
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $field) {
332
            $_SESSION['AdditionalFilters']['MediaType'][$key] = true;
333
        }
334
    }
107 - 335
 
66 - 336
    foreach ($_SESSION["resultArr"] as & $row) {
337
        $row["Show"] = true;
338
    }
339
}
340
 
65 - 341
// print result table or card deck
59 - 342
function printResult() {
343
    if ($_SESSION["currentLayout"] == 'TableView') {
78 - 344
        return buildTable($_SESSION["resultArr"]);
65 - 345
    }
346
    else /* CardView */ {
78 - 347
        return buildCardDeck($_SESSION["resultArr"]);
59 - 348
    }
349
}
350
 
65 - 351
// build HTML table from array
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
 
1403
        curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1404
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1405
        curl_setopt($ch, CURLOPT_HEADER, 0);
1406
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1407
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
1408
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1409
        curl_setopt($ch, CURLOPT_URL, $url);
137 - 1410
 
129 - 1411
        curl_multi_add_handle($multi, $ch);
137 - 1412
 
129 - 1413
        $channels[$url] = $ch;
1414
    }
137 - 1415
 
129 - 1416
    // While we're still active, execute curl
1417
    $active = null;
1418
    do {
1419
        $mrc = curl_multi_exec($multi, $active);
1420
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
137 - 1421
 
129 - 1422
    while ($active && $mrc == CURLM_OK) {
1423
        // Wait for activity on any curl-connection
1424
        if (curl_multi_select($multi) == -1) {
1425
            continue;
1426
        }
137 - 1427
 
138 - 1428
        // Continue to exec until curl is ready to give us more data
129 - 1429
        do {
1430
            $mrc = curl_multi_exec($multi, $active);
1431
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1432
    }
137 - 1433
 
129 - 1434
    // Loop through the channels and retrieve the received
1435
    // content, then remove the handle from the multi-handle
1436
    foreach ($channels as $url => $channel) {
1437
        $response[$url] = curl_multi_getcontent($channel);
1438
        if ($response[$url] === false) {
1439
            error_log('Curl Request Error: ' . curl_error($channel) . ' (' . curl_errno($channel) . ')');
1440
            error_log('Url: ' . $url);
1441
            $response[$url] = '';
1442
        }
1443
        curl_multi_remove_handle($multi, $channel);
1444
    }
137 - 1445
 
129 - 1446
    // Close the multi-handle and return our results
1447
    curl_multi_close($multi);
1448
 
1449
    return($response);
1450
}
1451
 
20 - 1452
// Retrieve search history for current session id
14 - 1453
function getSearchHistory() {
127 - 1454
    $xh = new Html;
1455
    $xh->init($_SESSION["htmlIndent"]);
1456
 
141 - 1457
    $sql = "select searchTerm, advSearchTerm, max(access) from searches where onlyStore <> 'Y' and (sessId = '" . session_id() . "'";
38 - 1458
    if (!empty($_SESSION['sessData']['userID'])) {
1459
        $sql .= " or userID = '" . $_SESSION['sessData']['userID'] . "'";
1460
    }
141 - 1461
    $sql .= ") group by searchTerm order by max(access) desc, searchTerm limit 0,50;";
14 - 1462
    $conn = MySessionHandler::getDBSessionId();
1463
 
20 - 1464
    if ($result = mysqli_query($conn, $sql)) {
1465
        if (mysqli_num_rows($result) > 0) {
65 - 1466
            while ($row = mysqli_fetch_assoc($result)) {
138 - 1467
                $xh->add_attribute("value", $row["advSearchTerm"] ? "*ADV*" . $row["advSearchTerm"] : $row["searchTerm"]);
1468
                $xh->tag("option", $row["searchTerm"]);
20 - 1469
            }
14 - 1470
        }
1471
    }
65 - 1472
    else if (mysqli_errno($conn)) {
1473
        error_log("MySQL Read Searches SQL: " . $sql);
1474
        error_log("MySQL Read Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1475
    }
14 - 1476
 
127 - 1477
    $html = $xh->flush();
1478
    //error_log(print_r($html, 1));
1479
 
1480
    return $html;
14 - 1481
}
1482
 
41 - 1483
// Retrieve coupons codes
1484
function getCouponCodes() {
1485
    $lastAdvertiser = "";
1486
 
127 - 1487
    $xh = new Html;
1488
    $xh->init($_SESSION["htmlIndent"]);
1489
 
41 - 1490
    if (!isLoggedIn()) {
127 - 1491
        $xh->add_attribute("class", "container bg-warning text-center py-3");
1492
        $xh->tag('div');
1493
            $xh->add_attribute("class", "display-6");
1494
            $xh->tag('p');
1495
                $xh->add_attribute("class", "material-icons");
1496
                $xh->tag('i', "error_outline");
1497
                $xh->tag('span', " Please login to your Find Cheap Music account in order to see the coupons.");
1498
            $xh->close(); // p
1499
        $xh->close(); // div
1500
 
1501
        $html = $xh->flush();
1502
       //error_log(print_r($html, 1));
1503
 
1504
        return $html;
41 - 1505
    }
1506
 
144 - 1507
    $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 - 1508
    $conn = MySessionHandler::getDBSessionId();
1509
 
1510
    if ($result = mysqli_query($conn, $sql)) {
1511
        if (mysqli_num_rows($result) > 0) {
127 - 1512
            $xh->add_attribute("class", "container py-4 border bg-light");
134 - 1513
            $xh->add_attribute("id", "couponList");
127 - 1514
            $xh->tag('div');
65 - 1515
            while ($row = mysqli_fetch_assoc($result)) {
1516
                if ($row["advertiser"] != $lastAdvertiser) {
41 - 1517
                    if (!empty($lastAdvertiser)) {
127 - 1518
                        $xh->close(); // ul
41 - 1519
                    }
127 - 1520
                    $xh->add_attribute("class", "text-center mt-3 mb-1");
1521
                    $xh->tag('h2', $row["advertiser"]);
1522
                    $xh->add_attribute("class", "list-group");
1523
                    $xh->tag('ul');
41 - 1524
                    $lastAdvertiser = $row["advertiser"];
1525
                }
51 - 1526
                if (!empty($row["url"])) {
127 - 1527
                    $xh->add_attribute("class", "list-group-item");
1528
                    $xh->tag('li');
144 - 1529
                        $xh->add_attribute("class", "container btn btn-link text-center coupon-link");
127 - 1530
                        $xh->add_attribute("target", "_blank");
1531
                        $xh->add_attribute("href", htmlentities($row["url"]));
1532
                        $xh->add_attribute("rel", "nofollow noreferrer noopener");
134 - 1533
                        $xh->add_attribute("data-advertiser", $row["advertiser"]);
127 - 1534
                        $xh->tag('a');
144 - 1535
                            $str = '<strong>' . $row["description"];
127 - 1536
                            if (!empty($row["couponcode"])) {
1537
                                $str .= ' (Use Coupon Code "' . $row["couponcode"] . '")';
1538
                            }
144 - 1539
                            $str .= '</strong>';
1540
                            $xh->tag('div', $str);
1541
                            if (!empty($row["image"])) {
1542
                                $xh->add_attribute("class", "text-center mt-3");
1543
                                $xh->tag('div');
1544
                                    $xh->add_attribute("class", "border-0 lazyload");
1545
                                    $xh->add_attribute("src", PIXEL);
1546
                                    $xh->add_attribute("data-src", htmlentities($row["image"]));
1547
                                    $xh->add_attribute("alt", $row["advertiser"] . " Coupon");
1548
                                    $xh->single_tag('img');
1549
                                $xh->close(); // div
127 - 1550
                            }
1551
                        $xh->close(); // a
1552
                    $xh->close(); // li
41 - 1553
                }
1554
            }
137 - 1555
 
127 - 1556
            if (!empty($lastAdvertiser)) {
1557
                $xh->close(); // ul
1558
            }
134 - 1559
 
1560
    $xh->add_attribute("nonce", base64_encode($_SESSION["nonce"]));
1561
    $xh->tag('script');
137 - 1562
        $str  = my_trim('document.addEventListener("DOMContentLoaded", function() {');
1563
        $str .= my_trim('    document.getElementById("couponList").addEventListener("click", function(event) {');
1564
        $str .= my_trim('        e = event.target.closest("a");');
1565
        $str .= my_trim('        if (e && e.classList.contains("coupon-link")) {');
1566
        $str .= my_trim('            window.dataLayer.push({ "event" : "trackEvent", "eventCategory" : "Coupon", "eventAction" : "Click", "eventLabel" : e.getAttribute("data-advertiser")});');
1567
        $str .= my_trim('        }');
1568
        $str .= my_trim('    });');
1569
        $str .= my_trim('});');
134 - 1570
    $xh->insert_code($str);
1571
    $xh->close(); // script
1572
 
127 - 1573
            $xh->close(); // div
41 - 1574
        }
65 - 1575
    }
1576
    else if (mysqli_errno($conn)) {
127 - 1577
        $xh->add_attribute("class", "container bg-info text-center py-3");
1578
        $xh->tag('div');
1579
            $xh->add_attribute("class", "display-6");
1580
            $xh->tag('p');
1581
                $xh->add_attribute("class", "material-icons");
1582
                $xh->tag('i', "loyalty");
1583
                $xh->tag('span', " No Coupons available at the moment...");
1584
            $xh->close(); // p
1585
        $xh->close(); // div
41 - 1586
    }
1587
 
127 - 1588
    $html = $xh->flush();
1589
    //error_log(print_r($html, 1));
1590
 
1591
    return $html;
41 - 1592
}
1593
 
14 - 1594
// Delete left over progressbar files older than 2 days
1595
function cleanupPbFiles() {
153 - 1596
    $files = glob(TMP_DIR . "pb*.txt");
65 - 1597
    $now = time();
14 - 1598
    foreach ($files as $file) {
1599
        if (is_file($file)) {
1600
            if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days and older
1601
                unlink($file);
1602
            }
65 - 1603
        }
14 - 1604
    }
1605
}
1606
 
1607
// Update progressbar file for a session
129 - 1608
function updatePbFile($flag = false, $desc = null) {
1609
    static $max_pb = 10; // max progressbar steps
22 - 1610
    static $current = 0;
129 - 1611
    static $lastTime = 0;
1612
    static $startTime = 0;
1613
    static $timers = [];
23 - 1614
 
22 - 1615
    if ($flag) {
129 - 1616
        if ($desc == "Start") {
1617
            $current = 0;
1618
            $timers = [];
1619
            $startTime = $lastTime = microtime(true);
1620
        } else if (strpos($desc, "End:") === 0) {
1621
            $nowTime = microtime(true);
1622
            $timers["Total"] = intval(($nowTime - $startTime) * 1000);
1623
            $pieces = explode(":", $desc);
1624
            savePbTimers($timers, $pieces[1]);
1625
        }
65 - 1626
    }
1627
    else {
22 - 1628
        ++$current;
129 - 1629
        $nowTime = microtime(true);
1630
        $diffTime = $nowTime - $lastTime;
1631
        $lastTime = $nowTime;
1632
        $timers[$desc] = intval($diffTime * 1000);
1633
   }
22 - 1634
 
1635
    if ($current > $max_pb) {
1636
        error_log("max_pb $max_pb is too small, current step is $current. Adjust tools.php (updatePbFile).");
1637
        $max_pb = $current;
1638
    }
65 - 1639
    $filename = session_id() . "_" . MySessionHandler::getSessionTab();
14 - 1640
    $arr_content = array();
1641
 
20 - 1642
    $percent = intval($current / $max_pb * 100);
14 - 1643
 
1644
    $arr_content['percent'] = $percent;
1645
    $arr_content['message'] = $current . " search(es) processed.";
153 - 1646
    $file = TMP_DIR . "pb_" . $filename . ".txt";
14 - 1647
 
77 - 1648
    if ($percent >= 100) {
1649
        @unlink($file);
1650
    } else {
1651
        file_put_contents($file, json_encode($arr_content));
1652
    }
14 - 1653
}
20 - 1654
 
1655
// Linkshare / CJ Affiliate csv dump
1656
function ls_cj_csv($fields) {
1657
    static $fh = null;
1658
    $delimiter = ',';
1659
    $enclosure = '"';
1660
    $mysql_null = false;
1661
 
1662
    if (!$fh) {
1663
        $fh = fopen("ls_cj.csv", "a+");
1664
    }
1665
 
1666
    $delimiter_esc = preg_quote($delimiter, '/');
1667
    $enclosure_esc = preg_quote($enclosure, '/');
1668
 
1669
    $output = array();
1670
    foreach ($fields as $field) {
1671
        if ($field === null && $mysql_null) {
1672
            $output[] = 'NULL';
1673
            continue;
1674
        }
1675
 
65 - 1676
        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure) : $field;
20 - 1677
    }
1678
 
1679
    fwrite($fh, join($delimiter, $output) . "\n");
1680
}
35 - 1681
 
1682
// Login in check
1683
function isLoggedIn() {
65 - 1684
    return (!empty($_SESSION['sessData']['userLoggedIn']) && !empty($_SESSION['sessData']['userID'])) ? true : false;
35 - 1685
}
1686
 
1687
// unset all login system session data
1688
function unsetSessData() {
1689
    unset($_SESSION['sessData']['userLoggedIn']);
1690
    unset($_SESSION['sessData']['userID']);
1691
    unset($_SESSION['sessData']['loginType']);
36 - 1692
}
1693
 
1694
// get user image name
1695
function getUserImage($userData) {
1696
    if (empty($userData) || empty($userData['picture'])) {
109 - 1697
        return 'login/assets/images/default.png';
36 - 1698
    }
38 - 1699
 
36 - 1700
    $httpPos = strpos($userData['picture'], 'http');
1701
    if ($httpPos === false) {
65 - 1702
        return 'login/' . UPLOAD_PATH . 'profile_picture/' . $userData['picture'];
36 - 1703
    }
1704
 
1705
    return $userData['picture'];
38 - 1706
}
39 - 1707
 
1708
function startsWith($haystack, $needle) {
1709
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
1710
}
1711
 
1712
function endsWith($haystack, $needle) {
1713
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
45 - 1714
}
50 - 1715
 
1716
function displayBarcode($barcode) {
1717
    $barcode = trim(preg_replace("/[^0-9]/", "", $barcode));
1718
    $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
1719
 
1720
    if ($barcodeType == "UPC" && strlen($barcode) == 12) {
1721
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 5) . "-" . substr($barcode, 6, 5) . "-" . substr($barcode, 11, 1);
65 - 1722
    }
1723
    else if (($barcodeType == "EAN" || $barcodeType == "ISBN") && strlen($barcode) == 13) {
50 - 1724
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 6) . "-" . substr($barcode, 7, 6);
65 - 1725
    }
1726
    else if ($barcodeType == "EAN" && strlen($barcode) == 14) {
50 - 1727
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 2) . "-" . substr($barcode, 3, 5) . "-" . substr($barcode, 8, 5) . "-" . substr($barcode, 13, 1);
65 - 1728
    }
1729
    else {
50 - 1730
        return $barcode;
1731
    }
52 - 1732
}
93 - 1733
 
1734
// fuzzy search to verify titles are relevant
1735
function verifyResultArr() {
1736
    require_once ('php/Fuse/Bitap/Bitap.php');
1737
    require_once ('php/Fuse/Bitap/matched_indices.php');
1738
    require_once ('php/Fuse/Bitap/pattern_alphabet.php');
1739
    require_once ('php/Fuse/Bitap/regex_search.php');
1740
    require_once ('php/Fuse/Bitap/score.php');
1741
    require_once ('php/Fuse/Bitap/search.php');
1742
    require_once ('php/Fuse/Helpers/deep_value.php');
1743
    require_once ('php/Fuse/Helpers/is_list.php');
1744
    require_once ('php/Fuse/Fuse.php');
1745
 
137 - 1746
    if (!empty($_SESSION["advSearch"]["Barcode"]) || empty($_SESSION["resultArr"]) || empty($_SESSION["searchTerm"])) {
93 - 1747
        return;
1748
    }
1749
 
1750
    $options = [
1751
      'shouldSort' => false,
1752
    //  'tokenize' => true,
1753
    //  'matchAllTokens' => true,
1754
    //  'findAllMatches' => true,
1755
      'includeScore' => true,
1756
      'includeMatches' => true,
1757
      'threshold' => 0.6,
1758
      'location' => 0,
1759
      'distance' => 100,
1760
      'minMatchCharLength' => 5,
1761
      'keys' => [ "Title" ]
1762
    ];
1763
 
1764
    $fuse = new Fuse($_SESSION["resultArr"], $options);
1765
    $result = $fuse->search($_SESSION["searchTerm"]);
1766
 
1767
    $_SESSION["resultArr"] = [];
1768
    foreach($result as $r) {
97 - 1769
        $r['item']['score'] = (!empty($r['score']) ? $r['score'] : 0);
1770
        $r['item']['indices'] = (!empty($r['matches'][0]['indices']) ? $r['matches'][0]['indices'] : []);
93 - 1771
        $_SESSION['resultArr'][] = $r['item'];
1772
    }
1773
 
1774
    /* debug start
1775
    $lines = [];
1776
    foreach($_SESSION['resultArr'] as $r) {
1777
        $p = 0;
1778
        $t = '';
1779
        foreach($r['indices'] as $ind) {
1780
            if ($p < $ind[0]) {
1781
                $t .= substr($r['Title'], $p, $ind[0] - $p);
1782
            }
1783
            $t .= "<b>" . substr($r['Title'], $ind[0], $ind[1] - $ind[0] + 1) . "</b>";
1784
            $p = $ind[1] + 1;
1785
        }
1786
        if ($p < strlen($r['Title'])) {
1787
            $t .= substr($r['Title'], $p);
1788
        }
1789
        $lines[] = array ('score' => $r['score'], 'title' => $t);
1790
    }
1791
 
1792
    usort($lines, 'compare_score');
1793
    echo "<p>";
1794
    foreach($lines as $l) {
1795
        echo $l['score'] . ": " . $l['title'] . "<br/>";
1796
    }
1797
    echo "</p>";
1798
    debug end */
1799
}
1800
 
1801
// compare score for sort low to high
1802
function compare_score($a, $b) {
1803
    return ($a['score'] > $b['score']);
1804
}
96 - 1805
 
1806
function my_error_log($msg) {
153 - 1807
    error_log("[" . date("d-M-Y H:m:s") . "] " . $msg . PHP_EOL, 3, LOG_DIR . "my_php_error.log");
96 - 1808
}
99 - 1809
 
129 - 1810
function savePbTimers($timers, $id) {
1811
    $conn = MySessionHandler::getDBSessionId();
1812
 
1813
    $sql = "INSERT
1814
                INTO searchPerformance
1815
                (id, Discogs, eBay_New, Linkshare, CJ_Affiliate, Walmart, iTunes, Amazon_API, Amazon_Scrape, Impact, eBay_Used, Total)
1816
                VALUES ($id, " . $timers['Discogs'] . ",
1817
" . $timers['eBay New'] . ",
1818
" . $timers['Linkshare'] . ",
1819
" . $timers['CJ Affiliate'] . ",
1820
" . $timers['Walmart'] . ",
1821
" . $timers['iTunes'] . ",
1822
" . $timers['Amazon API'] . ",
1823
" . $timers['Amazon Scrape'] . ",
1824
" . $timers['Impact'] . ",
1825
" . $timers['eBay Used'] . ",
1826
" . $timers['Total'] . ")";
1827
 
1828
    if (!($result = mysqli_query($conn, $sql))) {
1829
        error_log("MySQL Write SearchPerformance Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1830
    }
1831
 
1832
    return $result;
1833
}
1834
 
99 - 1835
function saveSearchCache($vendor, $query, $subquery, $text) {
1836
    $conn = MySessionHandler::getDBSessionId();
1837
 
1838
    $created = mysqli_real_escape_string($conn, time());
1839
    $v = mysqli_real_escape_string($conn, $vendor);
1840
    $q = mysqli_real_escape_string($conn, $query);
1841
    $s = mysqli_real_escape_string($conn, $subquery);
1842
    $r = base64_encode(gzencode($text));
1843
 
1844
    $sql = "INSERT
1845
                INTO searchCache
1846
                (created, vendor, query, subquery, result)
110 - 1847
                VALUES ('$created', '$v', '$q', '$s', '$r')
1848
                ON DUPLICATE KEY UPDATE result = '$r'";
99 - 1849
 
1850
    if (!($result = mysqli_query($conn, $sql))) {
1851
        error_log("MySQL Write SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1852
    }
1853
 
1854
    return $result;
1855
}
1856
 
1857
 
1858
function expireSearchCache() {
1859
    $conn = MySessionHandler::getDBSessionId();
1860
    $t = MySessionHandler::getDBExpirationTime();
1861
 
1862
    $expired = mysqli_real_escape_string($conn, time() - $t);
1863
 
1864
    $sql = "DELETE
1865
                FROM searchCache
1866
                WHERE created < $expired";
1867
 
1868
    if (!($result = mysqli_query($conn, $sql))) {
1869
        error_log("MySQL Delete SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1870
    }
1871
}
1872
 
1873
function getSearchCache($vendor, $query, $subquery) {
1874
    $conn = MySessionHandler::getDBSessionId();
1875
 
1876
    $v = mysqli_real_escape_string($conn, $vendor);
1877
    $q = mysqli_real_escape_string($conn, $query);
1878
    $s = mysqli_real_escape_string($conn, $subquery);
1879
    $sql = "select result from searchCache where vendor = '$v' and query = '$q' and subquery = '$s'";
1880
 
1881
    if ($result = mysqli_query($conn, $sql)) {
1882
        if (mysqli_num_rows($result) == 1) {
1883
            if ($row = mysqli_fetch_assoc($result)) {
1884
                return gzdecode(base64_decode($row["result"]));
1885
            }
1886
        }
1887
    }
1888
    else if (mysqli_errno($conn)) {
1889
        error_log("MySQL Read SearchCache SQL: " . $sql);
1890
        error_log("MySQL Read SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1891
    }
1892
 
1893
    return false;
104 - 1894
}
107 - 1895
 
1896
 
1897
function getGeoLocation() {
1898
    if (!empty($_SESSION['buyer']['Zip']) || empty($_SERVER['REMOTE_ADDR'])) {
1899
        return;
1900
    }
1901
 
1902
    $conn = MySessionHandler::getDBSessionId();
1903
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
1904
 
154 - 1905
    $sql = "select zip from geoLocation where ip = ?";
1906
    $stmt = mysqli_prepare($conn, $sql);
1907
    mysqli_stmt_bind_param($stmt, 's', $ip);
107 - 1908
 
154 - 1909
    if (mysqli_stmt_execute($stmt)) {
1910
        mysqli_stmt_bind_result($stmt, $zip);
1911
        mysqli_stmt_fetch($stmt);
1912
        if (!empty($zip)) {
1913
            $_SESSION['buyer']['Zip'] = $zip;
1914
            return;
107 - 1915
        }
1916
    }
1917
    else if (mysqli_errno($conn)) {
1918
        error_log("MySQL Read geoLocation SQL: " . $sql);
1919
        error_log("MySQL Read geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1920
    }
1921
 
154 - 1922
    mysqli_stmt_close($stmt);
1923
 
107 - 1924
    $vendors = Vendors::getInstance();
1925
    $config = $vendors->getVendor(Vendors::IPAPI);
1926
    $key = $config['KEY'];
1927
 
1928
    $loc = file_get_contents("http://api.ipapi.com/api/" . $_SERVER['REMOTE_ADDR'] . "?access_key=" . $key);
1929
    if ($loc == false) {
1930
        return;
1931
    }
1932
 
1933
    $json = json_decode($loc);
1934
    if (!empty($json->error)) {
1935
        error_log("geoLocation Error: " . $json->error->info . " (" . $json->error->code . " | " . $json->error->type . ")");
1936
        return;
1937
    }
1938
 
1939
    $created = mysqli_real_escape_string($conn, time());
1940
    $countryCode = mysqli_real_escape_string($conn, $json->{'country_code'});
1941
    $zip = mysqli_real_escape_string($conn, $json->zip);
1942
    $language = mysqli_real_escape_string($conn, $json->location->languages[0]->code);
154 - 1943
    $is_eu = $json->location->{'is_eu'} ? '1' : '0';
107 - 1944
 
1945
    $sql = "INSERT
1946
                INTO geoLocation
1947
                (ip, created, countryCode, zip, language, is_eu)
154 - 1948
                VALUES (?, ?, ?, ?, ?, ?)";
107 - 1949
 
154 - 1950
    $stmt = mysqli_prepare($conn, $sql);
1951
    mysqli_stmt_bind_param($stmt, 'sdssss', $ip, $created, $countryCode, $zip, $language, $is_eu);
1952
 
1953
    if (!($result = mysqli_stmt_execute($stmt))) {
1954
        error_log("MySQL Write geoLocation SQL: " . $sql);
107 - 1955
        error_log("MySQL Write geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1956
    }
154 - 1957
 
1958
    mysqli_stmt_close($stmt);
107 - 1959
}
1960
 
1961
function timeStampUrl($file) {
121 - 1962
    if (@file_exists($file)) {
109 - 1963
        return $file . "?" . filemtime($file);
1964
    }
127 - 1965
 
109 - 1966
    return $file;
108 - 1967
}
137 - 1968
 
1969
function my_trim($str) {
1970
    return (trim($str) . ($_SESSION["htmlIndent"] > 0 ? "\n" : ""));
1971
}
1972
 
1973
function buildDiscogsSearchTerm() {
138 - 1974
    if ($_SERVER["REQUEST_METHOD"] == "POST" || $_SERVER["REQUEST_METHOD"] == "GET") {
1975
        unset($_SESSION["advSearch"]);
1976
        $_SESSION["searchTerm"] = "";
141 - 1977
        $_SESSION["advSearchTerm"] = "";
138 - 1978
    }
137 - 1979
 
1980
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
1981
        if ($_POST["submitBtn"] == "Search") {
138 - 1982
            if (empty($_POST['searchTerm'])) {
1983
                return;
1984
            }
154 - 1985
 
141 - 1986
            if (strpos($_POST["searchTerm"], "*ADV*") === 0) {
1987
                $_SESSION["advSearchTerm"] = substr($_POST["searchTerm"], 5);
138 - 1988
                $_SESSION["advSearch"] = [];
1989
                $_SESSION["searchTerm"] = "";
141 - 1990
                $arr = explode(AS_TOKEN, $_SESSION["advSearchTerm"], 5);
138 - 1991
                foreach ($arr as $crit) {
141 - 1992
                    $s = explode(AS_FIELD, $crit);
138 - 1993
                    $_SESSION["searchTerm"] .= " " . $s[1];
137 - 1994
 
138 - 1995
                    if ($s[0] === "t") {
1996
                        $_SESSION["advSearch"]["Title"] = $s[1];
141 - 1997
                    } else if ($s[0] === "a") {
138 - 1998
                        $_SESSION["advSearch"]["Artist"] = $s[1];
141 - 1999
                    } else if ($s[0] === "tr") {
138 - 2000
                        $_SESSION["advSearch"]["Track"] = $s[1];
141 - 2001
                    } else if ($s[0] === "b") {
138 - 2002
                        $_SESSION["advSearch"]["Barcode"] = $s[1];
141 - 2003
                    } else if ($s[0] === "c") {
138 - 2004
                        $_SESSION["advSearch"]["Catno"] = $s[1];
141 - 2005
                    } else if ($s[0] === "l") {
138 - 2006
                        $_SESSION["advSearch"]["Label"] = $s[1];
141 - 2007
                    } else if ($s[0] === "co") {
138 - 2008
                        $_SESSION["advSearch"]["Country"] = $s[1];
141 - 2009
                    } else if ($s[0] === "y") {
138 - 2010
                        $_SESSION["advSearch"]["Year"] = $s[1];
2011
                    }
2012
                }
2013
                $_SESSION["searchTerm"] = trim($_SESSION["searchTerm"]);
2014
            } else {
2015
                $_SESSION["searchTerm"] = searchFriendlyString($_POST['searchTerm']);
2016
 
2017
                $barcodeType = clsLibGTIN::GTINCheck($_SESSION["searchTerm"], false, 1);
2018
                $barcodeValue = clsLibGTIN::GTINCheck($_SESSION["searchTerm"]);
2019
                if (!empty($barcodeType) && !empty($barcodeValue)) {
2020
                    $_SESSION["advSearch"]["Barcode"] = $barcodeValue;
141 - 2021
                    $_SESSION["advSearchTerm"] = "b" . AS_FIELD . $barcodeValue;
138 - 2022
                }
137 - 2023
            }
2024
        } else if ($_POST["submitBtn"] == "advSearch") {
2025
            $_SESSION["searchTerm"] = searchFriendlyString($_POST["searchTerm"]);
2026
            $_SESSION["advSearch"] = [];
141 - 2027
            $arr = [];
137 - 2028
            if (!empty($_POST["advTitle"])) {
2029
                $_SESSION["advSearch"]["Title"] = searchFriendlyString($_POST["advTitle"]);
141 - 2030
                $arr[] = "t" . AS_FIELD . $_SESSION["advSearch"]["Title"];
137 - 2031
            }
2032
            if (!empty($_POST["advArtist"])) {
2033
                $_SESSION["advSearch"]["Artist"] = searchFriendlyString($_POST["advArtist"]);
141 - 2034
                $arr[] = "a" . AS_FIELD . $_SESSION["advSearch"]["Artist"];
137 - 2035
            }
2036
            if (!empty($_POST["advTrack"])) {
2037
                $_SESSION["advSearch"]["Track"] = searchFriendlyString($_POST["advTrack"]);
141 - 2038
                $arr[] = "tr" . AS_FIELD . $_SESSION["advSearch"]["Track"];
137 - 2039
            }
2040
            if (!empty($_POST["advBarcode"])) {
2041
                $_SESSION["advSearch"]["Barcode"] = searchFriendlyString($_POST["advBarcode"]);
141 - 2042
                $arr[] = "b" . AS_FIELD . $_SESSION["advSearch"]["Barcode"];
137 - 2043
            }
2044
            if (!empty($_POST["advCatno"])) {
2045
                $_SESSION["advSearch"]["Catno"] = searchFriendlyString($_POST["advCatno"]);
141 - 2046
                $arr[] = "c" . AS_FIELD . $_SESSION["advSearch"]["Catno"];
137 - 2047
            }
2048
            if (!empty($_POST["advLabel"])) {
2049
                $_SESSION["advSearch"]["Label"] = searchFriendlyString($_POST["advLabel"]);
141 - 2050
                $arr[] = "l" . AS_FIELD . $_SESSION["advSearch"]["Label"];
137 - 2051
            }
2052
            if (!empty($_POST["advCountry"])) {
2053
                $_SESSION["advSearch"]["Country"] = searchFriendlyString($_POST["advCountry"]);
141 - 2054
                $arr[] = "co" . AS_FIELD . $_SESSION["advSearch"]["Country"];
137 - 2055
            }
2056
            if (!empty($_POST["advYear"])) {
2057
                $_SESSION["advSearch"]["Year"] = searchFriendlyString($_POST["advYear"]);
141 - 2058
                $arr[] = "y" . AS_FIELD . $_SESSION["advSearch"]["Year"];
137 - 2059
            }
141 - 2060
            $_SESSION["advSearchTerm"] = join(AS_TOKEN, $arr);
137 - 2061
        } else if ($_POST["submitBtn"] == "discogsSearch") {
141 - 2062
            if (!empty($_POST['discogsBarcode']) && empty($_POST['discogsTitle']) && empty($_POST['discogsArtist'])) {
137 - 2063
                $_SESSION["advSearch"]["Barcode"] = searchFriendlyString($_POST['discogsBarcode']);
2064
                $_SESSION["searchTerm"] = $_SESSION["advSearch"]["Barcode"];
141 - 2065
                $_SESSION["advSearchTerm"] = "b" . AS_FIELD . $_SESSION["searchTerm"];
137 - 2066
            }
141 - 2067
            else
2068
             {
2069
                $_SESSION["searchTerm"] = "";
2070
                $arr = [];
137 - 2071
                if (!empty($_POST['discogsTitle'])) {
2072
                    $_SESSION["advSearch"]["Title"] = searchFriendlyString($_POST['discogsTitle']);
141 - 2073
                    $arr[] = "t" . AS_FIELD . $_SESSION["advSearch"]["Title"];
2074
                    $_SESSION["searchTerm"] .= trim($_SESSION["advSearch"]["Title"]);
137 - 2075
                }
2076
 
141 - 2077
                if (!empty($_POST['discogsTitle']) && !empty($_POST['discogsArtist'])) {
2078
                    $_SESSION["searchTerm"] .= " ";
2079
                }
2080
 
137 - 2081
                if (!empty($_POST['discogsArtist'])) {
2082
                    $_SESSION["advSearch"]["Artist"] = searchFriendlyString($_POST['discogsArtist']);
141 - 2083
                    $arr[] = "a" . AS_FIELD . $_SESSION["advSearch"]["Artist"];
2084
                    $_SESSION["searchTerm"] .= trim($_SESSION["advSearch"]["Artist"]);
137 - 2085
                }
2086
 
141 - 2087
                $_SESSION["advSearchTerm"] = join(AS_TOKEN, $arr);
137 - 2088
            }
2089
        }
2090
    } else if ($_SERVER["REQUEST_METHOD"] == "GET") {
2091
        $_SESSION["searchTerm"] = searchFriendlyString($_GET["q"] ?? "");
154 - 2092
 
138 - 2093
        $barcodeType = clsLibGTIN::GTINCheck($_SESSION["searchTerm"], false, 1);
2094
        $barcodeValue = clsLibGTIN::GTINCheck($_SESSION["searchTerm"]);
2095
        if (!empty($barcodeType) && !empty($barcodeValue)) {
2096
            $_SESSION["advSearch"]["Barcode"] = $barcodeValue;
141 - 2097
            $_SESSION["advSearchTerm"] = "b" . AS_FIELD . $barcodeValue;
138 - 2098
        }
2099
   }
153 - 2100
}