Subversion Repositories cheapmusic

Rev

Rev 133 | Rev 136 | 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");
134 - 816
        $xh->add_attribute("name", "submitBtn");
127 - 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");
134 - 829
        $xh->add_attribute("name", "submitBtn");
127 - 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");
134 - 1029
    $xh->add_attribute("id", "detailTabSubmit");
127 - 1030
    $xh->add_attribute("class", "btn btn-success detailFilterButton");
134 - 1031
    $xh->add_attribute("name", "submitBtn");
127 - 1032
    $xh->add_attribute("value", "Apply");
1033
    $xh->tag('button', "Apply");
1034
    $xh->add_attribute("type", "submit");
134 - 1035
    $xh->add_attribute("id", "detailTabReset");
127 - 1036
    $xh->add_attribute("class", "btn btn-danger detailFilterButton");
134 - 1037
    $xh->add_attribute("name", "submitBtn");
127 - 1038
    $xh->add_attribute("value", "Reset");
1039
    $xh->tag('button', "Reset");
1040
    $xh->close(); // div
1041
    $xh->close(); // form
66 - 1042
 
127 - 1043
    $html = $xh->flush();
1044
    //error_log(print_r($html, 1));
1045
 
1046
    return $html;
5 - 1047
}
1 - 1048
 
65 - 1049
// compare price for sort low to high
1050
function compare_price($a, $b) {
1051
    return strnatcmp($a['ConvertedTotalPrice'], $b['ConvertedTotalPrice']);
5 - 1052
}
13 - 1053
 
65 - 1054
// print monetary values with correct symbol and thousands/decimal delimiters
1055
function print_monetary($num, $curr) {
1056
    if ($curr == "USD") {
1057
        return ("$" . number_format($num, 2, '.', ','));
1058
    }
1059
    else if ($curr == "CAD") {
1060
        return ("C $" . number_format($num, 2, '.', ','));
1061
    }
1062
    else if ($curr == "EUR") {
1063
        return (number_format($num, 2, ',', '.') . "&euro;");
1064
    }
1065
    else if ($curr == "GBP") {
1066
        return ("&pound;" . number_format($num, 2, '.', ','));
1067
    }
1068
    else if ($curr == "AUD") {
1069
        return ("AU $" . number_format($num, 2, '.', ','));
1070
    }
1 - 1071
 
65 - 1072
    return ($curr . " " . number_format($num, 2, '.', ','));
5 - 1073
}
1 - 1074
 
65 - 1075
// find lowest used / new prices
66 - 1076
function findLowestCondition($condition) {
65 - 1077
    foreach ($_SESSION["resultArr"] as $row) {
1078
        if (!$row["Show"]) {
1079
            continue;
1080
        }
1 - 1081
 
66 - 1082
        if ($condition == $row["Condition"]) {
65 - 1083
            return ($row["ConvertedTotalPrice"]);
1084
        }
1085
    }
5 - 1086
 
65 - 1087
    return (0);
5 - 1088
}
1089
 
65 - 1090
// find lowest cd, record, digital and book prices
66 - 1091
function findLowestMediaType($mediaType) {
65 - 1092
    foreach ($_SESSION["resultArr"] as $row) {
1093
        if (!$row["Show"]) {
1094
            continue;
1095
        }
20 - 1096
 
66 - 1097
        if ($mediaType == $row["MediaType"]) {
65 - 1098
            return ($row["ConvertedTotalPrice"]);
1099
        }
1100
    }
20 - 1101
 
65 - 1102
    return (0);
20 - 1103
}
1104
 
65 - 1105
// find lowest non-zero double value in array
1106
function minNotNull(Array $values) {
1107
    return min(array_diff(array_map('doubleval', $values) , array(
1108
 
1109
    )));
13 - 1110
}
11 - 1111
 
65 - 1112
// apply exchange rates
1113
function applyExchangeRates($arr) {
1114
    foreach ($arr as & $value) {
1115
        $value["ConvertedPrice"] = $value["Price"];
1116
        $value["ConvertedShippingCost"] = $value["ShippingCost"];
1 - 1117
 
65 - 1118
        if ($_SESSION["buyer"]["Currency"] != $value["Currency"]) {
1119
            $value["ConvertedPrice"] = number_format($value["Price"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["Currency"]) , 2, '.', '');
1120
        }
1 - 1121
 
65 - 1122
        if ($_SESSION["buyer"]["Currency"] != $value["ShippingCurrency"]) {
1123
            $value["ConvertedShippingCost"] = number_format($value["ShippingCost"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["ShippingCurrency"]) , 2, '.', '');
1124
        }
1 - 1125
 
65 - 1126
        $value["ConvertedTotalPrice"] = number_format($value["ConvertedPrice"] + $value["ConvertedShippingCost"], 2, '.', '');
1127
    }
5 - 1128
 
65 - 1129
    return ($arr);
5 - 1130
}
1131
 
