Subversion Repositories cheapmusic

Rev

Rev 96 | Rev 100 | 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 [];
125
    }
81 - 126
 
99 - 127
    if ($needMatches) {
128
        $cnt = 0;
129
        $_SESSION["discogs"] = startMatches();
130
    }
81 - 131
 
99 - 132
    $listings = 0;
133
    // If the response was loaded, parse it and store in array
134
    foreach ($parsed_json->SearchResult->Items as $current) {
135
        // [ProductGroup] => Digital Music Album
136
        if ($searchIndex == "MP3Downloads" && !empty($current->ItemAttributes->TrackSequence)) {
137
            continue; // skip individual songs
138
        }
81 - 139
 
99 - 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
 
99 - 157
        $pic = str_replace('http://', 'https://', (string)$current->Images->Primary->Medium->URL);
158
        if (empty($pic)) {
159
            continue;
160
        }
81 - 161
 
99 - 162
        if (strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "Audio CD") !== false) {
163
            $mediaType = "CD";
164
        }
165
        else if (strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "MP3 Music") !== false) {
166
            $mediaType = "Digital";
167
        }
168
        else if (strpos($current->ItemInfo->Classifications->Binding->DisplayValue, "Vinyl") !== false) {
169
            $mediaType = "Record";
170
        }
171
        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) {
172
            $mediaType = "Book";
173
        }
174
        else {
175
            continue;
176
        }
81 - 177
 
178
        if ($needMatches) {
99 - 179
            // bugbug: check maxMasterCnt?
180
            $_SESSION["discogs"] .= addMatch($current, ++$cnt, $mediaType);
81 - 181
        }
182
 
99 - 183
        $title = (string)$current->ItemInfo->Title->DisplayValue;
184
        $artists = getArtists($current);
185
        $contributers = getContributers($current);
186
        if (!empty($artists)) {
187
            $title .= " by " . join(", ", $artists);
188
        }
189
        else if (!empty($contributers)) {
190
            $title .= " by " . join(", ", $contributers);
191
        }
81 - 192
 
99 - 193
        $url = str_replace('http://', 'https://', (string)$current->DetailPageURL);
81 - 194
 
99 - 195
        if (empty($url)) {
196
            continue;
197
        }
81 - 198
 
99 - 199
        $bestOffer = false;
81 - 200
 
99 - 201
        $url = str_replace('http://', 'https://', (string)$current->DetailPageURL);
202
        $url .= "&condition=";
81 - 203
 
99 - 204
        if (!empty($current->Offers->Listings)) {
205
            foreach ($current->Offers->Listings as $offer) {
206
                $country = 'US';
207
                if (isset($offer->MerchantInfo->DefaultShippingCountry)) {
208
                    $country = $offer->MerchantInfo->DefaultShippingCountry;
209
                }
210
                $merchantName = "Amazon";
211
                if (strpos($offer->MerchantInfo->Name, "Amazon") === false) {
212
                    $merchantName .= " Marketplace";
213
                }
81 - 214
 
99 - 215
                $condition = (string)$offer->Condition->Value;
216
                $url .= $condition;
217
                $detailCondition = $condition;
218
                if ($condition == "Collectible") {
219
                    $condition = 'Used';
220
                    $detailCondition = "Collectible";
221
                }
222
                if ($condition == "Refurbished") {
223
                    $condition = 'Used';
224
                    $detailCondition = "Refurbished";
225
                }
226
                $currency = (string)$offer->Price->Currency;
227
                $price = number_format(floatval($offer->Price->Amount) , 2, '.', '');
81 - 228
 
99 - 229
                if ($price <= "0.00") {
230
                    continue;
231
                }
81 - 232
 
99 - 233
                $timeLeft = 0;
234
                $listingType = 'Fixed';
235
                $location = 'US';
236
                $zip = '';
237
                $feedbackScore = - 1;
238
                $feedbackPercent = - 1;
239
                $sellerName = "";
240
                $handlingTime = 0;
241
                if ($offer->DeliveryInfo->IsPrimeEligible === true) {
242
                    $sellerName = "Prime";
81 - 243
                }
99 - 244
                if ($mediaType == "Digital") {
245
                    $shippingCost = 0.00;
246
                    $shippingEstimated = false;
247
                    $shippingCurrency = 'USD';
248
                }
249
                else {
250
                    $shippingCost = 3.99; // bugbug
251
                    $shippingEstimated = true; // bugbug
252
                    $shippingCurrency = 'USD';
253
                }
254
                $freeShippingCap = !empty($offer->DeliveryInfo->IsFreeShippingEligible) ? 25 : 0;
81 - 255
 
99 - 256
                if (++$listings > $numResults) {
257
                    continue;
258
                }
81 - 259
 
99 - 260
                $arr[] = array(
261
                    "Merchant" => $merchantName,
262
                    "Condition" => $condition,
263
                    "Title" => $title,
264
                    "Barcode" => $barcode,
265
                    "BarcodeType" => $barcodeType,
266
                    "Image" => $pic,
267
                    "URL" => $url,
268
                    "MediaType" => $mediaType,
269
                    "DetailCondition" => $detailCondition,
270
                    "Country" => $country,
271
                    "BestOffer" => $bestOffer,
272
                    "TimeLeft" => $timeLeft,
273
                    "Price" => $price,
274
                    "Currency" => $currency,
275
                    "ListingType" => $listingType,
276
                    "Location" => $location,
277
                    "Zip" => $zip,
278
                    "FeedbackScore" => $feedbackScore,
279
                    "FeedbackPercent" => $feedbackPercent,
280
                    "SellerName" => $sellerName,
281
                    "HandlingTime" => $handlingTime,
282
                    "ShippingCost" => $shippingCost,
283
                    "ShippingEstimated" => $shippingEstimated,
284
                    "ShippingCurrency" => $shippingCurrency,
285
                    "FreeShippingCap" => $freeShippingCap,
286
                    "Show" => true
287
                );
81 - 288
            }
289
        }
