Subversion Repositories cheapmusic

Rev

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

Rev Author Line No. Line
1 - 1
<?php
65 - 2
include_once ('php/clsLibGTIN.php');
3
include_once ('php/exchangeRates.php');
4
include_once ('php/countryCodes.php');
5
include_once ('php/constants.php');
6
include_once ('php/ebay.php');
7
include_once ('php/discogs.php');
8
include_once ('php/linkshare.php');
9
include_once ('php/cjaffiliate.php');
10
include_once ('php/walmart.php');
11
include_once ('php/itunes.php');
81 - 12
include_once ('php/amazon.php');
1 - 13
 
20 - 14
error_reporting(E_ALL);
15
 
65 - 16
// search
5 - 17
function performSearch() {
14 - 18
    $currentMd5SearchTerm = md5SearchTerm();
19
    if ($currentMd5SearchTerm == $_SESSION['md5LastSearch']) {
20
        return;
21
    }
22
    $_SESSION['md5LastSearch'] = $currentMd5SearchTerm;
23
 
81 - 24
    $_SESSION["barcode"]["Type"] = clsLibGTIN::GTINCheck($_SESSION["searchTerm"], false, 1);
25
    $_SESSION["barcode"]["Value"] = clsLibGTIN::GTINCheck($_SESSION["searchTerm"]);
26
 
22 - 27
    updatePbFile(true);
28
 
81 - 29
    findDiscogsMaster($_SESSION["searchTerm"]);
30
    updatePbFile();
31
 
65 - 32
    $_SESSION["currentView"] = 'All';
33
    $_SESSION["currentLayout"] = 'TableView';
34
    $_SESSION["resultArr"] = [];
35
    $_SESSION["resultArr"] = searchAll($_SESSION["searchTerm"]);
22 - 36
    updatePbFile();
23 - 37
 
65 - 38
    $_SESSION["resultArr"] = applySearchFilter($_SESSION["resultArr"]);
22 - 39
    updatePbFile();
5 - 40
 
65 - 41
    //echo "<pre>";print_r($_SESSION["resultArr"]);echo "</pre>";
66 - 42
    $_SESSION["lowestPrice"]["Used"] = findLowestCondition("Used");
43
    $_SESSION["lowestPrice"]["New"] = findLowestCondition("New");
44
    $_SESSION["lowestPrice"]["CD"] = findLowestMediaType("CD");
45
    $_SESSION["lowestPrice"]["Record"] = findLowestMediaType("Record");
46
    $_SESSION["lowestPrice"]["Digital"] = findLowestMediaType("Digital");
47
    $_SESSION["lowestPrice"]["Book"] = findLowestMediaType("Book");
65 - 48
    $_SESSION["lowestPrice"]["All"] = 0.00;
49
    if (array_sum($_SESSION["lowestPrice"]) > 0) {
50
        $_SESSION["lowestPrice"]["All"] = minNotNull($_SESSION["lowestPrice"]);
51
    }
22 - 52
    updatePbFile();
13 - 53
 
65 - 54
    saveSearchResult();
22 - 55
    updatePbFile();
5 - 56
}
57
 
9 - 58
function resetSessionVars() {
59
    $_SESSION["searchTerm"] = '';
46 - 60
    $_SESSION["discogsTitle"] = '';
61
    $_SESSION["discogsArtist"] = '';
14 - 62
    $_SESSION['md5LastSearch'] = '';
65 - 63
    $_SESSION["currentView"] = 'All';
64
    $_SESSION["currentLayout"] = 'TableView';
65
    $_SESSION["barcode"]["Type"] = '';
66
    $_SESSION["barcode"]["Value"] = '';
9 - 67
 
65 - 68
    $_SESSION["resultArr"] = [];
9 - 69
 
65 - 70
    $_SESSION["lowestPrice"]["Used"] = 0.00;
71
    $_SESSION["lowestPrice"]["New"] = 0.00;
72
    $_SESSION["lowestPrice"]["CD"] = 0.00;
73
    $_SESSION["lowestPrice"]["Record"] = 0.00;
74
    $_SESSION["lowestPrice"]["Digital"] = 0.00;
75
    $_SESSION["lowestPrice"]["Book"] = 0.00;
76
    $_SESSION["lowestPrice"]["All"] = 0.00;
9 - 77
}
78
 
65 - 79
// search for items on all sites
72 - 80
function searchAll($searchKey, $batchFlag = false) {
65 - 81
    $arr = [];
82
    if ($_SESSION["filterCondition"]["New"]) {
83
        $arr = get_vendor($arr, 'get_ebay', $searchKey, constant("NEW"));
84
    }
72 - 85
    if (!$batchFlag) { updatePbFile(); }
65 - 86
    if ($_SESSION["filterCondition"]["New"]) {
87
        $arr = get_vendor($arr, 'get_linkshare', $searchKey, constant("NEW"));
88
    }
72 - 89
    if (!$batchFlag) { updatePbFile(); }
65 - 90
    if ($_SESSION["filterCondition"]["New"]) {
91
        $arr = get_vendor($arr, 'get_cjaffiliate', $searchKey, constant("NEW"));
92
    }
72 - 93
    if (!$batchFlag) { updatePbFile(); }
65 - 94
    if ($_SESSION["filterCondition"]["New"]) {
95
        $arr = get_vendor($arr, 'get_walmart', $searchKey, constant("NEW"));
96
    }
72 - 97
    if (!$batchFlag) { updatePbFile(); }
65 - 98
    if ($_SESSION["filterCondition"]["New"]) {
99
        $arr = get_vendor($arr, 'get_itunes', $searchKey, constant("NEW"));
100
    }
72 - 101
    if (!$batchFlag) { updatePbFile(); }
17 - 102
 
81 - 103
    $arr = get_vendor($arr, 'get_amazon', $searchKey, constant("NEW"));
104
    if (!$batchFlag) { updatePbFile(); }
105
 
65 - 106
    if ($_SESSION["filterCondition"]["Used"]) {
107
        $arr = get_vendor($arr, 'get_ebay', $searchKey, constant("USED"));
108
    }
72 - 109
    if (!$batchFlag) { updatePbFile(); }
17 - 110
 
66 - 111
//echo "<pre>";print_r($arr);echo "</pre";
24 - 112
 
65 - 113
    $arr = applyExchangeRates($arr);
114
    usort($arr, 'compare_price');
72 - 115
    if (!$batchFlag) { updatePbFile(); }
5 - 116
 
65 - 117
    return $arr;
5 - 118
}
119
 
20 - 120
// Search and merge
121
function get_vendor($arr, $func, $searchKey, $condition) {
65 - 122
    $arrTemp = $func($searchKey, $condition);
20 - 123
    return array_merge($arrTemp, $arr);
124
}
125
 
65 - 126
// check search filters
13 - 127
function checkSearchFilters() {
5 - 128
    $_SESSION["filterWarnings"] = "";
129
    $filterOk = true;
130
 
65 - 131
    if (!$_SESSION["filterCondition"]["New"] && !$_SESSION["filterCondition"]["Used"]) {
132
        $_SESSION["filterWarnings"] .= '<div class="alert alert-danger"><i class="fas fa-filter mr-1"></i> Please select at least one Condition (New or Used)</div>';
133
        $filterOk = false;
134
    }
5 - 135
 
65 - 136
    if (!$_SESSION["filterMediaType"]["CD"] && !$_SESSION["filterMediaType"]["Record"] && !$_SESSION["filterMediaType"]["Digital"] && !$_SESSION["filterMediaType"]["Book"]) {
137
        $_SESSION["filterWarnings"] .= '<div class="alert alert-danger"><i class="fas fa-filter mr-1"></i> Please select at least one Media Type (CD, Record, Digital or Book)</div>';
138
        $filterOk = false;
139
    }
13 - 140
 
65 - 141
    return ($filterOk);
5 - 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
 
65 - 231
// filter view result table $_SESSION["resultArr"] for All, New, Used, Digital, or Book
232
function filterResults() {
233
    foreach ($_SESSION["resultArr"] as & $row) {
234
        if ($_SESSION["currentView"] == 'All') {
235
            $row["Show"] = true;
236
        }
237
        else {
66 - 238
            $row["Show"] = ($_SESSION["currentView"] == $row["Condition"] || $_SESSION["currentView"] == $row["MediaType"]);
65 - 239
        }
240
    }
5 - 241
}
13 - 242
 
66 - 243
// filter view result table $_SESSION["resultArr"] for detailed filter selection
244
function detailFilterResults($selArr) {
67 - 245
    if (!empty($selArr['filterCondition'])) {
246
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
247
            $_SESSION['AdditionalFilters']['Condition'][$key] = false;
248
        }
249
        if (!is_array($selArr['filterCondition'])) { $selArr['filterCondition'] = [ $selArr['filterCondition'] ];}
250
        foreach($selArr['filterCondition'] as $value) {
251
            $_SESSION['AdditionalFilters']['Condition'][$value] = true;
252
        }
253
    } else {
68 - 254
        $selArr['filterCondition'] = [];
77 - 255
        if (!empty($_SESSION['AdditionalFilters']['Condition'])) {
256
            foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
257
                if ($value) {
258
                    $selArr['filterCondition'][] = $key;
259
                }
68 - 260
            }
261
        }
66 - 262
    }
