Subversion Repositories cheapmusic

Rev

Rev 99 | Rev 101 | 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
 
100 - 157
        $pic = !empty($item->Images->Primary->Medium->URL) ? (string)$item->Images->Primary->Medium->URL : "images/no-image-available.jpg";
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?
181
            $_SESSION["discogs"] .= addMatch($current, ++$cnt, $mediaType);
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 {
298
            $_SESSION["discogs"] .= endMatches();
299
        }
81 - 300
    }
99 - 301
 
81 - 302
    // If the response does not indicate 'Success,' log the error(s)
99 - 303
    /******************
81 - 304
    else {
96 - 305
        my_error_log($url);
99 - 306
        if (!empty($parsed_json->OperationRequest->Errors)) {
307
            foreach($parsed_json->OperationRequest->Errors->Error as $error){
96 - 308
                my_error_log($error->Message . " (" . $error->Code . ")");
81 - 309
            }
99 - 310
        } else if (!empty($parsed_json->Errors)) {
311
            foreach($parsed_json->OperationRequest->Errors->Error as $error){
96 - 312
                my_error_log($error->Message . " (" . $error->Code . ")");
81 - 313
            }
99 - 314
        } else if (!empty($parsed_json->Error)) {
315
            my_error_log($parsed_json->Error->Message . " (" . $parsed_json->Error->Code . ")");
81 - 316
        } else {
96 - 317
            my_error_log(print_r($result, 1));
81 - 318
        }
319
    }
99 - 320
    ******************/
81 - 321
 
322
    return $arr;
323
}
324
 
325
function startMatches() {
326
    $str = "<div class=\"container-fluid bg-secondary\">";
327
    $str .= "<h4 class=\"text-center py-2\">Matching Albums</h4>";
328
    $str .= "<form method=\"post\" action=\"/index.php\">";
329
    $str .= "<input type=\"hidden\" name=\"sessionTab\" value=\"" . MySessionHandler::getSessionTab() . "\">";
330
    $str .= "<input id=\"discogsTitle\" type=\"hidden\" name=\"discogsTitle\" value=\"\">";
331
    $str .= "<input id=\"discogsArtist\" type=\"hidden\" name=\"discogsArtist\" value=\"\">";
332
    $str .= "<input id=\"discogsBarcode\" type=\"hidden\" name=\"discogsBarcode\" value=\"\">";
333
    $str .= "<div id=\"discogsDeck\" class=\"card-deck\">";
334
 
335
    return $str;
336
}
337
 
338
function endMatches() {
339
    $str = "</div>";
340
    $str .= "</form>";
341
    $str .= "</div>";
342
 
343
    return $str;
344
}
345
 
