Subversion Repositories cheapmusic

Rev

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