263
 
67 - 264
    if (!empty($selArr['filterMediaType'])) {
265
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
266
            $_SESSION['AdditionalFilters']['MediaType'][$key] = false;
267
        }
268
        if (!is_array($selArr['filterMediaType'])) { $selArr['filterMediaType'] = [ $selArr['filterMediaType'] ];}
269
        foreach($selArr['filterMediaType'] as $value) {
270
            $_SESSION['AdditionalFilters']['MediaType'][$value] = true;
271
        }
272
    } else {
68 - 273
        $selArr['filterMediaType'] = [];
77 - 274
        if (!empty($_SESSION['AdditionalFilters']['MediaType'])) {
275
            foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
276
                if ($value) {
277
                    $selArr['filterMediaType'][] = $key;
278
                }
68 - 279
            }
280
        }
66 - 281
    }
282
 
67 - 283
    if (!empty($selArr['filterShipFrom'])) {
284
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
285
            $_SESSION['AdditionalFilters']['ShippingFrom'][$key] = false;
286
        }
287
        if (!is_array($selArr['filterShipFrom'])) { $selArr['filterShipFrom'] = [ $selArr['filterShipFrom'] ];}
288
        foreach($selArr['filterShipFrom'] as $value) {
289
            $_SESSION['AdditionalFilters']['ShippingFrom'][$value] = true;
290
        }
291
    } else {
68 - 292
        $selArr['filterShipFrom'] = [];
77 - 293
        if (!empty($_SESSION['AdditionalFilters']['ShippingFrom'])) {
294
            foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
295
                if ($value) {
296
                    $selArr['filterShipFrom'][] = $key;
297
                }
68 - 298
            }
299
        }
66 - 300
    }
301
 
67 - 302
    if (!empty($selArr['filterMerchant'])) {
303
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
304
            $_SESSION['AdditionalFilters']['Merchant'][$key] = false;
305
        }
306
        if (!is_array($selArr['filterMerchant'])) { $selArr['filterMerchant'] = [ $selArr['filterMerchant'] ];}
307
        foreach($selArr['filterMerchant'] as $value) {
308
            $_SESSION['AdditionalFilters']['Merchant'][$value] = true;
309
        }
310
    } else {
68 - 311
        $selArr['filterMerchant'] = [];
77 - 312
        if (!empty($_SESSION['AdditionalFilters']['Merchant'])) {
313
            foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
314
                if ($value) {
315
                    $selArr['filterMerchant'][] = $key;
316
                }
68 - 317
            }
318
        }
66 - 319
    }
320
 
321
    foreach ($_SESSION["resultArr"] as & $row) {
322
        $row["Show"] = true;
323
 
324
        if (!in_array($row["Condition"], $selArr['filterCondition']) ||
325
            !in_array($row["MediaType"], $selArr['filterMediaType']) ||
326
            !in_array($row["Merchant"], $selArr['filterMerchant']) ||
327
            !in_array($row["Country"], $selArr['filterShipFrom'])) {
328
            $row["Show"] = false;
329
        }
330
    }
331
}
332
 
333
function resetDetailFilter() {
334
    if (isset($_SESSION['AdditionalFilters']['Merchant'])) {
335
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $field) {
336
            $_SESSION['AdditionalFilters']['Merchant'][$key] = true;
337
        }
338
    }
339
 
340
    if (isset($_SESSION['AdditionalFilters']['Seller'])) {
341
        foreach($_SESSION['AdditionalFilters']['Seller'] as $key => $field) {
342
            $_SESSION['AdditionalFilters']['Seller'][$key] = true;
343
        }
344
    }
345
 
346
    if (isset($_SESSION['AdditionalFilters']['Condition'])) {
347
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $field) {
348
            $_SESSION['AdditionalFilters']['Condition'][$key] = true;
349
        }
350
    }
351
 
352
    if (isset($_SESSION['AdditionalFilters']['DetailCondition'])) {
353
        foreach($_SESSION['AdditionalFilters']['DetailCondition'] as $key => $field) {
354
            $_SESSION['AdditionalFilters']['DetailCondition'][$key] = true;
355
        }
356
    }
357
 
358
    if (isset($_SESSION['AdditionalFilters']['ShippingFrom'])) {
359
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $field) {
360
            $_SESSION['AdditionalFilters']['ShippingFrom'][$key] = true;
361
        }
362
    }
363
 
364
    if (isset($_SESSION['AdditionalFilters']['MediaType'])) {
365
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $field) {
366
            $_SESSION['AdditionalFilters']['MediaType'][$key] = true;
367
        }
368
    }
369
 
370
    foreach ($_SESSION["resultArr"] as & $row) {
371
        $row["Show"] = true;
372
    }
373
}
374
 
65 - 375
// print result table or card deck
59 - 376
function printResult() {
377
    if ($_SESSION["currentLayout"] == 'TableView') {
78 - 378
        return buildTable($_SESSION["resultArr"]);
65 - 379
    }
380
    else /* CardView */ {
78 - 381
        return buildCardDeck($_SESSION["resultArr"]);
59 - 382
    }
383
}
384
 