36 - 1132
// sanitize user input
65 - 1133
function sanitizeInput($data) {
1134
    $data = trim(preg_replace('/[\t\n\r\s]+/', ' ', $data));
1135
    $data = stripslashes($data);
1136
    $data = htmlspecialchars($data);
1137
    return $data;
5 - 1138
}
1 - 1139
 
52 - 1140
// sanitize user input (plus delete apostrophe)
1141
function sanitizeInput2($data) {
65 - 1142
    $data = trim(preg_replace('/[\t\n\r\s\']+/', ' ', $data));
1143
    $data = stripslashes($data);
1144
    $data = htmlspecialchars($data, ENT_QUOTES | ENT_HTML5);
1145
    return $data;
52 - 1146
}
1147
 
14 - 1148
// convert certain utf-8 characters to ascii
1149
function cleanString($str) {
1150
    $utf8 = array(
65 - 1151
        '/[áàâãªä]/u' => 'a',
1152
        '/[ÁÀÂÃÄ]/u' => 'A',
1153
        '/[ÍÌÎÏ]/u' => 'I',
1154
        '/[íìîï]/u' => 'i',
1155
        '/[éèêë]/u' => 'e',
1156
        '/[ÉÈÊË]/u' => 'E',
1157
        '/[óòôõºö]/u' => 'o',
1158
        '/[ÓÒÔÕÖ]/u' => 'O',
1159
        '/[úùûü]/u' => 'u',
1160
        '/[ÚÙÛÜ]/u' => 'U',
1161
        '/ç/' => 'c',
1162
        '/Ç/' => 'C',
1163
        '/ñ/' => 'n',
1164
        '/Ñ/' => 'N',
1165
        '/–/' => '-', // UTF-8 hyphen to "normal" hyphen
1166
        '/[’‘‹›‚]/u' => ' ', // Literally a single quote
1167
        '/[“”«»„]/u' => ' ', // Double quote
1168
        '/ /' => ' ', // nonbreaking space (equiv. to 0x160)
66 - 1169
 
14 - 1170
    );
1171
 
65 - 1172
    return preg_replace(array_keys($utf8) , array_values($utf8) , $str);
14 - 1173
}
1174
 
1175
// Clean the search string
1176
function searchFriendlyString($str) {
1177
    $str = strip_tags($str);
1178
    $str = stripslashes($str);
1179
    $str = cleanString($str);
65 - 1180
    $str = str_replace(array(
1181
        "[",
1182
        "]",
1183
        "<",
1184
        ">",
1185
        "(",
1186
        ")",
1187
        " - ",
1188
        " & ",
1189
        " / "
1190
    ) , " ", $str); // eliminate single '-', '&', '/' and brackets
1191
    $str = trim(preg_replace('/[\t\n\r\s]+/', ' ', $str)); // delete extra whitespaces
14 - 1192
    return ucwords($str);
1193
}
1194
 
65 - 1195
// get a SESSION value, return empty string if not set
1196
function getSV($var) {
1197
    if (!isset($_SESSION[$var])) {
1198
        return ('');
1199
    }
1 - 1200
 
65 - 1201
    return ($_SESSION[$var]);
5 - 1202
}
1203
 
65 - 1204
// initialize a SESSION value if not set
1205
function initSV($var, $value) {
1206
    if (!isset($_SESSION[$var])) {
1207
        $_SESSION[$var] = $value;
1208
    }
5 - 1209
}
1 - 1210
 
65 - 1211
// initialize sessions variables
1212
function initSessionVariables() {
1213
    initSV("resultArr", []);
1214
    initSV("barcode", array(
1215
        "Type" => "",
1216
        "Value" => ""
1217
    ));
1218
    initSV("buyer", array(
1219
        "Country" => "United States",
1220
        "Currency" => "USD",
1221
        "Zip" => ""
1222
    ));
1223
    initSV("filterCondition", array(
1224
        "New" => true,
1225
        "Used" => true
1226
    ));
1227
    initSV("filterMediaType", array(
1228
        "CD" => true,
1229
        "Record" => true,
1230
        "Digital" => true,
1231
        "Book" => true
1232
    ));
1233
    initSV("currentLayout", "TableView");
1234
    initSV("lowestPrice", array(
1235
        "Used" => 0.00,
1236
        "New" => 0.00,
1237
        "CD" => 0.00,
1238
        "Record" => 0.00,
1239
        "Digital" => 0.00,
1240
        "Book" => "0.00",
1241
        "All" => 0.00
1242
    ));
5 - 1243
}
1244
 
14 - 1245
function md5SearchTerm() {
1246
    $data = array();
1247
    $data['cond'] = $_SESSION['filterCondition'];
1248
    $data['type'] = $_SESSION['filterMediaType'];
17 - 1249
    $data['buyer'] = $_SESSION['buyer'];
65 - 1250
    $data['term'] = array(
1251
        $_SESSION['searchTerm']
1252
    );
14 - 1253
 
65 - 1254
    return (md5(json_encode($data)));
14 - 1255
}
1256
 
