Subversion Repositories cheapmusic

Rev

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

Rev Author Line No. Line
81 - 1
<?php
2
include_once ('php/constants.php');
3
 
4
error_reporting(E_ALL);
5
 
6
// Get itunes listings
7
function get_amazon($query, $searchCondition) {
8
    $vendors = Vendors::getInstance();
9
    $config = $vendors->getVendor(Vendors::AMAZON);
10
 
11
    $needMatches = empty($_SESSION["discogs"]);
12
    $arrMusic = [];
13
    $arrDigital = [];
82 - 14
    $arrBooks = [];
81 - 15
 
16
    // Music
17
    $arrMusic = get_amazonCategory($config, $query, "Music", $needMatches);
18
 
19
    // Digital Music
20
    if ($_SESSION["filterMediaType"]["Digital"]) {
99 - 21
        $arrDigital = get_amazonCategory($config, $query, "DigitalMusic");
81 - 22
    }
23
 
24
    if ($_SESSION["filterMediaType"]["Book"]) {
25
        // Books
26
        $arrBooks = get_amazonCategory($config, $query, "Books");
27
    }
28
 
29
    return (array_merge($arrMusic, $arrDigital, $arrBooks));
30
}
31
 
32
// Get Amazon listings
33
function get_amazonCategory($config, $query, $searchIndex, $needMatches = false) {
94 - 34
    $numResults = $config['numResults'];
81 - 35
 
36
    if ($needMatches) {
37
        $_SESSION["discogs"] = "";
38
    }
39
 
99 - 40
    $response = getSearchCache("amazon", $query, $searchIndex);
41
    if ($response === false) {
42
        $serviceName = "ProductAdvertisingAPI";
43
        $region = "us-east-1";
44
        $accessKey = $config["access_key_id"];
45
        $secretKey = $config["secret_key"];
46
        $associate_tag = $config['associate_tag'];
47
$payload="{"
48
        ." \"Keywords\": \"$query\","
49
        ." \"Resources\": ["
50
        ."  \"Images.Primary.Medium\","
51
        ."  \"Images.Primary.Large\","
52
        ."  \"ItemInfo.ByLineInfo\","
53
        ."  \"ItemInfo.ContentInfo\","
54
        ."  \"ItemInfo.Classifications\","
55
        ."  \"ItemInfo.ExternalIds\","
56
        ."  \"ItemInfo.ManufactureInfo\","
57
        ."  \"ItemInfo.ProductInfo\","
58
        ."  \"ItemInfo.TechnicalInfo\","
59
        ."  \"ItemInfo.Title\","
60
        ."  \"Offers.Listings.Condition\","
61
        ."  \"Offers.Listings.Condition.SubCondition\","
62
        ."  \"Offers.Listings.DeliveryInfo.IsAmazonFulfilled\","
63
        ."  \"Offers.Listings.DeliveryInfo.IsFreeShippingEligible\","
64
        ."  \"Offers.Listings.DeliveryInfo.IsPrimeEligible\","
65
        ."  \"Offers.Listings.DeliveryInfo.ShippingCharges\","
66
        ."  \"Offers.Listings.MerchantInfo\","
67
        ."  \"Offers.Listings.Price\""
68
        ." ],"
69
        ." \"SearchIndex\": \"$searchIndex\","
70
        ." \"Availability\": \"Available\","
71
        ." \"Condition\": \"Any\","
72
        ." \"OfferCount\": 3,"
73
        ." \"SortBy\": \"Price:LowToHigh\","
74
        ." \"PartnerTag\": \"$associate_tag\","
75
        ." \"PartnerType\": \"Associates\","
76
        ." \"Marketplace\": \"www.amazon.com\""
77
        ."}";
78
        $host = "webservices.amazon.com";
79
        $uriPath = "/paapi5/searchitems";
81 - 80
 
99 - 81
        $awsv4 = new AwsV4($accessKey, $secretKey);
82
        $awsv4->setRegionName($region);
83
        $awsv4->setServiceName($serviceName);
84
        $awsv4->setPath($uriPath);
85
        $awsv4->setPayload($payload);
86
        $awsv4->setRequestMethod("POST");
87
        $awsv4->addHeader('content-encoding', 'amz-1.0');
88
        $awsv4->addHeader('content-type', 'application/json; charset=utf-8');
89
        $awsv4->addHeader('host', $host);
90
        $awsv4->addHeader('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems');
91
        $headers = $awsv4->getHeaders();
92
        $headerArr = [];
93
        foreach ($headers as $key => $value) {
94
            $headerArr[] = $key . ': ' . $value;
95
        }
81 - 96
 
99 - 97
        $ch = curl_init();
98
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
99
        curl_setopt($ch, CURLOPT_URL, 'https://' . $host . $uriPath);
100
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
101
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
102
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
103
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
104
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
105
        curl_setopt($ch, CURLOPT_REFERER, 'https://' . $host . $uriPath);
106
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
107
        curl_setopt($ch, CURLOPT_POST, 1);
108
        $response = curl_exec($ch);
109
        curl_close($ch);
81 - 110
 
99 - 111
        saveSearchCache("amazon", $query, $searchIndex, $response);
81 - 112
    }
113
 
99 - 114
    $parsed_json = json_decode($response);
115
//echo "<br><pre>";print_r($parsed_json);echo "</pre>";
116
    $arr = [];
81 - 117
 
99 - 118
    if (isset($parsed_json->Errors)) {
119
        foreach ($parsed_json->Errors as $error) {
120
            if ($error->Code != "NoResults") {
121
                my_error_log("Amazon Search - " . $error->Message . " (" . $error->Code . ")");
122
            }
123
        }
124
        return [];
106 - 125
    } else if (!isset($parsed_json->SearchResult)) {
126
        my_error_log("Amazon Search - No Search Result.");
127
        return [];
99 - 128
    }
81 - 129
 
99 - 130
    if ($needMatches) {
131
        $cnt = 0;
132
        $_SESSION["discogs"] = startMatches();
133
    }
81 - 134
 
99 - 135
    $listings = 0;
120 - 136
    $wlAddArr = [];
137
    $wlSearchArr = [];
99 - 138
    // If the response was loaded, parse it and store in array
139
    foreach ($parsed_json->SearchResult->Items as $current) {
140
        if (isset($current->ItemInfo->ExternalIds->UPCs)) {
141
            $barcode = (string)$current->ItemInfo->ExternalIds->UPCs->DisplayValues[0];
142
        }
143
        else if (isset($current->ItemInfo->ExternalIds->EANs)) {
144
            $barcode = (string)$current->ItemInfo->ExternalIds->EANs->DisplayValues[0];
145
        }
146
        else if (isset($current->ItemInfo->ExternalIds->ISBNs)) {
147
            $barcode = (string)$current->ItemInfo->ExternalIds->ISBNs->DisplayValues[0];
148
        }
149
        else if (isset($current->ItemInfo->ExternalIds->EISBNs)) {
150
            $barcode = (string)$current->ItemInfo->ExternalIds->EISBNs->DisplayValues[0];
151
        }
152
        else {
153
            $barcode = "";
154
        }
155
        $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
81 - 156
 
102 - 157
        $pic = !empty($current->Images->Primary->Medium->URL) ? (string)$current->Images->Primary->Medium->URL : "images/no-image-available.jpg";
100 - 158
        $pic = str_replace('http://', 'https://', $pic);
99 - 159
        if (empty($pic)) {
160
            continue;
161
        }
81 - 162
 
99 - 163
        if (strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "Audio CD") !== false) {
164
            $mediaType = "CD";
165
        }
166
        else if (strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "MP3 Music") !== false) {
167
            $mediaType = "Digital";
168
        }
