Subversion Repositories cheapmusic

Rev

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

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