-
Notifications
You must be signed in to change notification settings - Fork 593
/
SCS.php
2255 lines (1956 loc) · 64.1 KB
/
SCS.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
/**
* $Id$
*
* Copyright (c) 2014, Sina Cloud Storage. All rights reserved.
* @author Bruce Chen <[email protected]>
* @link http://weibo.com/smcz
*/
/**
* Sina Cloud Storage PHP class
*
* @link http://weibo.com/smcz
* @version 0.1.0-dev
*/
class SCS
{
// ACL flags
const ACL_PRIVATE = 'private';
const ACL_PUBLIC_READ = 'public-read';
const ACL_PUBLIC_READ_WRITE = 'public-read-write';
const ACL_AUTHENTICATED_READ = 'authenticated-read';
const STORAGE_CLASS_STANDARD = 'STANDARD';
const STORAGE_CLASS_RRS = 'REDUCED_REDUNDANCY';
const SSE_NONE = '';
const SSE_AES256 = 'AES256';
/**
* The SCS Access key
*
* @var string
* @access private
* @static
*/
private static $__accessKey = null;
/**
* SCS Secret Key
*
* @var string
* @access private
* @static
*/
private static $__secretKey = null;
/**
* SSL Client key
*
* @var string
* @access private
* @static
*/
private static $__sslKey = null;
/**
* SCS URI
*
* @var string
* @acess public
* @static
*/
public static $endpoint = 'sinacloud.net';
/**
* Proxy information
*
* @var null|array
* @access public
* @static
*/
public static $proxy = null;
/**
* Connect using SSL?
*
* @var bool
* @access public
* @static
*/
public static $useSSL = false;
/**
* Use SSL validation?
*
* @var bool
* @access public
* @static
*/
public static $useSSLValidation = true;
/**
* Use PHP exceptions?
*
* @var bool
* @access public
* @static
*/
public static $useExceptions = false;
/**
* Time offset applied to time()
* @access private
* @static
*/
private static $__timeOffset = 5;
/**
* SSL client key
*
* @var bool
* @access public
* @static
*/
public static $sslKey = null;
/**
* SSL client certfificate
*
* @var string
* @acess public
* @static
*/
public static $sslCert = null;
/**
* SSL CA cert (only required if you are having problems with your system CA cert)
*
* @var string
* @access public
* @static
*/
public static $sslCACert = null;
/**
* SCS Key Pair ID
*
* @var string
* @access private
* @static
*/
private static $__signingKeyPairId = null;
/**
* Key resource, freeSigningKey() must be called to clear it from memory
*
* @var bool
* @access private
* @static
*/
private static $__signingKeyResource = false;
/**
* Constructor - if you're not using the class statically
*
* @param string $accessKey Access key
* @param string $secretKey Secret key
* @param boolean $useSSL Enable SSL
* @param string $endpoint Amazon URI
* @return void
*/
public function __construct($accessKey = null, $secretKey = null, $useSSL = false, $endpoint = 'sinacloud.net')
{
if ($accessKey !== null && $secretKey !== null)
self::setAuth($accessKey, $secretKey);
self::$useSSL = $useSSL;
self::$endpoint = $endpoint;
}
/**
* Set the service endpoint
*
* @param string $host Hostname
* @return void
*/
public function setEndpoint($host)
{
self::$endpoint = $host;
}
/**
* Set SCS access key and secret key
*
* @param string $accessKey Access key
* @param string $secretKey Secret key
* @return void
*/
public static function setAuth($accessKey, $secretKey)
{
self::$__accessKey = $accessKey;
self::$__secretKey = $secretKey;
}
/**
* Check if SCS keys have been set
*
* @return boolean
*/
public static function hasAuth() {
return (self::$__accessKey !== null && self::$__secretKey !== null);
}
/**
* Set SSL on or off
*
* @param boolean $enabled SSL enabled
* @param boolean $validate SSL certificate validation
* @return void
*/
public static function setSSL($enabled, $validate = true)
{
self::$useSSL = $enabled;
self::$useSSLValidation = $validate;
}
/**
* Set SSL client certificates (experimental)
*
* @param string $sslCert SSL client certificate
* @param string $sslKey SSL client key
* @param string $sslCACert SSL CA cert (only required if you are having problems with your system CA cert)
* @return void
*/
public static function setSSLAuth($sslCert = null, $sslKey = null, $sslCACert = null)
{
self::$sslCert = $sslCert;
self::$sslKey = $sslKey;
self::$sslCACert = $sslCACert;
}
/**
* Set proxy information
*
* @param string $host Proxy hostname and port (localhost:1234)
* @param string $user Proxy username
* @param string $pass Proxy password
* @param constant $type CURL proxy type
* @return void
*/
public static function setProxy($host, $user = null, $pass = null, $type = CURLPROXY_SOCKS5)
{
self::$proxy = array('host' => $host, 'type' => $type, 'user' => $user, 'pass' => $pass);
}
/**
* Set the error mode to exceptions
*
* @param boolean $enabled Enable exceptions
* @return void
*/
public static function setExceptions($enabled = true)
{
self::$useExceptions = $enabled;
}
/**
* Set SCS time correction offset (use carefully)
*
* This can be used when an inaccurate system time is generating
* invalid request signatures. It should only be used as a last
* resort when the system time cannot be changed.
*
* @param string $offset Time offset (set to zero to use SCS server time)
* @return void
*/
public static function setTimeCorrectionOffset($offset = 0)
{
if ($offset == 0)
{
$rest = new SCSRequest('HEAD');
$rest = $rest->getResponse();
$awstime = $rest->headers['date'];
$systime = time();
$offset = $systime > $awstime ? -($systime - $awstime) : ($awstime - $systime);
}
self::$__timeOffset = $offset;
}
/**
* Set signing key
*
* @param string $keyPairId SCS Key Pair ID
* @param string $signingKey Private Key
* @param boolean $isFile Load private key from file, set to false to load string
* @return boolean
*/
public static function setSigningKey($keyPairId, $signingKey, $isFile = true)
{
self::$__signingKeyPairId = $keyPairId;
if ((self::$__signingKeyResource = openssl_pkey_get_private($isFile ?
file_get_contents($signingKey) : $signingKey)) !== false) return true;
self::__triggerError('SCS::setSigningKey(): Unable to open load private key: '.$signingKey, __FILE__, __LINE__);
return false;
}
/**
* Free signing key from memory, MUST be called if you are using setSigningKey()
*
* @return void
*/
public static function freeSigningKey()
{
if (self::$__signingKeyResource !== false)
openssl_free_key(self::$__signingKeyResource);
}
/**
* Internal error handler
*
* @internal Internal error handler
* @param string $message Error message
* @param string $file Filename
* @param integer $line Line number
* @param integer $code Error code
* @return void
*/
private static function __triggerError($message, $file, $line, $code = 0)
{
if (self::$useExceptions)
throw new SCSException($message, $file, $line, $code);
else
trigger_error($message, E_USER_WARNING);
}
/**
* Get a list of buckets
*
* @param boolean $detailed Returns detailed bucket list when true
* @return array | false
*/
public static function listBuckets($detailed = false)
{
$rest = new SCSRequest('GET', '', '', self::$endpoint);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("SCS::listBuckets(): [%s] %s", $rest->error['code'],
$rest->error['message']), __FILE__, __LINE__);
return false;
}
$results = array();
if (!isset($rest->body->Buckets)) return $results;
if ($detailed)
{
if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
$results['owner'] = array(
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
);
$results['buckets'] = array();
//foreach ($rest->body->Buckets->Bucket as $b)
foreach ($rest->body->Buckets as $b)
$results['buckets'][] = array(
'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate), 'consumed_bytes' => (string)$b->ConsumedBytes
);
} else
foreach ($rest->body->Buckets as $b) $results[] = (string)$b->Name;
//foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name;
return $results;
}
/**
* Get contents for a bucket
*
* If maxKeys is null this method will loop through truncated result sets
*
* @param string $bucket Bucket name
* @param string $prefix Prefix
* @param string $marker Marker (last file listed)
* @param string $maxKeys Max keys (maximum number of keys to return)
* @param string $delimiter Delimiter
* @param boolean $returnCommonPrefixes Set to true to return CommonPrefixes
* @param boolean &$isTruncated
* @return array | false
*/
public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null, $delimiter = null, $returnCommonPrefixes = false, &$nextMarker = null, &$isTruncated = false)
{
$rest = new SCSRequest('GET', $bucket, '', self::$endpoint);
if ($maxKeys == 0) $maxKeys = null;
if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
if ($marker !== null && $marker !== '') $rest->setParameter('marker', $marker);
if ($maxKeys !== null && $maxKeys !== '') $rest->setParameter('max-keys', $maxKeys);
if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
$response = $rest->getResponse();
if ($response->error === false && $response->code !== 200)
$response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
if ($response->error !== false)
{
self::__triggerError(sprintf("SCS::getBucket(): [%s] %s",
$response->error['code'], $response->error['message']), __FILE__, __LINE__);
return false;
}
$results = array();
if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes))
{
foreach ($response->body->CommonPrefixes as $c)
$results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix);
}
$nextMarker = null;
if (isset($response->body, $response->body->Contents))
{
foreach ($response->body->Contents as $c)
{
$a = get_object_vars($c);
$results[(string)$c->Name] = array(
'name' => (string)$c->Name,
'time' => strtotime((string)$a['Last-Modified']),
'type' => (string)$a['Content-Type'],
'owner' => (string)$a['Owner'],
'size' => (int)$c->Size,
//'hash' => substr((string)$c->ETag, 1, -1),
'md5' => (string)$c->MD5,
'sha1' => (string)$c->SHA1,
);
$nextMarker = (string)$c->Name;
}
}
if (isset($response->body, $response->body->IsTruncated))
$isTruncated = (bool)$response->body->IsTruncated;
if (isset($response->body, $response->body->IsTruncated) && (bool)$response->body->IsTruncated == false)
return $results;
if (isset($response->body, $response->body->NextMarker))
$nextMarker = (string)$response->body->NextMarker;
// Loop through truncated results if maxKeys isn't specified
if ($maxKeys == null && $nextMarker !== null && (bool)$response->body->IsTruncated == true)
{
do
{
$rest = new SCSRequest('GET', $bucket, '', self::$endpoint);
if ($prefix !== null && $prefix !== '')
$rest->setParameter('prefix', $prefix);
$rest->setParameter('marker', $nextMarker);
if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
if (($response = $rest->getResponse()) == false || $response->code !== 200) break;
if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes))
{
foreach ($response->body->CommonPrefixes as $c)
$results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix);
}
if (isset($response->body, $response->body->Contents))
{
foreach ($response->body->Contents as $c)
{
$a = get_object_vars($c);
$results[(string)$c->Name] = array(
'name' => (string)$c->Name,
'time' => strtotime((string)$a['Last-Modified']),
'type' => (string)$a['Content-Type'],
'owner' => (string)$a['Owner'],
'size' => (int)$c->Size,
//'hash' => substr((string)$c->ETag, 1, -1),
'md5' => (string)$c->MD5,
'sha1' => (string)$c->SHA1,
);
$nextMarker = (string)$c->Name;
}
}
if (isset($response->body, $response->body->NextMarker))
$nextMarker = (string)$response->body->NextMarker;
} while ($response !== false && (bool)$response->body->IsTruncated == true);
}
return $results;
}
/**
* Put a bucket
*
* @param string $bucket Bucket name
* @param constant $acl ACL flag
* @param string $location Set as "EU" to create buckets hosted in Europe
* @return boolean
*/
public static function putBucket($bucket, $acl = self::ACL_PRIVATE, $location = false)
{
$rest = new SCSRequest('PUT', $bucket, '', self::$endpoint);
$rest->setAmzHeader('x-amz-acl', $acl);
if ($location !== false)
{
$dom = new DOMDocument;
$createBucketConfiguration = $dom->createElement('CreateBucketConfiguration');
$locationConstraint = $dom->createElement('LocationConstraint', $location);
$createBucketConfiguration->appendChild($locationConstraint);
$dom->appendChild($createBucketConfiguration);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
}
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("SCS::putBucket({$bucket}, {$acl}, {$location}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Delete an empty bucket
*
* @param string $bucket Bucket name
* @return boolean
*/
public static function deleteBucket($bucket)
{
$rest = new SCSRequest('DELETE', $bucket, '', self::$endpoint);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("SCS::deleteBucket({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* realFileSize()
*
* @param string $file Input file path
* @return long file bytes
*/
public static function realFileSize($file)
{
$fp = fopen($file, 'rb');
$pos = 0;
$size = 1073741824;
fseek($fp, 0, SEEK_SET);
while ($size > 1)
{
fseek($fp, $size, SEEK_CUR);
if (fgetc($fp) === false)
{
fseek($fp, -$size, SEEK_CUR);
$size = (int)($size / 2);
}
else
{
fseek($fp, -1, SEEK_CUR);
$pos += $size;
}
}
while (fgetc($fp) !== false) $pos++;
fclose($fp);
return $pos;
}
/**
* Create input info array for putObject()
*
* @param string $file Input file
* @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own)
* @return array | false
*/
public static function inputFile($file, $md5sum = true)
{
if (!file_exists($file) || !is_file($file) || !is_readable($file))
{
self::__triggerError('SCS::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__);
return false;
}
return array('file' => $file, 'size' => self::realFileSize($file), 'md5sum' => $md5sum !== false ?
(is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '');
}
/**
* Create input array info for putObject() with a resource
*
* @param string $resource Input resource to read from
* @param integer $bufferSize Input byte size
* @param string $md5sum MD5 hash to send (optional)
* @return array | false
*/
public static function inputResource(&$resource, $bufferSize = false, $md5sum = '')
{
if (!is_resource($resource) || (int)$bufferSize < 0)
{
self::__triggerError('SCS::inputResource(): Invalid resource or buffer size', __FILE__, __LINE__);
return false;
}
// Try to figure out the bytesize
if ($bufferSize === false)
{
if (fseek($resource, 0, SEEK_END) < 0 || ($bufferSize = ftell($resource)) === false)
{
self::__triggerError('SCS::inputResource(): Unable to obtain resource size', __FILE__, __LINE__);
return false;
}
fseek($resource, 0);
}
$input = array('size' => $bufferSize, 'md5sum' => $md5sum);
$input['fp'] =& $resource;
return $input;
}
/**
* Create input array info for putObject() with a resource multipart
*
* @param string $resource Input resource to read from
* @param integer $partSize
* @param string $uploadId
* @param integer $partNumber
* @return array | false
*/
public static function inputResourceMultipart(&$resource, $partSize, $uploadId, $partNumber)
{
if (!is_resource($resource) || (int)$partSize <= 0)
{
self::__triggerError('SCS::inputResourceMultipart(): Invalid resource or part size', __FILE__, __LINE__);
return false;
}
$data = fread($resource, $partSize);
$input = array(
'data' => $data,
'md5sum' => base64_encode(md5($data, true))
);
$input['uploadId'] = $uploadId;
$input['partNumber'] = $partNumber;
return $input;
}
/**
* Put an object
*
* @param mixed $input Input data
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Array of x-amz-meta-* headers
* @param array $requestHeaders Array of request headers or content type as a string
* @param constant $storageClass Storage class constant
* @param constant $serverSideEncryption Server-side encryption
* @return boolean | mixed
*/
public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD, $serverSideEncryption = self::SSE_NONE)
{
if ($input === false) return false;
$rest = new SCSRequest('PUT', $bucket, $uri, self::$endpoint);
if (!is_array($input)) $input = array(
'data' => $input, 'size' => strlen($input),
'md5sum' => base64_encode(md5($input, true))
);
// Data
if (isset($input['fp']))
$rest->fp =& $input['fp'];
elseif (isset($input['file']))
$rest->fp = @fopen($input['file'], 'rb');
elseif (isset($input['data']))
$rest->data = $input['data'];
// Content-Length (required)
if (isset($input['size']) && $input['size'] >= 0)
$rest->size = $input['size'];
else {
if (isset($input['file']))
$rest->size = self::realFileSize($input['file']);
elseif (isset($input['data']))
$rest->size = strlen($input['data']);
}
if (isset($input['uploadId'], $input['partNumber'])) {
$rest->setParameter('uploadId', $input['uploadId']);
$rest->setParameter('partNumber', $input['partNumber']);
}
// Custom request headers (Content-Type, Content-Disposition, Content-Encoding)
if (is_array($requestHeaders))
foreach ($requestHeaders as $h => $v) $rest->setHeader($h, $v);
elseif (is_string($requestHeaders)) // Support for legacy contentType parameter
$input['type'] = $requestHeaders;
// Content-Type
if (!isset($input['type']))
{
if (isset($requestHeaders['Content-Type']))
$input['type'] =& $requestHeaders['Content-Type'];
elseif (isset($input['file']))
$input['type'] = self::__getMIMEType($input['file']);
else
$input['type'] = 'application/octet-stream';
}
if ($storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class
$rest->setAmzHeader('x-amz-storage-class', $storageClass);
if ($serverSideEncryption !== self::SSE_NONE) // Server-side encryption
$rest->setAmzHeader('x-amz-server-side-encryption', $serverSideEncryption);
// We need to post with Content-Length and Content-Type, MD5 is optional
if ($rest->size >= 0 && ($rest->fp !== false || $rest->data !== false))
{
$rest->setHeader('Content-Type', $input['type']);
if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
$rest->setAmzHeader('x-amz-acl', $acl);
foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
$rest->getResponse();
} else
$rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false)
{
self::__triggerError(sprintf("SCS::putObject(): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
if (isset($input['uploadId'], $input['partNumber'])) {
return $rest->response->headers;
}
return true;
}
/**
* Put an object from a file (legacy function)
*
* @param string $file Input file path
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Array of x-amz-meta-* headers
* @param string $contentType Content type
* @return boolean
*/
public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null)
{
return self::putObject(self::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
}
/**
* Put an object from a string (legacy function)
*
* @param string $string Input data
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Array of x-amz-meta-* headers
* @param string $contentType Content type
* @return boolean
*/
public static function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain')
{
return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
}
/**
* Get an object
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param mixed $saveTo Filename or resource to write to
* @return mixed
*/
public static function getObject($bucket, $uri, $saveTo = false)
{
$rest = new SCSRequest('GET', $bucket, $uri, self::$endpoint);
if ($saveTo !== false)
{
if (is_resource($saveTo))
$rest->fp =& $saveTo;
else
if (($rest->fp = @fopen($saveTo, 'wb')) !== false)
$rest->file = realpath($saveTo);
else
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
if ($rest->response->error === false) $rest->getResponse();
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false)
{
self::__triggerError(sprintf("SCS::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->response;
}
/**
* Get object information
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param boolean $returnInfo Return response information
* @return mixed | false
*/
public static function getObjectInfo($bucket, $uri, $returnInfo = true)
{
$rest = new SCSRequest('HEAD', $bucket, $uri, self::$endpoint);
$rest = $rest->getResponse();
if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("SCS::getObjectInfo({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
}
/**
* Get Meta
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @return mixed | false
*/
public static function getMeta($bucket, $uri = '')
{
$rest = new SCSRequest('GET', $bucket, $uri, self::$endpoint);
$rest->setParameter('meta', null);
$rest = $rest->getResponse();
if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("SCS::getMeta({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->code == 200 ? $rest->body : false;
}
/**
* Copy an object
*
* @param string $srcBucket Source bucket name
* @param string $srcUri Source object URI
* @param string $bucket Destination bucket name
* @param string $uri Destination object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Optional array of x-amz-meta-* headers
* @param array $requestHeaders Optional array of request headers (content type, disposition, etc.)
* @param constant $storageClass Storage class constant
* @return mixed | false
*/
public static function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD)
{
$rest = new SCSRequest('PUT', $bucket, $uri, self::$endpoint);
$rest->setHeader('Content-Length', 0);
foreach ($requestHeaders as $h => $v) $rest->setHeader($h, $v);
foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
if ($storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class
$rest->setAmzHeader('x-amz-storage-class', $storageClass);
$rest->setAmzHeader('x-amz-acl', $acl);
$rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, rawurlencode($srcUri)));
//$rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, $srcUri));
if (sizeof($requestHeaders) > 0 || sizeof($metaHeaders) > 0)
$rest->setAmzHeader('x-amz-metadata-directive', 'REPLACE');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("SCS::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return isset($rest->body->LastModified, $rest->body->ETag) ? array(
'time' => strtotime((string)$rest->body->LastModified),
'hash' => substr((string)$rest->body->ETag, 1, -1)
) : false;
}
/**
* Set up a bucket redirection
*
* @param string $bucket Bucket name
* @param string $location Target host name
* @return boolean
*/
public static function setBucketRedirect($bucket = NULL, $location = NULL)
{
$rest = new SCSRequest('PUT', $bucket, '', self::$endpoint);
if( empty($bucket) || empty($location) ) {
self::__triggerError("SCS::setBucketRedirect({$bucket}, {$location}): Empty parameter.", __FILE__, __LINE__);
return false;
}
$dom = new DOMDocument;
$websiteConfiguration = $dom->createElement('WebsiteConfiguration');
$redirectAllRequestsTo = $dom->createElement('RedirectAllRequestsTo');
$hostName = $dom->createElement('HostName', $location);
$redirectAllRequestsTo->appendChild($hostName);
$websiteConfiguration->appendChild($redirectAllRequestsTo);
$dom->appendChild($websiteConfiguration);
$rest->setParameter('website', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("SCS::setBucketRedirect({$bucket}, {$location}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Set logging for a bucket
*
* @param string $bucket Bucket name
* @param string $targetBucket Target bucket (where logs are stored)
* @param string $targetPrefix Log prefix (e,g; domain.com-)
* @return boolean
*/
public static function setBucketLogging($bucket, $targetBucket, $targetPrefix = null)
{
// The SCS log delivery group has to be added to the target bucket's ACP
if ($targetBucket !== null && ($acp = self::getAccessControlPolicy($targetBucket, '')) !== false)
{
// Only add permissions to the target bucket when they do not exist
$aclWriteSet = false;
$aclReadSet = false;