99 - 290
    }
81 - 291
 
99 - 292
    if ($needMatches) {
293
        if ($cnt = 0) {
294
            $_SESSION["discogs"] = "";
81 - 295
        }
99 - 296
        else {
297
            $_SESSION["discogs"] .= endMatches();
298
        }
81 - 299
    }
99 - 300
 
81 - 301
    // If the response does not indicate 'Success,' log the error(s)
99 - 302
    /******************
81 - 303
    else {
96 - 304
        my_error_log($url);
99 - 305
        if (!empty($parsed_json->OperationRequest->Errors)) {
306
            foreach($parsed_json->OperationRequest->Errors->Error as $error){
96 - 307
                my_error_log($error->Message . " (" . $error->Code . ")");
81 - 308
            }
99 - 309
        } else if (!empty($parsed_json->Errors)) {
310
            foreach($parsed_json->OperationRequest->Errors->Error as $error){
96 - 311
                my_error_log($error->Message . " (" . $error->Code . ")");
81 - 312
            }
99 - 313
        } else if (!empty($parsed_json->Error)) {
314
            my_error_log($parsed_json->Error->Message . " (" . $parsed_json->Error->Code . ")");
81 - 315
        } else {
96 - 316
            my_error_log(print_r($result, 1));
81 - 317
        }
318
    }
99 - 319
    ******************/
81 - 320
 
321
    return $arr;
322
}
323
 
324
function startMatches() {
325
    $str = "<div class=\"container-fluid bg-secondary\">";
326
    $str .= "<h4 class=\"text-center py-2\">Matching Albums</h4>";
327
    $str .= "<form method=\"post\" action=\"/index.php\">";
328
    $str .= "<input type=\"hidden\" name=\"sessionTab\" value=\"" . MySessionHandler::getSessionTab() . "\">";
329
    $str .= "<input id=\"discogsTitle\" type=\"hidden\" name=\"discogsTitle\" value=\"\">";
330
    $str .= "<input id=\"discogsArtist\" type=\"hidden\" name=\"discogsArtist\" value=\"\">";
331
    $str .= "<input id=\"discogsBarcode\" type=\"hidden\" name=\"discogsBarcode\" value=\"\">";
332
    $str .= "<div id=\"discogsDeck\" class=\"card-deck\">";
333
 
334
    return $str;
335
}
336
 
337
function endMatches() {
338
    $str = "</div>";
339
    $str .= "</form>";
340
    $str .= "</div>";
341
 
342
    return $str;
343
}
344
 
