5 * Copyright (c) 2013, Donovan Schönknecht. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
10 * - Redistributions of source code must retain the above copyright notice,
11 * this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
28 * Amazon S3 is a trademark of Amazon.com, Inc. or its affiliates.
34 * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
40 const ACL_PRIVATE
= 'private';
41 const ACL_PUBLIC_READ
= 'public-read';
42 const ACL_PUBLIC_READ_WRITE
= 'public-read-write';
43 const ACL_AUTHENTICATED_READ
= 'authenticated-read';
45 const STORAGE_CLASS_STANDARD
= 'STANDARD';
46 const STORAGE_CLASS_RRS
= 'REDUCED_REDUNDANCY';
49 const SSE_AES256
= 'AES256';
58 private static $__accessKey = null;
67 private static $__secretKey = null;
76 private static $__sslKey = null;
79 * Default delimiter to be used, for example while getBucket().
84 public static $defDelimiter = null;
93 public static $endpoint = 's3.amazonaws.com';
102 public static $proxy = null;
111 public static $useSSL = false;
114 * Use SSL validation?
120 public static $useSSLValidation = true;
129 public static $useSSLVersion = CURL_SSLVERSION_TLSv1
;
132 * Use PHP exceptions?
138 public static $useExceptions = false;
141 * Time offset applied to time()
145 private static $__timeOffset = 0;
154 public static $sslKey = null;
157 * SSL client certfificate
163 public static $sslCert = null;
166 * SSL CA cert (only required if you are having problems with your system CA cert)
172 public static $sslCACert = null;
181 private static $__signingKeyPairId = null;
184 * Key resource, freeSigningKey() must be called to clear it from memory
190 private static $__signingKeyResource = false;
194 * Constructor - if you're not using the class statically
196 * @param string $accessKey Access key
197 * @param string $secretKey Secret key
198 * @param boolean $useSSL Enable SSL
199 * @param string $endpoint Amazon URI
202 public function __construct($accessKey = null, $secretKey = null, $useSSL = false, $endpoint = 's3.amazonaws.com')
204 if ($accessKey !== null && $secretKey !== null)
205 self
::setAuth($accessKey, $secretKey);
206 self
::$useSSL = $useSSL;
207 self
::$endpoint = $endpoint;
212 * Set the service endpoint
214 * @param string $host Hostname
217 public function setEndpoint($host)
219 self
::$endpoint = $host;
224 * Set AWS access key and secret key
226 * @param string $accessKey Access key
227 * @param string $secretKey Secret key
230 public static function setAuth($accessKey, $secretKey)
232 self
::$__accessKey = $accessKey;
233 self
::$__secretKey = $secretKey;
238 * Check if AWS keys have been set
242 public static function hasAuth() {
243 return (self
::$__accessKey !== null && self
::$__secretKey !== null);
250 * @param boolean $enabled SSL enabled
251 * @param boolean $validate SSL certificate validation
254 public static function setSSL($enabled, $validate = true)
256 self
::$useSSL = $enabled;
257 self
::$useSSLValidation = $validate;
262 * Set SSL client certificates (experimental)
264 * @param string $sslCert SSL client certificate
265 * @param string $sslKey SSL client key
266 * @param string $sslCACert SSL CA cert (only required if you are having problems with your system CA cert)
269 public static function setSSLAuth($sslCert = null, $sslKey = null, $sslCACert = null)
271 self
::$sslCert = $sslCert;
272 self
::$sslKey = $sslKey;
273 self
::$sslCACert = $sslCACert;
278 * Set proxy information
280 * @param string $host Proxy hostname and port (localhost:1234)
281 * @param string $user Proxy username
282 * @param string $pass Proxy password
283 * @param constant $type CURL proxy type
286 public static function setProxy($host, $user = null, $pass = null, $type = CURLPROXY_SOCKS5
)
288 self
::$proxy = array('host' => $host, 'type' => $type, 'user' => $user, 'pass' => $pass);
293 * Set the error mode to exceptions
295 * @param boolean $enabled Enable exceptions
298 public static function setExceptions($enabled = true)
300 self
::$useExceptions = $enabled;
305 * Set AWS time correction offset (use carefully)
307 * This can be used when an inaccurate system time is generating
308 * invalid request signatures. It should only be used as a last
309 * resort when the system time cannot be changed.
311 * @param string $offset Time offset (set to zero to use AWS server time)
314 public static function setTimeCorrectionOffset($offset = 0)
318 $rest = new S3Request('HEAD');
319 $rest = $rest->getResponse();
320 $awstime = $rest->headers
['date'];
322 $offset = $systime > $awstime ?
-($systime - $awstime) : ($awstime - $systime);
324 self
::$__timeOffset = $offset;
331 * @param string $keyPairId AWS Key Pair ID
332 * @param string $signingKey Private Key
333 * @param boolean $isFile Load private key from file, set to false to load string
336 public static function setSigningKey($keyPairId, $signingKey, $isFile = true)
338 self
::$__signingKeyPairId = $keyPairId;
339 if ((self
::$__signingKeyResource = openssl_pkey_get_private($isFile ?
340 file_get_contents($signingKey) : $signingKey)) !== false) return true;
341 self
::__triggerError('S3::setSigningKey(): Unable to open load private key: '.$signingKey, __FILE__
, __LINE__
);
347 * Free signing key from memory, MUST be called if you are using setSigningKey()
351 public static function freeSigningKey()
353 if (self
::$__signingKeyResource !== false)
355 // TODO: Remove this block once PHP 8.0 becomes required.
356 if (PHP_MAJOR_VERSION
< 8) {
357 openssl_free_key(self
::$__signingKeyResource);
359 self
::$__signingKeyResource = null;
365 * Internal error handler
367 * @internal Internal error handler
368 * @param string $message Error message
369 * @param string $file Filename
370 * @param integer $line Line number
371 * @param integer $code Error code
374 private static function __triggerError($message, $file, $line, $code = 0)
376 if (self
::$useExceptions)
377 throw new S3Exception($message, $file, $line, $code);
379 trigger_error($message, E_USER_WARNING
);
384 * Get a list of buckets
386 * @param boolean $detailed Returns detailed bucket list when true
387 * @return array | false
389 public static function listBuckets($detailed = false)
391 $rest = new S3Request('GET', '', '', self
::$endpoint);
392 $rest = $rest->getResponse();
393 if ($rest->error
=== false && $rest->code
!== 200)
394 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
395 if ($rest->error
!== false)
397 self
::__triggerError(sprintf("S3::listBuckets(): [%s] %s", $rest->error
['code'],
398 $rest->error
['message']), __FILE__
, __LINE__
);
402 if (!isset($rest->body
->Buckets
)) return $results;
406 if (isset($rest->body
->Owner
, $rest->body
->Owner
->ID
, $rest->body
->Owner
->DisplayName
))
407 $results['owner'] = array(
408 'id' => (string)$rest->body
->Owner
->ID
, 'name' => (string)$rest->body
->Owner
->DisplayName
410 $results['buckets'] = array();
411 foreach ($rest->body
->Buckets
->Bucket
as $b)
412 $results['buckets'][] = array(
413 'name' => (string)$b->Name
, 'time' => strtotime((string)$b->CreationDate
)
416 foreach ($rest->body
->Buckets
->Bucket
as $b) $results[] = (string)$b->Name
;
423 * Get contents for a bucket
425 * If maxKeys is null this method will loop through truncated result sets
427 * @param string $bucket Bucket name
428 * @param string $prefix Prefix
429 * @param string $marker Marker (last file listed)
430 * @param string $maxKeys Max keys (maximum number of keys to return)
431 * @param string $delimiter Delimiter
432 * @param boolean $returnCommonPrefixes Set to true to return CommonPrefixes
433 * @return array | false
435 public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null, $delimiter = null, $returnCommonPrefixes = false)
437 $rest = new S3Request('GET', $bucket, '', self
::$endpoint);
438 if ($maxKeys == 0) $maxKeys = null;
439 if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
440 if ($marker !== null && $marker !== '') $rest->setParameter('marker', $marker);
441 if ($maxKeys !== null && $maxKeys !== '') $rest->setParameter('max-keys', $maxKeys);
442 if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
443 else if (!empty(self
::$defDelimiter)) $rest->setParameter('delimiter', self
::$defDelimiter);
444 $response = $rest->getResponse();
445 if ($response->error
=== false && $response->code
!== 200)
446 $response->error
= array('code' => $response->code
, 'message' => 'Unexpected HTTP status');
447 if ($response->error
!== false)
449 self
::__triggerError(sprintf("S3::getBucket(): [%s] %s",
450 $response->error
['code'], $response->error
['message']), __FILE__
, __LINE__
);
457 if (isset($response->body
, $response->body
->Contents
))
458 foreach ($response->body
->Contents
as $c)
460 $results[(string)$c->Key
] = array(
461 'name' => (string)$c->Key
,
462 'time' => strtotime((string)$c->LastModified
),
463 'size' => (int)$c->Size
,
464 'hash' => substr((string)$c->ETag
, 1, -1)
466 $nextMarker = (string)$c->Key
;
469 if ($returnCommonPrefixes && isset($response->body
, $response->body
->CommonPrefixes
))
470 foreach ($response->body
->CommonPrefixes
as $c)
471 $results[(string)$c->Prefix
] = array('prefix' => (string)$c->Prefix
);
473 if (isset($response->body
, $response->body
->IsTruncated
) &&
474 (string)$response->body
->IsTruncated
== 'false') return $results;
476 if (isset($response->body
, $response->body
->NextMarker
))
477 $nextMarker = (string)$response->body
->NextMarker
;
479 // Loop through truncated results if maxKeys isn't specified
480 if ($maxKeys == null && $nextMarker !== null && (string)$response->body
->IsTruncated
== 'true')
483 $rest = new S3Request('GET', $bucket, '', self
::$endpoint);
484 if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
485 $rest->setParameter('marker', $nextMarker);
486 if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
488 if (($response = $rest->getResponse()) == false ||
$response->code
!== 200) break;
490 if (isset($response->body
, $response->body
->Contents
))
491 foreach ($response->body
->Contents
as $c)
493 $results[(string)$c->Key
] = array(
494 'name' => (string)$c->Key
,
495 'time' => strtotime((string)$c->LastModified
),
496 'size' => (int)$c->Size
,
497 'hash' => substr((string)$c->ETag
, 1, -1)
499 $nextMarker = (string)$c->Key
;
502 if ($returnCommonPrefixes && isset($response->body
, $response->body
->CommonPrefixes
))
503 foreach ($response->body
->CommonPrefixes
as $c)
504 $results[(string)$c->Prefix
] = array('prefix' => (string)$c->Prefix
);
506 if (isset($response->body
, $response->body
->NextMarker
))
507 $nextMarker = (string)$response->body
->NextMarker
;
509 } while ($response !== false && (string)$response->body
->IsTruncated
== 'true');
518 * @param string $bucket Bucket name
519 * @param constant $acl ACL flag
520 * @param string $location Set as "EU" to create buckets hosted in Europe
523 public static function putBucket($bucket, $acl = self
::ACL_PRIVATE
, $location = false)
525 $rest = new S3Request('PUT', $bucket, '', self
::$endpoint);
526 $rest->setAmzHeader('x-amz-acl', $acl);
528 if ($location !== false)
530 $dom = new DOMDocument
;
531 $createBucketConfiguration = $dom->createElement('CreateBucketConfiguration');
532 $locationConstraint = $dom->createElement('LocationConstraint', $location);
533 $createBucketConfiguration->appendChild($locationConstraint);
534 $dom->appendChild($createBucketConfiguration);
535 $rest->data
= $dom->saveXML();
536 $rest->size
= strlen($rest->data
);
537 $rest->setHeader('Content-Type', 'application/xml');
539 $rest = $rest->getResponse();
541 if ($rest->error
=== false && $rest->code
!== 200)
542 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
543 if ($rest->error
!== false)
545 self
::__triggerError(sprintf("S3::putBucket({$bucket}, {$acl}, {$location}): [%s] %s",
546 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
554 * Delete an empty bucket
556 * @param string $bucket Bucket name
559 public static function deleteBucket($bucket)
561 $rest = new S3Request('DELETE', $bucket, '', self
::$endpoint);
562 $rest = $rest->getResponse();
563 if ($rest->error
=== false && $rest->code
!== 204)
564 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
565 if ($rest->error
!== false)
567 self
::__triggerError(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
568 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
576 * Create input info array for putObject()
578 * @param string $file Input file
579 * @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own)
580 * @return array | false
582 public static function inputFile($file, $md5sum = true)
584 if (!file_exists($file) ||
!is_file($file) ||
!is_readable($file))
586 self
::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__
, __LINE__
);
589 clearstatcache(false, $file);
590 return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ?
591 (is_string($md5sum) ?
$md5sum : base64_encode(md5_file($file, true))) : '');
596 * Create input array info for putObject() with a resource
598 * @param string $resource Input resource to read from
599 * @param integer $bufferSize Input byte size
600 * @param string $md5sum MD5 hash to send (optional)
601 * @return array | false
603 public static function inputResource(&$resource, $bufferSize = false, $md5sum = '')
605 if (!is_resource($resource) ||
(int)$bufferSize < 0)
607 self
::__triggerError('S3::inputResource(): Invalid resource or buffer size', __FILE__
, __LINE__
);
611 // Try to figure out the bytesize
612 if ($bufferSize === false)
614 if (fseek($resource, 0, SEEK_END
) < 0 ||
($bufferSize = ftell($resource)) === false)
616 self
::__triggerError('S3::inputResource(): Unable to obtain resource size', __FILE__
, __LINE__
);
622 $input = array('size' => $bufferSize, 'md5sum' => $md5sum);
623 $input['fp'] =& $resource;
631 * @param mixed $input Input data
632 * @param string $bucket Bucket name
633 * @param string $uri Object URI
634 * @param constant $acl ACL constant
635 * @param array $metaHeaders Array of x-amz-meta-* headers
636 * @param array $requestHeaders Array of request headers or content type as a string
637 * @param constant $storageClass Storage class constant
638 * @param constant $serverSideEncryption Server-side encryption
641 public static function putObject($input, $bucket, $uri, $acl = self
::ACL_PRIVATE
, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self
::STORAGE_CLASS_STANDARD
, $serverSideEncryption = self
::SSE_NONE
)
643 if ($input === false) return false;
644 $rest = new S3Request('PUT', $bucket, $uri, self
::$endpoint);
646 if (!is_array($input)) $input = array(
647 'data' => $input, 'size' => strlen($input),
648 'md5sum' => base64_encode(md5($input, true))
652 if (isset($input['fp']))
653 $rest->fp
=& $input['fp'];
654 elseif (isset($input['file']))
655 $rest->fp
= @fopen
($input['file'], 'rb');
656 elseif (isset($input['data']))
657 $rest->data
= $input['data'];
659 // Content-Length (required)
660 if (isset($input['size']) && $input['size'] >= 0)
661 $rest->size
= $input['size'];
663 if (isset($input['file'])) {
664 clearstatcache(false, $input['file']);
665 $rest->size
= filesize($input['file']);
667 elseif (isset($input['data']))
668 $rest->size
= strlen($input['data']);
671 // Custom request headers (Content-Type, Content-Disposition, Content-Encoding)
672 if (is_array($requestHeaders))
673 foreach ($requestHeaders as $h => $v)
674 strpos($h, 'x-amz-') === 0 ?
$rest->setAmzHeader($h, $v) : $rest->setHeader($h, $v);
675 elseif (is_string($requestHeaders)) // Support for legacy contentType parameter
676 $input['type'] = $requestHeaders;
679 if (!isset($input['type']))
681 if (isset($requestHeaders['Content-Type']))
682 $input['type'] =& $requestHeaders['Content-Type'];
683 elseif (isset($input['file']))
684 $input['type'] = self
::__getMIMEType($input['file']);
686 $input['type'] = 'application/octet-stream';
689 if ($storageClass !== self
::STORAGE_CLASS_STANDARD
) // Storage class
690 $rest->setAmzHeader('x-amz-storage-class', $storageClass);
692 if ($serverSideEncryption !== self
::SSE_NONE
) // Server-side encryption
693 $rest->setAmzHeader('x-amz-server-side-encryption', $serverSideEncryption);
695 // We need to post with Content-Length and Content-Type, MD5 is optional
696 if ($rest->size
>= 0 && ($rest->fp
!== false ||
$rest->data
!== false))
698 $rest->setHeader('Content-Type', $input['type']);
699 if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
701 $rest->setAmzHeader('x-amz-acl', $acl);
702 foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
703 $rest->getResponse();
705 $rest->response
->error
= array('code' => 0, 'message' => 'Missing input parameters');
707 if ($rest->response
->error
=== false && $rest->response
->code
!== 200)
708 $rest->response
->error
= array('code' => $rest->response
->code
, 'message' => 'Unexpected HTTP status');
709 if ($rest->response
->error
!== false)
711 self
::__triggerError(sprintf("S3::putObject(): [%s] %s",
712 $rest->response
->error
['code'], $rest->response
->error
['message']), __FILE__
, __LINE__
);
720 * Put an object from a file (legacy function)
722 * @param string $file Input file path
723 * @param string $bucket Bucket name
724 * @param string $uri Object URI
725 * @param constant $acl ACL constant
726 * @param array $metaHeaders Array of x-amz-meta-* headers
727 * @param string $contentType Content type
730 public static function putObjectFile($file, $bucket, $uri, $acl = self
::ACL_PRIVATE
, $metaHeaders = array(), $contentType = null)
732 return self
::putObject(self
::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
737 * Put an object from a string (legacy function)
739 * @param string $string Input data
740 * @param string $bucket Bucket name
741 * @param string $uri Object URI
742 * @param constant $acl ACL constant
743 * @param array $metaHeaders Array of x-amz-meta-* headers
744 * @param string $contentType Content type
747 public static function putObjectString($string, $bucket, $uri, $acl = self
::ACL_PRIVATE
, $metaHeaders = array(), $contentType = 'text/plain')
749 return self
::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
756 * @param string $bucket Bucket name
757 * @param string $uri Object URI
758 * @param mixed $saveTo Filename or resource to write to
761 public static function getObject($bucket, $uri, $saveTo = false)
763 $rest = new S3Request('GET', $bucket, $uri, self
::$endpoint);
764 if ($saveTo !== false)
766 if (is_resource($saveTo))
767 $rest->fp
=& $saveTo;
769 if (($rest->fp
= @fopen
($saveTo, 'wb')) !== false)
770 $rest->file
= realpath($saveTo);
772 $rest->response
->error
= array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
774 if ($rest->response
->error
=== false) $rest->getResponse();
776 if ($rest->response
->error
=== false && $rest->response
->code
!== 200)
777 $rest->response
->error
= array('code' => $rest->response
->code
, 'message' => 'Unexpected HTTP status');
778 if ($rest->response
->error
!== false)
780 self
::__triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
781 $rest->response
->error
['code'], $rest->response
->error
['message']), __FILE__
, __LINE__
);
784 return $rest->response
;
789 * Get object information
791 * @param string $bucket Bucket name
792 * @param string $uri Object URI
793 * @param boolean $returnInfo Return response information
794 * @return mixed | false
796 public static function getObjectInfo($bucket, $uri, $returnInfo = true)
798 $rest = new S3Request('HEAD', $bucket, $uri, self
::$endpoint);
799 $rest = $rest->getResponse();
800 if ($rest->error
=== false && ($rest->code
!== 200 && $rest->code
!== 404))
801 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
802 if ($rest->error
!== false)
804 self
::__triggerError(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s",
805 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
808 return $rest->code
== 200 ?
$returnInfo ?
$rest->headers
: true : false;
815 * @param string $srcBucket Source bucket name
816 * @param string $srcUri Source object URI
817 * @param string $bucket Destination bucket name
818 * @param string $uri Destination object URI
819 * @param constant $acl ACL constant
820 * @param array $metaHeaders Optional array of x-amz-meta-* headers
821 * @param array $requestHeaders Optional array of request headers (content type, disposition, etc.)
822 * @param constant $storageClass Storage class constant
823 * @return mixed | false
825 public static function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self
::ACL_PRIVATE
, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self
::STORAGE_CLASS_STANDARD
)
827 $rest = new S3Request('PUT', $bucket, $uri, self
::$endpoint);
828 $rest->setHeader('Content-Length', 0);
829 foreach ($requestHeaders as $h => $v)
830 strpos($h, 'x-amz-') === 0 ?
$rest->setAmzHeader($h, $v) : $rest->setHeader($h, $v);
831 foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
832 if ($storageClass !== self
::STORAGE_CLASS_STANDARD
) // Storage class
833 $rest->setAmzHeader('x-amz-storage-class', $storageClass);
834 $rest->setAmzHeader('x-amz-acl', $acl);
835 $rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, rawurlencode($srcUri)));
836 if (sizeof($requestHeaders) > 0 ||
sizeof($metaHeaders) > 0)
837 $rest->setAmzHeader('x-amz-metadata-directive', 'REPLACE');
839 $rest = $rest->getResponse();
840 if ($rest->error
=== false && $rest->code
!== 200)
841 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
842 if ($rest->error
!== false)
844 self
::__triggerError(sprintf("S3::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s",
845 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
848 return isset($rest->body
->LastModified
, $rest->body
->ETag
) ?
array(
849 'time' => strtotime((string)$rest->body
->LastModified
),
850 'hash' => substr((string)$rest->body
->ETag
, 1, -1)
856 * Set up a bucket redirection
858 * @param string $bucket Bucket name
859 * @param string $location Target host name
862 public static function setBucketRedirect($bucket = NULL, $location = NULL)
864 $rest = new S3Request('PUT', $bucket, '', self
::$endpoint);
866 if( empty($bucket) ||
empty($location) ) {
867 self
::__triggerError("S3::setBucketRedirect({$bucket}, {$location}): Empty parameter.", __FILE__
, __LINE__
);
871 $dom = new DOMDocument
;
872 $websiteConfiguration = $dom->createElement('WebsiteConfiguration');
873 $redirectAllRequestsTo = $dom->createElement('RedirectAllRequestsTo');
874 $hostName = $dom->createElement('HostName', $location);
875 $redirectAllRequestsTo->appendChild($hostName);
876 $websiteConfiguration->appendChild($redirectAllRequestsTo);
877 $dom->appendChild($websiteConfiguration);
878 $rest->setParameter('website', null);
879 $rest->data
= $dom->saveXML();
880 $rest->size
= strlen($rest->data
);
881 $rest->setHeader('Content-Type', 'application/xml');
882 $rest = $rest->getResponse();
884 if ($rest->error
=== false && $rest->code
!== 200)
885 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
886 if ($rest->error
!== false)
888 self
::__triggerError(sprintf("S3::setBucketRedirect({$bucket}, {$location}): [%s] %s",
889 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
897 * Set logging for a bucket
899 * @param string $bucket Bucket name
900 * @param string $targetBucket Target bucket (where logs are stored)
901 * @param string $targetPrefix Log prefix (e,g; domain.com-)
904 public static function setBucketLogging($bucket, $targetBucket, $targetPrefix = null)
906 // The S3 log delivery group has to be added to the target bucket's ACP
907 if ($targetBucket !== null && ($acp = self
::getAccessControlPolicy($targetBucket, '')) !== false)
909 // Only add permissions to the target bucket when they do not exist
910 $aclWriteSet = false;
912 foreach ($acp['acl'] as $acl)
913 if ($acl['type'] == 'Group' && $acl['uri'] == 'http://acs.amazonaws.com/groups/s3/LogDelivery')
915 if ($acl['permission'] == 'WRITE') $aclWriteSet = true;
916 elseif ($acl['permission'] == 'READ_ACP') $aclReadSet = true;
918 if (!$aclWriteSet) $acp['acl'][] = array(
919 'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'WRITE'
921 if (!$aclReadSet) $acp['acl'][] = array(
922 'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'READ_ACP'
924 if (!$aclReadSet ||
!$aclWriteSet) self
::setAccessControlPolicy($targetBucket, '', $acp);
927 $dom = new DOMDocument
;
928 $bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
929 $bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
930 if ($targetBucket !== null)
932 if ($targetPrefix == null) $targetPrefix = $bucket . '-';
933 $loggingEnabled = $dom->createElement('LoggingEnabled');
934 $loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
935 $loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
936 // TODO: Add TargetGrants?
937 $bucketLoggingStatus->appendChild($loggingEnabled);
939 $dom->appendChild($bucketLoggingStatus);
941 $rest = new S3Request('PUT', $bucket, '', self
::$endpoint);
942 $rest->setParameter('logging', null);
943 $rest->data
= $dom->saveXML();
944 $rest->size
= strlen($rest->data
);
945 $rest->setHeader('Content-Type', 'application/xml');
946 $rest = $rest->getResponse();
947 if ($rest->error
=== false && $rest->code
!== 200)
948 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
949 if ($rest->error
!== false)
951 self
::__triggerError(sprintf("S3::setBucketLogging({$bucket}, {$targetBucket}): [%s] %s",
952 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
960 * Get logging status for a bucket
962 * This will return false if logging is not enabled.
963 * Note: To enable logging, you also need to grant write access to the log group
965 * @param string $bucket Bucket name
966 * @return array | false
968 public static function getBucketLogging($bucket)
970 $rest = new S3Request('GET', $bucket, '', self
::$endpoint);
971 $rest->setParameter('logging', null);
972 $rest = $rest->getResponse();
973 if ($rest->error
=== false && $rest->code
!== 200)
974 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
975 if ($rest->error
!== false)
977 self
::__triggerError(sprintf("S3::getBucketLogging({$bucket}): [%s] %s",
978 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
981 if (!isset($rest->body
->LoggingEnabled
)) return false; // No logging
983 'targetBucket' => (string)$rest->body
->LoggingEnabled
->TargetBucket
,
984 'targetPrefix' => (string)$rest->body
->LoggingEnabled
->TargetPrefix
,
990 * Disable bucket logging
992 * @param string $bucket Bucket name
995 public static function disableBucketLogging($bucket)
997 return self
::setBucketLogging($bucket, null);
1002 * Get a bucket's location
1004 * @param string $bucket Bucket name
1005 * @return string | false
1007 public static function getBucketLocation($bucket)
1009 $rest = new S3Request('GET', $bucket, '', self
::$endpoint);
1010 $rest->setParameter('location', null);
1011 $rest = $rest->getResponse();
1012 if ($rest->error
=== false && $rest->code
!== 200)
1013 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1014 if ($rest->error
!== false)
1016 self
::__triggerError(sprintf("S3::getBucketLocation({$bucket}): [%s] %s",
1017 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1020 return (isset($rest->body
[0]) && (string)$rest->body
[0] !== '') ?
(string)$rest->body
[0] : 'US';
1025 * Set object or bucket Access Control Policy
1027 * @param string $bucket Bucket name
1028 * @param string $uri Object URI
1029 * @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy)
1032 public static function setAccessControlPolicy($bucket, $uri = '', $acp = array())
1034 $dom = new DOMDocument
;
1035 $dom->formatOutput
= true;
1036 $accessControlPolicy = $dom->createElement('AccessControlPolicy');
1037 $accessControlList = $dom->createElement('AccessControlList');
1039 // It seems the owner has to be passed along too
1040 $owner = $dom->createElement('Owner');
1041 $owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
1042 $owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
1043 $accessControlPolicy->appendChild($owner);
1045 foreach ($acp['acl'] as $g)
1047 $grant = $dom->createElement('Grant');
1048 $grantee = $dom->createElement('Grantee');
1049 $grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
1050 if (isset($g['id']))
1051 { // CanonicalUser (DisplayName is omitted)
1052 $grantee->setAttribute('xsi:type', 'CanonicalUser');
1053 $grantee->appendChild($dom->createElement('ID', $g['id']));
1055 elseif (isset($g['email']))
1056 { // AmazonCustomerByEmail
1057 $grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
1058 $grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
1060 elseif ($g['type'] == 'Group')
1062 $grantee->setAttribute('xsi:type', 'Group');
1063 $grantee->appendChild($dom->createElement('URI', $g['uri']));
1065 $grant->appendChild($grantee);
1066 $grant->appendChild($dom->createElement('Permission', $g['permission']));
1067 $accessControlList->appendChild($grant);
1070 $accessControlPolicy->appendChild($accessControlList);
1071 $dom->appendChild($accessControlPolicy);
1073 $rest = new S3Request('PUT', $bucket, $uri, self
::$endpoint);
1074 $rest->setParameter('acl', null);
1075 $rest->data
= $dom->saveXML();
1076 $rest->size
= strlen($rest->data
);
1077 $rest->setHeader('Content-Type', 'application/xml');
1078 $rest = $rest->getResponse();
1079 if ($rest->error
=== false && $rest->code
!== 200)
1080 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1081 if ($rest->error
!== false)
1083 self
::__triggerError(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
1084 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1092 * Get object or bucket Access Control Policy
1094 * @param string $bucket Bucket name
1095 * @param string $uri Object URI
1096 * @return mixed | false
1098 public static function getAccessControlPolicy($bucket, $uri = '')
1100 $rest = new S3Request('GET', $bucket, $uri, self
::$endpoint);
1101 $rest->setParameter('acl', null);
1102 $rest = $rest->getResponse();
1103 if ($rest->error
=== false && $rest->code
!== 200)
1104 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1105 if ($rest->error
!== false)
1107 self
::__triggerError(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
1108 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1113 if (isset($rest->body
->Owner
, $rest->body
->Owner
->ID
, $rest->body
->Owner
->DisplayName
))
1114 $acp['owner'] = array(
1115 'id' => (string)$rest->body
->Owner
->ID
, 'name' => (string)$rest->body
->Owner
->DisplayName
1118 if (isset($rest->body
->AccessControlList
))
1120 $acp['acl'] = array();
1121 foreach ($rest->body
->AccessControlList
->Grant
as $grant)
1123 foreach ($grant->Grantee
as $grantee)
1125 if (isset($grantee->ID
, $grantee->DisplayName
)) // CanonicalUser
1126 $acp['acl'][] = array(
1127 'type' => 'CanonicalUser',
1128 'id' => (string)$grantee->ID
,
1129 'name' => (string)$grantee->DisplayName
,
1130 'permission' => (string)$grant->Permission
1132 elseif (isset($grantee->EmailAddress
)) // AmazonCustomerByEmail
1133 $acp['acl'][] = array(
1134 'type' => 'AmazonCustomerByEmail',
1135 'email' => (string)$grantee->EmailAddress
,
1136 'permission' => (string)$grant->Permission
1138 elseif (isset($grantee->URI
)) // Group
1139 $acp['acl'][] = array(
1141 'uri' => (string)$grantee->URI
,
1142 'permission' => (string)$grant->Permission
1155 * @param string $bucket Bucket name
1156 * @param string $uri Object URI
1159 public static function deleteObject($bucket, $uri)
1161 $rest = new S3Request('DELETE', $bucket, $uri, self
::$endpoint);
1162 $rest = $rest->getResponse();
1163 if ($rest->error
=== false && $rest->code
!== 204)
1164 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1165 if ($rest->error
!== false)
1167 self
::__triggerError(sprintf("S3::deleteObject(): [%s] %s",
1168 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1176 * Get a query string authenticated URL
1178 * @param string $bucket Bucket name
1179 * @param string $uri Object URI
1180 * @param integer $lifetime Lifetime in seconds
1181 * @param boolean $hostBucket Use the bucket name as the hostname
1182 * @param boolean $https Use HTTPS ($hostBucket should be false for SSL verification)
1185 public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false)
1187 $expires = self
::__getTime() +
$lifetime;
1188 $uri = str_replace(array('%2F', '%2B'), array('/', '+'), rawurlencode($uri));
1189 return sprintf(($https ?
'https' : 'http').'://%s/%s?AWSAccessKeyId=%s&Expires=%u&Signature=%s',
1190 // $hostBucket ? $bucket : $bucket.'.s3.amazonaws.com', $uri, self::$__accessKey, $expires,
1191 $hostBucket ?
$bucket : self
::$endpoint.'/'.$bucket, $uri, self
::$__accessKey, $expires,
1192 urlencode(self
::__getHash("GET\n\n\n{$expires}\n/{$bucket}/{$uri}")));
1197 * Get a CloudFront signed policy URL
1199 * @param array $policy Policy
1202 public static function getSignedPolicyURL($policy)
1204 $data = json_encode($policy);
1206 if (!openssl_sign($data, $signature, self
::$__signingKeyResource)) return false;
1208 $encoded = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($data));
1209 $signature = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($signature));
1211 $url = $policy['Statement'][0]['Resource'] . '?';
1212 foreach (array('Policy' => $encoded, 'Signature' => $signature, 'Key-Pair-Id' => self
::$__signingKeyPairId) as $k => $v)
1213 $url .= $k.'='.str_replace('%2F', '/', rawurlencode($v)).'&';
1214 return substr($url, 0, -1);
1219 * Get a CloudFront canned policy URL
1221 * @param string $url URL to sign
1222 * @param integer $lifetime URL lifetime
1225 public static function getSignedCannedURL($url, $lifetime)
1227 return self
::getSignedPolicyURL(array(
1228 'Statement' => array(
1229 array('Resource' => $url, 'Condition' => array(
1230 'DateLessThan' => array('AWS:EpochTime' => self
::__getTime() +
$lifetime)
1238 * Get upload POST parameters for form uploads
1240 * @param string $bucket Bucket name
1241 * @param string $uriPrefix Object URI prefix
1242 * @param constant $acl ACL constant
1243 * @param integer $lifetime Lifetime in seconds
1244 * @param integer $maxFileSize Maximum filesize in bytes (default 5MB)
1245 * @param string $successRedirect Redirect URL or 200 / 201 status code
1246 * @param array $amzHeaders Array of x-amz-meta-* headers
1247 * @param array $headers Array of request headers or content type as a string
1248 * @param boolean $flashVars Includes additional "Filename" variable posted by Flash
1251 public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self
::ACL_PRIVATE
, $lifetime = 3600,
1252 $maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false)
1254 // Create policy object
1255 $policy = new stdClass
;
1256 $policy->expiration
= gmdate('Y-m-d\TH:i:s\Z', (self
::__getTime() +
$lifetime));
1257 $policy->conditions
= array();
1258 $obj = new stdClass
; $obj->bucket
= $bucket; array_push($policy->conditions
, $obj);
1259 $obj = new stdClass
; $obj->acl
= $acl; array_push($policy->conditions
, $obj);
1261 $obj = new stdClass
; // 200 for non-redirect uploads
1262 if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
1263 $obj->success_action_status
= (string)$successRedirect;
1265 $obj->success_action_redirect
= $successRedirect;
1266 array_push($policy->conditions
, $obj);
1268 if ($acl !== self
::ACL_PUBLIC_READ
)
1269 array_push($policy->conditions
, array('eq', '$acl', $acl));
1271 array_push($policy->conditions
, array('starts-with', '$key', $uriPrefix));
1272 if ($flashVars) array_push($policy->conditions
, array('starts-with', '$Filename', ''));
1273 foreach (array_keys($headers) as $headerKey)
1274 array_push($policy->conditions
, array('starts-with', '$'.$headerKey, ''));
1275 foreach ($amzHeaders as $headerKey => $headerVal)
1277 $obj = new stdClass
;
1278 $obj->{$headerKey} = (string)$headerVal;
1279 array_push($policy->conditions
, $obj);
1281 array_push($policy->conditions
, array('content-length-range', 0, $maxFileSize));
1282 $policy = base64_encode(str_replace('\/', '/', json_encode($policy)));
1284 // Create parameters
1285 $params = new stdClass
;
1286 $params->AWSAccessKeyId
= self
::$__accessKey;
1287 $params->key
= $uriPrefix.'${filename}';
1288 $params->acl
= $acl;
1289 $params->policy
= $policy; unset($policy);
1290 $params->signature
= self
::__getHash($params->policy
);
1291 if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
1292 $params->success_action_status
= (string)$successRedirect;
1294 $params->success_action_redirect
= $successRedirect;
1295 foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
1296 foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
1302 * Create a CloudFront distribution
1304 * @param string $bucket Bucket name
1305 * @param boolean $enabled Enabled (true/false)
1306 * @param array $cnames Array containing CNAME aliases
1307 * @param string $comment Use the bucket name as the hostname
1308 * @param string $defaultRootObject Default root object
1309 * @param string $originAccessIdentity Origin access identity
1310 * @param array $trustedSigners Array of trusted signers
1311 * @return array | false
1313 public static function createDistribution($bucket, $enabled = true, $cnames = array(), $comment = null, $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array())
1315 if (!extension_loaded('openssl'))
1317 self
::__triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): %s",
1318 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1321 $useSSL = self
::$useSSL;
1323 self
::$useSSL = true; // CloudFront requires SSL
1324 $rest = new S3Request('POST', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com');
1325 $rest->data
= self
::__getCloudFrontDistributionConfigXML(
1326 $bucket.'.s3.amazonaws.com',
1329 (string)microtime(true),
1332 $originAccessIdentity,
1336 $rest->size
= strlen($rest->data
);
1337 $rest->setHeader('Content-Type', 'application/xml');
1338 $rest = self
::__getCloudFrontResponse($rest);
1340 self
::$useSSL = $useSSL;
1342 if ($rest->error
=== false && $rest->code
!== 201)
1343 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1344 if ($rest->error
!== false)
1346 self
::__triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): [%s] %s",
1347 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1349 } elseif ($rest->body
instanceof SimpleXMLElement
)
1350 return self
::__parseCloudFrontDistributionConfig($rest->body
);
1356 * Get CloudFront distribution info
1358 * @param string $distributionId Distribution ID from listDistributions()
1359 * @return array | false
1361 public static function getDistribution($distributionId)
1363 if (!extension_loaded('openssl'))
1365 self
::__triggerError(sprintf("S3::getDistribution($distributionId): %s",
1366 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1369 $useSSL = self
::$useSSL;
1371 self
::$useSSL = true; // CloudFront requires SSL
1372 $rest = new S3Request('GET', '', '2010-11-01/distribution/'.$distributionId, 'cloudfront.amazonaws.com');
1373 $rest = self
::__getCloudFrontResponse($rest);
1375 self
::$useSSL = $useSSL;
1377 if ($rest->error
=== false && $rest->code
!== 200)
1378 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1379 if ($rest->error
!== false)
1381 self
::__triggerError(sprintf("S3::getDistribution($distributionId): [%s] %s",
1382 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1385 elseif ($rest->body
instanceof SimpleXMLElement
)
1387 $dist = self
::__parseCloudFrontDistributionConfig($rest->body
);
1388 $dist['hash'] = $rest->headers
['hash'];
1389 $dist['id'] = $distributionId;
1397 * Update a CloudFront distribution
1399 * @param array $dist Distribution array info identical to output of getDistribution()
1400 * @return array | false
1402 public static function updateDistribution($dist)
1404 if (!extension_loaded('openssl'))
1406 self
::__triggerError(sprintf("S3::updateDistribution({$dist['id']}): %s",
1407 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1411 $useSSL = self
::$useSSL;
1413 self
::$useSSL = true; // CloudFront requires SSL
1414 $rest = new S3Request('PUT', '', '2010-11-01/distribution/'.$dist['id'].'/config', 'cloudfront.amazonaws.com');
1415 $rest->data
= self
::__getCloudFrontDistributionConfigXML(
1419 $dist['callerReference'],
1421 $dist['defaultRootObject'],
1422 $dist['originAccessIdentity'],
1423 $dist['trustedSigners']
1426 $rest->size
= strlen($rest->data
);
1427 $rest->setHeader('If-Match', $dist['hash']);
1428 $rest = self
::__getCloudFrontResponse($rest);
1430 self
::$useSSL = $useSSL;
1432 if ($rest->error
=== false && $rest->code
!== 200)
1433 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1434 if ($rest->error
!== false)
1436 self
::__triggerError(sprintf("S3::updateDistribution({$dist['id']}): [%s] %s",
1437 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1440 $dist = self
::__parseCloudFrontDistributionConfig($rest->body
);
1441 $dist['hash'] = $rest->headers
['hash'];
1449 * Delete a CloudFront distribution
1451 * @param array $dist Distribution array info identical to output of getDistribution()
1454 public static function deleteDistribution($dist)
1456 if (!extension_loaded('openssl'))
1458 self
::__triggerError(sprintf("S3::deleteDistribution({$dist['id']}): %s",
1459 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1463 $useSSL = self
::$useSSL;
1465 self
::$useSSL = true; // CloudFront requires SSL
1466 $rest = new S3Request('DELETE', '', '2008-06-30/distribution/'.$dist['id'], 'cloudfront.amazonaws.com');
1467 $rest->setHeader('If-Match', $dist['hash']);
1468 $rest = self
::__getCloudFrontResponse($rest);
1470 self
::$useSSL = $useSSL;
1472 if ($rest->error
=== false && $rest->code
!== 204)
1473 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1474 if ($rest->error
!== false)
1476 self
::__triggerError(sprintf("S3::deleteDistribution({$dist['id']}): [%s] %s",
1477 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1485 * Get a list of CloudFront distributions
1489 public static function listDistributions()
1491 if (!extension_loaded('openssl'))
1493 self
::__triggerError(sprintf("S3::listDistributions(): [%s] %s",
1494 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1498 $useSSL = self
::$useSSL;
1499 self
::$useSSL = true; // CloudFront requires SSL
1500 $rest = new S3Request('GET', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com');
1501 $rest = self
::__getCloudFrontResponse($rest);
1502 self
::$useSSL = $useSSL;
1504 if ($rest->error
=== false && $rest->code
!== 200)
1505 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1506 if ($rest->error
!== false)
1508 self
::__triggerError(sprintf("S3::listDistributions(): [%s] %s",
1509 $rest->error
['code'], $rest->error
['message']), __FILE__
, __LINE__
);
1512 elseif ($rest->body
instanceof SimpleXMLElement
&& isset($rest->body
->DistributionSummary
))
1515 if (isset($rest->body
->Marker
, $rest->body
->MaxItems
, $rest->body
->IsTruncated
))
1517 //$info['marker'] = (string)$rest->body->Marker;
1518 //$info['maxItems'] = (int)$rest->body->MaxItems;
1519 //$info['isTruncated'] = (string)$rest->body->IsTruncated == 'true' ? true : false;
1521 foreach ($rest->body
->DistributionSummary
as $summary)
1522 $list[(string)$summary->Id
] = self
::__parseCloudFrontDistributionConfig($summary);
1530 * List CloudFront Origin Access Identities
1534 public static function listOriginAccessIdentities()
1536 if (!extension_loaded('openssl'))
1538 self
::__triggerError(sprintf("S3::listOriginAccessIdentities(): [%s] %s",
1539 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1543 self
::$useSSL = true; // CloudFront requires SSL
1544 $rest = new S3Request('GET', '', '2010-11-01/origin-access-identity/cloudfront', 'cloudfront.amazonaws.com');
1545 $rest = self
::__getCloudFrontResponse($rest);
1546 $useSSL = self
::$useSSL;
1548 if ($rest->error
=== false && $rest->code
!== 200)
1549 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1550 if ($rest->error
!== false)
1552 trigger_error(sprintf("S3::listOriginAccessIdentities(): [%s] %s",
1553 $rest->error
['code'], $rest->error
['message']), E_USER_WARNING
);
1557 if (isset($rest->body
->CloudFrontOriginAccessIdentitySummary
))
1559 $identities = array();
1560 foreach ($rest->body
->CloudFrontOriginAccessIdentitySummary
as $identity)
1561 if (isset($identity->S3CanonicalUserId
))
1562 $identities[(string)$identity->Id
] = array('id' => (string)$identity->Id
, 's3CanonicalUserId' => (string)$identity->S3CanonicalUserId
);
1570 * Invalidate objects in a CloudFront distribution
1572 * Thanks to Martin Lindkvist for S3::invalidateDistribution()
1574 * @param string $distributionId Distribution ID from listDistributions()
1575 * @param array $paths Array of object paths to invalidate
1578 public static function invalidateDistribution($distributionId, $paths)
1580 if (!extension_loaded('openssl'))
1582 self
::__triggerError(sprintf("S3::invalidateDistribution(): [%s] %s",
1583 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1587 $useSSL = self
::$useSSL;
1588 self
::$useSSL = true; // CloudFront requires SSL
1589 $rest = new S3Request('POST', '', '2010-08-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com');
1590 $rest->data
= self
::__getCloudFrontInvalidationBatchXML($paths, (string)microtime(true));
1591 $rest->size
= strlen($rest->data
);
1592 $rest = self
::__getCloudFrontResponse($rest);
1593 self
::$useSSL = $useSSL;
1595 if ($rest->error
=== false && $rest->code
!== 201)
1596 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1597 if ($rest->error
!== false)
1599 trigger_error(sprintf("S3::invalidate('{$distributionId}',{$paths}): [%s] %s",
1600 $rest->error
['code'], $rest->error
['message']), E_USER_WARNING
);
1608 * Get a InvalidationBatch DOMDocument
1610 * @internal Used to create XML in invalidateDistribution()
1611 * @param array $paths Paths to objects to invalidateDistribution
1612 * @param int $callerReference
1615 private static function __getCloudFrontInvalidationBatchXML($paths, $callerReference = '0')
1617 $dom = new DOMDocument('1.0', 'UTF-8');
1618 $dom->formatOutput
= true;
1619 $invalidationBatch = $dom->createElement('InvalidationBatch');
1620 foreach ($paths as $path)
1621 $invalidationBatch->appendChild($dom->createElement('Path', $path));
1623 $invalidationBatch->appendChild($dom->createElement('CallerReference', $callerReference));
1624 $dom->appendChild($invalidationBatch);
1625 return $dom->saveXML();
1630 * List your invalidation batches for invalidateDistribution() in a CloudFront distribution
1632 * http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html
1633 * returned array looks like this:
1636 * [I31TWB0CN9V6XD] => InProgress
1637 * [IT3TFE31M0IHZ] => Completed
1638 * [I12HK7MPO1UQDA] => Completed
1639 * [I1IA7R6JKTC3L2] => Completed
1642 * @param string $distributionId Distribution ID from listDistributions()
1645 public static function getDistributionInvalidationList($distributionId)
1647 if (!extension_loaded('openssl'))
1649 self
::__triggerError(sprintf("S3::getDistributionInvalidationList(): [%s] %s",
1650 "CloudFront functionality requires SSL"), __FILE__
, __LINE__
);
1654 $useSSL = self
::$useSSL;
1655 self
::$useSSL = true; // CloudFront requires SSL
1656 $rest = new S3Request('GET', '', '2010-11-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com');
1657 $rest = self
::__getCloudFrontResponse($rest);
1658 self
::$useSSL = $useSSL;
1660 if ($rest->error
=== false && $rest->code
!== 200)
1661 $rest->error
= array('code' => $rest->code
, 'message' => 'Unexpected HTTP status');
1662 if ($rest->error
!== false)
1664 trigger_error(sprintf("S3::getDistributionInvalidationList('{$distributionId}'): [%s]",
1665 $rest->error
['code'], $rest->error
['message']), E_USER_WARNING
);
1668 elseif ($rest->body
instanceof SimpleXMLElement
&& isset($rest->body
->InvalidationSummary
))
1671 foreach ($rest->body
->InvalidationSummary
as $summary)
1672 $list[(string)$summary->Id
] = (string)$summary->Status
;
1681 * Get a DistributionConfig DOMDocument
1683 * http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?PutConfig.html
1685 * @internal Used to create XML in createDistribution() and updateDistribution()
1686 * @param string $bucket S3 Origin bucket
1687 * @param boolean $enabled Enabled (true/false)
1688 * @param string $comment Comment to append
1689 * @param string $callerReference Caller reference
1690 * @param array $cnames Array of CNAME aliases
1691 * @param string $defaultRootObject Default root object
1692 * @param string $originAccessIdentity Origin access identity
1693 * @param array $trustedSigners Array of trusted signers
1696 private static function __getCloudFrontDistributionConfigXML($bucket, $enabled, $comment, $callerReference = '0', $cnames = array(), $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array())
1698 $dom = new DOMDocument('1.0', 'UTF-8');
1699 $dom->formatOutput
= true;
1700 $distributionConfig = $dom->createElement('DistributionConfig');
1701 $distributionConfig->setAttribute('xmlns', 'http://cloudfront.amazonaws.com/doc/2010-11-01/');
1703 $origin = $dom->createElement('S3Origin');
1704 $origin->appendChild($dom->createElement('DNSName', $bucket));
1705 if ($originAccessIdentity !== null) $origin->appendChild($dom->createElement('OriginAccessIdentity', $originAccessIdentity));
1706 $distributionConfig->appendChild($origin);
1708 if ($defaultRootObject !== null) $distributionConfig->appendChild($dom->createElement('DefaultRootObject', $defaultRootObject));
1710 $distributionConfig->appendChild($dom->createElement('CallerReference', $callerReference));
1711 foreach ($cnames as $cname)
1712 $distributionConfig->appendChild($dom->createElement('CNAME', $cname));
1713 if ($comment !== '') $distributionConfig->appendChild($dom->createElement('Comment', $comment));
1714 $distributionConfig->appendChild($dom->createElement('Enabled', $enabled ?
'true' : 'false'));
1716 $trusted = $dom->createElement('TrustedSigners');
1717 foreach ($trustedSigners as $id => $type)
1718 $trusted->appendChild($id !== '' ?
$dom->createElement($type, $id) : $dom->createElement($type));
1719 $distributionConfig->appendChild($trusted);
1721 $dom->appendChild($distributionConfig);
1722 //var_dump($dom->saveXML());
1723 return $dom->saveXML();
1728 * Parse a CloudFront distribution config
1730 * See http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?GetDistribution.html
1732 * @internal Used to parse the CloudFront DistributionConfig node to an array
1733 * @param object &$node DOMNode
1736 private static function __parseCloudFrontDistributionConfig(&$node)
1738 if (isset($node->DistributionConfig
))
1739 return self
::__parseCloudFrontDistributionConfig($node->DistributionConfig
);
1742 if (isset($node->Id
, $node->Status
, $node->LastModifiedTime
, $node->DomainName
))
1744 $dist['id'] = (string)$node->Id
;
1745 $dist['status'] = (string)$node->Status
;
1746 $dist['time'] = strtotime((string)$node->LastModifiedTime
);
1747 $dist['domain'] = (string)$node->DomainName
;
1750 if (isset($node->CallerReference
))
1751 $dist['callerReference'] = (string)$node->CallerReference
;
1753 if (isset($node->Enabled
))
1754 $dist['enabled'] = (string)$node->Enabled
== 'true' ?
true : false;
1756 if (isset($node->S3Origin
))
1758 if (isset($node->S3Origin
->DNSName
))
1759 $dist['origin'] = (string)$node->S3Origin
->DNSName
;
1761 $dist['originAccessIdentity'] = isset($node->S3Origin
->OriginAccessIdentity
) ?
1762 (string)$node->S3Origin
->OriginAccessIdentity
: null;
1765 $dist['defaultRootObject'] = isset($node->DefaultRootObject
) ?
(string)$node->DefaultRootObject
: null;
1767 $dist['cnames'] = array();
1768 if (isset($node->CNAME
))
1769 foreach ($node->CNAME
as $cname)
1770 $dist['cnames'][(string)$cname] = (string)$cname;
1772 $dist['trustedSigners'] = array();
1773 if (isset($node->TrustedSigners
))
1774 foreach ($node->TrustedSigners
as $signer)
1776 if (isset($signer->Self
))
1777 $dist['trustedSigners'][''] = 'Self';
1778 elseif (isset($signer->KeyPairId
))
1779 $dist['trustedSigners'][(string)$signer->KeyPairId
] = 'KeyPairId';
1780 elseif (isset($signer->AwsAccountNumber
))
1781 $dist['trustedSigners'][(string)$signer->AwsAccountNumber
] = 'AwsAccountNumber';
1784 $dist['comment'] = isset($node->Comment
) ?
(string)$node->Comment
: null;
1790 * Grab CloudFront response
1792 * @internal Used to parse the CloudFront S3Request::getResponse() output
1793 * @param object &$rest S3Request instance
1796 private static function __getCloudFrontResponse(&$rest)
1798 $rest->getResponse();
1799 if ($rest->response
->error
=== false && isset($rest->response
->body
) &&
1800 is_string($rest->response
->body
) && substr($rest->response
->body
, 0, 5) == '<?xml')
1802 $rest->response
->body
= simplexml_load_string($rest->response
->body
);
1803 // Grab CloudFront errors
1804 if (isset($rest->response
->body
->Error
, $rest->response
->body
->Error
->Code
,
1805 $rest->response
->body
->Error
->Message
))
1807 $rest->response
->error
= array(
1808 'code' => (string)$rest->response
->body
->Error
->Code
,
1809 'message' => (string)$rest->response
->body
->Error
->Message
1811 unset($rest->response
->body
);
1814 return $rest->response
;
1819 * Get MIME type for file
1821 * To override the putObject() Content-Type, add it to $requestHeaders
1823 * To use fileinfo, ensure the MAGIC environment variable is set
1825 * @internal Used to get mime types
1826 * @param string &$file File path
1829 private static function __getMIMEType(&$file)
1831 static $exts = array(
1832 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif',
1833 'png' => 'image/png', 'ico' => 'image/x-icon', 'pdf' => 'application/pdf',
1834 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'svg' => 'image/svg+xml',
1835 'svgz' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash',
1836 'zip' => 'application/zip', 'gz' => 'application/x-gzip',
1837 'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
1838 'bz2' => 'application/x-bzip2', 'rar' => 'application/x-rar-compressed',
1839 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload',
1840 'cab' => 'application/vnd.ms-cab-compressed', 'txt' => 'text/plain',
1841 'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
1842 'css' => 'text/css', 'js' => 'text/javascript',
1843 'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
1844 'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
1845 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
1846 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
1849 $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION
));
1850 if (isset($exts[$ext])) return $exts[$ext];
1852 // Use fileinfo if available
1853 if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
1854 ($finfo = finfo_open(FILEINFO_MIME
, $_ENV['MAGIC'])) !== false)
1856 if (($type = finfo_file($finfo, $file)) !== false)
1858 // Remove the charset and grab the last content-type
1859 $type = explode(' ', str_replace('; charset=', ';charset=', $type));
1860 $type = array_pop($type);
1861 $type = explode(';', $type);
1862 $type = trim(array_shift($type));
1864 finfo_close($finfo);
1865 if ($type !== false && strlen($type) > 0) return $type;
1868 return 'application/octet-stream';
1873 * Get the current time
1875 * @internal Used to apply offsets to sytem time
1878 public static function __getTime()
1880 return time() + self
::$__timeOffset;
1885 * Generate the auth string: "AWS AccessKey:Signature"
1887 * @internal Used by S3Request::getResponse()
1888 * @param string $string String to sign
1891 public static function __getSignature($string)
1893 return 'AWS '.self
::$__accessKey.':'.self
::__getHash($string);
1898 * Creates a HMAC-SHA1 hash
1900 * This uses the hash extension if loaded
1902 * @internal Used by __getSignature()
1903 * @param string $string String to sign
1906 private static function __getHash($string)
1908 return base64_encode(extension_loaded('hash') ?
1909 hash_hmac('sha1', $string, self
::$__secretKey, true) : pack('H*', sha1(
1910 (str_pad(self
::$__secretKey, 64, chr(0x00)) ^
(str_repeat(chr(0x5c), 64))) .
1911 pack('H*', sha1((str_pad(self
::$__secretKey, 64, chr(0x00)) ^
1912 (str_repeat(chr(0x36), 64))) . $string)))));
1920 * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
1921 * @version 0.5.0-dev
1923 final class S3Request
1963 private $resource = '';
1966 * Additional request parameters
1971 private $parameters = array();
1974 * Amazon specific request headers
1979 private $amzHeaders = array();
1982 * HTTP request headers
1987 private $headers = array(
1988 'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
2013 public $data = false;
2016 * S3 request respone
2024 * Filename or resource to write to.
2034 * @param string $verb Verb
2035 * @param string $bucket Bucket name
2036 * @param string $uri Object URI
2037 * @param string $endpoint AWS endpoint URI
2040 function __construct($verb, $bucket = '', $uri = '', $endpoint = 's3.amazonaws.com')
2043 $this->endpoint
= $endpoint;
2044 $this->verb
= $verb;
2045 $this->bucket
= $bucket;
2046 $this->uri
= $uri !== '' ?
'/'.str_replace('%2F', '/', rawurlencode($uri)) : '/';
2048 //if ($this->bucket !== '')
2049 // $this->resource = '/'.$this->bucket.$this->uri;
2051 // $this->resource = $this->uri;
2053 if ($this->bucket
!== '')
2055 if ($this->__dnsBucketName($this->bucket
))
2057 $this->headers
['Host'] = $this->bucket
.'.'.$this->endpoint
;
2058 $this->resource = '/'.$this->bucket
.$this->uri
;
2062 $this->headers
['Host'] = $this->endpoint
;
2063 $this->uri
= $this->uri
;
2064 if ($this->bucket
!== '') $this->uri
= '/'.$this->bucket
.$this->uri
;
2066 $this->resource = $this->uri
;
2071 $this->headers
['Host'] = $this->endpoint
;
2072 $this->resource = $this->uri
;
2076 $this->headers
['Date'] = gmdate('D, d M Y H:i:s T');
2077 $this->response
= new STDClass
;
2078 $this->response
->error
= false;
2079 $this->response
->body
= null;
2080 $this->response
->headers
= array();
2085 * Set request parameter
2087 * @param string $key Key
2088 * @param string $value Value
2091 public function setParameter($key, $value)
2093 $this->parameters
[$key] = $value;
2098 * Set request header
2100 * @param string $key Key
2101 * @param string $value Value
2104 public function setHeader($key, $value)
2106 $this->headers
[$key] = $value;
2111 * Set x-amz-meta-* header
2113 * @param string $key Key
2114 * @param string $value Value
2117 public function setAmzHeader($key, $value)
2119 $this->amzHeaders
[$key] = $value;
2124 * Get the S3 response
2126 * @return object | false
2128 public function getResponse()
2131 if (sizeof($this->parameters
) > 0)
2133 $query = substr($this->uri
, -1) !== '?' ?
'?' : '&';
2134 foreach ($this->parameters
as $var => $value)
2135 if ($value == null ||
$value == '') $query .= $var.'&';
2136 else $query .= $var.'='.rawurlencode($value).'&';
2137 $query = substr($query, 0, -1);
2138 $this->uri
.= $query;
2140 if (array_key_exists('acl', $this->parameters
) ||
2141 array_key_exists('location', $this->parameters
) ||
2142 array_key_exists('torrent', $this->parameters
) ||
2143 array_key_exists('website', $this->parameters
) ||
2144 array_key_exists('logging', $this->parameters
))
2145 $this->resource .= $query;
2147 $url = (S3
::$useSSL ?
'https://' : 'http://') . ($this->headers
['Host'] !== '' ?
$this->headers
['Host'] : $this->endpoint
) . $this->uri
;
2149 //var_dump('bucket: ' . $this->bucket, 'uri: ' . $this->uri, 'resource: ' . $this->resource, 'url: ' . $url);
2152 $curl = curl_init();
2153 curl_setopt($curl, CURLOPT_USERAGENT
, 'S3/php');
2157 // Set protocol version
2158 curl_setopt($curl, CURLOPT_SSLVERSION
, S3
::$useSSLVersion);
2160 // SSL Validation can now be optional for those with broken OpenSSL installations
2161 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, S3
::$useSSLValidation ?
2 : 0);
2162 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, S3
::$useSSLValidation ?
1 : 0);
2164 if (S3
::$sslKey !== null) curl_setopt($curl, CURLOPT_SSLKEY
, S3
::$sslKey);
2165 if (S3
::$sslCert !== null) curl_setopt($curl, CURLOPT_SSLCERT
, S3
::$sslCert);
2166 if (S3
::$sslCACert !== null) curl_setopt($curl, CURLOPT_CAINFO
, S3
::$sslCACert);
2169 curl_setopt($curl, CURLOPT_URL
, $url);
2171 if (S3
::$proxy != null && isset(S3
::$proxy['host']))
2173 curl_setopt($curl, CURLOPT_PROXY
, S3
::$proxy['host']);
2174 curl_setopt($curl, CURLOPT_PROXYTYPE
, S3
::$proxy['type']);
2175 if (isset(S3
::$proxy['user'], S3
::$proxy['pass']) && S3
::$proxy['user'] != null && S3
::$proxy['pass'] != null)
2176 curl_setopt($curl, CURLOPT_PROXYUSERPWD
, sprintf('%s:%s', S3
::$proxy['user'], S3
::$proxy['pass']));
2180 $headers = array(); $amz = array();
2181 foreach ($this->amzHeaders
as $header => $value)
2182 if (strlen($value) > 0) $headers[] = $header.': '.$value;
2183 foreach ($this->headers
as $header => $value)
2184 if (strlen($value) > 0) $headers[] = $header.': '.$value;
2186 // Collect AMZ headers for signature
2187 foreach ($this->amzHeaders
as $header => $value)
2188 if (strlen($value) > 0) $amz[] = strtolower($header).':'.$value;
2190 // AMZ headers must be sorted
2191 if (sizeof($amz) > 0)
2194 usort($amz, array(&$this, '__sortMetaHeadersCmp'));
2195 $amz = "\n".implode("\n", $amz);
2200 // Authorization string (CloudFront stringToSign should only contain a date)
2201 if ($this->headers
['Host'] == 'cloudfront.amazonaws.com')
2202 $headers[] = 'Authorization: ' . S3
::__getSignature($this->headers
['Date']);
2205 $headers[] = 'Authorization: ' . S3
::__getSignature(
2207 $this->headers
['Content-MD5']."\n".
2208 $this->headers
['Content-Type']."\n".
2209 $this->headers
['Date'].$amz."\n".
2215 curl_setopt($curl, CURLOPT_HTTPHEADER
, $headers);
2216 curl_setopt($curl, CURLOPT_HEADER
, false);
2217 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, false);
2218 curl_setopt($curl, CURLOPT_WRITEFUNCTION
, array(&$this, '__responseWriteCallback'));
2219 curl_setopt($curl, CURLOPT_HEADERFUNCTION
, array(&$this, '__responseHeaderCallback'));
2220 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, true);
2223 switch ($this->verb
)
2226 case 'PUT': case 'POST': // POST only used for CloudFront
2227 if ($this->fp
!== false)
2229 curl_setopt($curl, CURLOPT_PUT
, true);
2230 curl_setopt($curl, CURLOPT_INFILE
, $this->fp
);
2231 if ($this->size
>= 0)
2232 curl_setopt($curl, CURLOPT_INFILESIZE
, $this->size
);
2234 elseif ($this->data
!== false)
2236 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, $this->verb
);
2237 curl_setopt($curl, CURLOPT_POSTFIELDS
, $this->data
);
2240 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, $this->verb
);
2243 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, 'HEAD');
2244 curl_setopt($curl, CURLOPT_NOBODY
, true);
2247 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, 'DELETE');
2252 // Execute, grab errors
2253 if (curl_exec($curl))
2254 $this->response
->code
= curl_getinfo($curl, CURLINFO_HTTP_CODE
);
2256 $this->response
->error
= array(
2257 'code' => curl_errno($curl),
2258 'message' => curl_error($curl),
2259 'resource' => $this->resource
2264 // Parse body into XML
2265 if ($this->response
->error
=== false && isset($this->response
->headers
['type']) &&
2266 $this->response
->headers
['type'] == 'application/xml' && isset($this->response
->body
))
2268 $this->response
->body
= simplexml_load_string($this->response
->body
);
2271 if (!in_array($this->response
->code
, array(200, 204, 206)) &&
2272 isset($this->response
->body
->Code
, $this->response
->body
->Message
))
2274 $this->response
->error
= array(
2275 'code' => (string)$this->response
->body
->Code
,
2276 'message' => (string)$this->response
->body
->Message
2278 if (isset($this->response
->body
->Resource))
2279 $this->response
->error
['resource'] = (string)$this->response
->body
->Resource;
2280 unset($this->response
->body
);
2284 // Clean up file resources
2285 if ($this->fp
!== false && is_resource($this->fp
)) fclose($this->fp
);
2287 return $this->response
;
2291 * Sort compare for meta headers
2293 * @internal Used to sort x-amz meta headers
2294 * @param string $a String A
2295 * @param string $b String B
2298 private function __sortMetaHeadersCmp($a, $b)
2300 $lenA = strpos($a, ':');
2301 $lenB = strpos($b, ':');
2302 $minLen = min($lenA, $lenB);
2303 $ncmp = strncmp($a, $b, $minLen);
2304 if ($lenA == $lenB) return $ncmp;
2305 if (0 == $ncmp) return $lenA < $lenB ?
-1 : 1;
2310 * CURL write callback
2312 * @param resource &$curl CURL resource
2313 * @param string &$data Data
2316 private function __responseWriteCallback(&$curl, &$data)
2318 if (in_array($this->response
->code
, array(200, 206)) && $this->fp
!== false)
2319 return fwrite($this->fp
, $data);
2321 $this->response
->body
.= $data;
2322 return strlen($data);
2327 * Check DNS conformity
2329 * @param string $bucket Bucket name
2332 private function __dnsBucketName($bucket)
2334 if (strlen($bucket) > 63 ||
preg_match("/[^a-z0-9\.-]/", $bucket) > 0) return false;
2335 if (S3
::$useSSL && strstr($bucket, '.') !== false) return false;
2336 if (strstr($bucket, '-.') !== false) return false;
2337 if (strstr($bucket, '..') !== false) return false;
2338 if (!preg_match("/^[0-9a-z]/", $bucket)) return false;
2339 if (!preg_match("/[0-9a-z]$/", $bucket)) return false;
2345 * CURL header callback
2347 * @param resource $curl CURL resource
2348 * @param string $data Data
2351 private function __responseHeaderCallback($curl, $data)
2353 if (($strlen = strlen($data)) <= 2) return $strlen;
2354 if (substr($data, 0, 4) == 'HTTP')
2355 $this->response
->code
= (int)substr($data, 9, 3);
2358 $data = trim($data);
2359 if (strpos($data, ': ') === false) return $strlen;
2360 list($header, $value) = explode(': ', $data, 2);
2361 if ($header == 'Last-Modified')
2362 $this->response
->headers
['time'] = strtotime($value);
2363 elseif ($header == 'Date')
2364 $this->response
->headers
['date'] = strtotime($value);
2365 elseif ($header == 'Content-Length')
2366 $this->response
->headers
['size'] = (int)$value;
2367 elseif ($header == 'Content-Type')
2368 $this->response
->headers
['type'] = $value;
2369 elseif ($header == 'ETag')
2370 $this->response
->headers
['hash'] = $value[0] == '"' ?
substr($value, 1, -1) : $value;
2371 elseif (preg_match('/^x-amz-meta-.*$/', $header))
2372 $this->response
->headers
[$header] = $value;
2380 * S3 exception class
2382 * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
2383 * @version 0.5.0-dev
2386 class S3Exception
extends Exception
{
2390 * @param string $message Exception message
2391 * @param string $file File in which exception was created
2392 * @param string $line Line number on which exception was created
2393 * @param int $code Exception code
2395 function __construct($message, $file, $line, $code = 0)
2397 parent
::__construct($message, $code);
2398 $this->file
= $file;
2399 $this->line
= $line;