-
Notifications
You must be signed in to change notification settings - Fork 63
/
S3.php
1002 lines (827 loc) · 27.9 KB
/
S3.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Utopia\Storage\Device;
use Exception;
use Utopia\Storage\Device;
use Utopia\Storage\Storage;
class S3 extends Device
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
const METHOD_HEAD = 'HEAD';
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_CONNECT = 'CONNECT';
const METHOD_TRACE = 'TRACE';
const HTTP_VERSION_1_1 = CURL_HTTP_VERSION_1_1;
const HTTP_VERSION_2_0 = CURL_HTTP_VERSION_2_0;
const HTTP_VERSION_2 = CURL_HTTP_VERSION_2;
const HTTP_VERSION_1_0 = CURL_HTTP_VERSION_1_0;
/**
* AWS Regions constants
*/
const US_EAST_1 = 'us-east-1';
const US_EAST_2 = 'us-east-2';
const US_WEST_1 = 'us-west-1';
const US_WEST_2 = 'us-west-2';
const AF_SOUTH_1 = 'af-south-1';
const AP_EAST_1 = 'ap-east-1';
const AP_SOUTH_1 = 'ap-south-1';
const AP_NORTHEAST_3 = 'ap-northeast-3';
const AP_NORTHEAST_2 = 'ap-northeast-2';
const AP_NORTHEAST_1 = 'ap-northeast-1';
const AP_SOUTHEAST_1 = 'ap-southeast-1';
const AP_SOUTHEAST_2 = 'ap-southeast-2';
const CA_CENTRAL_1 = 'ca-central-1';
const EU_CENTRAL_1 = 'eu-central-1';
const EU_WEST_1 = 'eu-west-1';
const EU_SOUTH_1 = 'eu-south-1';
const EU_WEST_2 = 'eu-west-2';
const EU_WEST_3 = 'eu-west-3';
const EU_NORTH_1 = 'eu-north-1';
const SA_EAST_1 = 'eu-north-1';
const CN_NORTH_1 = 'cn-north-1';
const CN_NORTH_4 = 'cn-north-4';
const CN_NORTHWEST_1 = 'cn-northwest-1';
const ME_SOUTH_1 = 'me-south-1';
const US_GOV_EAST_1 = 'us-gov-east-1';
const US_GOV_WEST_1 = 'us-gov-west-1';
/**
* AWS ACL Flag constants
*/
const ACL_PRIVATE = 'private';
const ACL_PUBLIC_READ = 'public-read';
const ACL_PUBLIC_READ_WRITE = 'public-read-write';
const ACL_AUTHENTICATED_READ = 'authenticated-read';
protected const MAX_PAGE_SIZE = 1000;
protected static int $retryAttempts = 3;
protected static int $retryDelay = 500; // milliseconds
/**
* @var string
*/
protected string $accessKey;
/**
* @var string
*/
protected string $secretKey;
/**
* @var string
*/
protected string $bucket;
/**
* @var string
*/
protected string $region;
/**
* @var string
*/
protected string $acl = self::ACL_PRIVATE;
/**
* @var string
*/
protected string $root = 'temp';
/**
* @var array
*/
protected array $headers = [
'host' => '',
'date' => '',
'content-md5' => '',
'content-type' => '',
];
/**
* @var array
*/
protected array $amzHeaders;
/**
* Http version
*
* @var int|null
*/
protected ?int $curlHttpVersion = null;
/**
* S3 Constructor
*
* @param string $root
* @param string $accessKey
* @param string $secretKey
* @param string $bucket
* @param string $region
* @param string $acl
*/
public function __construct(string $root, string $accessKey, string $secretKey, string $bucket, string $region = self::US_EAST_1, string $acl = self::ACL_PRIVATE, $endpointUrl = '')
{
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
$this->bucket = $bucket;
$this->region = $region;
$this->root = $root;
$this->acl = $acl;
$this->amzHeaders = [];
if (! empty($endpointUrl)) {
$host = $bucket.'.'.$endpointUrl;
} else {
$host = match ($region) {
self::CN_NORTH_1, self::CN_NORTH_4, self::CN_NORTHWEST_1 => $bucket.'.s3.'.$region.'.amazonaws.cn',
default => $bucket.'.s3.'.$region.'.amazonaws.com'
};
}
$this->headers['host'] = $host;
}
/**
* @return string
*/
public function getName(): string
{
return 'S3 Storage';
}
/**
* @return string
*/
public function getType(): string
{
return Storage::DEVICE_S3;
}
/**
* @return string
*/
public function getDescription(): string
{
return 'S3 Bucket Storage drive for AWS or on premise solution';
}
/**
* @return string
*/
public function getRoot(): string
{
return $this->root;
}
/**
* @param string $filename
* @param string|null $prefix
* @return string
*/
public function getPath(string $filename, string $prefix = null): string
{
return $this->getRoot().DIRECTORY_SEPARATOR.$filename;
}
/**
* Set http version
*
*
* @param int|null $httpVersion
* @return self
*/
public function setHttpVersion(?int $httpVersion): self
{
$this->curlHttpVersion = $httpVersion;
return $this;
}
/**
* Set retry attempts
*
* @param int $attempts
* @return void
*/
public static function setRetryAttempts(int $attempts)
{
self::$retryAttempts = $attempts;
}
/**
* Set retry delay in milliseconds
*
* @param int $delay
* @return void
*/
public static function setRetryDelay(int $delay): void
{
self::$retryDelay = $delay;
}
/**
* Upload.
*
* Upload a file to desired destination in the selected disk.
* return number of chunks uploaded or 0 if it fails.
*
* @param string $source
* @param string $path
* @param int chunk
* @param int chunks
* @param array $metadata
* @return int
*
* @throws \Exception
*/
public function upload(string $source, string $path, int $chunk = 1, int $chunks = 1, array &$metadata = []): int
{
return $this->uploadData(\file_get_contents($source), $path, \mime_content_type($source), $chunk, $chunks, $metadata);
}
/**
* Upload Data.
*
* Upload file contents to desired destination in the selected disk.
* return number of chunks uploaded or 0 if it fails.
*
* @param string $source
* @param string $path
* @param string $contentType
* @param int chunk
* @param int chunks
* @param array $metadata
* @return int
*
* @throws \Exception
*/
public function uploadData(string $data, string $path, string $contentType, int $chunk = 1, int $chunks = 1, array &$metadata = []): int
{
if ($chunk == 1 && $chunks == 1) {
return $this->write($path, $data, $contentType);
}
$uploadId = $metadata['uploadId'] ?? null;
if (empty($uploadId)) {
$uploadId = $this->createMultipartUpload($path, $contentType);
$metadata['uploadId'] = $uploadId;
}
$metadata['parts'] ??= [];
$metadata['chunks'] ??= 0;
$etag = $this->uploadPart($data, $path, $contentType, $chunk, $uploadId);
// skip incrementing if the chunk was re-uploaded
if (! array_key_exists($chunk, $metadata['parts'])) {
$metadata['chunks']++;
}
$metadata['parts'][$chunk] = $etag;
if ($metadata['chunks'] == $chunks) {
$this->completeMultipartUpload($path, $uploadId, $metadata['parts']);
}
return $metadata['chunks'];
}
/**
* Transfer
*
* @param string $path
* @param string $destination
* @param Device $device
* @return string
*/
public function transfer(string $path, string $destination, Device $device): bool
{
$response = [];
try {
$response = $this->getInfo($path);
} catch (\Throwable $e) {
throw new Exception('File not found');
}
$size = (int) ($response['content-length'] ?? 0);
$contentType = $response['content-type'] ?? '';
if ($size <= $this->transferChunkSize) {
$source = $this->read($path);
return $device->write($destination, $source, $contentType);
}
$totalChunks = \ceil($size / $this->transferChunkSize);
$metadata = ['content_type' => $contentType];
for ($counter = 0; $counter < $totalChunks; $counter++) {
$start = $counter * $this->transferChunkSize;
$data = $this->read($path, $start, $this->transferChunkSize);
$device->uploadData($data, $destination, $contentType, $counter + 1, $totalChunks, $metadata);
}
return true;
}
/**
* Start Multipart Upload
*
* Initiate a multipart upload and return an upload ID.
*
* @param string $path
* @param string $contentType
* @return string
*
* @throws \Exception
*/
protected function createMultipartUpload(string $path, string $contentType): string
{
$uri = $path !== '' ? '/'.\str_replace(['%2F', '%3F'], ['/', '?'], \rawurlencode($path)) : '/';
$this->headers['content-md5'] = \base64_encode(md5('', true));
unset($this->amzHeaders['x-amz-content-sha256']);
$this->headers['content-type'] = $contentType;
$this->amzHeaders['x-amz-acl'] = $this->acl;
$response = $this->call(self::METHOD_POST, $uri, '', ['uploads' => '']);
return $response->body['UploadId'];
}
/**
* Upload Part
*
* @param string $source
* @param string $path
* @param int $chunk
* @param string $uploadId
* @return string
*
* @throws \Exception
*/
protected function uploadPart(string $data, string $path, string $contentType, int $chunk, string $uploadId): string
{
$uri = $path !== '' ? '/'.\str_replace(['%2F', '%3F'], ['/', '?'], \rawurlencode($path)) : '/';
$this->headers['content-type'] = $contentType;
$this->headers['content-md5'] = \base64_encode(md5($data, true));
$this->amzHeaders['x-amz-content-sha256'] = \hash('sha256', $data);
unset($this->amzHeaders['x-amz-acl']); // ACL header is not allowed in parts, only createMultipartUpload accepts this header.
$response = $this->call(self::METHOD_PUT, $uri, $data, [
'partNumber' => $chunk,
'uploadId' => $uploadId,
]);
return $response->headers['etag'];
}
/**
* Complete Multipart Upload
*
* @param string $path
* @param string $uploadId
* @param array $parts
* @return bool
*
* @throws \Exception
*/
protected function completeMultipartUpload(string $path, string $uploadId, array $parts): bool
{
$uri = $path !== '' ? '/'.\str_replace(['%2F', '%3F'], ['/', '?'], \rawurlencode($path)) : '/';
$body = '<CompleteMultipartUpload>';
foreach ($parts as $key => $etag) {
$body .= "<Part><ETag>{$etag}</ETag><PartNumber>{$key}</PartNumber></Part>";
}
$body .= '</CompleteMultipartUpload>';
$this->amzHeaders['x-amz-content-sha256'] = \hash('sha256', $body);
$this->headers['content-md5'] = \base64_encode(md5($body, true));
$this->call(self::METHOD_POST, $uri, $body, ['uploadId' => $uploadId]);
return true;
}
/**
* Abort Chunked Upload
*
* @param string $path
* @param string $extra
* @return bool
*
* @throws \Exception
*/
public function abort(string $path, string $extra = ''): bool
{
$uri = $path !== '' ? '/'.\str_replace(['%2F', '%3F'], ['/', '?'], \rawurlencode($path)) : '/';
unset($this->headers['content-type']);
$this->headers['content-md5'] = \base64_encode(md5('', true));
$this->call(self::METHOD_DELETE, $uri, '', ['uploadId' => $extra]);
return true;
}
/**
* Read file or part of file by given path, offset and length.
*
* @param string $path
* @param int offset
* @param int length
* @return string
*
* @throws \Exception
*/
public function read(string $path, int $offset = 0, int $length = null): string
{
unset($this->amzHeaders['x-amz-acl']);
unset($this->amzHeaders['x-amz-content-sha256']);
unset($this->headers['content-type']);
$this->headers['content-md5'] = \base64_encode(md5('', true));
$uri = ($path !== '') ? '/'.\str_replace('%2F', '/', \rawurlencode($path)) : '/';
if ($length !== null) {
$end = $offset + $length - 1;
$this->headers['range'] = "bytes=$offset-$end";
}
$response = $this->call(self::METHOD_GET, $uri, decode: false);
return $response->body;
}
/**
* Write file by given path.
*
* @param string $path
* @param string $data
* @return bool
*
* @throws \Exception
*/
public function write(string $path, string $data, string $contentType = ''): bool
{
$uri = $path !== '' ? '/'.\str_replace(['%2F', '%3F'], ['/', '?'], \rawurlencode($path)) : '/';
$this->headers['content-type'] = $contentType;
$this->headers['content-md5'] = \base64_encode(md5($data, true)); //TODO whould this work well with big file? can we skip it?
$this->amzHeaders['x-amz-content-sha256'] = \hash('sha256', $data);
$this->amzHeaders['x-amz-acl'] = $this->acl;
$this->call(self::METHOD_PUT, $uri, $data);
return true;
}
/**
* Delete file in given path, Return true on success and false on failure.
*
* @see http://php.net/manual/en/function.filesize.php
*
* @param string $path
* @return bool
*
* @throws \Exception
*/
public function delete(string $path, bool $recursive = false): bool
{
$uri = ($path !== '') ? '/'.\str_replace('%2F', '/', \rawurlencode($path)) : '/';
unset($this->headers['content-type']);
unset($this->amzHeaders['x-amz-acl']);
unset($this->amzHeaders['x-amz-content-sha256']);
$this->headers['content-md5'] = \base64_encode(md5('', true));
$this->call(self::METHOD_DELETE, $uri);
return true;
}
/**
* Get list of objects in the given path.
*
* @param string $prefix
* @param int $maxKeys
* @param string $continuationToken
* @return array
*
* @throws Exception
*/
protected function listObjects(string $prefix = '', int $maxKeys = self::MAX_PAGE_SIZE, string $continuationToken = ''): array
{
if ($maxKeys > self::MAX_PAGE_SIZE) {
throw new Exception('Cannot list more than '.self::MAX_PAGE_SIZE.' objects');
}
$uri = '/';
$prefix = ltrim($prefix, '/'); /** S3 specific requirement that prefix should never contain a leading slash */
$this->headers['content-type'] = 'text/plain';
$this->headers['content-md5'] = \base64_encode(md5('', true));
unset($this->amzHeaders['x-amz-content-sha256']);
unset($this->amzHeaders['x-amz-acl']);
$parameters = [
'list-type' => 2,
'prefix' => $prefix,
'max-keys' => $maxKeys,
];
if (! empty($continuationToken)) {
$parameters['continuation-token'] = $continuationToken;
}
$response = $this->call(self::METHOD_GET, $uri, '', $parameters);
return $response->body;
}
/**
* Delete files in given path, path must be a directory. Return true on success and false on failure.
*
* @param string $path
* @return bool
*
* @throws \Exception
*/
public function deletePath(string $path): bool
{
$path = $this->getRoot().'/'.$path;
$uri = '/';
$continuationToken = '';
do {
$objects = $this->listObjects($path, continuationToken: $continuationToken);
$count = (int) ($objects['KeyCount'] ?? 1);
if ($count < 1) {
break;
}
$continuationToken = $objects['NextContinuationToken'] ?? '';
$body = '<Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/">';
if ($count > 1) {
foreach ($objects['Contents'] as $object) {
$body .= "<Object><Key>{$object['Key']}</Key></Object>";
}
} else {
$body .= "<Object><Key>{$objects['Contents']['Key']}</Key></Object>";
}
$body .= '<Quiet>true</Quiet>';
$body .= '</Delete>';
$this->amzHeaders['x-amz-content-sha256'] = \hash('sha256', $body);
$this->headers['content-md5'] = \base64_encode(md5($body, true));
$this->call(self::METHOD_POST, $uri, $body, ['delete' => '']);
} while (! empty($continuationToken));
return true;
}
/**
* Check if file exists
*
* @param string $path
* @return bool
*/
public function exists(string $path): bool
{
try {
$this->getInfo($path);
} catch (\Throwable $th) {
return false;
}
return true;
}
/**
* Returns given file path its size.
*
* @see http://php.net/manual/en/function.filesize.php
*
* @param string $path
* @return int
*/
public function getFileSize(string $path): int
{
$response = $this->getInfo($path);
return (int) ($response['content-length'] ?? 0);
}
/**
* Returns given file path its mime type.
*
* @see http://php.net/manual/en/function.mime-content-type.php
*
* @param string $path
* @return string
*/
public function getFileMimeType(string $path): string
{
$response = $this->getInfo($path);
return $response['content-type'] ?? '';
}
/**
* Returns given file path its MD5 hash value.
*
* @see http://php.net/manual/en/function.md5-file.php
*
* @param string $path
* @return string
*/
public function getFileHash(string $path): string
{
$etag = $this->getInfo($path)['etag'] ?? '';
return (! empty($etag)) ? substr($etag, 1, -1) : $etag;
}
/**
* Create a directory at the specified path.
*
* Returns true on success or if the directory already exists and false on error
*
* @param $path
* @return bool
*/
public function createDirectory(string $path): bool
{
/* S3 is an object store and does not have the concept of directories */
return true;
}
/**
* Get directory size in bytes.
*
* Return -1 on error
*
* Based on http://www.jonasjohn.de/snippets/php/dir-size.htm
*
* @param string $path
* @return int
*/
public function getDirectorySize(string $path): int
{
return -1;
}
/**
* Get Partition Free Space.
*
* disk_free_space — Returns available space on filesystem or disk partition
*
* @return float
*/
public function getPartitionFreeSpace(): float
{
return -1;
}
/**
* Get Partition Total Space.
*
* disk_total_space — Returns the total size of a filesystem or disk partition
*
* @return float
*/
public function getPartitionTotalSpace(): float
{
return -1;
}
/**
* Get all files and directories inside a directory.
*
* @param string $dir Directory to scan
* @param int $max
* @param string $continuationToken
* @return array<mixed>
*
* @throws Exception
*/
public function getFiles(string $dir, int $max = self::MAX_PAGE_SIZE, string $continuationToken = ''): array
{
$data = $this->listObjects($dir, $max, $continuationToken);
// Set to false if all the results were returned. Set to true if more keys are available to return.
$data['IsTruncated'] = $data['IsTruncated'] === 'true';
// KeyCount is the number of keys returned with this request.
$data['KeyCount'] = intval($data['KeyCount']);
// Sets the maximum number of keys returned to the response. By default, the action returns up to 1,000 key names.
$data['MaxKeys'] = intval($data['MaxKeys']);
return $data;
}
/**
* Get file info
*
* @param string $path
* @return array
*
* @throws Exception
*/
private function getInfo(string $path): array
{
unset($this->headers['content-type']);
unset($this->amzHeaders['x-amz-acl']);
unset($this->amzHeaders['x-amz-content-sha256']);
$this->headers['content-md5'] = \base64_encode(md5('', true));
$uri = $path !== '' ? '/'.\str_replace('%2F', '/', \rawurlencode($path)) : '/';
$response = $this->call(self::METHOD_HEAD, $uri);
return $response->headers;
}
/**
* Generate the headers for AWS Signature V4
*
* @param string $method
* @param string $uri
* @param array parameters
* @return string
*/
private function getSignatureV4(string $method, string $uri, array $parameters = []): string
{
$service = 's3';
$region = $this->region;
$algorithm = 'AWS4-HMAC-SHA256';
$combinedHeaders = [];
$amzDateStamp = \substr($this->amzHeaders['x-amz-date'], 0, 8);
// CanonicalHeaders
foreach ($this->headers as $k => $v) {
$combinedHeaders[\strtolower($k)] = \trim($v);
}
foreach ($this->amzHeaders as $k => $v) {
$combinedHeaders[\strtolower($k)] = \trim($v);
}
uksort($combinedHeaders, [&$this, 'sortMetaHeadersCmp']);
// Convert null query string parameters to strings and sort
uksort($parameters, [&$this, 'sortMetaHeadersCmp']);
$queryString = \http_build_query($parameters, '', '&', PHP_QUERY_RFC3986);
// Payload
$amzPayload = [$method];
$qsPos = \strpos($uri, '?');
$amzPayload[] = ($qsPos === false ? $uri : \substr($uri, 0, $qsPos));
$amzPayload[] = $queryString;
foreach ($combinedHeaders as $k => $v) { // add header as string to requests
$amzPayload[] = $k.':'.$v;
}
$amzPayload[] = ''; // add a blank entry so we end up with an extra line break
$amzPayload[] = \implode(';', \array_keys($combinedHeaders)); // SignedHeaders
$amzPayload[] = $this->amzHeaders['x-amz-content-sha256']; // payload hash
$amzPayloadStr = \implode("\n", $amzPayload); // request as string
// CredentialScope
$credentialScope = [$amzDateStamp, $region, $service, 'aws4_request'];
// stringToSign
$stringToSignStr = \implode("\n", [
$algorithm,
$this->amzHeaders['x-amz-date'],
\implode('/', $credentialScope),
\hash('sha256', $amzPayloadStr),
]);
// Make Signature
$kSecret = 'AWS4'.$this->secretKey;
$kDate = \hash_hmac('sha256', $amzDateStamp, $kSecret, true);
$kRegion = \hash_hmac('sha256', $region, $kDate, true);
$kService = \hash_hmac('sha256', $service, $kRegion, true);
$kSigning = \hash_hmac('sha256', 'aws4_request', $kService, true);
$signature = \hash_hmac('sha256', \mb_convert_encoding($stringToSignStr, 'utf-8'), $kSigning);
return $algorithm.' '.\implode(',', [
'Credential='.$this->accessKey.'/'.\implode('/', $credentialScope),
'SignedHeaders='.\implode(';', \array_keys($combinedHeaders)),
'Signature='.$signature,
]);
}
/**
* Get the S3 response
*
* @param string $method
* @param string $uri
* @param string $data
* @param array $parameters
* @param bool $decode
* @return object
*
* @throws \Exception
*/
protected function call(string $method, string $uri, string $data = '', array $parameters = [], bool $decode = true)
{
$uri = $this->getAbsolutePath($uri);
$url = 'https://'.$this->headers['host'].$uri.'?'.\http_build_query($parameters, '', '&', PHP_QUERY_RFC3986);
$response = new \stdClass;
$response->body = '';
$response->headers = [];
// Basic setup
$curl = \curl_init();
\curl_setopt($curl, CURLOPT_USERAGENT, 'utopia-php/storage');
\curl_setopt($curl, CURLOPT_URL, $url);
// Headers
$httpHeaders = [];
$this->amzHeaders['x-amz-date'] = \gmdate('Ymd\THis\Z');
if (! isset($this->amzHeaders['x-amz-content-sha256'])) {
$this->amzHeaders['x-amz-content-sha256'] = \hash('sha256', $data);
}
foreach ($this->amzHeaders as $header => $value) {
if (\strlen($value) > 0) {
$httpHeaders[] = $header.': '.$value;
}
}
$this->headers['date'] = \gmdate('D, d M Y H:i:s T');
foreach ($this->headers as $header => $value) {
if (\strlen($value) > 0) {
$httpHeaders[] = $header.': '.$value;
}
}
$httpHeaders[] = 'Authorization: '.$this->getSignatureV4($method, $uri, $parameters);
\curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
\curl_setopt($curl, CURLOPT_HEADER, false);
\curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
if ($this->curlHttpVersion != null) {
\curl_setopt($curl, CURLOPT_HTTP_VERSION, $this->curlHttpVersion);
}
\curl_setopt($curl, CURLOPT_WRITEFUNCTION, function ($curl, string $data) use ($response) {
$response->body .= $data;
return \strlen($data);
});
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($curl, string $header) use (&$response) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) { // ignore invalid headers
return $len;
}
$response->headers[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
});
\curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
\curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
// Request types
switch ($method) {
case self::METHOD_PUT:
case self::METHOD_POST: // POST only used for CloudFront
\curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case self::METHOD_HEAD:
case self::METHOD_DELETE:
\curl_setopt($curl, CURLOPT_NOBODY, true);
break;
}
$result = \curl_exec($curl);
$response->code = \curl_getinfo($curl, CURLINFO_HTTP_CODE);
$attempt = 0;
while ($attempt < self::$retryAttempts && $response->code === 503) {
usleep(self::$retryDelay * 1000);
$attempt++;
$result = \curl_exec($curl);
$response->code = \curl_getinfo($curl, CURLINFO_HTTP_CODE);
}
if (! $result) {
throw new Exception(\curl_error($curl));
}
if ($response->code >= 400) {
throw new Exception($response->body, $response->code);
}
\curl_close($curl);
// Parse body into XML
if ($decode && ((isset($response->headers['content-type']) && $response->headers['content-type'] == 'application/xml') || (str_starts_with($response->body, '<?xml') && ($response->headers['content-type'] ?? '') !== 'image/svg+xml'))) {
$response->body = \simplexml_load_string($response->body);
$response->body = json_decode(json_encode($response->body), true);
}
return $response;
}
/**
* Sort compare for meta headers
*
* @internal Used to sort x-amz meta headers
*
* @param string $a String A
* @param string $b String B
* @return int
*/
private function sortMetaHeadersCmp($a, $b)
{
$lenA = \strlen($a);
$lenB = \strlen($b);
$minLen = \min($lenA, $lenB);
$ncmp = \strncmp($a, $b, $minLen);
if ($lenA == $lenB) {
return $ncmp;
}
if (0 == $ncmp) {
return $lenA < $lenB ? -1 : 1;
}
return $ncmp;