65 - 1257
// check POST value, return true if set and false if not
1258
function checkPV($var) {
1259
    if (isset($_POST[$var])) {
1260
        return (true);
1261
    }
1 - 1262
 
65 - 1263
    return (false);
5 - 1264
}
1265
 
65 - 1266
// get POST or GET value, return empty if not set
1267
function getPGV($var) {
1268
    if (isset($_POST[$var])) {
1269
        return ($_POST[$var]);
1270
    }
1271
    else if (isset($_GET[$var])) {
1272
        return ($_GET[$var]);
1273
    }
14 - 1274
 
65 - 1275
    return ("");
14 - 1276
}
1277
 
65 - 1278
function saveSearchResult() {
1279
    $conn = MySessionHandler::getDBSessionId();
13 - 1280
 
65 - 1281
    $access = mysqli_real_escape_string($conn, time());
1282
    // BUGBUG
1283
    //  country
1284
    //  currency
1285
    $zip = mysqli_real_escape_string($conn, $_SESSION['buyer']['Zip']);
1286
    $condNew = $_SESSION['filterCondition']['New'] ? 'Y' : 'N';
1287
    $condUsed = $_SESSION['filterCondition']['Used'] ? 'Y' : 'N';
1288
    $mediaCD = $_SESSION['filterMediaType']['CD'] ? 'Y' : 'N';
1289
    $mediaRecord = $_SESSION['filterMediaType']['Record'] ? 'Y' : 'N';
1290
    $mediaDigital = $_SESSION['filterMediaType']['Digital'] ? 'Y' : 'N';
1291
    $mediaBook = $_SESSION['filterMediaType']['Book'] ? 'Y' : 'N';
1292
    $data = mysqli_real_escape_string($conn, $_SESSION['searchTerm']);
1293
    $lowNew = floatval($_SESSION['lowestPrice']['New']);
1294
    $lowUsed = floatval($_SESSION['lowestPrice']['Used']);
116 - 1295
    $lowCD = floatval($_SESSION['lowestPrice']['CD']);
1296
    $lowRecord = floatval($_SESSION['lowestPrice']['Record']);
65 - 1297
    $lowDigital = floatval($_SESSION['lowestPrice']['Digital']);
1298
    $lowBook = floatval($_SESSION['lowestPrice']['Book']);
1299
    $count = count($_SESSION['resultArr']);
1300
    $userId = (empty($_SESSION['sessData']['userID']) ? 'NULL' : $_SESSION['sessData']['userID']);
96 - 1301
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
8 - 1302
 
65 - 1303
    $sql = "INSERT
20 - 1304
                INTO searches
116 - 1305
                (sessId, access, ip, zip, condNew, condUsed, mediaCD, mediaRecord, mediaDigital, mediaBook, data, lowNew, lowUsed, lowCD, lowRecord, lowDigital, lowBook, count, userId)
1306
                VALUES ('" . session_id() . "', '$access', '$ip', '$zip', '$condNew', '$condUsed', '$mediaCD', '$mediaRecord', '$mediaDigital', '$mediaBook', '$data', $lowNew, $lowUsed, $lowCD, $lowRecord, $lowDigital, $lowBook, $count, $userId)";
8 - 1307
 
65 - 1308
    if (!($result = mysqli_query($conn, $sql))) {
1309
        error_log("MySQL Write Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1310
    }
13 - 1311
 
129 - 1312
 
1313
    return(mysqli_insert_id($conn));
65 - 1314
}
13 - 1315
 
17 - 1316
function getUrl($url, $userAgent = null) {
1317
    $ch = curl_init();
1318
 
1319
    // Set request header with language and charset
1320
    $header = array(
1321
        "Accept-Language: en-US,en;q=0.5",
1322
        "Accept-Charset: UTF-8,*;q=0.5"
1323
    );
1324
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1325
 
1326
    // Set optional user-agent
1327
    if ($userAgent) {
1328
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1329
    }
1330
 
1331
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1332
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1333
    curl_setopt($ch, CURLOPT_HEADER, 0);
84 - 1334
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1335
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
17 - 1336
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1337
    curl_setopt($ch, CURLOPT_URL, $url);
1338
    $response = curl_exec($ch);
1339
    if ($response === false) {
20 - 1340
        error_log('Curl Request Error: ' . curl_error($ch) . ' (' . curl_errno($ch) . ')');
1341
        error_log('Url: ' . $url);
17 - 1342
        $response = '';
1343
    }
23 - 1344
 
17 - 1345
    curl_close($ch);
1346
 
1347
    return $response;
1348
}
1349
 
129 - 1350
function getMultiUrl($urls, $userAgent = null) {
1351
    $multi = curl_multi_init();
1352
    $channels = [];
1353
    $response = [];
1354
    // Set request header with language and charset
1355
    $header = array(
1356
        "Accept-Language: en-US,en;q=0.5",
1357
        "Accept-Charset: UTF-8,*;q=0.5"
1358
    );
1359
 
1360
    // Loop through the URLs, create curl-handles
1361
    // and attach the handles to our multi-request
1362
    foreach ($urls as $url) {
1363
        $ch = curl_init();
1364
 
1365
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1366
 
1367
        // Set optional user-agent
1368
        if ($userAgent) {
1369
            curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1370
        }
1371
 
1372
        curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1373
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1374
        curl_setopt($ch, CURLOPT_HEADER, 0);
1375
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1376
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
1377
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1378
        curl_setopt($ch, CURLOPT_URL, $url);
1379
 
1380
        curl_multi_add_handle($multi, $ch);
1381
 
1382
        $channels[$url] = $ch;
1383
    }
1384
 
1385
    // While we're still active, execute curl
1386
    $active = null;
1387
    do {
1388
        $mrc = curl_multi_exec($multi, $active);
1389
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1390
 
1391
    while ($active && $mrc == CURLM_OK) {
1392
        // Wait for activity on any curl-connection
1393
        if (curl_multi_select($multi) == -1) {
1394
            continue;
1395
        }
1396
 
1397
        // Continue to exec until curl is ready to
1398
        // give us more data
1399
        do {
1400
            $mrc = curl_multi_exec($multi, $active);
1401
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
1402
    }
1403
 
1404
    // Loop through the channels and retrieve the received
1405
    // content, then remove the handle from the multi-handle
1406
    foreach ($channels as $url => $channel) {
1407
        $response[$url] = curl_multi_getcontent($channel);
1408
        if ($response[$url] === false) {
1409
            error_log('Curl Request Error: ' . curl_error($channel) . ' (' . curl_errno($channel) . ')');
1410
            error_log('Url: ' . $url);
1411
            $response[$url] = '';
1412
        }
1413
        curl_multi_remove_handle($multi, $channel);
1414
    }
1415
 
1416
    // Close the multi-handle and return our results
1417
    curl_multi_close($multi);
1418
 
1419
    return($response);
1420
}
1421
 
20 - 1422
// Retrieve search history for current session id
14 - 1423
function getSearchHistory() {
127 - 1424
    $xh = new Html;
1425
    $xh->init($_SESSION["htmlIndent"]);
1426
 
38 - 1427
    $sql = "select data, max(access) from searches where sessId = '" . session_id() . "'";
1428
    if (!empty($_SESSION['sessData']['userID'])) {
1429
        $sql .= " or userID = '" . $_SESSION['sessData']['userID'] . "'";
1430
    }
1431
    $sql .= " group by data order by max(access) desc, data limit 0,30;";
14 - 1432
    $conn = MySessionHandler::getDBSessionId();
1433
 
20 - 1434
    if ($result = mysqli_query($conn, $sql)) {
1435
        if (mysqli_num_rows($result) > 0) {
65 - 1436
            while ($row = mysqli_fetch_assoc($result)) {
127 - 1437
                $xh->tag("option", $row["data"]);
20 - 1438
            }
14 - 1439
        }
1440
    }
65 - 1441
    else if (mysqli_errno($conn)) {
1442
        error_log("MySQL Read Searches SQL: " . $sql);
1443
        error_log("MySQL Read Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1444
    }
14 - 1445
 
127 - 1446
    $html = $xh->flush();
1447
    //error_log(print_r($html, 1));
1448
 
1449
    return $html;
14 - 1450
}
1451
 
41 - 1452
// Retrieve coupons codes
1453
function getCouponCodes() {
1454
    $lastAdvertiser = "";
1455
 
127 - 1456
    $xh = new Html;
1457
    $xh->init($_SESSION["htmlIndent"]);
1458
 
41 - 1459
    if (!isLoggedIn()) {
127 - 1460
        $xh->add_attribute("class", "container bg-warning text-center py-3");
1461
        $xh->tag('div');
1462
            $xh->add_attribute("class", "display-6");
1463
            $xh->tag('p');
1464
                $xh->add_attribute("class", "material-icons");
1465
                $xh->tag('i', "error_outline");
1466
                $xh->tag('span', " Please login to your Find Cheap Music account in order to see the coupons.");
1467
            $xh->close(); // p
1468
        $xh->close(); // div
1469
 
1470
        $html = $xh->flush();
1471
       //error_log(print_r($html, 1));
1472
 
1473
        return $html;
41 - 1474
    }
1475
 
65 - 1476
    $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 - 1477
    $conn = MySessionHandler::getDBSessionId();
1478
 
1479
    if ($result = mysqli_query($conn, $sql)) {
1480
        if (mysqli_num_rows($result) > 0) {
127 - 1481
            $xh->add_attribute("class", "container py-4 border bg-light");
134 - 1482
            $xh->add_attribute("id", "couponList");
127 - 1483
            $xh->tag('div');
65 - 1484
            while ($row = mysqli_fetch_assoc($result)) {
1485
                if ($row["advertiser"] != $lastAdvertiser) {
41 - 1486
                    if (!empty($lastAdvertiser)) {
127 - 1487
                        $xh->close(); // ul
41 - 1488
                    }
127 - 1489
                    $xh->add_attribute("class", "text-center mt-3 mb-1");
1490
                    $xh->tag('h2', $row["advertiser"]);
1491
                    $xh->add_attribute("class", "list-group");
1492
                    $xh->tag('ul');
41 - 1493
                    $lastAdvertiser = $row["advertiser"];
1494
                }
51 - 1495
                if (!empty($row["url"])) {
127 - 1496
                    $xh->add_attribute("class", "list-group-item");
1497
                    $xh->tag('li');
134 - 1498
                        $xh->add_attribute("class", "btn btn-link text-left coupon-link");
127 - 1499
                        $xh->add_attribute("target", "_blank");
1500
                        $xh->add_attribute("href", htmlentities($row["url"]));
1501
                        $xh->add_attribute("rel", "nofollow noreferrer noopener");
134 - 1502
                        $xh->add_attribute("data-advertiser", $row["advertiser"]);
127 - 1503
                        $xh->tag('a');
1504
                            $str = '<strong>' . $row["description"] . '</strong> until ' . $row["enddate"];
1505
                            if (!empty($row["couponcode"])) {
1506
                                $str .= ' (Use Coupon Code "' . $row["couponcode"] . '")';
1507
                            }
1508
                            if (!empty($row["pixel"])) {
1509
                                $xh->add_attribute("class", "border-0 lazyload");
1510
                                $xh->add_attribute("src",PIXEL);
1511
                                $xh->add_attribute("data-src", htmlentities($row["pixel"]));
1512
                                $xh->add_attribute("width", "1");
1513
                                $xh->add_attribute("height", "1");
1514
                                $xh->add_attribute("alt", $row["advertiser"] . " Coupon");
1515
                                $xh->single_tag('img');
1516
                            }
1517
                            $xh->tag('span', $str);
1518
                        $xh->close(); // a
1519
                    $xh->close(); // li
41 - 1520
                }
1521
            }
127 - 1522
 
1523
            if (!empty($lastAdvertiser)) {
1524
                $xh->close(); // ul
1525
            }
134 - 1526
 
1527
    $xh->add_attribute("nonce", base64_encode($_SESSION["nonce"]));
1528
    $xh->tag('script');
1529
        $str  = trim('document.addEventListener("DOMContentLoaded", function() {');
1530
        $str .= trim('    document.getElementById("couponList").addEventListener("click", function(event) {');
1531
        $str .= trim('        e = event.target.closest("a");');
1532
        $str .= trim('        if (e && e.classList.contains("coupon-link")) {');
1533
        $str .= trim('            window.dataLayer.push({ "event" : "trackEvent", "eventCategory" : "Coupon", "eventAction" : "Click", "eventLabel" : e.getAttribute("data-advertiser")});');
1534
        $str .= trim('        }');
1535
        $str .= trim('    });');
1536
        $str .= trim('});');
1537
    $xh->insert_code($str);
1538
    $xh->close(); // script
1539
 
127 - 1540
            $xh->close(); // div
41 - 1541
        }
65 - 1542
    }
1543
    else if (mysqli_errno($conn)) {
127 - 1544
        $xh->add_attribute("class", "container bg-info text-center py-3");
1545
        $xh->tag('div');
1546
            $xh->add_attribute("class", "display-6");
1547
            $xh->tag('p');
1548
                $xh->add_attribute("class", "material-icons");
1549
                $xh->tag('i', "loyalty");
1550
                $xh->tag('span', " No Coupons available at the moment...");
1551
            $xh->close(); // p
1552
        $xh->close(); // div
41 - 1553
    }
1554
 
127 - 1555
    $html = $xh->flush();
1556
    //error_log(print_r($html, 1));
1557
 
1558
    return $html;
41 - 1559
}
1560
 
14 - 1561
// Delete left over progressbar files older than 2 days
1562
function cleanupPbFiles() {
84 - 1563
    $files = glob("../MyFiles/tmp/pb*.txt");
65 - 1564
    $now = time();
14 - 1565
    foreach ($files as $file) {
1566
        if (is_file($file)) {
1567
            if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days and older
1568
                unlink($file);
1569
            }
65 - 1570
        }
14 - 1571
    }
1572
}
1573
 
1574
// Update progressbar file for a session
129 - 1575
function updatePbFile($flag = false, $desc = null) {
1576
    static $max_pb = 10; // max progressbar steps
22 - 1577
    static $current = 0;
129 - 1578
    static $lastTime = 0;
1579
    static $startTime = 0;
1580
    static $timers = [];
23 - 1581
 
22 - 1582
    if ($flag) {
129 - 1583
        if ($desc == "Start") {
1584
            $current = 0;
1585
            $timers = [];
1586
            $startTime = $lastTime = microtime(true);
1587
        } else if (strpos($desc, "End:") === 0) {
1588
            $nowTime = microtime(true);
1589
            $timers["Total"] = intval(($nowTime - $startTime) * 1000);
1590
            $pieces = explode(":", $desc);
1591
            savePbTimers($timers, $pieces[1]);
1592
        }
65 - 1593
    }
1594
    else {
22 - 1595
        ++$current;
129 - 1596
        $nowTime = microtime(true);
1597
        $diffTime = $nowTime - $lastTime;
1598
        $lastTime = $nowTime;
1599
        $timers[$desc] = intval($diffTime * 1000);
1600
   }
22 - 1601
 
1602
    if ($current > $max_pb) {
1603
        error_log("max_pb $max_pb is too small, current step is $current. Adjust tools.php (updatePbFile).");
1604
        $max_pb = $current;
1605
    }
65 - 1606
    $filename = session_id() . "_" . MySessionHandler::getSessionTab();
14 - 1607
    $arr_content = array();
1608
 
20 - 1609
    $percent = intval($current / $max_pb * 100);
14 - 1610
 
1611
    $arr_content['percent'] = $percent;
1612
    $arr_content['message'] = $current . " search(es) processed.";
84 - 1613
    $file = "../MyFiles/tmp/pb_" . $filename . ".txt";
14 - 1614
 
77 - 1615
    if ($percent >= 100) {
1616
        @unlink($file);
1617
    } else {
1618
        file_put_contents($file, json_encode($arr_content));
1619
    }
14 - 1620
}
20 - 1621
 
1622
// Linkshare / CJ Affiliate csv dump
1623
function ls_cj_csv($fields) {
1624
    static $fh = null;
1625
    $delimiter = ',';
1626
    $enclosure = '"';
1627
    $mysql_null = false;
1628
 
1629
    if (!$fh) {
1630
        $fh = fopen("ls_cj.csv", "a+");
1631
    }
1632
 
1633
    $delimiter_esc = preg_quote($delimiter, '/');
1634
    $enclosure_esc = preg_quote($enclosure, '/');
1635
 
1636
    $output = array();
1637
    foreach ($fields as $field) {
1638
        if ($field === null && $mysql_null) {
1639
            $output[] = 'NULL';
1640
            continue;
1641
        }
1642
 
65 - 1643
        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure) : $field;
20 - 1644
    }
1645
 
1646
    fwrite($fh, join($delimiter, $output) . "\n");
1647
}
35 - 1648
 
1649
// Login in check
1650
function isLoggedIn() {
65 - 1651
    return (!empty($_SESSION['sessData']['userLoggedIn']) && !empty($_SESSION['sessData']['userID'])) ? true : false;
35 - 1652
}
1653
 
1654
// unset all login system session data
1655
function unsetSessData() {
1656
    unset($_SESSION['sessData']['userLoggedIn']);
1657
    unset($_SESSION['sessData']['userID']);
1658
    unset($_SESSION['sessData']['loginType']);
36 - 1659
}
1660
 
1661
// get user image name
1662
function getUserImage($userData) {
1663
    if (empty($userData) || empty($userData['picture'])) {
109 - 1664
        return 'login/assets/images/default.png';
36 - 1665
    }
38 - 1666
 
36 - 1667
    $httpPos = strpos($userData['picture'], 'http');
1668
    if ($httpPos === false) {
65 - 1669
        return 'login/' . UPLOAD_PATH . 'profile_picture/' . $userData['picture'];
36 - 1670
    }
1671
 
1672
    return $userData['picture'];
38 - 1673
}
39 - 1674
 
1675
function startsWith($haystack, $needle) {
1676
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
1677
}
1678
 
1679
function endsWith($haystack, $needle) {
1680
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
45 - 1681
}
50 - 1682
 
1683
function displayBarcode($barcode) {
1684
    $barcode = trim(preg_replace("/[^0-9]/", "", $barcode));
1685
    $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
1686
 
1687
    if ($barcodeType == "UPC" && strlen($barcode) == 12) {
1688
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 5) . "-" . substr($barcode, 6, 5) . "-" . substr($barcode, 11, 1);
65 - 1689
    }
1690
    else if (($barcodeType == "EAN" || $barcodeType == "ISBN") && strlen($barcode) == 13) {
50 - 1691
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 6) . "-" . substr($barcode, 7, 6);
65 - 1692
    }
1693
    else if ($barcodeType == "EAN" && strlen($barcode) == 14) {
50 - 1694
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 2) . "-" . substr($barcode, 3, 5) . "-" . substr($barcode, 8, 5) . "-" . substr($barcode, 13, 1);
65 - 1695
    }