65 - 385
// build HTML table from array
78 - 386
function buildTable($arr) {
66 - 387
    global $mediaTypeTextArr;
388
    global $mediaTypeIconArr;
389
 
59 - 390
    $str = "";
1 - 391
 
78 - 392
    if (count($arr) > 0) {
81 - 393
        $str .= "<div class=\"table\">"; // bugbug responsive?
68 - 394
        $str .= "<table class=\"table table-striped table-condensed table-hover small bg-info\">";
81 - 395
        $str .= "<thead class=\"thead-dark table-header-sticky\"><tr><th>Image</th><th class=\"text-left\">Title / Merchant</th><th>Condition</th><th class=\"hide-small\">Price</th><th class=\"hide-small\">S/H</th><th>Total</th><th class=\"hide-extra-small\"></th></tr></thead>";
65 - 396
        $str .= "<tbody>";
17 - 397
 
78 - 398
        foreach ($arr as $row) {
65 - 399
            if (!$row["Show"]) {
400
                continue;
401
            }
1 - 402
 
54 - 403
            $href = "href=\"" . $row["URL"] . "\" target=\"_blank\" onclick=\"saveTransfer('" . $row["URL"] . "'); return true;\"";
59 - 404
            $title = $row["Title"];
405
            if (mb_strlen($row["Title"], 'UTF-8') > MAXTITLELENGTH) {
65 - 406
                $title = mb_substr($row["Title"], 0, MAXTITLELENGTH, 'UTF-8') . '...';
59 - 407
            }
5 - 408
 
65 - 409
            $str .= "<tr>";
13 - 410
 
9 - 411
            // Image
79 - 412
            $str .= "<td><a " . $href . " data-toggle=\"tooltip\" title=\"Buy It Now\"><img class=\"img-fluid\" src=\"" . $row["Image"] . "\" alt=\"Item Image\"></a></td>";
1 - 413
 
9 - 414
            // Title / Merchant
65 - 415
            $str .= "<td class=\"text-left\"><span class=\"font-weight-bold\"><a class=\"bg-info\" " . $href . " data-toggle=\"tooltip\" title=\"Buy It Now\">" . $title . "</a></span>";
58 - 416
            $str .= "<br/><br/>";
65 - 417
            $str .= "<span class=\"font-weight-bold\">" . $row["Merchant"] . "</span>";
418
            if ($row["FeedbackScore"] != - 1) {
419
                $str .= "<span class=\"hide-extra-small\"><br/>" . $row["SellerName"] . " (" . number_format($row["FeedbackScore"], 0, "", ",") . " / " . $row["FeedbackPercent"] . "%)</span>";
420
            }
421
            else if (!empty($row["SellerName"])) {
422
                $str .= "<span class=\"hide-extra-small\"><br/>" . $row["SellerName"] . "</span>";
423
            }
424
            if (!empty($row["TimeLeft"])) {
24 - 425
                $str .= "<br>" . $row["TimeLeft"];
65 - 426
            }
427
            $str .= "</td>";
1 - 428
 
9 - 429
            // Condition
65 - 430
            $str .= "<td>";
66 - 431
            $mediaTypeIcon = 'media-icon ' . $mediaTypeIconArr[$row["MediaType"]];
432
            $tooltip = $mediaTypeTextArr[$row["MediaType"]];
433
            $str .= "<span class=\"font-weight-bold\">" . $row["DetailCondition"] . "</span>";
65 - 434
            $str .= "<br/><br/>";
66 - 435
            $str .= "<i class=\"" . $mediaTypeIcon . "\" title=\"" . $tooltip . "\" data-toggle=\"tooltip\" data-placement=\"right\" data-delay=\"200\"></i>";
65 - 436
            $str .= "</td>";
5 - 437
 
9 - 438
            // Price
65 - 439
            $str .= "<td class=\"hide-small\">" . print_monetary($row["Price"], $row["Currency"]);
440
            if ($row["Currency"] != $_SESSION["buyer"]["Currency"]) {
441
                $str .= "<br/>&asymp; " . print_monetary($row["ConvertedPrice"], $_SESSION["buyer"]["Currency"]);
442
            }
443
            if ($row["BestOffer"] == "true") {
444
                $str .= "<br>Best Offer Accepted";
445
            }
446
            $str .= "</td>";
1 - 447
 
9 - 448
            // Shipping and Handling Cost
65 - 449
            $str .= "<td class=\"hide-small\">";
450
            if ($row["ShippingCost"] == 0.00) {
451
                $str .= "Free Shipping";
452
            }
453
            else {
454
                $str .= print_monetary($row["ShippingCost"], $row["ShippingCurrency"]);
81 - 455
                if ($row["ShippingEstimated"]) {
456
                    $str .= "*";
457
                }
65 - 458
            }
459
            if ($row["ShippingCost"] > 0.00 && $row["ShippingCurrency"] != $_SESSION["buyer"]["Currency"]) {
460
                $str .= "<br/>&asymp; " . print_monetary($row["ConvertedShippingCost"], $_SESSION["buyer"]["Currency"]);
461
            }
24 - 462
            if ($row["HandlingTime"] > 0) {
463
                $str .= "<br>Handling Time " . $row["HandlingTime"] . " day" . ($row["HandlingTime"] > 1 ? "s" : "");
464
            }
465
            if ($row["ShippingCost"] > 0.00 && $row["FreeShippingCap"] > 0) {
466
                $str .= "<br>Free Shipping over " . print_monetary($row["FreeShippingCap"], $_SESSION["buyer"]["Currency"]);
467
            }
65 - 468
            $str .= "<br/><img class=\"img-fluid\" title=\"Ships from " . getCountry($row["Country"]) . "\" data-toggle=\"tooltip\" data-placement=\"right\" data-delay=\"200\" src=\"/images/flags/" . $row["Country"] . ".png\" alt=\"" . getCountry($row["Country"]) . " Flag\"></td>";
1 - 469
 
9 - 470
            // Total Price
65 - 471
            $str .= "<td class=\"font-weight-bolder\">" . print_monetary($row["ConvertedTotalPrice"], $_SESSION["buyer"]["Currency"]) . "</td>";
1 - 472
 
9 - 473
            // Link
54 - 474
            if ($row["Merchant"] == "iTunes") {
66 - 475
                if ($row["MediaType"] == "Digital") {
54 - 476
                    $badge = "images/US-UK_Apple_Music_Badge_RGB.svg";
65 - 477
                }
478
                else {
54 - 479
                    $badge = "images/US_UK_Apple_Books_Badge_Get_RGB_071818.svg";
480
                }
60 - 481
                $linkImage = "<a class=\"btn\" role=\"button\" " . $href . "><img class=\"img-fluid\" src=\"" . $badge . "\" alt=\"iTunes Badge\"></a>";
81 - 482
            } else if (strpos($row["Merchant"], "eBay") !== false) {
483
                $linkImage = "<a class=\"btn\" role=\"button\" " . $href . "><img class=\"img-fluid\" src=\"images/ebay-right-now.gif\" alt=\"iTunes Badge\"></a>";
484
            } else if (strpos($row["Merchant"], "Amazon") !== false) {
485
                $linkImage = "<a class=\"btn\" role=\"button\" " . $href . "><img class=\"img-fluid\" src=\"images/amazon-buy3.gif\" alt=\"iTunes Badge\"></a>";
486
            } else {
54 - 487
                $linkImage = "<a class=\"btn btn-danger\" role=\"button\" " . $href . "><i class=\"fas fa-shopping-cart btn-shop\"></i><span class=\"hide-small\"><br>Buy It Now</span></a>";
488
            }
65 - 489
            $str .= "<td class=\"hide-extra-small text-center\">" . $linkImage . "</td>";
1 - 490
 
65 - 491
            $str .= "</tr>";
9 - 492
        }
17 - 493
 
65 - 494
        $str .= "</tbody>";
495
        $str .= "<tfoot class=\"text-right\"><tr><td class=\"font-italic\" colspan=\"7\">Prices retrieved on " . gmdate("Y-m-d H:i") . " UTC<br>Daily exchange rates update</td></tr></tfoot>";
496
        $str .= "</table>";
497
        $str .= "</div>";
498
    }
499
    else {
59 - 500
        $str = printNoResultsWarning();
9 - 501
    }
1 - 502
 
65 - 503
    return ($str);
59 - 504
}
1 - 505
 
65 - 506
// build HTML card deck from array
78 - 507
function buildCardDeck($arr) {
66 - 508
    global $mediaTypeTextArr;
509
    global $mediaTypeIconArr;
510
 
65 - 511
    $str = "";
59 - 512
 
78 - 513
    if (count($arr) > 0) {
61 - 514
        $str .= "<div class=\"card-deck small\">";
59 - 515
 
78 - 516
        foreach ($arr as $row) {
65 - 517
            if (!$row["Show"]) {
518
                continue;
519
            }
59 - 520
 
521
            $href = "href=\"" . $row["URL"] . "\" target=\"_blank\" onclick=\"saveTransfer('" . $row["URL"] . "'); return true;\"";
522
            $title = $row["Title"];
523
            if (mb_strlen($row["Title"], 'UTF-8') > MAXTITLELENGTH) {
65 - 524
                $title = mb_substr($row["Title"], 0, MAXTITLELENGTH, 'UTF-8') . '...';
59 - 525
            }
526
 
65 - 527
            $str .= "<div class=\"card m-2 shadow mx-auto result-card\">";
59 - 528
 
529
            // Image
68 - 530
            $str .= "<a class=\"p-0 m-0 bg-light text-center result-image\" " . $href . " data-toggle=\"tooltip\" title=\"Buy It Now\"><img class=\"p-0 m-0 responsive-image\" src=\"" . $row["Image"] . "\" alt=\"Item Image\"></a>";
59 - 531
 
65 - 532
            $str .= "<div class=\"card-body bg-light d-flex flex-column\">";
59 - 533
            // Title / Merchant
65 - 534
            $str .= "<p class=\"card-title font-weight-bold\"><a " . $href . " data-toggle=\"tooltip\" title=\"Buy It Now\">" . $title . "</a></p>";
535
            $str .= "<div class=\"card-text mt-auto\"><span class=\"font-weight-bold\">" . $row["Merchant"] . "</span>";
536
            $str .= "<br>";
59 - 537
 
66 - 538
            // Condition / MediaType
539
            $mediaTypeIcon = 'media-icon ' . $mediaTypeIconArr[$row["MediaType"]];
540
            $tooltip = $mediaTypeTextArr[$row["MediaType"]];
541
            $str .= $row["DetailCondition"];
542
            $str .= "<i class=\"float-right " . $mediaTypeIcon . "\" title=\"" . $tooltip . "\" data-toggle=\"tooltip\" data-placement=\"right\" data-delay=\"200\"></i>";
65 - 543
            $str .= "<br>";
59 - 544
 
545
            // Total Price
65 - 546
            $str .= "<span class=\"font-weight-bolder\">" . print_monetary($row["ConvertedTotalPrice"], $_SESSION["buyer"]["Currency"]) . "</span>";
60 - 547
            $str .= "</div>";
59 - 548
 
549
            $str .= "</div>";
550
 
551
            // Link / Ships from Flag
64 - 552
            $str .= "<div class=\"card-footer bg-dark\">";
60 - 553
            $str .= "<div class=\"row\">";
65 - 554
            $str .= "<div class=\"col-9\">";
59 - 555
            if ($row["Merchant"] == "iTunes") {
66 - 556
                if ($row["MediaType"] == "Digital") {
59 - 557
                    $badge = "images/US-UK_Apple_Music_Badge_RGB.svg";
65 - 558
                }
559
                else {
59 - 560
                    $badge = "images/US_UK_Apple_Books_Badge_Get_RGB_071818.svg";
561
                }
61 - 562
                $linkImage = "<a class=\"btn p-0 m-0\" role=\"button\" " . $href . "><img class=\"img-fluid p-0 m-0\" src=\"" . $badge . "\" alt=\"iTunes Badge\"></a>";
81 - 563
            } else if (strpos($row["Merchant"], "eBay") !== false) {
564
                $linkImage = "<a class=\"btn p-0 m-0\" role=\"button\" " . $href . "><img class=\"img-fluid p-0 m-0\" src=\"images/ebay-right-now.gif\" alt=\"iTunes Badge\"></a>";
565
            } else if (strpos($row["Merchant"], "Amazon") !== false) {
566
                $linkImage = "<a class=\"btn p-0 m-0\" role=\"button\" " . $href . "><img class=\"img-fluid p-0 m-0\" src=\"images/amazon-buy3.gif\" alt=\"iTunes Badge\"></a>";
65 - 567
            }
568
            else {
61 - 569
                $linkImage = "<a class=\"btn btn-danger m-0\" role=\"button\" " . $href . "><i class=\"fas fa-shopping-cart\"></i></a>";
59 - 570
            }
65 - 571
            $str .= $linkImage;
59 - 572
            $str .= "</div>";
65 - 573
            $str .= "<div class=\"col-3\">";
574
            $str .= "<img class=\"float-right\" title=\"Ships from " . getCountry($row["Country"]) . "\" data-toggle=\"tooltip\" data-placement=\"right\" data-delay=\"200\" src=\"/images/flags/" . $row["Country"] . ".png\" alt=\"" . getCountry($row["Country"]) . " Flag\">";
60 - 575
            $str .= "</div>";
65 - 576
            $str .= "</div>";
577
            $str .= "</div>";
59 - 578
 
65 - 579
            $str .= "</div>";
59 - 580
        }
581
 
65 - 582
        $str .= "</div>";
583
        $str .= "<div class=\"py-2 text-right\"><p class=\"font-italic\">Prices retrieved on " . gmdate("Y-m-d H:i") . " UTC<br>Daily exchange rates update</p></div>";
584
    }
585
    else {
59 - 586
        $str = printNoResultsWarning();
587
    }
588
 
65 - 589
    return ($str);
5 - 590
}
591
 