169
        else if (strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "Vinyl") !== false) {
170
            $mediaType = "Record";
171
        }
172
        else if (strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "Paperback") !== false || strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "Sheet") !== false || strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "Hardcover") !== false) {
173
            $mediaType = "Book";
174
        }
175
        else {
176
            continue;
177
        }
81 - 178
 
179
        if ($needMatches) {
99 - 180
            // bugbug: check maxMasterCnt?
120 - 181
            $_SESSION["discogs"] .= addMatch($current, ++$cnt, $mediaType, $wlAddArr, $wlSearchArr);
81 - 182
        }
183
 
99 - 184
        $title = (string)$current->ItemInfo->Title->DisplayValue;
185
        $artists = getArtists($current);
186
        $contributers = getContributers($current);
187
        if (!empty($artists)) {
188
            $title .= " by " . join(", ", $artists);
189
        }
190
        else if (!empty($contributers)) {
191
            $title .= " by " . join(", ", $contributers);
192
        }
81 - 193
 
99 - 194
        $url = str_replace('http://', 'https://', (string)$current->DetailPageURL);
81 - 195
 
99 - 196
        if (empty($url)) {
197
            continue;
198
        }
81 - 199
 
99 - 200
        $bestOffer = false;
81 - 201
 
99 - 202
        $url = str_replace('http://', 'https://', (string)$current->DetailPageURL);
203
        $url .= "&condition=";
81 - 204
 