1696
    else {
50 - 1697
        return $barcode;
1698
    }
52 - 1699
}
93 - 1700
 
1701
// fuzzy search to verify titles are relevant
1702
function verifyResultArr() {
1703
    require_once ('php/Fuse/Bitap/Bitap.php');
1704
    require_once ('php/Fuse/Bitap/matched_indices.php');
1705
    require_once ('php/Fuse/Bitap/pattern_alphabet.php');
1706
    require_once ('php/Fuse/Bitap/regex_search.php');
1707
    require_once ('php/Fuse/Bitap/score.php');
1708
    require_once ('php/Fuse/Bitap/search.php');
1709
    require_once ('php/Fuse/Helpers/deep_value.php');
1710
    require_once ('php/Fuse/Helpers/is_list.php');
1711
    require_once ('php/Fuse/Fuse.php');
1712
 
1713
    if (!empty($_SESSION["barcode"]["Value"]) || empty($_SESSION["resultArr"])) {
1714
        return;
1715
    }
1716
 
1717
    $options = [
1718
      'shouldSort' => false,
1719
    //  'tokenize' => true,
1720
    //  'matchAllTokens' => true,
1721
    //  'findAllMatches' => true,
1722
      'includeScore' => true,
1723
      'includeMatches' => true,
1724
      'threshold' => 0.6,
1725
      'location' => 0,
1726
      'distance' => 100,
1727
      'minMatchCharLength' => 5,
1728
      'keys' => [ "Title" ]
1729
    ];
1730
 
1731
    $fuse = new Fuse($_SESSION["resultArr"], $options);
1732
    $result = $fuse->search($_SESSION["searchTerm"]);
1733
 
1734
    $_SESSION["resultArr"] = [];
1735
    foreach($result as $r) {
97 - 1736
        $r['item']['score'] = (!empty($r['score']) ? $r['score'] : 0);
1737
        $r['item']['indices'] = (!empty($r['matches'][0]['indices']) ? $r['matches'][0]['indices'] : []);
93 - 1738
        $_SESSION['resultArr'][] = $r['item'];
1739
    }
1740
 
1741
    /* debug start
1742
    $lines = [];
1743
    foreach($_SESSION['resultArr'] as $r) {
1744
        $p = 0;
1745
        $t = '';
1746
        foreach($r['indices'] as $ind) {
1747
            if ($p < $ind[0]) {
1748
                $t .= substr($r['Title'], $p, $ind[0] - $p);
1749
            }
1750
            $t .= "<b>" . substr($r['Title'], $ind[0], $ind[1] - $ind[0] + 1) . "</b>";
1751
            $p = $ind[1] + 1;
1752
        }
1753
        if ($p < strlen($r['Title'])) {
1754
            $t .= substr($r['Title'], $p);
1755
        }
1756
        $lines[] = array ('score' => $r['score'], 'title' => $t);
1757
    }
1758
 
1759
    usort($lines, 'compare_score');
1760
    echo "<p>";
1761
    foreach($lines as $l) {
1762
        echo $l['score'] . ": " . $l['title'] . "<br/>";
1763
    }
1764
    echo "</p>";
1765
    debug end */
1766
}
1767
 