65 - 592
// print directions when no results are found
59 - 593
function printNoResultsWarning() {
594
    $str = "<div class=\"text-center bg-warning p-3 rounded\">";
595
    $str .= "<p class=\"display-5 font-weight-bold\">Your search returned no results</p>";
596
    $str .= "<p>You may want to try the following:</p>";
70 - 597
    $str .= "<ul><li>Check the spelling</li><li>Try using fewer words</li><li>Check the search filter (<i class=\"fas fa-filter\"></i>) if you used one</li><li>Try using artist and title if you used a barcode; some albums have been released under various barcodes</li></ul>";
59 - 598
    $str .= "</div>";
599
 
600
    return $str;
601
}
602
 
66 - 603
function printResultHeader() {
604
    $str = '';
605
    $str .= '<nav class="navbar bg-black mt-2 pb-0">';
606
    $str .= '<ul class="nav nav-tabs">';
607
    $str .= '  <li class="nav-item border-0">';
608
    $str .= '    <a id="quickTab" class="nav-link';
68 - 609
    $str .= ($_SESSION["currentView"] == 'Apply' ? ' bg-white invert' : ' active bg-white') . '" href="#quickFilter">Quick</a>';
66 - 610
    $str .= '  </li>';
611
    $str .= '  <li class="nav-item border-0">';
612
    $str .= '    <a id="detailTab" class="nav-link';
68 - 613
    $str .= ($_SESSION["currentView"] == 'Apply' ? ' active bg-white' : ' bg-white invert') . '" href="#detailFilter">Detailed</a>';
66 - 614
    $str .= '  </li>';
615
    $str .= '</ul>';
616
    $str .= '<span class="ml-auto">';
617
    $str .= '    <button name="submit" value="TableView" type="' . getButtonType("TableView") . '" class="btn btn-sm filterButtonSmall ' . getBackgroundColor("TableView") . '"';
618
    $str .= ' data-toggle="tooltip" title="Table View" onclick="$(this).tooltip(\'hide\');"><span class="display-6 font-weight-bolder"><i class="fas fa-th-list"></i></span></button>';
619
    $str .= '    <button name="submit" value="CardView" type="' . getButtonType("CardView") . '" class="btn btn-sm filterButtonSmall ' . getBackgroundColor("CardView") . '"';
620
    $str .= ' data-toggle="tooltip" title="Card View" onclick="$(this).tooltip(\'hide\');"><span class="display-6 font-weight-bolder"><i class="fas fa-th-large"></i></span></button>';
621
    $str .= '</span>';
622
    $str .= '<span class="navbar-text text-white float-right ml-3">Showing ' . count(array_filter($_SESSION["resultArr"], function ($entry) { return ($entry['Show'] === true); })) . ' of ' . count($_SESSION["resultArr"]) . '</span>';
623
    $str .= '</nav>';
68 - 624
    $str .= '<div class="tab-content mb-3 bg-white">';
66 - 625
    $str .= '  <div id="quickFilter" class="tab-pane';
626
    $str .= ($_SESSION["currentView"] == 'Apply' ? '' : ' active') . '"><br>';
627
    $str .= resultHeader();
628
    $str .= '  </div>';
629
    $str .= '  <div id="detailFilter" class="container tab-pane';
630
    $str .= ($_SESSION["currentView"] == 'Apply' ? ' active' : ' bg-white') . '"><br>';
631
    $str .= detailResultHeader();
632
    $str .= '  </div>';
633
    $str .= '</div>';
634
 
635
  return $str;
636
}
637
 
65 - 638
// print summary/header on top of listing table
66 - 639
function resultHeader() {
11 - 640
    $str = '<div class="d-flex flex-wrap justify-content-center p-2">';
65 - 641
    $str .= '    <button name="submit" value="All" type="' . getButtonType("All") . '" class="btn mx-2 filterButton ' . getBackgroundColor("All") . '"';
642
    if ($_SESSION["lowestPrice"]["All"] <= 0) {
643
        $str .= ' disabled';
644
    }
645
    $str .= '><span class="display-6 font-weight-bolder">All</span><span class="display-7"> from</span><br><span class="display-6 font-weight-bolder">' . print_monetary($_SESSION["lowestPrice"]["All"], $_SESSION["buyer"]["Currency"]) . '</span>';
66 - 646
    $str .= '    <span class="badge">' . (isset($_SESSION['AdditionalFilterCounters']['Condition']['All']) ? $_SESSION['AdditionalFilterCounters']['Condition']['All'] : '') . '</span></button>';
62 - 647
    $str .= '    <button name="submit" value="New" type="' . getButtonType("New") . '" class="btn mx-2 filterButton ' . getBackgroundColor("New") . '"';
65 - 648
    if ($_SESSION["lowestPrice"]["New"] <= 0) {
649
        $str .= ' disabled';
650
    }
651
    $str .= '><span class="display-6 font-weight-bolder">New</span><span class="display-7"> from</span><br><span class="display-6 font-weight-bolder">' . print_monetary($_SESSION["lowestPrice"]["New"], $_SESSION["buyer"]["Currency"]) . '</span>';
66 - 652
    $str .= '    <span class="badge">' . (isset($_SESSION['AdditionalFilterCounters']['Condition']['New']) ? $_SESSION['AdditionalFilterCounters']['Condition']['New'] : '') . '</span></button>';
62 - 653
    $str .= '    <button name="submit" value="Used" type="' . getButtonType("Used") . '" class="btn mx-2 filterButton ' . getBackgroundColor("Used") . '"';
65 - 654
    if ($_SESSION["lowestPrice"]["Used"] <= 0) {
655
        $str .= ' disabled';
656
    }
20 - 657
    $str .= '><span class="display-6 font-weight-bolder">Used</span><span class="display-7"> from</span><br><span class="display-6 font-weight-bolder">' . print_monetary($_SESSION["lowestPrice"]["Used"], $_SESSION["buyer"]["Currency"]) . '</span>';
66 - 658
    $str .= '    <span class="badge">' . (isset($_SESSION['AdditionalFilterCounters']['Condition']['Used']) ? $_SESSION['AdditionalFilterCounters']['Condition']['Used'] : '') . '</span></button>';
659
 
660
    $str .= '</div>';
661
 
662
    return $str;
663
}
664
 