99 - 205
        if (!empty($current->Offers->Listings)) {
206
            foreach ($current->Offers->Listings as $offer) {
207
                $country = 'US';
208
                if (isset($offer->MerchantInfo->DefaultShippingCountry)) {
209
                    $country = $offer->MerchantInfo->DefaultShippingCountry;
210
                }
211
                $merchantName = "Amazon";
212
                if (strpos($offer->MerchantInfo->Name, "Amazon") === false) {
213
                    $merchantName .= " Marketplace";
214
                }
81 - 215
 
99 - 216
                $condition = (string)$offer->Condition->Value;
217
                $url .= $condition;
218
                $detailCondition = $condition;
219
                if ($condition == "Collectible") {
220
                    $condition = 'Used';
221
                    $detailCondition = "Collectible";
222
                }
223
                if ($condition == "Refurbished") {
224
                    $condition = 'Used';
225
                    $detailCondition = "Refurbished";
226
                }
227
                $currency = (string)$offer->Price->Currency;
228
                $price = number_format(floatval($offer->Price->Amount) , 2, '.', '');
81 - 229
 
99 - 230
                if ($price <= "0.00") {
231
                    continue;
232
                }
81 - 233
 
99 - 234
                $timeLeft = 0;
235
                $listingType = 'Fixed';
236
                $location = 'US';
237
                $zip = '';
238
                $feedbackScore = - 1;
239
                $feedbackPercent = - 1;
240
                $sellerName = "";
241
                $handlingTime = 0;
242
                if ($offer->DeliveryInfo->IsPrimeEligible === true) {
243
                    $sellerName = "Prime";
81 - 244
                }
99 - 245
                if ($mediaType == "Digital") {
246
                    $shippingCost = 0.00;
247
                    $shippingEstimated = false;
248
                    $shippingCurrency = 'USD';
249
                }
250
                else {
251
                    $shippingCost = 3.99; // bugbug
252
                    $shippingEstimated = true; // bugbug
253
                    $shippingCurrency = 'USD';
254
                }
255
                $freeShippingCap = !empty($offer->DeliveryInfo->IsFreeShippingEligible) ? 25 : 0;
81 - 256
 
99 - 257
                if (++$listings > $numResults) {
258
                    continue;
259
                }
81 - 260
 
99 - 261
                $arr[] = array(
262
                    "Merchant" => $merchantName,
263
                    "Condition" => $condition,
264
                    "Title" => $title,
265
                    "Barcode" => $barcode,
266
                    "BarcodeType" => $barcodeType,
267
                    "Image" => $pic,
268
                    "URL" => $url,
269
                    "MediaType" => $mediaType,
270
                    "DetailCondition" => $detailCondition,
271
                    "Country" => $country,
272
                    "BestOffer" => $bestOffer,
273
                    "TimeLeft" => $timeLeft,
274
                    "Price" => $price,
275
                    "Currency" => $currency,
276
                    "ListingType" => $listingType,
277
                    "Location" => $location,
278
                    "Zip" => $zip,
279
                    "FeedbackScore" => $feedbackScore,
280
                    "FeedbackPercent" => $feedbackPercent,
281
                    "SellerName" => $sellerName,
282
                    "HandlingTime" => $handlingTime,
283
                    "ShippingCost" => $shippingCost,
284
                    "ShippingEstimated" => $shippingEstimated,
285
                    "ShippingCurrency" => $shippingCurrency,
286
                    "FreeShippingCap" => $freeShippingCap,
287
                    "Show" => true
288
                );
81 - 289
            }
290
        }
99 - 291
    }
81 - 292
 
99 - 293
    if ($needMatches) {
294
        if ($cnt = 0) {
295
            $_SESSION["discogs"] = "";
81 - 296
        }
99 - 297
        else {
121 - 298
            $_SESSION["discogs"] .= '<script nonce="xxxNONCExxx">';
120 - 299
            $_SESSION["discogs"] .= 'function addDiscogsEventsWait() {';
300
            $_SESSION["discogs"] .= 'document.addEventListener("DOMContentLoaded", function() {';
301
            $_SESSION["discogs"] .= '	addDiscogsEvents();';
302
            $_SESSION["discogs"] .= '});';
303
            $_SESSION["discogs"] .= '}';
304
 
305
            $_SESSION["discogs"] .= 'function addDiscogsEvents() {';
306
            foreach($wlAddArr as $k=>$v) {
307
                $_SESSION["discogs"] .= 'el = document.getElementById("' . $k . '");';
308
                $_SESSION["discogs"] .= 'if (el) document.getElementById("' . $k . '").addEventListener("click", function() {';
309
                $_SESSION["discogs"] .= $v;
310
                $_SESSION["discogs"] .= '	});';
311
            }
312
 
313
            foreach($wlSearchArr as $k=>$v) {
314
                $_SESSION["discogs"] .= 'el = document.getElementById("' . $k . '");';
315
                $_SESSION["discogs"] .= 'if (el) document.getElementById("' . $k . '").addEventListener("click", function() {';
316
                $_SESSION["discogs"] .= $v;
317
                $_SESSION["discogs"] .= '	});';
318
            }
319
            $_SESSION["discogs"] .= '}';
320
            $_SESSION["discogs"] .= 'addDiscogsEventsWait();';
321
            $_SESSION["discogs"] .= '</script>';
322
 
99 - 323
            $_SESSION["discogs"] .= endMatches();
324
        }
81 - 325
    }