345
function addMatch($item, $cnt, $mediaType) {
346
    $artists = getArtists($item);
347
 
99 - 348
    $contributers = getContributers($item);
81 - 349
 
99 - 350
    $label = "";
351
    if (!empty($item->ItemInfo->ByLineInfo->Manufacturer)) {
352
        $label = $item->ItemInfo->ByLineInfo->Manufacturer.DisplayValue;
81 - 353
    }
354
 
355
    $languages = [];
99 - 356
    if (!empty($item->ItemInfo->ContentInfo->Languages)) {
357
        foreach ($item->ItemInfo->ContentInfo->Languages->DisplayValues as $language) {
81 - 358
            if ((string)$language->Type != "Unknown") {
99 - 359
                $languages[] = $language->DisplayValue . " (" . $language->Type . ")";
81 - 360
            }
361
        }
362
    }
363
 
364
    $modal = "";
365
    $str = "<div class=\"card mx-auto discogs-card\">";
366
    $str .= "<div class=\"card-header bg-info d-flex h-100\">";
99 - 367
    $str .= "<p class=\"card-title font-weight-bold small flex-grow-1\">" . (string)$item->ItemInfo->Title->DisplayValue . " by ";
81 - 368
    $searchArtists = "";
99 - 369
    if (!empty($artists)) {
370
        if (count($artists) < 5) {
371
            $wlArtists = join(", ", $artists);
372
            if (!empty($artists) && $artists[0] != 'Various') {
373
                $searchArtists = join(" ", $artists);
374
            }
375
        } else {
376
            $wlArtists = "Various Artists";
81 - 377
        }
378
    }
99 - 379
    else if (!empty($contributers)) {
380
        if (count($contributers) < 5) {
381
            $wlArtists = join(", ", $contributers);
382
            if (!empty($contributers) && $contributers[0] != 'Various') {
383
                $searchArtists = join(" ", $contributers);
384
            }
385
        } else {
386
            $wlArtists = "Various Artists";
387
        }
81 - 388
    }
389
    $str .= $wlArtists;
390
    $str .= "</p>";
391
    $str .= "</div>";
392
 
99 - 393
    $thumbnail = !empty($item->Images->Primary->Medium->URL) ? (string)$item->Images->Primary->Medium->URL : "images/no-image-available.jpg";
81 - 394
 
395
    $str .= "<div class=\"card-body bg-light mx-auto p-0 m-0\">";
396
    $str .= "<img class=\"btn responsive-image p-0 m-0\" src=\"" . $thumbnail . "\" data-toggle=\"modal\" data-target=\"#masterModal" . $cnt . "\" title=\"Album Information\" data-toggle2=\"tooltip\" alt=\"Cover Thumbnail\">";
397
    $str .= "</div>";
398
    $str .= "<div class=\"card-footer bg-dark p-0 m-0\">";
399
    $str .= "<div class=\"container clearfix p-0 m-0\">";
400
    $str .= "<span class=\"float-left\">";
401
    $str .= "<button type=\"button\" class=\"btn btn-primary m-1 btn-sm\" data-toggle=\"modal\" data-target=\"#masterModal" . $cnt . "\" title=\"Album Information\" data-toggle2=\"tooltip\"><i class=\"fas fa-info\"></i></button>";
402
 
403
    $str .= "</span>";
404
 
405
    $str .= "<span class=\"float-right\">";
406
 
407
    $barcode = "";
408
    $tmpBarcode = "";
99 - 409
    if (isset($item->ItemInfo->ExternalIds->UPCs)) {
410
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->UPCs->DisplayValues[0];
81 - 411
    }
99 - 412
    else if (isset($item->ItemInfo->ExternalIds->EANs)) {
413
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->EANs->DisplayValues[0];
414
    }
415
    else if (isset($item->ItemInfo->ExternalIds->ISBNs)) {
416
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->ISBNs->DisplayValues[0];
417
    }
418
    else if (isset($item->ItemInfo->ExternalIds->EISBNs)) {
419
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->EISBNs->DisplayValues[0];
420
    }
81 - 421
    $barcodeType = clsLibGTIN::GTINCheck($tmpBarcode, false, 1);
422
    if (!empty($barcodeType)) {
423
        $barcode = $tmpBarcode;
424
    }
425
 
426
    if (isLoggedIn() && !checkWishlist('asin', $item->ASIN)) {
427
        $wlArr = array(
428
            'asin' => (string)$item->ASIN,
99 - 429
            'title' => (string)$item->ItemInfo->Title->DisplayValue,
81 - 430
            'artist' => $wlArtists,
431
            'barcode' => $barcode,
432
            'thumbnail' => $thumbnail,
433
            'url' => (string)$item->DetailPageURL
434
        );
435
        $wl = base64_encode(json_encode($wlArr));
436
        $str .= "  <button type=\"button\" class=\"btn btn-primary m-1 btn-sm\" onclick=\"addWishlist('" . $_SESSION['sessData']['userID'] . "',this," . $cnt . ",'" . $wl . "');\" title=\"Add to Wishlist\" data-toggle=\"tooltip\"><i class=\"fas fa-bookmark\"></i></button>";
437
    }
438
 
99 - 439
    $searchTitle = 'Searching for:<br><br><strong>' . (string)$item->ItemInfo->Title->DisplayValue . ' by' . $wlArtists . '</strong>';
81 - 440
    if (!empty($barcode)) {
441
        $searchTitle .= " (" . displayBarcode($barcode) . ")";
442
    }
443
 
99 - 444
    $str .= "  <button type=\"submit\" name=\"submit\" value=\"discogsSearch\" class=\"btn btn-primary m-1 btn-sm\" onclick=\"document.getElementById('discogsTitle').value = '" . addslashes((string)$item->ItemInfo->Title->DisplayValue) . "';document.getElementById('discogsArtist').value = '" . addslashes($searchArtists) . "';document.getElementById('discogsBarcode').value = '" . $barcode . "';progressBar('" . sanitizeInput2($searchTitle) . "');\" title=\"Search for Store Offers\" data-toggle=\"tooltip\"><i class=\"fas fa-search\"></i></button>";
81 - 445
    $str .= "</span>";
446
    $str .= "</div>";
447
    $str .= "<span id=\"wishlistAdd" . $cnt . "\"></span>";
448
    $str .= "</div>";
449
 
450
    $modal .= "<div id=\"masterModal" . $cnt . "\" class=\"modal\">";
451
    $modal .= "<div class=\"modal-dialog\">";
452
    $modal .= "<div class=\"modal-content\">";
453
    $modal .= "<div class=\"modal-header bg-primary\">";
99 - 454
    $modal .= "<h4 class=\"modal-title mx-auto\">" . (string)$item->ItemInfo->Title->DisplayValue . " by " . $wlArtists . "</h4>";
81 - 455
    $modal .= "<button type=\"button\" class=\"close\" data-dismiss=\"modal\"><i class=\"fas fa-window-close btn-dismiss\"></i></button>";
456
    $modal .= "</div>";
457
 
458
    $modal .= "<div class=\"modal-body bg-white mx-auto\">";
459
 
99 - 460
    if (!empty($item->Images->Primary->Large->URL)) {
461
        $modal .= "<img class=\"responsive-image mx-auto mb-4\" src=\"" . (string)$item->Images->Primary->Large->URL . "\" alt=\"Cover Image\">";
81 - 462
    }
463
 
464
    $modal .= "<table class=\"table-borderless table-condensed small mx-auto\">";
99 - 465
    $modal .= "<tr><td class=\"px-1\">Title:</td><td class=\"px-1\">" . (string)$item->ItemInfo->Title->DisplayValue . "</td></tr>";
81 - 466
 
467
    $modal .= "<tr><td class=\"px-1\">Artist:</td><td class=\"px-1\">" . join(", ", $artists) . "</td></tr>";
99 - 468
    if (!empty($contributers)) {
469
        $modal .= "<tr><td class=\"px-1\">Creator:</td><td class=\"px-1\">" . join(", ", $contributers) . "</td></tr>";
81 - 470
    }
471
 
472
    if (!empty($actors)) {
473
        $modal .= "<tr><td class=\"px-1\">Actor:</td><td class=\"px-1\">" . join(", ", $actors) . "</td></tr>";
474
    }
475
 
476
    if (!empty($directors)) {
477
        $modal .= "<tr><td class=\"px-1\">Director:</td><td class=\"px-1\">" . join(", ", $directors) . "</td></tr>";
478
    }
479
 
480
    if (!empty($authors)) {
481
        $modal .= "<tr><td class=\"px-1\">Author:</td><td class=\"px-1\">" . join(", ", $authors) . "</td></tr>";
482
    }
483
 
99 - 484
    if (!empty($item->ItemInfo->Classifications->Binding)) {
485
        $modal .= "<tr><td class=\"px-1\">Type:</td><td class=\"px-1\">" . (string)$item->ItemInfo->Classifications->Binding->DisplayValue . "</td></tr>";
81 - 486
    }
487
 
488
    if (!empty($item->ItemAttributes->MediaType)) {
489
        $modal .= "<tr><td class=\"px-1\">Media Type:</td><td class=\"px-1\">" . (string)$item->ItemAttributes->MediaType . "</td></tr>";
490
    }
491
 
492
    if (!empty($barcode)) {
493
        $modal .= "<tr><td class=\"px-1\">Barcode:</td><td class=\"px-1\">" . displayBarcode($barcode) . "</td></tr>";
494
    }
495
 
99 - 496
    if (!empty($label)) {
497
        $modal .= "<tr><td class=\"px-1\">Label:</td><td class=\"px-1\">" . $label . "</td></tr>";
81 - 498
    }
499
 
500
    if (!empty($languages)) {
501
        $modal .= "<tr><td class=\"px-1\">Languages:</td><td class=\"px-1\">" . join(", ", $languages) . "</td></tr>";
502
    }
503
 
99 - 504
    if (!empty($item->ItemInfo->ContentInfo->PublicationDate)) {
505
        $modal .= "<tr><td class=\"px-1\">Publication Date:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->PublicationDate . "</td></tr>";
81 - 506
    }
507
 
99 - 508
    if (!empty($item->ItemInfo->ContentInfo->ReleaseDate)) {
509
        $modal .= "<tr><td class=\"px-1\">Release Date:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->ReleaseDate . "</td></tr>";
81 - 510
    }
511
 
99 - 512
    if (!empty($item->ItemInfo->ContentInfo->UnitCount->DisplayValue)) {
513
        $modal .= "<tr><td class=\"px-1\">Number of Discs:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->UnitCount->DisplayValue . "</td></tr>";
81 - 514
    }
515
 
99 - 516
    if (!empty($item->ItemInfo->ContentInfo->PagesCount->DisplayValue)) {
517
        $modal .= "<tr><td class=\"px-1\">Number of Pages:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->PagesCount->DisplayValue . "</td></tr>";
81 - 518
    }
519
 
520
    $modal .= "</table>";
521
    $modal .= "</div>";
522
    $modal .= "<div class=\"modal-footer bg-white justify-content-between\">";
523
    $modal .= "<span class=\"float-right\"><button type=\"button\" class=\"btn btn-danger\" data-dismiss=\"modal\">Close</button></span>";
524
    $modal .= "</div>";
525
    $modal .= "</div>";
526
    $modal .= "</div>";
527
    $modal .= "</div>";
528
    $str .= $modal;
529
    $str .= "</div>";
530
 
531
    return $str;
532
}
533
 