346
function addMatch($item, $cnt, $mediaType) {
347
    $artists = getArtists($item);
348
 
99 - 349
    $contributers = getContributers($item);
81 - 350
 
99 - 351
    $label = "";
352
    if (!empty($item->ItemInfo->ByLineInfo->Manufacturer)) {
100 - 353
        $label = $item->ItemInfo->ByLineInfo->Manufacturer->DisplayValue;
81 - 354
    }
355
 
356
    $languages = [];
99 - 357
    if (!empty($item->ItemInfo->ContentInfo->Languages)) {
358
        foreach ($item->ItemInfo->ContentInfo->Languages->DisplayValues as $language) {
81 - 359
            if ((string)$language->Type != "Unknown") {
99 - 360
                $languages[] = $language->DisplayValue . " (" . $language->Type . ")";
81 - 361
            }
362
        }
363
    }
364
 
365
    $modal = "";
366
    $str = "<div class=\"card mx-auto discogs-card\">";
367
    $str .= "<div class=\"card-header bg-info d-flex h-100\">";
99 - 368
    $str .= "<p class=\"card-title font-weight-bold small flex-grow-1\">" . (string)$item->ItemInfo->Title->DisplayValue . " by ";
81 - 369
    $searchArtists = "";
99 - 370
    if (!empty($artists)) {
371
        if (count($artists) < 5) {
372
            $wlArtists = join(", ", $artists);
373
            if (!empty($artists) && $artists[0] != 'Various') {
374
                $searchArtists = join(" ", $artists);
375
            }
376
        } else {
377
            $wlArtists = "Various Artists";
81 - 378
        }
379
    }
99 - 380
    else if (!empty($contributers)) {
381
        if (count($contributers) < 5) {
382
            $wlArtists = join(", ", $contributers);
383
            if (!empty($contributers) && $contributers[0] != 'Various') {
384
                $searchArtists = join(" ", $contributers);
385
            }
386
        } else {
387
            $wlArtists = "Various Artists";
388
        }
81 - 389
    }
390
    $str .= $wlArtists;
391
    $str .= "</p>";
392
    $str .= "</div>";
393
 
99 - 394
    $thumbnail = !empty($item->Images->Primary->Medium->URL) ? (string)$item->Images->Primary->Medium->URL : "images/no-image-available.jpg";
81 - 395
 
396
    $str .= "<div class=\"card-body bg-light mx-auto p-0 m-0\">";
397
    $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\">";
398
    $str .= "</div>";
399
    $str .= "<div class=\"card-footer bg-dark p-0 m-0\">";
400
    $str .= "<div class=\"container clearfix p-0 m-0\">";
401
    $str .= "<span class=\"float-left\">";
402
    $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>";
403
 
404
    $str .= "</span>";
405
 
406
    $str .= "<span class=\"float-right\">";
407
 
408
    $barcode = "";
409
    $tmpBarcode = "";
99 - 410
    if (isset($item->ItemInfo->ExternalIds->UPCs)) {
411
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->UPCs->DisplayValues[0];
81 - 412
    }
99 - 413
    else if (isset($item->ItemInfo->ExternalIds->EANs)) {
414
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->EANs->DisplayValues[0];
415
    }
416
    else if (isset($item->ItemInfo->ExternalIds->ISBNs)) {
417
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->ISBNs->DisplayValues[0];
418
    }
419
    else if (isset($item->ItemInfo->ExternalIds->EISBNs)) {
420
        $tmpBarcode = (string)$item->ItemInfo->ExternalIds->EISBNs->DisplayValues[0];
421
    }
81 - 422
    $barcodeType = clsLibGTIN::GTINCheck($tmpBarcode, false, 1);
423
    if (!empty($barcodeType)) {
424
        $barcode = $tmpBarcode;
425
    }
426
 
427
    if (isLoggedIn() && !checkWishlist('asin', $item->ASIN)) {
428
        $wlArr = array(
429
            'asin' => (string)$item->ASIN,
99 - 430
            'title' => (string)$item->ItemInfo->Title->DisplayValue,
81 - 431
            'artist' => $wlArtists,
432
            'barcode' => $barcode,
433
            'thumbnail' => $thumbnail,
434
            'url' => (string)$item->DetailPageURL
435
        );
436
        $wl = base64_encode(json_encode($wlArr));
437
        $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>";
438
    }
439
 
99 - 440
    $searchTitle = 'Searching for:<br><br><strong>' . (string)$item->ItemInfo->Title->DisplayValue . ' by' . $wlArtists . '</strong>';
81 - 441
    if (!empty($barcode)) {
442
        $searchTitle .= " (" . displayBarcode($barcode) . ")";
443
    }
444
 
99 - 445
    $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 - 446
    $str .= "</span>";
447
    $str .= "</div>";
448
    $str .= "<span id=\"wishlistAdd" . $cnt . "\"></span>";
449
    $str .= "</div>";
450
 
451
    $modal .= "<div id=\"masterModal" . $cnt . "\" class=\"modal\">";
452
    $modal .= "<div class=\"modal-dialog\">";
453
    $modal .= "<div class=\"modal-content\">";
454
    $modal .= "<div class=\"modal-header bg-primary\">";
99 - 455
    $modal .= "<h4 class=\"modal-title mx-auto\">" . (string)$item->ItemInfo->Title->DisplayValue . " by " . $wlArtists . "</h4>";
81 - 456
    $modal .= "<button type=\"button\" class=\"close\" data-dismiss=\"modal\"><i class=\"fas fa-window-close btn-dismiss\"></i></button>";
457
    $modal .= "</div>";
458
 
459
    $modal .= "<div class=\"modal-body bg-white mx-auto\">";
460
 
99 - 461
    if (!empty($item->Images->Primary->Large->URL)) {
462
        $modal .= "<img class=\"responsive-image mx-auto mb-4\" src=\"" . (string)$item->Images->Primary->Large->URL . "\" alt=\"Cover Image\">";
81 - 463
    }
464
 
465
    $modal .= "<table class=\"table-borderless table-condensed small mx-auto\">";
99 - 466
    $modal .= "<tr><td class=\"px-1\">Title:</td><td class=\"px-1\">" . (string)$item->ItemInfo->Title->DisplayValue . "</td></tr>";
81 - 467
 
468
    $modal .= "<tr><td class=\"px-1\">Artist:</td><td class=\"px-1\">" . join(", ", $artists) . "</td></tr>";
99 - 469
    if (!empty($contributers)) {
470
        $modal .= "<tr><td class=\"px-1\">Creator:</td><td class=\"px-1\">" . join(", ", $contributers) . "</td></tr>";
81 - 471
    }
472
 
473
    if (!empty($actors)) {
474
        $modal .= "<tr><td class=\"px-1\">Actor:</td><td class=\"px-1\">" . join(", ", $actors) . "</td></tr>";
475
    }
476
 
477
    if (!empty($directors)) {
478
        $modal .= "<tr><td class=\"px-1\">Director:</td><td class=\"px-1\">" . join(", ", $directors) . "</td></tr>";
479
    }
480
 
481
    if (!empty($authors)) {
482
        $modal .= "<tr><td class=\"px-1\">Author:</td><td class=\"px-1\">" . join(", ", $authors) . "</td></tr>";
483
    }
484
 
99 - 485
    if (!empty($item->ItemInfo->Classifications->Binding)) {
486
        $modal .= "<tr><td class=\"px-1\">Type:</td><td class=\"px-1\">" . (string)$item->ItemInfo->Classifications->Binding->DisplayValue . "</td></tr>";
81 - 487
    }
488
 
489
    if (!empty($item->ItemAttributes->MediaType)) {
490
        $modal .= "<tr><td class=\"px-1\">Media Type:</td><td class=\"px-1\">" . (string)$item->ItemAttributes->MediaType . "</td></tr>";
491
    }
492
 
493
    if (!empty($barcode)) {
494
        $modal .= "<tr><td class=\"px-1\">Barcode:</td><td class=\"px-1\">" . displayBarcode($barcode) . "</td></tr>";
495
    }
496
 
99 - 497
    if (!empty($label)) {
498
        $modal .= "<tr><td class=\"px-1\">Label:</td><td class=\"px-1\">" . $label . "</td></tr>";
81 - 499
    }
500
 
501
    if (!empty($languages)) {
502
        $modal .= "<tr><td class=\"px-1\">Languages:</td><td class=\"px-1\">" . join(", ", $languages) . "</td></tr>";
503
    }
504
 
99 - 505
    if (!empty($item->ItemInfo->ContentInfo->PublicationDate)) {
100 - 506
        $modal .= "<tr><td class=\"px-1\">Publication Date:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->PublicationDate->DisplayValue . "</td></tr>";
81 - 507
    }
508
 
99 - 509
    if (!empty($item->ItemInfo->ContentInfo->ReleaseDate)) {
100 - 510
        $modal .= "<tr><td class=\"px-1\">Release Date:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->ReleaseDate->DisplayValue . "</td></tr>";
81 - 511
    }
512
 
99 - 513
    if (!empty($item->ItemInfo->ContentInfo->UnitCount->DisplayValue)) {
514
        $modal .= "<tr><td class=\"px-1\">Number of Discs:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->UnitCount->DisplayValue . "</td></tr>";
81 - 515
    }
516
 
99 - 517
    if (!empty($item->ItemInfo->ContentInfo->PagesCount->DisplayValue)) {
518
        $modal .= "<tr><td class=\"px-1\">Number of Pages:</td><td class=\"px-1\">" . (string)$item->ItemInfo->ContentInfo->PagesCount->DisplayValue . "</td></tr>";
81 - 519
    }
520
 
521
    $modal .= "</table>";
522
    $modal .= "</div>";
523
    $modal .= "<div class=\"modal-footer bg-white justify-content-between\">";
524
    $modal .= "<span class=\"float-right\"><button type=\"button\" class=\"btn btn-danger\" data-dismiss=\"modal\">Close</button></span>";
525
    $modal .= "</div>";
526
    $modal .= "</div>";
527
    $modal .= "</div>";
528
    $modal .= "</div>";
529
    $str .= $modal;
530
    $str .= "</div>";
531
 
532
    return $str;
533
}
534
 