99 - 326
 
81 - 327
    // If the response does not indicate 'Success,' log the error(s)
99 - 328
    /******************
81 - 329
    else {
96 - 330
        my_error_log($url);
99 - 331
        if (!empty($parsed_json->OperationRequest->Errors)) {
332
            foreach($parsed_json->OperationRequest->Errors->Error as $error){
96 - 333
                my_error_log($error->Message . " (" . $error->Code . ")");
81 - 334
            }
99 - 335
        } else if (!empty($parsed_json->Errors)) {
336
            foreach($parsed_json->OperationRequest->Errors->Error as $error){
96 - 337
                my_error_log($error->Message . " (" . $error->Code . ")");
81 - 338
            }
99 - 339
        } else if (!empty($parsed_json->Error)) {
340
            my_error_log($parsed_json->Error->Message . " (" . $parsed_json->Error->Code . ")");
81 - 341
        } else {
96 - 342
            my_error_log(print_r($result, 1));
81 - 343
        }
344
    }
99 - 345
    ******************/
81 - 346
 
347
    return $arr;
348
}
349
 
350
function startMatches() {
351
    $str = "<div class=\"container-fluid bg-secondary\">";
352
    $str .= "<h4 class=\"text-center py-2\">Matching Albums</h4>";
353
    $str .= "<form method=\"post\" action=\"/index.php\">";
116 - 354
    $str .= "<input type=\"hidden\" name=\"sessionTab\" value=\"" . MySessionHandler::getSessionTab() . "\" />";
122 - 355
    $str .= "<input type=\"hidden\" name=\"nonce\" value=\"" . $_SESSION["nonce"] . "\" />";
116 - 356
    $str .= "<input id=\"discogsTitle\" type=\"hidden\" name=\"discogsTitle\" value=\"\" />";
357
    $str .= "<input id=\"discogsArtist\" type=\"hidden\" name=\"discogsArtist\" value=\"\" />";
358
    $str .= "<input id=\"discogsBarcode\" type=\"hidden\" name=\"discogsBarcode\" value=\"\" />";
81 - 359
    $str .= "<div id=\"discogsDeck\" class=\"card-deck\">";
360
 
361
    return $str;
362
}
363
 
364
function endMatches() {
365
    $str = "</div>";
366
    $str .= "</form>";
367
    $str .= "</div>";
368
 
369
    return $str;
370
}
371
 