665
function detailResultHeader() {
666
    global $mediaTypeTextArr;
667
    global $mediaTypeIconArr;
668
 
669
    $str = '';
670
    $str .= '            <form id="detailFilterForm">';
671
    $str .= '                <input type="hidden" name="sessionTab" value="' . MySessionHandler::getSessionTab() . '">';
672
    $str .= '                <div class="">';
673
    $str .= '                    <div class="card-group">';
674
    $str .= '';
675
 
676
    // Condition
677
    if (isset($_SESSION['AdditionalFilterCounters']['Condition'])) {
678
        $str .= '                        <div class="card m-2">';
679
        $str .= '                            <div class="card-header font-weight-bold">Condition</div>';
680
        $str .= '                            <div class="card-body">';
681
        $cnt = count($_SESSION['AdditionalFilterCounters']['Condition']);
682
        foreach($_SESSION['AdditionalFilters']['Condition'] as $key => $value) {
683
            $str .= '                                <div class="form-check">';
684
            $str .= '                                    <label class="form-check-label">';
685
            $str .= '                                        <input name="filterCondition[]" type="checkbox" value="' . $key . '" class="form-check-input"';
686
            $str .= ($value ? " checked" : "");
687
            $str .= ($cnt > 2 ? "" : " disabled");
688
            $str .= '>' . $key . '<span class="badge badge-pill badge-dark ml-2">' . $_SESSION['AdditionalFilterCounters']['Condition'][$key] . '</span>';
689
            $str .= '                                    </label>';
690
            $str .= '                                </div>';
691
        }
692
        $str .= '                            </div>';
693
        $str .= '                        </div>';
13 - 694
    }
66 - 695
 
696
    // Media Type
697
    if (isset($_SESSION['AdditionalFilterCounters']['MediaType'])) {
698
        $str .= '                        <div class="card m-2">';
699
        $str .= '                            <div class="card-header font-weight-bold">Media Type</div>';
700
        $str .= '                            <div class="card-body">';
701
        $cnt = count($_SESSION['AdditionalFilterCounters']['MediaType']);
702
        foreach($_SESSION['AdditionalFilters']['MediaType'] as $key => $value) {
703
            $str .= '                                <div class="form-check">';
704
            $str .= '                                    <label class="form-check-label">';
705
            $str .= '                                        <input name="filterMediaType[]" type="checkbox" value="' . $key . '" class="form-check-input"';
706
            $str .= ($value ? " checked" : "");
707
            $str .= ($cnt > 1 ? "" : " disabled");
708
            $str .= '><i class="' . $mediaTypeIconArr[$key] . '"></i> ' . $mediaTypeTextArr[$key];
709
            $str .= '<span class="badge badge-pill badge-dark ml-2">' . $_SESSION['AdditionalFilterCounters']['MediaType'][$key] . '</span>';
710
            $str .= '                                    </label>';
711
            $str .= '                                </div>';
712
        }
713
        $str .= '                            </div>';
714
        $str .= '                        </div>';
65 - 715
    }
59 - 716
 
66 - 717
    // Merchant
718
    if (isset($_SESSION['AdditionalFilterCounters']['Merchant'])) {
719
        $str .= '                        <div class="card m-2">';
720
        $str .= '                            <div class="card-header font-weight-bold">Merchant</div>';
721
        $str .= '                            <div class="card-body">';
722
        $cnt = count($_SESSION['AdditionalFilterCounters']['Merchant']);
723
        foreach($_SESSION['AdditionalFilters']['Merchant'] as $key => $value) {
724
            $str .= '                                <div class="form-check">';
725
            $str .= '                                    <label class="form-check-label">';
726
            $str .= '                                        <input name="filterMerchant[]" type="checkbox" value="' . $key . '" class="form-check-input"';
727
            $str .= ($value ? " checked" : "");
728
            $str .= ($cnt > 1 ? "" : " disabled");
729
            $str .= '>' . $key . '<span class="badge badge-pill badge-dark ml-2">' . $_SESSION['AdditionalFilterCounters']['Merchant'][$key] . '</span>';
730
            $str .= '                                    </label>';
731
            $str .= '                                </div>';
732
        }
733
        $str .= '                            </div>';
734
        $str .= '                        </div>';
735
    }
1 - 736
 
66 - 737
    // Shipping From
738
    if (isset($_SESSION['AdditionalFilterCounters']['ShippingFrom'])) {
739
        $str .= '                        <div class="card m-2">';
740
        $str .= '                            <div class="card-header font-weight-bold">Shipping From</div>';
741
        $str .= '                            <div class="card-body">';
742
        $cnt = count($_SESSION['AdditionalFilterCounters']['ShippingFrom']);
743
        foreach($_SESSION['AdditionalFilters']['ShippingFrom'] as $key => $value) {
744
            $str .= '                                <div class="form-check">';
745
            $str .= '                                    <label class="form-check-label">';
746
            $str .= '                                        <input name="filterShipFrom[]" type="checkbox" value="' . $key . '" class="form-check-input"';
747
            $str .= ($value ? " checked" : "");
748
            $str .= ($cnt > 1 ? "" : " disabled");
749
            $str .= '><img class="img-fluid" title="Ships from ' . getCountry($key) . '" data-toggle="tooltip" data-delay="200" src="/images/flags/' . $key . '.png" alt="' . getCountry($key) . ' Flag"><span class="badge badge-pill badge-dark ml-2">' . $_SESSION['AdditionalFilterCounters']['ShippingFrom'][$key] . '</span>';
750
            $str .= '                                    </label>';
751
            $str .= '                                </div>';
752
        }
753
        $str .= '                            </div>';
754
        $str .= '                        </div>';
755
    }
756
 
757
    $str .= '                    </div>';
758
    $str .= '                </div>';
759
    $str .= '';
760
    $str .= '                <div class="p-2">';
761
    $str .= '                    <button type="submit" class="btn btn-success detailFilterButton" name="submit" value="Apply">Apply</button>';
762
    $str .= '                    <button type="submit" class="btn btn-danger detailFilterButton" name="submit" value="Reset">Reset</button>';
763
    $str .= '                </div>';
764
    $str .= '            </form>';
765
 
65 - 766
    return $str;
5 - 767
}
1 - 768
 
65 - 769
// get top button background color
770
function getBackgroundColor($sel) {
771
    if ($_SESSION["currentView"] == $sel || $_SESSION["currentLayout"] == $sel) {
772
        return ("btn-primary active");
773
    }
5 - 774
 
65 - 775
    return ("btn-primary invert");
13 - 776
}
5 - 777
 
65 - 778
// get top button type
779
function getButtonType($sel) {
780
    if ($_SESSION["currentView"] == $sel || $_SESSION["currentLayout"] == $sel) {
781
        return ("button");
782
    }
5 - 783
 
65 - 784
    return ("submit");
13 - 785
}
5 - 786
 
65 - 787
// compare price for sort low to high
788
function compare_price($a, $b) {
789
    return strnatcmp($a['ConvertedTotalPrice'], $b['ConvertedTotalPrice']);
5 - 790
}
13 - 791
 
65 - 792
// print monetary values with correct symbol and thousands/decimal delimiters
793
function print_monetary($num, $curr) {
794
    if ($curr == "USD") {
795
        return ("$" . number_format($num, 2, '.', ','));
796
    }
797
    else if ($curr == "CAD") {
798
        return ("C $" . number_format($num, 2, '.', ','));
799
    }
800
    else if ($curr == "EUR") {
801
        return (number_format($num, 2, ',', '.') . "&euro;");
802
    }
803
    else if ($curr == "GBP") {
804
        return ("&pound;" . number_format($num, 2, '.', ','));
805
    }
806
    else if ($curr == "AUD") {
807
        return ("AU $" . number_format($num, 2, '.', ','));
808
    }
1 - 809
 
65 - 810
    return ($curr . " " . number_format($num, 2, '.', ','));
5 - 811
}
1 - 812
 
65 - 813
// find lowest used / new prices
66 - 814
function findLowestCondition($condition) {
65 - 815
    foreach ($_SESSION["resultArr"] as $row) {
816
        if (!$row["Show"]) {
817
            continue;
818
        }
1 - 819
 
66 - 820
        if ($condition == $row["Condition"]) {
65 - 821
            return ($row["ConvertedTotalPrice"]);
822
        }
823
    }
5 - 824
 
65 - 825
    return (0);
5 - 826
}
827
 
65 - 828
// find lowest cd, record, digital and book prices
66 - 829
function findLowestMediaType($mediaType) {
65 - 830
    foreach ($_SESSION["resultArr"] as $row) {
831
        if (!$row["Show"]) {
832
            continue;
833
        }
20 - 834
 
66 - 835
        if ($mediaType == $row["MediaType"]) {
65 - 836
            return ($row["ConvertedTotalPrice"]);
837
        }
838
    }
20 - 839
 
65 - 840
    return (0);
20 - 841
}
842
 
65 - 843
// find lowest non-zero double value in array
844
function minNotNull(Array $values) {
845
    return min(array_diff(array_map('doubleval', $values) , array(
846
 
847
    )));
13 - 848
}
11 - 849
 
65 - 850
// apply exchange rates
851
function applyExchangeRates($arr) {
852
    foreach ($arr as & $value) {
853
        $value["ConvertedPrice"] = $value["Price"];
854
        $value["ConvertedShippingCost"] = $value["ShippingCost"];
1 - 855
 
65 - 856
        if ($_SESSION["buyer"]["Currency"] != $value["Currency"]) {
857
            $value["ConvertedPrice"] = number_format($value["Price"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["Currency"]) , 2, '.', '');
858
        }
1 - 859
 
65 - 860
        if ($_SESSION["buyer"]["Currency"] != $value["ShippingCurrency"]) {
861
            $value["ConvertedShippingCost"] = number_format($value["ShippingCost"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["ShippingCurrency"]) , 2, '.', '');
862
        }
1 - 863
 
65 - 864
        $value["ConvertedTotalPrice"] = number_format($value["ConvertedPrice"] + $value["ConvertedShippingCost"], 2, '.', '');
865
    }
5 - 866
 
65 - 867
    return ($arr);
5 - 868
}
869
 
36 - 870
// sanitize user input
65 - 871
function sanitizeInput($data) {
872
    $data = trim(preg_replace('/[\t\n\r\s]+/', ' ', $data));
873
    $data = stripslashes($data);
874
    $data = htmlspecialchars($data);
875
    return $data;
5 - 876
}
1 - 877
 