535
function getArtists($item) {
536
    $artists = [];
537
 
99 - 538
    if (!empty($item->ItemInfo->ByLineInfo->Contributors)) {
539
        foreach ($item->ItemInfo->ByLineInfo->Contributors as $artist) {
540
            if ((string)$artist->Role == "Artist") {
541
                $artists[] = $artist->Name;
542
            }
81 - 543
        }
544
    }
545
 
546
    return $artists;
547
}
548
 
99 - 549
function getContributers($item) {
550
    $contributers = [];
551
 
552
    if (!empty($item->ItemInfo->ByLineInfo->Contributors)) {
553
        foreach ($item->ItemInfo->ByLineInfo->Contributors as $creator) {
554
            if ((string)$creator->Role == "Primary Contributor") {
555
                $contributers[] = $creator->Name;
81 - 556
            }
99 - 557
            else {
558
                $contributers[] = $creator->Name . " (" . $creator->Role . ")";
559
            }
81 - 560
        }
561
    }
562
 
99 - 563
    return $contributers;
81 - 564
}
99 - 565
 
566
class AwsV4 {
567
 
568
    private $accessKey = null;
569
    private $secretKey = null;
570
    private $path = null;
571
    private $regionName = null;
572
    private $serviceName = null;
573
    private $httpMethodName = null;
574
    private $queryParametes = array();
575
    private $awsHeaders = array();
576
    private $payload = "";
577
 
578
    private $HMACAlgorithm = "AWS4-HMAC-SHA256";
579
    private $aws4Request = "aws4_request";
580
    private $strSignedHeader = null;
581
    private $xAmzDate = null;
582
    private $currentDate = null;
583
 
584
    public function __construct($accessKey, $secretKey) {
585
        $this->accessKey = $accessKey;
586
        $this->secretKey = $secretKey;
587
        $this->xAmzDate = $this->getTimeStamp();
588
        $this->currentDate = $this->getDate();
589
    }
590
 
591
    function setPath($path) {
592
        $this->path = $path;
593
    }
594
 
595
    function setServiceName($serviceName) {
596
        $this->serviceName = $serviceName;
597
    }
598
 
599
    function setRegionName($regionName) {
600
        $this->regionName = $regionName;
601
    }
602
 
603
    function setPayload($payload) {
604
        $this->payload = $payload;
605
    }
606
 
607
    function setRequestMethod($method) {
608
        $this->httpMethodName = $method;
609
    }
610
 
611
    function addHeader($headerName, $headerValue) {
612
        $this->awsHeaders[$headerName] = $headerValue;
613
    }
614
 
615
    private function prepareCanonicalRequest() {
616
        $canonicalURL = "";
617
        $canonicalURL .= $this->httpMethodName . "\n";
618
        $canonicalURL .= $this->path . "\n" . "\n";
619
        $signedHeaders = '';
620
        foreach ($this->awsHeaders as $key => $value) {
621
            $signedHeaders .= $key . ";";
622
            $canonicalURL .= $key . ":" . $value . "\n";
623
        }
624
        $canonicalURL .= "\n";
625
        $this->strSignedHeader = substr($signedHeaders, 0, -1);
626
        $canonicalURL .= $this->strSignedHeader . "\n";
627
        $canonicalURL .= $this->generateHex($this->payload);
628
        return $canonicalURL;
629
    }
630
 
631
    private function prepareStringToSign($canonicalURL) {
632
        $stringToSign = '';
633
        $stringToSign .= $this->HMACAlgorithm . "\n";
634
        $stringToSign .= $this->xAmzDate . "\n";
635
        $stringToSign .= $this->currentDate . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "\n";
636
        $stringToSign .= $this->generateHex($canonicalURL);
637
        return $stringToSign;
638
    }
639
 
640
    private function calculateSignature($stringToSign) {
641
        $signatureKey = $this->getSignatureKey($this->secretKey, $this->currentDate, $this->regionName, $this->serviceName);
642
        $signature = hash_hmac("sha256", $stringToSign, $signatureKey, true);
643
        $strHexSignature = strtolower(bin2hex($signature));
644
        return $strHexSignature;
645
    }
646
 
647
    public function getHeaders() {
648
        $this->awsHeaders['x-amz-date'] = $this->xAmzDate;
649
        ksort($this->awsHeaders);
650
 
651
        // Step 1: CREATE A CANONICAL REQUEST
652
        $canonicalURL = $this->prepareCanonicalRequest();
653
 
654
        // Step 2: CREATE THE STRING TO SIGN
655
        $stringToSign = $this->prepareStringToSign($canonicalURL);
656
 
657
        // Step 3: CALCULATE THE SIGNATURE
658
        $signature = $this->calculateSignature($stringToSign);
659
 
660
        // Step 4: CALCULATE AUTHORIZATION HEADER
661
        if ($signature) {
662
            $this->awsHeaders['Authorization'] = $this->buildAuthorizationString($signature);
663
            return $this->awsHeaders;
664
        }
665
    }
666
 
667
    private function buildAuthorizationString($strSignature) {
668
        return $this->HMACAlgorithm . " " . "Credential=" . $this->accessKey . "/" . $this->getDate() . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "," . "SignedHeaders=" . $this->strSignedHeader . "," . "Signature=" . $strSignature;
669
    }
670
 
671
    private function generateHex($data) {
672
        return strtolower(bin2hex(hash("sha256", $data, true)));
673
    }
674
 
675
    private function getSignatureKey($key, $date, $regionName, $serviceName) {
676
        $kSecret = "AWS4" . $key;
677
        $kDate = hash_hmac("sha256", $date, $kSecret, true);
678
        $kRegion = hash_hmac("sha256", $regionName, $kDate, true);
679
        $kService = hash_hmac("sha256", $serviceName, $kRegion, true);
680
        $kSigning = hash_hmac("sha256", $this->aws4Request, $kService, true);
681
 
682
        return $kSigning;
683
    }
684
 
685
    private function getTimeStamp() {
686
        return gmdate("Ymd\THis\Z");
687
    }
688
 
689
    private function getDate() {
690
        return gmdate("Ymd");
691
    }
692
}