534
function getArtists($item) {
535
    $artists = [];
536
 
99 - 537
    if (!empty($item->ItemInfo->ByLineInfo->Contributors)) {
538
        foreach ($item->ItemInfo->ByLineInfo->Contributors as $artist) {
539
            if ((string)$artist->Role == "Artist") {
540
                $artists[] = $artist->Name;
541
            }
81 - 542
        }
543
    }
544
 
545
    return $artists;
546
}
547
 
99 - 548
function getContributers($item) {
549
    $contributers = [];
550
 
551
    if (!empty($item->ItemInfo->ByLineInfo->Contributors)) {
552
        foreach ($item->ItemInfo->ByLineInfo->Contributors as $creator) {
553
            if ((string)$creator->Role == "Primary Contributor") {
554
                $contributers[] = $creator->Name;
81 - 555
            }
99 - 556
            else {
557
                $contributers[] = $creator->Name . " (" . $creator->Role . ")";
558
            }
81 - 559
        }
560
    }
561
 
99 - 562
    return $contributers;
81 - 563
}
99 - 564
 
565
class AwsV4 {
566
 
567
    private $accessKey = null;
568
    private $secretKey = null;
569
    private $path = null;
570
    private $regionName = null;
571
    private $serviceName = null;
572
    private $httpMethodName = null;
573
    private $queryParametes = array();
574
    private $awsHeaders = array();
575
    private $payload = "";
576
 
577
    private $HMACAlgorithm = "AWS4-HMAC-SHA256";
578
    private $aws4Request = "aws4_request";
579
    private $strSignedHeader = null;
580
    private $xAmzDate = null;
581
    private $currentDate = null;
582
 
583
    public function __construct($accessKey, $secretKey) {
584
        $this->accessKey = $accessKey;
585
        $this->secretKey = $secretKey;
586
        $this->xAmzDate = $this->getTimeStamp();
587
        $this->currentDate = $this->getDate();
588
    }
589
 
590
    function setPath($path) {
591
        $this->path = $path;
592
    }
593
 
594
    function setServiceName($serviceName) {
595
        $this->serviceName = $serviceName;
596
    }
597
 
598
    function setRegionName($regionName) {
599
        $this->regionName = $regionName;
600
    }
601
 
602
    function setPayload($payload) {
603
        $this->payload = $payload;
604
    }
605
 
606
    function setRequestMethod($method) {
607
        $this->httpMethodName = $method;
608
    }
609
 
610
    function addHeader($headerName, $headerValue) {
611
        $this->awsHeaders[$headerName] = $headerValue;
612
    }
613
 
614
    private function prepareCanonicalRequest() {
615
        $canonicalURL = "";
616
        $canonicalURL .= $this->httpMethodName . "\n";
617
        $canonicalURL .= $this->path . "\n" . "\n";
618
        $signedHeaders = '';
619
        foreach ($this->awsHeaders as $key => $value) {
620
            $signedHeaders .= $key . ";";
621
            $canonicalURL .= $key . ":" . $value . "\n";
622
        }
623
        $canonicalURL .= "\n";
624
        $this->strSignedHeader = substr($signedHeaders, 0, -1);
625
        $canonicalURL .= $this->strSignedHeader . "\n";
626
        $canonicalURL .= $this->generateHex($this->payload);
627
        return $canonicalURL;
628
    }
629
 
630
    private function prepareStringToSign($canonicalURL) {
631
        $stringToSign = '';
632
        $stringToSign .= $this->HMACAlgorithm . "\n";
633
        $stringToSign .= $this->xAmzDate . "\n";
634
        $stringToSign .= $this->currentDate . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "\n";
635
        $stringToSign .= $this->generateHex($canonicalURL);
636
        return $stringToSign;
637
    }
638
 
639
    private function calculateSignature($stringToSign) {
640
        $signatureKey = $this->getSignatureKey($this->secretKey, $this->currentDate, $this->regionName, $this->serviceName);
641
        $signature = hash_hmac("sha256", $stringToSign, $signatureKey, true);
642
        $strHexSignature = strtolower(bin2hex($signature));
643
        return $strHexSignature;
644
    }
645
 
646
    public function getHeaders() {
647
        $this->awsHeaders['x-amz-date'] = $this->xAmzDate;
648
        ksort($this->awsHeaders);
649
 
650
        // Step 1: CREATE A CANONICAL REQUEST
651
        $canonicalURL = $this->prepareCanonicalRequest();
652
 
653
        // Step 2: CREATE THE STRING TO SIGN
654
        $stringToSign = $this->prepareStringToSign($canonicalURL);
655
 
656
        // Step 3: CALCULATE THE SIGNATURE
657
        $signature = $this->calculateSignature($stringToSign);
658
 
659
        // Step 4: CALCULATE AUTHORIZATION HEADER
660
        if ($signature) {
661
            $this->awsHeaders['Authorization'] = $this->buildAuthorizationString($signature);
662
            return $this->awsHeaders;
663
        }
664
    }
665
 
666
    private function buildAuthorizationString($strSignature) {
667
        return $this->HMACAlgorithm . " " . "Credential=" . $this->accessKey . "/" . $this->getDate() . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "," . "SignedHeaders=" . $this->strSignedHeader . "," . "Signature=" . $strSignature;
668
    }
669
 
670
    private function generateHex($data) {
671
        return strtolower(bin2hex(hash("sha256", $data, true)));
672
    }
673
 
674
    private function getSignatureKey($key, $date, $regionName, $serviceName) {
675
        $kSecret = "AWS4" . $key;
676
        $kDate = hash_hmac("sha256", $date, $kSecret, true);
677
        $kRegion = hash_hmac("sha256", $regionName, $kDate, true);
678
        $kService = hash_hmac("sha256", $serviceName, $kRegion, true);
679
        $kSigning = hash_hmac("sha256", $this->aws4Request, $kService, true);
680
 
681
        return $kSigning;
682
    }
683
 
684
    private function getTimeStamp() {
685
        return gmdate("Ymd\THis\Z");
686
    }
687
 
688
    private function getDate() {
689
        return gmdate("Ymd");
690
    }
691
}