Subversion Repositories cheapmusic

Rev

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