52 - 878
// sanitize user input (plus delete apostrophe)
879
function sanitizeInput2($data) {
65 - 880
    $data = trim(preg_replace('/[\t\n\r\s\']+/', ' ', $data));
881
    $data = stripslashes($data);
882
    $data = htmlspecialchars($data, ENT_QUOTES | ENT_HTML5);
883
    return $data;
52 - 884
}
885
 
14 - 886
// convert certain utf-8 characters to ascii
887
function cleanString($str) {
888
    $utf8 = array(
65 - 889
        '/[áàâãªä]/u' => 'a',
890
        '/[ÁÀÂÃÄ]/u' => 'A',
891
        '/[ÍÌÎÏ]/u' => 'I',
892
        '/[íìîï]/u' => 'i',
893
        '/[éèêë]/u' => 'e',
894
        '/[ÉÈÊË]/u' => 'E',
895
        '/[óòôõºö]/u' => 'o',
896
        '/[ÓÒÔÕÖ]/u' => 'O',
897
        '/[úùûü]/u' => 'u',
898
        '/[ÚÙÛÜ]/u' => 'U',
899
        '/ç/' => 'c',
900
        '/Ç/' => 'C',
901
        '/ñ/' => 'n',
902
        '/Ñ/' => 'N',
903
        '/–/' => '-', // UTF-8 hyphen to "normal" hyphen
904
        '/[’‘‹›‚]/u' => ' ', // Literally a single quote
905
        '/[“”«»„]/u' => ' ', // Double quote
906
        '/ /' => ' ', // nonbreaking space (equiv. to 0x160)
66 - 907
 
14 - 908
    );
909
 
65 - 910
    return preg_replace(array_keys($utf8) , array_values($utf8) , $str);
14 - 911
}
912
 
913
// Clean the search string
914
function searchFriendlyString($str) {
915
    $str = strip_tags($str);
916
    $str = stripslashes($str);
917
    $str = cleanString($str);
65 - 918
    $str = str_replace(array(
919
        "[",
920
        "]",
921
        "<",
922
        ">",
923
        "(",
924
        ")",
925
        " - ",
926
        " & ",
927
        " / "
928
    ) , " ", $str); // eliminate single '-', '&', '/' and brackets
929
    $str = trim(preg_replace('/[\t\n\r\s]+/', ' ', $str)); // delete extra whitespaces
14 - 930
    return ucwords($str);
931
}
932
 
65 - 933
// get a SESSION value, return empty string if not set
934
function getSV($var) {
935
    if (!isset($_SESSION[$var])) {
936
        return ('');
937
    }
1 - 938
 
65 - 939
    return ($_SESSION[$var]);
5 - 940
}
941
 
65 - 942
// initialize a SESSION value if not set
943
function initSV($var, $value) {
944
    if (!isset($_SESSION[$var])) {
945
        $_SESSION[$var] = $value;
946
    }
5 - 947
}
1 - 948
 
65 - 949
// initialize sessions variables
950
function initSessionVariables() {
951
    initSV("resultArr", []);
952
    initSV("barcode", array(
953
        "Type" => "",
954
        "Value" => ""
955
    ));
956
    initSV("buyer", array(
957
        "Country" => "United States",
958
        "Currency" => "USD",
959
        "Zip" => ""
960
    ));
961
    initSV("filterCondition", array(
962
        "New" => true,
963
        "Used" => true
964
    ));
965
    initSV("filterMediaType", array(
966
        "CD" => true,
967
        "Record" => true,
968
        "Digital" => true,
969
        "Book" => true
970
    ));
971
    initSV("currentView", "All");
972
    initSV("currentLayout", "TableView");
973
    initSV("lowestPrice", array(
974
        "Used" => 0.00,
975
        "New" => 0.00,
976
        "CD" => 0.00,
977
        "Record" => 0.00,
978
        "Digital" => 0.00,
979
        "Book" => "0.00",
980
        "All" => 0.00
981
    ));
982
    initSV("filterWarnings", "");
983
    initSV("md5LastSearch", "");
5 - 984
}
985
 
14 - 986
function md5SearchTerm() {
987
    $data = array();
988
    $data['cond'] = $_SESSION['filterCondition'];
989
    $data['type'] = $_SESSION['filterMediaType'];
17 - 990
    $data['buyer'] = $_SESSION['buyer'];
65 - 991
    $data['term'] = array(
992
        $_SESSION['searchTerm']
993
    );
14 - 994
 
65 - 995
    return (md5(json_encode($data)));
14 - 996
}
997
 
65 - 998
// check POST value, return true if set and false if not
999
function checkPV($var) {
1000
    if (isset($_POST[$var])) {
1001
        return (true);
1002
    }
1 - 1003
 
65 - 1004
    return (false);
5 - 1005
}
1006
 
65 - 1007
// get POST or GET value, return empty if not set
1008
function getPGV($var) {
1009
    if (isset($_POST[$var])) {
1010
        return ($_POST[$var]);
1011
    }
1012
    else if (isset($_GET[$var])) {
1013
        return ($_GET[$var]);
1014
    }
14 - 1015
 
65 - 1016
    return ("");
14 - 1017
}
1018
 
1 - 1019
// print search filter modal with current selection
65 - 1020
function printSearchFilterModal() {
66 - 1021
    global $mediaTypeTextArr;
1022
    global $mediaTypeIconArr;
1023
 
65 - 1024
    $str = '';
1025
    $str .= '<div class="modal fade" id="filterModal">';
1026
    $str .= '    <div class="modal-dialog">';
1027
    $str .= '        <div class="modal-content">';
1028
    $str .= '';
1029
    $str .= '            <div class="modal-header bg-primary">';
1030
    $str .= '                <h4 class="modal-title">Search Filters</h4>';
1031
    $str .= '            </div>';
1032
    $str .= '';
1033
    $str .= '            <form method="post" action="/index.php" onsubmit="progressBar(\'Applying Modified Search Filter...\');">';
20 - 1034
    $str .= '                <input type="hidden" name="sessionTab" value="' . MySessionHandler::getSessionTab() . '">';
65 - 1035
    $str .= '                <div class="modal-body">';
1036
    $str .= '                    <div class="card-group">';
1037
    $str .= '';
1038
    $str .= '                        <div class="card m-2">';
1039
    $str .= '                            <div class="card-header font-weight-bold">Condition</div>';
1040
    $str .= '                            <div class="card-body">';
1041
    $str .= '                                <div class="form-check">';
1042
    $str .= '                                    <label class="form-check-label">';
66 - 1043
    $str .= '                                        <input name="filterCondition[]" type="checkbox" class="form-check-input" value="New"' . ($_SESSION["filterCondition"]["New"] ? " checked" : "") . '>New';
65 - 1044
    $str .= '                                    </label>';
1045
    $str .= '                                </div>';
1046
    $str .= '                                <div class="form-check">';
1047
    $str .= '                                    <label class="form-check-label">';
66 - 1048
    $str .= '                                        <input name="filterCondition[]" type="checkbox" class="form-check-input" value="Used"' . ($_SESSION["filterCondition"]["Used"] ? " checked" : "") . '>Used';
65 - 1049
    $str .= '                                    </label>';
1050
    $str .= '                                </div>';
1051
    $str .= '                            </div>';
1052
    $str .= '                        </div>';
1053
    $str .= '';
1054
    $str .= '                        <div class="card m-2">';
1055
    $str .= '                            <div class="card-header font-weight-bold">Media Type</div>';
1056
    $str .= '                            <div class="card-body">';
1057
    $str .= '                                <div class="form-check">';
1058
    $str .= '                                    <label class="form-check-label">';
66 - 1059
    $str .= '                                        <input name="filterMediaType[]" type="checkbox" class="form-check-input" value="CD"' . ($_SESSION["filterMediaType"]["CD"] ? " checked" : "") . '><i class="' . $mediaTypeIconArr["CD"] . '"></i> ' . $mediaTypeTextArr["CD"];
65 - 1060
    $str .= '                                    </label>';
1061
    $str .= '                                </div>';
1062
    $str .= '                                <div class="form-check">';
1063
    $str .= '                                    <label class="form-check-label">';
66 - 1064
    $str .= '                                        <input name="filterMediaType[]" type="checkbox" class="form-check-input" value="Record"' . ($_SESSION["filterMediaType"]["Record"] ? " checked" : "") . '><i class="' . $mediaTypeIconArr["Record"] . '"></i> ' . $mediaTypeTextArr["Record"];
65 - 1065
    $str .= '                                    </label>';
1066
    $str .= '                                </div>';
1067
    $str .= '                                <div class="form-check">';
1068
    $str .= '                                    <label class="form-check-label">';
66 - 1069
    $str .= '                                        <input name="filterMediaType[]" type="checkbox" class="form-check-input" value="Digital"' . ($_SESSION["filterMediaType"]["Digital"] ? " checked" : "") . '><i class="' . $mediaTypeIconArr["Digital"] . '"></i> ' . $mediaTypeTextArr["Digital"];
65 - 1070
    $str .= '                                    </label>';
1071
    $str .= '                                </div>';
1072
    $str .= '                                <div class="form-check">';
1073
    $str .= '                                    <label class="form-check-label">';
66 - 1074
    $str .= '                                        <input name="filterMediaType[]" type="checkbox" class="form-check-input" value="Book"' . ($_SESSION["filterMediaType"]["Book"] ? " checked" : "") . '><i class="' . $mediaTypeIconArr["Book"] . '"></i> ' . $mediaTypeTextArr["Book"];
65 - 1075
    $str .= '                                    </label>';
1076
    $str .= '                                </div>';
1077
    $str .= '                            </div>';
1078
    $str .= '                        </div>';
1079
    $str .= '                    </div>';
1080
    $str .= '                </div>';
1081
    $str .= '';
1082
    $str .= '                <div class="modal-footer bg-primary">';
1083
    $str .= '                  	 <input id="tempSearchTerm" type="hidden" name="searchTerm" value="">';
1084
    $str .= '                    <button type="submit" class="btn btn-success" name="submit" value="Save" onclick="document.getElementById(\'tempSearchTerm\').value = document.getElementById(\'searchTerm\').value;$(\'#filterModal\').modal(\'hide\');">Save</button>';
1085
    $str .= '                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>';
1086
    $str .= '                </div>';
1087
    $str .= '            </form>';
1088
    $str .= '        </div>';
1089
    $str .= '    </div>';
1090
    $str .= '</div>';
1 - 1091
 
65 - 1092
    return ($str);
1 - 1093
}
3 - 1094
 