120 - 372
function addMatch($item, $cnt, $mediaType, &$wlAddArr, &$wlSearchArr) {
81 - 373
    $artists = getArtists($item);
374
 
99 - 375
    $contributers = getContributers($item);
81 - 376
 
99 - 377
    $label = "";
378
    if (!empty($item->ItemInfo->ByLineInfo->Manufacturer)) {
100 - 379
        $label = $item->ItemInfo->ByLineInfo->Manufacturer->DisplayValue;
81 - 380
    }
381
 
382
    $languages = [];
99 - 383
    if (!empty($item->ItemInfo->ContentInfo->Languages)) {
384
        foreach ($item->ItemInfo->ContentInfo->Languages->DisplayValues as $language) {
81 - 385
            if ((string)$language->Type != "Unknown") {
99 - 386
                $languages[] = $language->DisplayValue . " (" . $language->Type . ")";
81 - 387
            }
388
        }
389
    }
390
 
101 - 391
    $genres = [];
392
    if (!empty($item->ItemInfo->Genre)) {
393
        foreach($item->ItemInfo->Genre as $genre) {
394
            $genres[] = join(" ", array_map('ucfirst', explode('-', $genre)));
395
        }
396
    }
397
 
398
    $runningTime = "";
399
    if (!empty($item->ItemInfo->RunningTime)) {
400
        if ($mediaType != 'Digital') {
401
            $runningTime = (string)$item->ItemInfo->RunningTime . " minutes";
402
        } else {
403
            $runningTime = gmdate("H:i:s", (int)$item->ItemInfo->RunningTime);
404
        }
405
    }
406
 
81 - 407
    $modal = "";
408
    $str = "<div class=\"card mx-auto discogs-card\">";
116 - 409
    $str .= "<div class=\"card-header bg-info d-flex\">";
99 - 410
    $str .= "<p class=\"card-title font-weight-bold small flex-grow-1\">" . (string)$item->ItemInfo->Title->DisplayValue . " by ";
81 - 411
    $searchArtists = "";
105 - 412
    $wlArtists = "";
99 - 413
    if (!empty($artists)) {
414
        if (count($artists) < 5) {
415
            $wlArtists = join(", ", $artists);
416
            if (!empty($artists) && $artists[0] != 'Various') {
417
                $searchArtists = join(" ", $artists);
418
            }
419
        } else {
420
            $wlArtists = "Various Artists";
81 - 421
        }
422
    }
99 - 423
    else if (!empty($contributers)) {
424
        if (count($contributers) < 5) {
425
            $wlArtists = join(", ", $contributers);
426
            if (!empty($contributers) && $contributers[0] != 'Various') {
427
                $searchArtists = join(" ", $contributers);
428
            }
429
        } else {
430
            $wlArtists = "Various Artists";
431
        }
81 - 432
    }
433
    $str .= $wlArtists;
434
    $str .= "</p>";
435
    $str .= "</div>";
436
 
99 - 437
    $thumbnail = !empty($item->Images->Primary->Medium->URL) ? (string)$item->Images->Primary->Medium->URL : "images/no-image-available.jpg";
81 - 438
 
116 - 439
    $str .= "<div class=\"card-body bg-light mx-auto p-0 m-0 h-100\">";
440
    $str .= "<img class=\"btn responsive-image p-0 m-0 lazyload\" src=\"data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=\" data-src=\"" . $thumbnail . "\" data-toggle=\"modal\" data-target=\"#masterModal" . $cnt . "\" title=\"Album Information\" data-toggle2=\"tooltip\" alt=\"Cover Thumbnail\" />";
81 - 441
    $str .= "</div>";
442
    $str .= "<div class=\"card-footer bg-dark p-0 m-0\">";
443
    $str .= "<div class=\"container clearfix p-0 m-0\">";
444
    $str .= "<span class=\"float-left\">";
122 - 445
    $str .= "<button type=\"button\" class=\"btn btn-primary btn-sm\" data-toggle=\"modal\" data-target=\"#masterModal" . $cnt . "\" title=\"Album Information\" data-toggle2=\"tooltip\"><i class=\"material-icons\">info_outline</i></button>";
81 - 446
 
447
    $str .= "</span>";
448
 
449
    $str .= "<span class=\"float-right\">";
450
 
451
    $barcode = "";
452
    $tmpBarcode = "";
99 - 453
    if (isset($item->ItemInfo->ExternalIds->UPCs)) {
454
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->UPCs->DisplayValues[0];
81 - 455
    }
99 - 456
    else if (isset($item->ItemInfo->ExternalIds->EANs)) {
457
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->EANs->DisplayValues[0];
458
    }
459
    else if (isset($item->ItemInfo->ExternalIds->ISBNs)) {
460
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->ISBNs->DisplayValues[0];
461
    }
462
    else if (isset($item->ItemInfo->ExternalIds->EISBNs)) {
463
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->EISBNs->DisplayValues[0];
464
    }
81 - 465
    $barcodeType = clsLibGTIN::GTINCheck($tmpBarcode, false, 1);
466
    if (!empty($barcodeType)) {
467
        $barcode = $tmpBarcode;
468
    }
469
 
470
    if (isLoggedIn() && !checkWishlist('asin', $item->ASIN)) {
471
        $wlArr = array(
472
            'asin' => (string)$item->ASIN,
99 - 473
            'title' => (string)$item->ItemInfo->Title->DisplayValue,
81 - 474
            'artist' => $wlArtists,
475
            'barcode' => $barcode,
476
            'thumbnail' => $thumbnail,
477
            'url' => (string)$item->DetailPageURL
478
        );
479
        $wl = base64_encode(json_encode($wlArr));
120 - 480
        $str .= "  <button id=\"wl" . $cnt . "Btn\" type=\"button\" class=\"btn btn-primary btn-sm\" title=\"Add to Wishlist\" data-toggle=\"tooltip\"><i class=\"material-icons\">bookmark</i></button>";
481
        $wlAddArr["wl" . $cnt . "Btn"] = 'addWishlist("' . $_SESSION['sessData']['userID'] . '", this,' . $cnt . ',"' . $wl . '");';
81 - 482
    }
483
 
104 - 484
    $searchTitle = 'Searching for:<br><br><strong>' . (string)$item->ItemInfo->Title->DisplayValue . ' by ' . $wlArtists . '</strong>';
81 - 485
    if (!empty($barcode)) {
486
        $searchTitle .= " (" . displayBarcode($barcode) . ")";
487
    }
488
 
120 - 489
    $str .= "  <button id=\"discogsSearch" . $cnt . "Btn\" type=\"submit\" name=\"submit\" value=\"discogsSearch\" class=\"btn btn-primary btn-sm\" title=\"Search for Store Offers\" data-toggle=\"tooltip\"><i class=\"material-icons\">search</i></button>";
81 - 490
    $str .= "</span>";
491
    $str .= "</div>";
120 - 492
 
493
    $wlSearchArr["discogsSearch" . $cnt . "Btn"] = 'document.getElementById("discogsTitle").value = "' . addslashes((string)$item->ItemInfo->Title->DisplayValue) . '";' .
494
                                                   'document.getElementById("discogsArtist").value = "' . addslashes($searchArtists) . '";' .
495
                                                   'document.getElementById("discogsBarcode").value = "' . $barcode . '";' .
496
                                                   'progressBar("' . $searchTitle . '");';
497
 
81 - 498
    $str .= "<span id=\"wishlistAdd" . $cnt . "\"></span>";
499
    $str .= "</div>";
500
 
501
    $modal .= "<div id=\"masterModal" . $cnt . "\" class=\"modal\">";
502
    $modal .= "<div class=\"modal-dialog\">";
503
    $modal .= "<div class=\"modal-content\">";
504
    $modal .= "<div class=\"modal-header bg-primary\">";
99 - 505
    $modal .= "<h4 class=\"modal-title mx-auto\">" . (string)$item->ItemInfo->Title->DisplayValue . " by " . $wlArtists . "</h4>";
120 - 506
    $modal .= "<button type=\"button\" class=\"close\" data-dismiss=\"modal\"><i class=\"material-icons btn-dismiss\">cancel_presentation</i></i></button>";
81 - 507
    $modal .= "</div>";
508
 
509
    $modal .= "<div class=\"modal-body bg-white mx-auto\">";
510
 
99 - 511
    if (!empty($item->Images->Primary->Large->URL)) {
116 - 512
        $modal .= "<img class=\"responsive-image mx-auto mb-4 lazyload\" src=\"data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=\" data-src=\"" . (string)$item->Images->Primary->Large->URL . "\" alt=\"Cover Image\" />";
81 - 513
    }
514
 
515
    $modal .= "<table class=\"table-borderless table-condensed small mx-auto\">";
99 - 516
    $modal .= "<tr><td class=\"px-1\">Title:</td><td class=\"px-1\">" . (string)$item->ItemInfo->Title->DisplayValue . "</td></tr>";
81 - 517
 
518
    $modal .= "<tr><td class=\"px-1\">Artist:</td><td class=\"px-1\">" . join(", ", $artists) . "</td></tr>";
99 - 519
    if (!empty($contributers)) {
520
        $modal .= "<tr><td class=\"px-1\">Creator:</td><td class=\"px-1\">" . join(", ", $contributers) . "</td></tr>";
81 - 521
    }
522
 
523
    if (!empty($actors)) {
524
        $modal .= "<tr><td class=\"px-1\">Actor:</td><td class=\"px-1\">" . join(", ", $actors) . "</td></tr>";
525
    }
526
 
527
    if (!empty($directors)) {
528
        $modal .= "<tr><td class=\"px-1\">Director:</td><td class=\"px-1\">" . join(", ", $directors) . "</td></tr>";
529
    }
530
 
531
    if (!empty($authors)) {
532
        $modal .= "<tr><td class=\"px-1\">Author:</td><td class=\"px-1\">" . join(", ", $authors) . "</td></tr>";
533
    }
534
 
99 - 535
    if (!empty($item->ItemInfo->Classifications->Binding)) {
536
        $modal .= "<tr><td class=\"px-1\">Type:</td><td class=\"px-1\">" . (string)$item->ItemInfo->Classifications->Binding->DisplayValue . "</td></tr>";
81 - 537
    }
538
 
101 - 539
    if (!empty($item->ItemInfo->MediaType)) { //
540
        $modal .= "<tr><td class=\"px-1\">Media Type:</td><td class=\"px-1\">" . (string)$item->ItemInfo->MediaType . "</td></tr>";
81 - 541
    }
542
 
543
    if (!empty($barcode)) {
544
        $modal .= "<tr><td class=\"px-1\">Barcode:</td><td class=\"px-1\">" . displayBarcode($barcode) . "</td></tr>";
545
    }
546
 
99 - 547
    if (!empty($label)) {
548
        $modal .= "<tr><td class=\"px-1\">Label:</td><td class=\"px-1\">" . $label . "</td></tr>";
81 - 549
    }
550
 
551
    if (!empty($languages)) {
552
        $modal .= "<tr><td class=\"px-1\">Languages:</td><td class=\"px-1\">" . join(", ", $languages) . "</td></tr>";
553
    }
554
 
99 - 555
    if (!empty($item->ItemInfo->ContentInfo->PublicationDate)) {
100 - 556
        $modal .= "<tr><td class=\"px-1\">Publication Date:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->PublicationDate->DisplayValue . "</td></tr>";
81 - 557
    }
558
 
99 - 559
    if (!empty($item->ItemInfo->ContentInfo->ReleaseDate)) {
100 - 560
        $modal .= "<tr><td class=\"px-1\">Release Date:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->ReleaseDate->DisplayValue . "</td></tr>";
81 - 561
    }
562
 
101 - 563
    if (!empty($genres)) {
564
        $modal .= "<tr><td class=\"px-1\">Genre:</td><td class=\"px-1\">" . join(", ", $genres) . "</td></tr>";
565
    }
566
 
99 - 567
    if (!empty($item->ItemInfo->ContentInfo->UnitCount->DisplayValue)) {
568
        $modal .= "<tr><td class=\"px-1\">Number of Discs:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->UnitCount->DisplayValue . "</td></tr>";
81 - 569
    }
570
 
99 - 571
    if (!empty($item->ItemInfo->ContentInfo->PagesCount->DisplayValue)) {
572
        $modal .= "<tr><td class=\"px-1\">Number of Pages:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->PagesCount->DisplayValue . "</td></tr>";
81 - 573
    }
574
 
101 - 575
    if (!empty($item->ItemInfo->RunningTime)) {
576
        $modal .= "<tr><td class=\"px-1\">Running Time:</td><td class=\"px-1\">" . $runningTime . "</td></tr>";
577
    }
578
 
579
    if (!empty($item->ItemInfo->Edition)) {
580
        $modal .= "<tr><td class=\"px-1\">Edition:</td><td class=\"px-1\">" . (string)$item->ItemInfo->Edition . "</td></tr>";
581
    }
582
 
583
    if (!empty($item->Tracks)) {
584
        $modal .= "<tr><td colspan=\"2\" class=\"px-1\">Tracks:</td></tr>";
585
        $modal .= "<tr><td colspan=\"2\">";
586
        $modal .= "<ul class=\"pl-3 pt-0 small list-unstyled\">";
587
        foreach ($item->Tracks->Disc as $disc) {
588
            if ((int)$item->ItemInfo->ContentInfo->UnitCount->DisplayValue > 1 && !empty($disc->attributes())) {
589
                $modal .= "<li class=\"font-weight-bold\">Disc " . $disc->attributes() . ":</li>";
590
            }
591
 
592
            foreach($disc->Track as $track) {
593
                $modal .= "<li>" . (!empty($track->attributes()) ? $track->attributes() . ") " : "") . $track . "</li>";
594
            }
595
        }
596
        $modal .= "</ul>";
597
        $modal .= "</td></tr>";
598
    }
599
 
81 - 600
    $modal .= "</table>";
601
    $modal .= "</div>";
602
    $modal .= "<div class=\"modal-footer bg-white justify-content-between\">";
603
    $modal .= "<span class=\"float-right\"><button type=\"button\" class=\"btn btn-danger\" data-dismiss=\"modal\">Close</button></span>";
604
    $modal .= "</div>";
605
    $modal .= "</div>";
606
    $modal .= "</div>";
607
    $modal .= "</div>";
608
    $str .= $modal;
609
    $str .= "</div>";
610
 
611
    return $str;
612
}
613
 