1768
// compare score for sort low to high
1769
function compare_score($a, $b) {
1770
    return ($a['score'] > $b['score']);
1771
}
96 - 1772
 
1773
function my_error_log($msg) {
1774
    error_log("[" . date("d-M-Y H:m:s") . "] " . $msg . PHP_EOL, 3, $_SERVER['DOCUMENT_ROOT'] . "/../MyFiles/logs/my_php_error.log");
1775
}
99 - 1776
 
129 - 1777
function savePbTimers($timers, $id) {
1778
    $conn = MySessionHandler::getDBSessionId();
1779
 
1780
    $sql = "INSERT
1781
                INTO searchPerformance
1782
                (id, Discogs, eBay_New, Linkshare, CJ_Affiliate, Walmart, iTunes, Amazon_API, Amazon_Scrape, Impact, eBay_Used, Total)
1783
                VALUES ($id, " . $timers['Discogs'] . ",
1784
" . $timers['eBay New'] . ",
1785
" . $timers['Linkshare'] . ",
1786
" . $timers['CJ Affiliate'] . ",
1787
" . $timers['Walmart'] . ",
1788
" . $timers['iTunes'] . ",
1789
" . $timers['Amazon API'] . ",
1790
" . $timers['Amazon Scrape'] . ",
1791
" . $timers['Impact'] . ",
1792
" . $timers['eBay Used'] . ",
1793
" . $timers['Total'] . ")";
1794
 
1795
    if (!($result = mysqli_query($conn, $sql))) {
1796
        error_log("MySQL Write SearchPerformance Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1797
    }
1798
 
1799
    return $result;
1800
}
1801
 
99 - 1802
function saveSearchCache($vendor, $query, $subquery, $text) {
1803
    $conn = MySessionHandler::getDBSessionId();
1804
 
1805
    $created = mysqli_real_escape_string($conn, time());
1806
    $v = mysqli_real_escape_string($conn, $vendor);
1807
    $q = mysqli_real_escape_string($conn, $query);
1808
    $s = mysqli_real_escape_string($conn, $subquery);
1809
    $r = base64_encode(gzencode($text));
1810
 
1811
    $sql = "INSERT
1812
                INTO searchCache
1813
                (created, vendor, query, subquery, result)
110 - 1814
                VALUES ('$created', '$v', '$q', '$s', '$r')
1815
                ON DUPLICATE KEY UPDATE result = '$r'";
99 - 1816
 
1817
    if (!($result = mysqli_query($conn, $sql))) {
1818
        error_log("MySQL Write SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1819
    }
1820
 
1821
    return $result;
1822
}
1823
 
1824
 
1825
function expireSearchCache() {
1826
    $conn = MySessionHandler::getDBSessionId();
1827
    $t = MySessionHandler::getDBExpirationTime();
1828
 
1829
    $expired = mysqli_real_escape_string($conn, time() - $t);
1830
 
1831
    $sql = "DELETE
1832
                FROM searchCache
1833
                WHERE created < $expired";
1834
 
1835
    if (!($result = mysqli_query($conn, $sql))) {
1836
        error_log("MySQL Delete SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1837
    }
1838
}
1839
 
1840
function getSearchCache($vendor, $query, $subquery) {
1841
    $conn = MySessionHandler::getDBSessionId();
1842
 
1843
    $v = mysqli_real_escape_string($conn, $vendor);
1844
    $q = mysqli_real_escape_string($conn, $query);
1845
    $s = mysqli_real_escape_string($conn, $subquery);
1846
    $sql = "select result from searchCache where vendor = '$v' and query = '$q' and subquery = '$s'";
1847
 
1848
    if ($result = mysqli_query($conn, $sql)) {
1849
        if (mysqli_num_rows($result) == 1) {
1850
            if ($row = mysqli_fetch_assoc($result)) {
1851
                return gzdecode(base64_decode($row["result"]));
1852
            }
1853
        }
1854
    }
1855
    else if (mysqli_errno($conn)) {
1856
        error_log("MySQL Read SearchCache SQL: " . $sql);
1857
        error_log("MySQL Read SearchCache Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1858
    }
1859
 
1860
    return false;
104 - 1861
}
107 - 1862
 
1863
 
1864
function getGeoLocation() {
1865
    if (!empty($_SESSION['buyer']['Zip']) || empty($_SERVER['REMOTE_ADDR'])) {
1866
        return;
1867
    }
1868
 
1869
    $conn = MySessionHandler::getDBSessionId();
1870
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
1871
 
1872
    $sql = "select zip from geoLocation where ip = '$ip'";
1873
 
1874
    if ($result = mysqli_query($conn, $sql)) {
1875
        if (mysqli_num_rows($result) == 1) {
1876
            if ($row = mysqli_fetch_assoc($result)) {
1877
                $_SESSION['buyer']['Zip'] = $row["zip"];
1878
                return;
1879
            }
1880
        }
1881
    }
1882
    else if (mysqli_errno($conn)) {
1883
        error_log("MySQL Read geoLocation SQL: " . $sql);
1884
        error_log("MySQL Read geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1885
    }
1886
 
1887
    $vendors = Vendors::getInstance();
1888
    $config = $vendors->getVendor(Vendors::IPAPI);
1889
    $key = $config['KEY'];
1890
 
1891
    $loc = file_get_contents("http://api.ipapi.com/api/" . $_SERVER['REMOTE_ADDR'] . "?access_key=" . $key);
1892
    if ($loc == false) {
1893
        return;
1894
    }
1895
 
1896
    $json = json_decode($loc);
1897
    if (!empty($json->error)) {
1898
        error_log("geoLocation Error: " . $json->error->info . " (" . $json->error->code . " | " . $json->error->type . ")");
1899
        return;
1900
    }
1901
 
1902
    $created = mysqli_real_escape_string($conn, time());
1903
    $countryCode = mysqli_real_escape_string($conn, $json->{'country_code'});
1904
    $zip = mysqli_real_escape_string($conn, $json->zip);
1905
    $language = mysqli_real_escape_string($conn, $json->location->languages[0]->code);
1906
    $is_eu = mysqli_real_escape_string($conn, $json->location->{'is_eu'} ? '1' : '0');
1907
 
1908
    $sql = "INSERT
1909
                INTO geoLocation
1910
                (ip, created, countryCode, zip, language, is_eu)
1911
                VALUES ('$ip', $created, '$countryCode', '$zip', '$language', '$is_eu')";
1912
 
1913
    if (!($result = mysqli_query($conn, $sql))) {
1914
        error_log("MySQL Write geoLocation Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1915
    }
1916
}
1917
 
1918
function timeStampUrl($file) {
121 - 1919
    if (@file_exists($file)) {
109 - 1920
        return $file . "?" . filemtime($file);
1921
    }
127 - 1922
 
109 - 1923
    return $file;
108 - 1924
}