1095
// print search info modal
65 - 1096
function printSearchInfoModal() {
66 - 1097
    global $mediaTypeTextArr;
1098
    global $mediaTypeIconArr;
1099
 
65 - 1100
    $str = '';
1101
    $str .= '<div class="modal fade" id="searchInfoModal">';
1102
    $str .= '    <div class="modal-dialog">';
1103
    $str .= '        <div class="modal-content">';
1104
    $str .= '';
1105
    $str .= '            <div class="modal-header bg-primary">';
1106
    $str .= '                <h4 class="modal-title">Search Tips</h4>';
1107
    $str .= '                <button type="button" class="close" data-dismiss="modal"><i class="fas fa-window-close btn-dismiss"></i></button>';
1108
    $str .= '            </div>';
1109
    $str .= '';
1110
    $str .= '            <div class="modal-body bg-light text-dark">';
1111
    $str .= '              <div class="shadow p-4 mb-4 bg-white">';
1112
    $str .= '                <h4><i class="fas fa-filter"></i> Filter</h4>';
1113
    $str .= '                <p><span class="font-weight-bold">Condition:</span>';
1114
    $str .= '                    <br>Select "New" and / or "Used". The standard is to search for both.</p>';
1115
    $str .= '                <p><span class="font-weight-bold">Media Type:</span>';
66 - 1116
    $str .= '                    <br>Select <i class="' . $mediaTypeIconArr["CD"] . '"></i> "' . $mediaTypeTextArr["CD"] . '", <i class="' . $mediaTypeIconArr["Record"] . '"></i> "' . $mediaTypeTextArr["Record"] . '", <i class="' . $mediaTypeIconArr["Digital"] . '"></i> "' . $mediaTypeTextArr["Digital"] . '" and / or <i class="' . $mediaTypeIconArr["Book"] . '"></i> "' . $mediaTypeTextArr["Book"] . '". The standard is to search for all types.</p>';
65 - 1117
    $str .= '              </div>';
1118
    $str .= '              <div class="shadow p-4 mb-4 bg-white">';
1119
    $str .= '                <h4><i class="fas fa-shipping-fast"></i> Shipping To</h4>';
1120
    $str .= '                <p><span class="font-weight-bold">Country / Currency:</span>';
1121
    $str .= '                    <br>At this time only "United States" / "USD" are supported. The exchange rates are updated daily.</p>';
1122
    $str .= '                <p><span class="font-weight-bold">Zip Code:</span>';
1123
    $str .= '                    <br>Enter your postal code to get the accurate shipping cost for items listed using a shipping rate table.</p>';
1124
    $str .= '              </div>';
1125
    $str .= '              <div class="shadow p-4 bg-white">';
1126
    $str .= '                <h4><i class="fas fa-search"></i> Search Keywords</h4>';
1127
    $str .= '                <p><span class="font-weight-bold">Barcode:</span>';
1128
    $str .= '                    <br>The 12 or 13 digit barcode, normally located on the back, offers the best chance to find a specific album.</p>';
1129
    $str .= '                <p><span class="font-weight-bold">Artist and Title:</span>';
1130
    $str .= '                    <br>The full name of the album, including artist and title, will usually lead to a specific album.</p>';
1131
    $str .= '                <p><span class="font-weight-bold">Just Artist or Title:</span>';
1132
    $str .= '                    <br>Searches for artist or title alone will bring up multiple albums. You can later narrow your search further down, if necessary.</p>';
1133
    $str .= '                    <p><span class="font-italic">The search algorithm prefers the barcode number whenever available. Since some albums have been released under various barcodes, try searching again for author and title should the barcode search come up empty.</span></p>';
1134
    $str .= '              </div>';
1135
    $str .= '            </div>';
1136
    $str .= '            <div class="modal-footer bg-primary">';
1137
    $str .= '                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>';
1138
    $str .= '            </div>';
1139
    $str .= '        </div>';
1140
    $str .= '    </div>';
1141
    $str .= '</div>';
3 - 1142
 
65 - 1143
    return ($str);
3 - 1144
}
8 - 1145
 