614
function getArtists($item) {
615
    $artists = [];
616
 
101 - 617
    if (!empty($item->ItemInfo->Artist)){
618
        $artists[] = $item->ItemInfo->Artist;
619
    } else if (!empty($item->ItemInfo->ByLineInfo->Contributors)) {
99 - 620
        foreach ($item->ItemInfo->ByLineInfo->Contributors as $artist) {
621
            if ((string)$artist->Role == "Artist") {
622
                $artists[] = $artist->Name;
623
            }
81 - 624
        }
625
    }
626
 
627
    return $artists;
628
}
629
 
99 - 630
function getContributers($item) {
631
    $contributers = [];
632
 
633
    if (!empty($item->ItemInfo->ByLineInfo->Contributors)) {
634
        foreach ($item->ItemInfo->ByLineInfo->Contributors as $creator) {
635
            if ((string)$creator->Role == "Primary Contributor") {
636
                $contributers[] = $creator->Name;
81 - 637
            }
99 - 638
            else {
639
                $contributers[] = $creator->Name . " (" . $creator->Role . ")";
640
            }
81 - 641
        }
642
    }
643
 
99 - 644
    return $contributers;
81 - 645
}
99 - 646
 
647
class AwsV4 {
648
 
649
    private $accessKey = null;
650
    private $secretKey = null;
651
    private $path = null;
652
    private $regionName = null;
653
    private $serviceName = null;
654
    private $httpMethodName = null;
655
    private $queryParametes = array();
656
    private $awsHeaders = array();
657
    private $payload = "";
658
 
659
    private $HMACAlgorithm = "AWS4-HMAC-SHA256";
660
    private $aws4Request = "aws4_request";
661
    private $strSignedHeader = null;
662
    private $xAmzDate = null;
663
    private $currentDate = null;
664
 
665
    public function __construct($accessKey, $secretKey) {
666
        $this->accessKey = $accessKey;
667
        $this->secretKey = $secretKey;
668
        $this->xAmzDate = $this->getTimeStamp();
669
        $this->currentDate = $this->getDate();
670
    }
671
 
672
    function setPath($path) {
673
        $this->path = $path;
674
    }
675
 
676
    function setServiceName($serviceName) {
677
        $this->serviceName = $serviceName;
678
    }
679
 
680
    function setRegionName($regionName) {
681
        $this->regionName = $regionName;
682
    }
683
 
684
    function setPayload($payload) {
685
        $this->payload = $payload;
686
    }
687
 
688
    function setRequestMethod($method) {
689
        $this->httpMethodName = $method;
690
    }
691
 
692
    function addHeader($headerName, $headerValue) {
693
        $this->awsHeaders[$headerName] = $headerValue;
694
    }
695
 
696
    private function prepareCanonicalRequest() {
697
        $canonicalURL = "";
698
        $canonicalURL .= $this->httpMethodName . "\n";
699
        $canonicalURL .= $this->path . "\n" . "\n";
700
        $signedHeaders = '';
701
        foreach ($this->awsHeaders as $key => $value) {
702
            $signedHeaders .= $key . ";";
703
            $canonicalURL .= $key . ":" . $value . "\n";
704
        }
705
        $canonicalURL .= "\n";
706
        $this->strSignedHeader = substr($signedHeaders, 0, -1);
707
        $canonicalURL .= $this->strSignedHeader . "\n";
708
        $canonicalURL .= $this->generateHex($this->payload);
709
        return $canonicalURL;
710
    }
711
 
712
    private function prepareStringToSign($canonicalURL) {
713
        $stringToSign = '';
714
        $stringToSign .= $this->HMACAlgorithm . "\n";
715
        $stringToSign .= $this->xAmzDate . "\n";
716
        $stringToSign .= $this->currentDate . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "\n";
717
        $stringToSign .= $this->generateHex($canonicalURL);
718
        return $stringToSign;
719
    }
720
 
721
    private function calculateSignature($stringToSign) {
722
        $signatureKey = $this->getSignatureKey($this->secretKey, $this->currentDate, $this->regionName, $this->serviceName);
723
        $signature = hash_hmac("sha256", $stringToSign, $signatureKey, true);
724
        $strHexSignature = strtolower(bin2hex($signature));
725
        return $strHexSignature;
726
    }
727
 
728
    public function getHeaders() {
729
        $this->awsHeaders['x-amz-date'] = $this->xAmzDate;
730
        ksort($this->awsHeaders);
731
 
732
        // Step 1: CREATE A CANONICAL REQUEST
733
        $canonicalURL = $this->prepareCanonicalRequest();
734
 
735
        // Step 2: CREATE THE STRING TO SIGN
736
        $stringToSign = $this->prepareStringToSign($canonicalURL);
737
 
738
        // Step 3: CALCULATE THE SIGNATURE
739
        $signature = $this->calculateSignature($stringToSign);
740
 
741
        // Step 4: CALCULATE AUTHORIZATION HEADER
742
        if ($signature) {
743
            $this->awsHeaders['Authorization'] = $this->buildAuthorizationString($signature);
744
            return $this->awsHeaders;
745
        }
746
    }
747
 
748
    private function buildAuthorizationString($strSignature) {
749
        return $this->HMACAlgorithm . " " . "Credential=" . $this->accessKey . "/" . $this->getDate() . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "," . "SignedHeaders=" . $this->strSignedHeader . "," . "Signature=" . $strSignature;
750
    }
751
 
752
    private function generateHex($data) {
753
        return strtolower(bin2hex(hash("sha256", $data, true)));
754
    }
755
 
756
    private function getSignatureKey($key, $date, $regionName, $serviceName) {
757
        $kSecret = "AWS4" . $key;
758
        $kDate = hash_hmac("sha256", $date, $kSecret, true);
759
        $kRegion = hash_hmac("sha256", $regionName, $kDate, true);
760
        $kService = hash_hmac("sha256", $serviceName, $kRegion, true);
761
        $kSigning = hash_hmac("sha256", $this->aws4Request, $kService, true);
762
 
763
        return $kSigning;
764
    }
765
 
766
    private function getTimeStamp() {
767
        return gmdate("Ymd\THis\Z");
768
    }
769
 
770
    private function getDate() {
771
        return gmdate("Ymd");
772
    }
773
}