65 - 1146
function saveSearchResult() {
1147
    $conn = MySessionHandler::getDBSessionId();
13 - 1148
 
65 - 1149
    $access = mysqli_real_escape_string($conn, time());
1150
    // BUGBUG
1151
    //  country
1152
    //  currency
1153
    $zip = mysqli_real_escape_string($conn, $_SESSION['buyer']['Zip']);
1154
    $condNew = $_SESSION['filterCondition']['New'] ? 'Y' : 'N';
1155
    $condUsed = $_SESSION['filterCondition']['Used'] ? 'Y' : 'N';
1156
    $mediaCD = $_SESSION['filterMediaType']['CD'] ? 'Y' : 'N';
1157
    $mediaRecord = $_SESSION['filterMediaType']['Record'] ? 'Y' : 'N';
1158
    $mediaDigital = $_SESSION['filterMediaType']['Digital'] ? 'Y' : 'N';
1159
    $mediaBook = $_SESSION['filterMediaType']['Book'] ? 'Y' : 'N';
1160
    $data = mysqli_real_escape_string($conn, $_SESSION['searchTerm']);
1161
    $lowNew = floatval($_SESSION['lowestPrice']['New']);
1162
    $lowUsed = floatval($_SESSION['lowestPrice']['Used']);
1163
    $lowDigital = floatval($_SESSION['lowestPrice']['Digital']);
1164
    $lowBook = floatval($_SESSION['lowestPrice']['Book']);
1165
    $count = count($_SESSION['resultArr']);
1166
    $userId = (empty($_SESSION['sessData']['userID']) ? 'NULL' : $_SESSION['sessData']['userID']);
8 - 1167
 
65 - 1168
    $sql = "INSERT
20 - 1169
                INTO searches
26 - 1170
                (sessId, access, zip, condNew, condUsed, mediaCD, mediaRecord, mediaDigital, mediaBook, data, lowNew, lowUsed, lowDigital, lowBook, count, userId)
35 - 1171
                VALUES ('" . session_id() . "', '$access', '$zip', '$condNew', '$condUsed', '$mediaCD', '$mediaRecord', '$mediaDigital', '$mediaBook', '$data', $lowNew, $lowUsed, $lowDigital, $lowBook, $count, $userId)";
8 - 1172
 
65 - 1173
    if (!($result = mysqli_query($conn, $sql))) {
1174
        error_log("MySQL Write Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1175
    }
13 - 1176
 
65 - 1177
    return $result;
1178
}
13 - 1179
 
17 - 1180
function getUrl($url, $userAgent = null) {
1181
    $ch = curl_init();
1182
 
1183
    // Set request header with language and charset
1184
    $header = array(
1185
        "Accept-Language: en-US,en;q=0.5",
1186
        "Accept-Charset: UTF-8,*;q=0.5"
1187
    );
1188
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1189
 
1190
    // Set optional user-agent
1191
    if ($userAgent) {
1192
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1193
    }
1194
 
1195
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
1196
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1197
    curl_setopt($ch, CURLOPT_HEADER, 0);
1198
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1199
    curl_setopt($ch, CURLOPT_URL, $url);
1200
    $response = curl_exec($ch);
1201
    if ($response === false) {
20 - 1202
        error_log('Curl Request Error: ' . curl_error($ch) . ' (' . curl_errno($ch) . ')');
1203
        error_log('Url: ' . $url);
17 - 1204
        $response = '';
1205
    }
23 - 1206
 
17 - 1207
    curl_close($ch);
1208
 
1209
    return $response;
1210
}
1211
 
20 - 1212
// Retrieve search history for current session id
14 - 1213
function getSearchHistory() {
1214
    $str = "";
38 - 1215
    $sql = "select data, max(access) from searches where sessId = '" . session_id() . "'";
1216
    if (!empty($_SESSION['sessData']['userID'])) {
1217
        $sql .= " or userID = '" . $_SESSION['sessData']['userID'] . "'";
1218
    }
1219
    $sql .= " group by data order by max(access) desc, data limit 0,30;";
14 - 1220
    $conn = MySessionHandler::getDBSessionId();
1221
 
20 - 1222
    if ($result = mysqli_query($conn, $sql)) {
1223
        if (mysqli_num_rows($result) > 0) {
65 - 1224
            while ($row = mysqli_fetch_assoc($result)) {
20 - 1225
                $str .= "<option>" . $row["data"] . "</option>";
1226
            }
14 - 1227
        }
1228
    }
65 - 1229
    else if (mysqli_errno($conn)) {
1230
        error_log("MySQL Read Searches SQL: " . $sql);
1231
        error_log("MySQL Read Searches Error: " . mysqli_error($conn) . " (" . mysqli_errno($conn) . ")");
1232
    }
14 - 1233
 
1234
    return $str;
1235
}
1236
 
41 - 1237
// Retrieve coupons codes
1238
function getCouponCodes() {
1239
    $str = "";
1240
    $lastAdvertiser = "";
1241
 
1242
    if (!isLoggedIn()) {
1243
        return ("<h2>Please login to your Find Cheap Music account in order to see the coupons.</h2>");
1244
    }
1245
 
65 - 1246
    $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 - 1247
    $conn = MySessionHandler::getDBSessionId();
1248
 
1249
    if ($result = mysqli_query($conn, $sql)) {
1250
        if (mysqli_num_rows($result) > 0) {
68 - 1251
            $str .= "<div class=\"container py-4 bg-secondary border\">";
65 - 1252
            while ($row = mysqli_fetch_assoc($result)) {
1253
                if ($row["advertiser"] != $lastAdvertiser) {
41 - 1254
                    if (!empty($lastAdvertiser)) {
68 - 1255
                        $str .= "</ul>";
41 - 1256
                    }
43 - 1257
                    $str .= "<h3 class=\"bg-primary text-center mt-3 mb-1\">" . $row["advertiser"] . "</h3>";
68 - 1258
                    $str .= "<ul class=\"list-group\">";
41 - 1259
                    $lastAdvertiser = $row["advertiser"];
1260
                }
51 - 1261
                if (!empty($row["url"])) {
68 - 1262
                    $str .= "<li class=\"list-group-item\"><a class=\"btn btn-link text-left\" target=\"_blank\" href=\"";
51 - 1263
                    $str .= $row["url"];
1264
                    $str .= "\">";
68 - 1265
                    $str .= "<strong>" . $row["description"] . "</strong> until " . $row["enddate"];
51 - 1266
                    if (!empty($row["couponcode"])) {
1267
                        $str .= " (Use Coupon Code \"" . $row["couponcode"] . "\")";
1268
                    }
1269
                    $str .= "</a>";
1270
                    if (!empty($row["pixel"])) {
61 - 1271
                        $str .= "<img src=\"" . $row["pixel"] . "\" width=\"1\" height=\"1\" class=\"border-0\" alt=\"" . $row["advertiser"] . " Coupon\"/>";
51 - 1272
                    }
68 - 1273
                    $str .= "</li>";
41 - 1274
                }
1275
            }
68 - 1276
            $str .= "</ul>";
41 - 1277
            $str .= "</div>";
1278
        }
65 - 1279
    }
1280
    else if (mysqli_errno($conn)) {
41 - 1281
        $str .= "<h2>No Coupons available at the moment...</h2>";
1282
    }
1283
 
1284
    return $str;
1285
}
1286
 
14 - 1287
// Delete left over progressbar files older than 2 days
1288
function cleanupPbFiles() {
1289
    $files = glob("../tmp/pb*.txt");
65 - 1290
    $now = time();
14 - 1291
    foreach ($files as $file) {
1292
        if (is_file($file)) {
1293
            if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days and older
1294
                unlink($file);
1295
            }
65 - 1296
        }
14 - 1297
    }
1298
}
1299
 
1300
// Update progressbar file for a session
22 - 1301
function updatePbFile($flag = false) {
81 - 1302
    static $max_pb = 13; // max progressbar steps
22 - 1303
    static $current = 0;
23 - 1304
 
22 - 1305
    if ($flag) {
1306
        $current = 0;
65 - 1307
    }
1308
    else {
22 - 1309
        ++$current;
1310
    }
1311
 
1312
    if ($current > $max_pb) {
1313
        error_log("max_pb $max_pb is too small, current step is $current. Adjust tools.php (updatePbFile).");
1314
        $max_pb = $current;
1315
    }
65 - 1316
    $filename = session_id() . "_" . MySessionHandler::getSessionTab();
14 - 1317
    $arr_content = array();
1318
 
20 - 1319
    $percent = intval($current / $max_pb * 100);
14 - 1320
 
1321
    $arr_content['percent'] = $percent;
1322
    $arr_content['message'] = $current . " search(es) processed.";
77 - 1323
    $file = "../tmp/pb_" . $filename . ".txt";
14 - 1324
 
77 - 1325
    if ($percent >= 100) {
1326
        @unlink($file);
1327
    } else {
1328
        file_put_contents($file, json_encode($arr_content));
1329
    }
14 - 1330
}
20 - 1331
 
1332
// Linkshare / CJ Affiliate csv dump
1333
function ls_cj_csv($fields) {
1334
    static $fh = null;
1335
    $delimiter = ',';
1336
    $enclosure = '"';
1337
    $mysql_null = false;
1338
 
1339
    if (!$fh) {
1340
        $fh = fopen("ls_cj.csv", "a+");
1341
    }
1342
 
1343
    $delimiter_esc = preg_quote($delimiter, '/');
1344
    $enclosure_esc = preg_quote($enclosure, '/');
1345
 
1346
    $output = array();
1347
    foreach ($fields as $field) {
1348
        if ($field === null && $mysql_null) {
1349
            $output[] = 'NULL';
1350
            continue;
1351
        }
1352
 
65 - 1353
        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure) : $field;
20 - 1354
    }
1355
 
1356
    fwrite($fh, join($delimiter, $output) . "\n");
1357
}
35 - 1358
 
1359
// Login in check
1360
function isLoggedIn() {
65 - 1361
    return (!empty($_SESSION['sessData']['userLoggedIn']) && !empty($_SESSION['sessData']['userID'])) ? true : false;
35 - 1362
}
1363
 
1364
// unset all login system session data
1365
function unsetSessData() {
1366
    unset($_SESSION['sessData']['userLoggedIn']);
1367
    unset($_SESSION['sessData']['userID']);
1368
    unset($_SESSION['sessData']['loginType']);
36 - 1369
}
1370
 
1371
// get user image name
1372
function getUserImage($userData) {
1373
    if (empty($userData) || empty($userData['picture'])) {
57 - 1374
        return 'login/assets/images/default.png';
36 - 1375
    }
38 - 1376
 
36 - 1377
    $httpPos = strpos($userData['picture'], 'http');
1378
    if ($httpPos === false) {
65 - 1379
        return 'login/' . UPLOAD_PATH . 'profile_picture/' . $userData['picture'];
36 - 1380
    }
1381
 
1382
    return $userData['picture'];
38 - 1383
}
39 - 1384
 
1385
function startsWith($haystack, $needle) {
1386
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
1387
}
1388
 
1389
function endsWith($haystack, $needle) {
1390
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
45 - 1391
}
50 - 1392
 
1393
function displayBarcode($barcode) {
1394
    $barcode = trim(preg_replace("/[^0-9]/", "", $barcode));
1395
    $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
1396
 
1397
    if ($barcodeType == "UPC" && strlen($barcode) == 12) {
1398
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 5) . "-" . substr($barcode, 6, 5) . "-" . substr($barcode, 11, 1);
65 - 1399
    }
1400
    else if (($barcodeType == "EAN" || $barcodeType == "ISBN") && strlen($barcode) == 13) {
50 - 1401
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 6) . "-" . substr($barcode, 7, 6);
65 - 1402
    }
1403
    else if ($barcodeType == "EAN" && strlen($barcode) == 14) {
50 - 1404
        return substr($barcode, 0, 1) . "-" . substr($barcode, 1, 2) . "-" . substr($barcode, 3, 5) . "-" . substr($barcode, 8, 5) . "-" . substr($barcode, 13, 1);
65 - 1405
    }
1406
    else {
50 - 1407
        return $barcode;
1408
    }
52 - 1409
}