PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/aws/services/s3.class.php

https://bitbucket.org/ardydedase/web-build-optimizer
PHP | 3639 lines | 1821 code | 463 blank | 1355 comment | 295 complexity | 96c14e0c753ef445895070abbb7c616e MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause
  1. <?php
  2. /*
  3. * Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License").
  6. * You may not use this file except in compliance with the License.
  7. * A copy of the License is located at
  8. *
  9. * http://aws.amazon.com/apache2.0
  10. *
  11. * or in the "license" file accompanying this file. This file is distributed
  12. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  13. * express or implied. See the License for the specific language governing
  14. * permissions and limitations under the License.
  15. */
  16. /*%******************************************************************************************%*/
  17. // EXCEPTIONS
  18. /**
  19. * Default S3 Exception.
  20. */
  21. class S3_Exception extends Exception {}
  22. /*%******************************************************************************************%*/
  23. // MAIN CLASS
  24. /**
  25. * Amazon S3 is a web service that enables you to store data in the cloud. You can then download the data
  26. * or use the data with other AWS services, such as Amazon Elastic Cloud Computer (EC2).
  27. *
  28. * Amazon Simple Storage Service (Amazon S3) is storage for the Internet. You can use Amazon S3 to store
  29. * and retrieve any amount of data at any time, from anywhere on the web. You can accomplish these tasks
  30. * using the AWS Management Console, which is a simple and intuitive web interface.
  31. *
  32. * To get the most out of Amazon S3, you need to understand a few simple concepts. Amazon S3 stores data
  33. * as objects in buckets. An object is comprised of a file and optionally any metadata that describes
  34. * that file.
  35. *
  36. * To store an object in Amazon S3, you upload the file you want to store to a bucket. When you upload a
  37. * file, you can set permissions on the object as well as any metadata.
  38. *
  39. * Buckets are the containers for objects. You can have one or more buckets. For each bucket, you can control
  40. * access to the bucket (who can create, delete, and list objects in the bucket), view access logs for the
  41. * bucket and its objects, and choose the geographical region where Amazon S3 will store the bucket and its
  42. * contents.
  43. *
  44. * Visit <http://aws.amazon.com/s3/> for more information.
  45. *
  46. * @version 2011.12.02
  47. * @license See the included NOTICE.md file for more information.
  48. * @copyright See the included NOTICE.md file for more information.
  49. * @link http://aws.amazon.com/s3/ Amazon Simple Storage Service
  50. * @link http://aws.amazon.com/documentation/s3/ Amazon Simple Storage Service documentation
  51. */
  52. class AmazonS3 extends CFRuntime
  53. {
  54. /*%******************************************************************************************%*/
  55. // CLASS CONSTANTS
  56. /**
  57. * The default endpoint.
  58. */
  59. const DEFAULT_URL = 's3.amazonaws.com';
  60. /**
  61. * Specify the queue URL for the US-East (Northern Virginia) Region.
  62. */
  63. const REGION_US_E1 = '';
  64. /**
  65. * Specify the queue URL for the US-West (Northern California) Region.
  66. */
  67. const REGION_US_W1 = 'us-west-1';
  68. /**
  69. * Specify the queue URL for the US-West (Oregon) Region.
  70. */
  71. const REGION_US_W2 = 'us-west-2';
  72. /**
  73. * Specify the queue URL for the EU (Ireland) Region.
  74. */
  75. const REGION_EU_W1 = 'EU';
  76. /**
  77. * Specify the queue URL for the Asia Pacific (Singapore) Region.
  78. */
  79. const REGION_APAC_SE1 = 'ap-southeast-1';
  80. /**
  81. * Specify the queue URL for the Asia Pacific (Japan) Region.
  82. */
  83. const REGION_APAC_NE1 = 'ap-northeast-1';
  84. /**
  85. * ACL: Owner-only read/write.
  86. */
  87. const ACL_PRIVATE = 'private';
  88. /**
  89. * ACL: Owner read/write, public read.
  90. */
  91. const ACL_PUBLIC = 'public-read';
  92. /**
  93. * ACL: Public read/write.
  94. */
  95. const ACL_OPEN = 'public-read-write';
  96. /**
  97. * ACL: Owner read/write, authenticated read.
  98. */
  99. const ACL_AUTH_READ = 'authenticated-read';
  100. /**
  101. * ACL: Bucket owner read.
  102. */
  103. const ACL_OWNER_READ = 'bucket-owner-read';
  104. /**
  105. * ACL: Bucket owner full control.
  106. */
  107. const ACL_OWNER_FULL_CONTROL = 'bucket-owner-full-control';
  108. /**
  109. * When applied to a bucket, grants permission to list the bucket. When applied to an object, this
  110. * grants permission to read the object data and/or metadata.
  111. */
  112. const GRANT_READ = 'READ';
  113. /**
  114. * When applied to a bucket, grants permission to create, overwrite, and delete any object in the
  115. * bucket. This permission is not supported for objects.
  116. */
  117. const GRANT_WRITE = 'WRITE';
  118. /**
  119. * Grants permission to read the ACL for the applicable bucket or object. The owner of a bucket or
  120. * object always has this permission implicitly.
  121. */
  122. const GRANT_READ_ACP = 'READ_ACP';
  123. /**
  124. * Gives permission to overwrite the ACP for the applicable bucket or object. The owner of a bucket
  125. * or object always has this permission implicitly. Granting this permission is equivalent to granting
  126. * FULL_CONTROL because the grant recipient can make any changes to the ACP.
  127. */
  128. const GRANT_WRITE_ACP = 'WRITE_ACP';
  129. /**
  130. * Provides READ, WRITE, READ_ACP, and WRITE_ACP permissions. It does not convey additional rights and
  131. * is provided only for convenience.
  132. */
  133. const GRANT_FULL_CONTROL = 'FULL_CONTROL';
  134. /**
  135. * The "AuthenticatedUsers" group for access control policies.
  136. */
  137. const USERS_AUTH = 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers';
  138. /**
  139. * The "AllUsers" group for access control policies.
  140. */
  141. const USERS_ALL = 'http://acs.amazonaws.com/groups/global/AllUsers';
  142. /**
  143. * The "LogDelivery" group for access control policies.
  144. */
  145. const USERS_LOGGING = 'http://acs.amazonaws.com/groups/s3/LogDelivery';
  146. /**
  147. * PCRE: Match all items
  148. */
  149. const PCRE_ALL = '/.*/i';
  150. /**
  151. * Standard storage redundancy.
  152. */
  153. const STORAGE_STANDARD = 'STANDARD';
  154. /**
  155. * Reduced storage redundancy.
  156. */
  157. const STORAGE_REDUCED = 'REDUCED_REDUNDANCY';
  158. /*%******************************************************************************************%*/
  159. // PROPERTIES
  160. /**
  161. * The request URL.
  162. */
  163. public $request_url;
  164. /**
  165. * The virtual host setting.
  166. */
  167. public $vhost;
  168. /**
  169. * The base XML elements to use for access control policy methods.
  170. */
  171. public $base_acp_xml;
  172. /**
  173. * The base XML elements to use for creating buckets in regions.
  174. */
  175. public $base_location_constraint;
  176. /**
  177. * The base XML elements to use for logging methods.
  178. */
  179. public $base_logging_xml;
  180. /**
  181. * The base XML elements to use for notifications.
  182. */
  183. public $base_notification_xml;
  184. /**
  185. * The base XML elements to use for versioning.
  186. */
  187. public $base_versioning_xml;
  188. /**
  189. * The base XML elements to use for completing a multipart upload.
  190. */
  191. public $complete_mpu_xml;
  192. /**
  193. * The base XML elements to use for website support.
  194. */
  195. public $website_config_xml;
  196. /**
  197. * The DNS vs. Path-style setting.
  198. */
  199. public $path_style = false;
  200. /**
  201. * The state of whether the prefix change is temporary or permanent.
  202. */
  203. public $temporary_prefix = false;
  204. /**
  205. * The state of whether the response should be parsed or not.
  206. */
  207. public $parse_the_response = true;
  208. /*%******************************************************************************************%*/
  209. // CONSTRUCTOR
  210. /**
  211. * Constructs a new instance of <AmazonS3>. If the <code>AWS_DEFAULT_CACHE_CONFIG</code> configuration
  212. * option is set, requests will be authenticated using a session token. Otherwise, requests will use
  213. * the older authentication method.
  214. *
  215. * @param string $key (Optional) Your AWS key, or a session key. If blank, it will look for the <code>AWS_KEY</code> constant.
  216. * @param string $secret_key (Optional) Your AWS secret key, or a session secret key. If blank, it will look for the <code>AWS_SECRET_KEY</code> constant.
  217. * @param string $token (optional) An AWS session token. If blank, a request will be made to the AWS Secure Token Service to fetch a set of session credentials.
  218. * @return boolean A value of <code>false</code> if no valid values are set, otherwise <code>true</code>.
  219. */
  220. public function __construct($key = null, $secret_key = null, $token = null)
  221. {
  222. $this->vhost = null;
  223. $this->api_version = '2006-03-01';
  224. $this->hostname = self::DEFAULT_URL;
  225. $this->base_acp_xml = '<?xml version="1.0" encoding="UTF-8"?><AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/latest/"></AccessControlPolicy>';
  226. $this->base_location_constraint = '<?xml version="1.0" encoding="UTF-8"?><CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/' . $this->api_version . '/"><LocationConstraint></LocationConstraint></CreateBucketConfiguration>';
  227. $this->base_logging_xml = '<?xml version="1.0" encoding="utf-8"?><BucketLoggingStatus xmlns="http://doc.s3.amazonaws.com/' . $this->api_version . '"></BucketLoggingStatus>';
  228. $this->base_notification_xml = '<?xml version="1.0" encoding="utf-8"?><NotificationConfiguration></NotificationConfiguration>';
  229. $this->base_versioning_xml = '<?xml version="1.0" encoding="utf-8"?><VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/' . $this->api_version . '/"></VersioningConfiguration>';
  230. $this->complete_mpu_xml = '<?xml version="1.0" encoding="utf-8"?><CompleteMultipartUpload></CompleteMultipartUpload>';
  231. $this->website_config_xml = '<?xml version="1.0" encoding="utf-8"?><WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/' . $this->api_version . '/"><IndexDocument><Suffix>index.html</Suffix></IndexDocument><ErrorDocument><Key>error.html</Key></ErrorDocument></WebsiteConfiguration>';
  232. $this->multi_object_delete_xml = '<?xml version="1.0" encoding="utf-8"?><Delete></Delete>';
  233. if (!$key && !defined('AWS_KEY'))
  234. {
  235. // @codeCoverageIgnoreStart
  236. throw new S3_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.');
  237. // @codeCoverageIgnoreEnd
  238. }
  239. if (!$secret_key && !defined('AWS_SECRET_KEY'))
  240. {
  241. // @codeCoverageIgnoreStart
  242. throw new S3_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.');
  243. // @codeCoverageIgnoreEnd
  244. }
  245. if (defined('AWS_DEFAULT_CACHE_CONFIG') && AWS_DEFAULT_CACHE_CONFIG)
  246. {
  247. return parent::session_based_auth($key, $secret_key, $token);
  248. }
  249. return parent::__construct($key, $secret_key, $token);
  250. }
  251. /*%******************************************************************************************%*/
  252. // AUTHENTICATION
  253. /**
  254. * Authenticates a connection to Amazon S3. Do not use directly unless implementing custom methods for
  255. * this class.
  256. *
  257. * @param string $bucket (Required) The name of the bucket to use.
  258. * @param array $opt (Optional) An associative array of parameters for authenticating. See the individual methods for allowed keys.
  259. * @param string $location (Do Not Use) Used internally by this function on occasions when Amazon S3 returns a redirect code and it needs to call itself recursively.
  260. * @param integer $redirects (Do Not Use) Used internally by this function on occasions when Amazon S3 returns a redirect code and it needs to call itself recursively.
  261. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  262. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_Authentication.html REST authentication
  263. */
  264. public function authenticate($bucket, $opt = null, $location = null, $redirects = 0, $nothing = null)
  265. {
  266. /*
  267. * Overriding or extending this class? You can pass the following "magic" keys into $opt.
  268. *
  269. * ## verb, resource, sub_resource and query_string ##
  270. * <verb> /<resource>?<sub_resource>&<query_string>
  271. * GET /filename.txt?versions&prefix=abc&max-items=1
  272. *
  273. * ## versionId, uploadId, partNumber, response-* ##
  274. * These don't follow the same rules as above, in that the they needs to be signed, while
  275. * other query_string values do not.
  276. *
  277. * ## curlopts ##
  278. * These values get passed directly to the cURL methods in RequestCore.
  279. *
  280. * ## fileUpload, fileDownload, seekTo ##
  281. * These are slightly modified and then passed to the cURL methods in RequestCore.
  282. *
  283. * ## headers ##
  284. * $opt['headers'] is an array, whose keys are HTTP headers to be sent.
  285. *
  286. * ## body ##
  287. * This is the request body that is sent to the server via PUT/POST.
  288. *
  289. * ## preauth ##
  290. * This is a hook that tells authenticate() to generate a pre-authenticated URL.
  291. *
  292. * ## returnCurlHandle ##
  293. * Tells authenticate() to return the cURL handle for the request instead of executing it.
  294. */
  295. /**
  296. * @todo: Handle duplicate headers with different values.
  297. */
  298. // Validate the S3 bucket name
  299. if (!$this->validate_bucketname_support($bucket))
  300. {
  301. // @codeCoverageIgnoreStart
  302. throw new S3_Exception('S3 does not support "' . $bucket . '" as a valid bucket name. Review "Bucket Restrictions and Limitations" in the S3 Developer Guide for more information.');
  303. // @codeCoverageIgnoreEnd
  304. }
  305. // Die if $opt isn't set.
  306. if (!$opt) return false;
  307. $method_arguments = func_get_args();
  308. // Use the caching flow to determine if we need to do a round-trip to the server.
  309. if ($this->use_cache_flow)
  310. {
  311. // Generate an identifier specific to this particular set of arguments.
  312. $cache_id = $this->key . '_' . get_class($this) . '_' . $bucket . '_' . sha1(serialize($method_arguments));
  313. // Instantiate the appropriate caching object.
  314. $this->cache_object = new $this->cache_class($cache_id, $this->cache_location, $this->cache_expires, $this->cache_compress);
  315. if ($this->delete_cache)
  316. {
  317. $this->use_cache_flow = false;
  318. $this->delete_cache = false;
  319. return $this->cache_object->delete();
  320. }
  321. // Invoke the cache callback function to determine whether to pull data from the cache or make a fresh request.
  322. $data = $this->cache_object->response_manager(array($this, 'cache_callback'), $method_arguments);
  323. if ($this->parse_the_response)
  324. {
  325. // Parse the XML body
  326. $data = $this->parse_callback($data);
  327. }
  328. // End!
  329. return $data;
  330. }
  331. // If we haven't already set a resource prefix...
  332. if (!$this->resource_prefix || $this->path_style)
  333. {
  334. // And if the bucket name isn't DNS-valid...
  335. if (!$this->validate_bucketname_create($bucket))
  336. {
  337. // Fall back to the older path-style URI
  338. $this->set_resource_prefix('/' . $bucket);
  339. $this->temporary_prefix = true;
  340. }
  341. elseif ($this->path_style)
  342. {
  343. // Fall back to the older path-style URI
  344. $this->set_resource_prefix('/' . $bucket);
  345. }
  346. }
  347. // Determine hostname
  348. $scheme = $this->use_ssl ? 'https://' : 'http://';
  349. if ($this->resource_prefix || $this->path_style) // Use bucket-in-path method.
  350. {
  351. $hostname = $this->hostname . $this->resource_prefix . (($bucket === '' || $this->resource_prefix === '/' . $bucket) ? '' : ('/' . $bucket));
  352. }
  353. else
  354. {
  355. $hostname = $this->vhost ? $this->vhost : (($bucket === '') ? $this->hostname : ($bucket . '.') . $this->hostname);
  356. }
  357. // Get the UTC timestamp in RFC 2616 format
  358. $date = gmdate(CFUtilities::DATE_FORMAT_RFC2616, (time() + (integer) $this->adjust_offset));
  359. // Storage for request parameters.
  360. $resource = '';
  361. $sub_resource = '';
  362. $querystringparams = array();
  363. $signable_querystringparams = array();
  364. $string_to_sign = '';
  365. $headers = array(
  366. 'Content-MD5' => '',
  367. 'Content-Type' => 'application/x-www-form-urlencoded',
  368. 'Date' => $date
  369. );
  370. /*%******************************************************************************************%*/
  371. // Do we have an authentication token?
  372. if ($this->auth_token)
  373. {
  374. $headers['X-Amz-Security-Token'] = $this->auth_token;
  375. }
  376. // Handle specific resources
  377. if (isset($opt['resource']))
  378. {
  379. $resource .= $opt['resource'];
  380. }
  381. // Merge query string values
  382. if (isset($opt['query_string']))
  383. {
  384. $querystringparams = array_merge($querystringparams, $opt['query_string']);
  385. }
  386. $query_string = $this->util->to_query_string($querystringparams);
  387. // Merge the signable query string values. Must be alphabetical.
  388. $signable_list = array(
  389. 'partNumber',
  390. 'response-cache-control',
  391. 'response-content-disposition',
  392. 'response-content-encoding',
  393. 'response-content-language',
  394. 'response-content-type',
  395. 'response-expires',
  396. 'uploadId',
  397. 'versionId'
  398. );
  399. foreach ($signable_list as $item)
  400. {
  401. if (isset($opt[$item]))
  402. {
  403. $signable_querystringparams[$item] = $opt[$item];
  404. }
  405. }
  406. $signable_query_string = $this->util->to_query_string($signable_querystringparams);
  407. // Merge the HTTP headers
  408. if (isset($opt['headers']))
  409. {
  410. $headers = array_merge($headers, $opt['headers']);
  411. }
  412. // Compile the URI to request
  413. $conjunction = '?';
  414. $signable_resource = '/' . str_replace('%2F', '/', rawurlencode($resource));
  415. $non_signable_resource = '';
  416. if (isset($opt['sub_resource']))
  417. {
  418. $signable_resource .= $conjunction . rawurlencode($opt['sub_resource']);
  419. $conjunction = '&';
  420. }
  421. if ($signable_query_string !== '')
  422. {
  423. $signable_query_string = $conjunction . $signable_query_string;
  424. $conjunction = '&';
  425. }
  426. if ($query_string !== '')
  427. {
  428. $non_signable_resource .= $conjunction . $query_string;
  429. $conjunction = '&';
  430. }
  431. $this->request_url = $scheme . $hostname . $signable_resource . $signable_query_string . $non_signable_resource;
  432. // Instantiate the request class
  433. $request = new $this->request_class($this->request_url, $this->proxy);
  434. // Update RequestCore settings
  435. $request->request_class = $this->request_class;
  436. $request->response_class = $this->response_class;
  437. // Pass along registered stream callbacks
  438. if ($this->registered_streaming_read_callback)
  439. {
  440. $request->register_streaming_read_callback($this->registered_streaming_read_callback);
  441. }
  442. if ($this->registered_streaming_write_callback)
  443. {
  444. $request->register_streaming_write_callback($this->registered_streaming_write_callback);
  445. }
  446. // Streaming uploads
  447. if (isset($opt['fileUpload']))
  448. {
  449. if (is_resource($opt['fileUpload']))
  450. {
  451. // Determine the length to read from the stream
  452. $length = null; // From current position until EOF by default, size determined by set_read_stream()
  453. if (isset($headers['Content-Length']))
  454. {
  455. $length = $headers['Content-Length'];
  456. }
  457. elseif (isset($opt['seekTo']))
  458. {
  459. // Read from seekTo until EOF by default
  460. $stats = fstat($opt['fileUpload']);
  461. if ($stats && $stats['size'] >= 0)
  462. {
  463. $length = $stats['size'] - (integer) $opt['seekTo'];
  464. }
  465. }
  466. $request->set_read_stream($opt['fileUpload'], $length);
  467. if ($headers['Content-Type'] === 'application/x-www-form-urlencoded')
  468. {
  469. $headers['Content-Type'] = 'application/octet-stream';
  470. }
  471. }
  472. else
  473. {
  474. $request->set_read_file($opt['fileUpload']);
  475. // Determine the length to read from the file
  476. $length = $request->read_stream_size; // The file size by default
  477. if (isset($headers['Content-Length']))
  478. {
  479. $length = $headers['Content-Length'];
  480. }
  481. elseif (isset($opt['seekTo']) && isset($length))
  482. {
  483. // Read from seekTo until EOF by default
  484. $length -= (integer) $opt['seekTo'];
  485. }
  486. $request->set_read_stream_size($length);
  487. // Attempt to guess the correct mime-type
  488. if ($headers['Content-Type'] === 'application/x-www-form-urlencoded')
  489. {
  490. $extension = explode('.', $opt['fileUpload']);
  491. $extension = array_pop($extension);
  492. $mime_type = CFMimeTypes::get_mimetype($extension);
  493. $headers['Content-Type'] = $mime_type;
  494. }
  495. }
  496. $headers['Content-Length'] = $request->read_stream_size;
  497. $headers['Content-MD5'] = '';
  498. }
  499. // Handle streaming file offsets
  500. if (isset($opt['seekTo']))
  501. {
  502. // Pass the seek position to RequestCore
  503. $request->set_seek_position((integer) $opt['seekTo']);
  504. }
  505. // Streaming downloads
  506. if (isset($opt['fileDownload']))
  507. {
  508. if (is_resource($opt['fileDownload']))
  509. {
  510. $request->set_write_stream($opt['fileDownload']);
  511. }
  512. else
  513. {
  514. $request->set_write_file($opt['fileDownload']);
  515. }
  516. }
  517. $curlopts = array();
  518. // Set custom CURLOPT settings
  519. if (isset($opt['curlopts']))
  520. {
  521. $curlopts = $opt['curlopts'];
  522. unset($opt['curlopts']);
  523. }
  524. // Debug mode
  525. if ($this->debug_mode)
  526. {
  527. $curlopts[CURLOPT_VERBOSE] = true;
  528. }
  529. // Set the curl options.
  530. if (count($curlopts))
  531. {
  532. $request->set_curlopts($curlopts);
  533. }
  534. // Do we have a verb?
  535. if (isset($opt['verb']))
  536. {
  537. $request->set_method($opt['verb']);
  538. $string_to_sign .= $opt['verb'] . "\n";
  539. }
  540. // Add headers and content when we have a body
  541. if (isset($opt['body']))
  542. {
  543. $request->set_body($opt['body']);
  544. $headers['Content-Length'] = strlen($opt['body']);
  545. if ($headers['Content-Type'] === 'application/x-www-form-urlencoded')
  546. {
  547. $headers['Content-Type'] = 'application/octet-stream';
  548. }
  549. if (!isset($opt['NoContentMD5']) || $opt['NoContentMD5'] !== true)
  550. {
  551. $headers['Content-MD5'] = $this->util->hex_to_base64(md5($opt['body']));
  552. }
  553. }
  554. // Handle query-string authentication
  555. if (isset($opt['preauth']) && (integer) $opt['preauth'] > 0)
  556. {
  557. unset($headers['Date']);
  558. $headers['Content-Type'] = '';
  559. $headers['Expires'] = is_int($opt['preauth']) ? $opt['preauth'] : strtotime($opt['preauth']);
  560. }
  561. // Sort headers
  562. uksort($headers, 'strnatcasecmp');
  563. // Add headers to request and compute the string to sign
  564. foreach ($headers as $header_key => $header_value)
  565. {
  566. // Strip linebreaks from header values as they're illegal and can allow for security issues
  567. $header_value = str_replace(array("\r", "\n"), '', $header_value);
  568. // Add the header if it has a value
  569. if ($header_value !== '')
  570. {
  571. $request->add_header($header_key, $header_value);
  572. }
  573. // Generate the string to sign
  574. if (
  575. strtolower($header_key) === 'content-md5' ||
  576. strtolower($header_key) === 'content-type' ||
  577. strtolower($header_key) === 'date' ||
  578. (strtolower($header_key) === 'expires' && isset($opt['preauth']) && (integer) $opt['preauth'] > 0)
  579. )
  580. {
  581. $string_to_sign .= $header_value . "\n";
  582. }
  583. elseif (substr(strtolower($header_key), 0, 6) === 'x-amz-')
  584. {
  585. $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n";
  586. }
  587. }
  588. // Add the signable resource location
  589. $string_to_sign .= ($this->resource_prefix ? $this->resource_prefix : '');
  590. $string_to_sign .= (($bucket === '' || $this->resource_prefix === '/' . $bucket) ? '' : ('/' . $bucket)) . $signable_resource . urldecode($signable_query_string);
  591. // Hash the AWS secret key and generate a signature for the request.
  592. $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->secret_key, true));
  593. $request->add_header('Authorization', 'AWS ' . $this->key . ':' . $signature);
  594. // If we're generating a URL, return certain data to the calling method.
  595. if (isset($opt['preauth']) && (integer) $opt['preauth'] > 0)
  596. {
  597. return $this->request_url . $conjunction . 'AWSAccessKeyId=' . $this->key . '&Expires=' . $headers['Expires'] . '&Signature=' . rawurlencode($signature);
  598. }
  599. elseif (isset($opt['preauth']))
  600. {
  601. return $this->request_url;
  602. }
  603. /*%******************************************************************************************%*/
  604. // If our changes were temporary, reset them.
  605. if ($this->temporary_prefix)
  606. {
  607. $this->temporary_prefix = false;
  608. $this->resource_prefix = null;
  609. }
  610. // Manage the (newer) batch request API or the (older) returnCurlHandle setting.
  611. if ($this->use_batch_flow)
  612. {
  613. $handle = $request->prep_request();
  614. $this->batch_object->add($handle);
  615. $this->use_batch_flow = false;
  616. return $handle;
  617. }
  618. elseif (isset($opt['returnCurlHandle']) && $opt['returnCurlHandle'] === true)
  619. {
  620. return $request->prep_request();
  621. }
  622. // Send!
  623. $request->send_request();
  624. // Prepare the response
  625. $headers = $request->get_response_header();
  626. $headers['x-aws-request-url'] = $this->request_url;
  627. $headers['x-aws-redirects'] = $redirects;
  628. $headers['x-aws-stringtosign'] = $string_to_sign;
  629. $headers['x-aws-requestheaders'] = $request->request_headers;
  630. // Did we have a request body?
  631. if (isset($opt['body']))
  632. {
  633. $headers['x-aws-requestbody'] = $opt['body'];
  634. }
  635. $data = new $this->response_class($headers, $this->parse_callback($request->get_response_body()), $request->get_response_code());
  636. // Did Amazon tell us to redirect? Typically happens for multiple rapid requests EU datacenters.
  637. // @see: http://docs.amazonwebservices.com/AmazonS3/latest/dev/Redirects.html
  638. // @codeCoverageIgnoreStart
  639. if ((integer) $request->get_response_code() === 307) // Temporary redirect to new endpoint.
  640. {
  641. $data = $this->authenticate($bucket, $opt, $headers['location'], ++$redirects);
  642. }
  643. // Was it Amazon's fault the request failed? Retry the request until we reach $max_retries.
  644. elseif ((integer) $request->get_response_code() === 500 || (integer) $request->get_response_code() === 503)
  645. {
  646. if ($redirects <= $this->max_retries)
  647. {
  648. // Exponential backoff
  649. $delay = (integer) (pow(4, $redirects) * 100000);
  650. usleep($delay);
  651. $data = $this->authenticate($bucket, $opt, null, ++$redirects);
  652. }
  653. }
  654. // @codeCoverageIgnoreEnd
  655. // Return!
  656. return $data;
  657. }
  658. /**
  659. * Validates whether or not the specified Amazon S3 bucket name is valid for DNS-style access. This
  660. * method is leveraged by any method that creates buckets.
  661. *
  662. * @param string $bucket (Required) The name of the bucket to validate.
  663. * @return boolean Whether or not the specified Amazon S3 bucket name is valid for DNS-style access. A value of <code>true</code> means that the bucket name is valid. A value of <code>false</code> means that the bucket name is invalid.
  664. */
  665. public function validate_bucketname_create($bucket)
  666. {
  667. // list_buckets() uses this. Let it pass.
  668. if ($bucket === '') return true;
  669. if (
  670. ($bucket === null || $bucket === false) || // Must not be null or false
  671. preg_match('/[^(a-z0-9\-\.)]/', $bucket) || // Must be in the lowercase Roman alphabet, period or hyphen
  672. !preg_match('/^([a-z]|\d)/', $bucket) || // Must start with a number or letter
  673. !(strlen($bucket) >= 3 && strlen($bucket) <= 63) || // Must be between 3 and 63 characters long
  674. (strpos($bucket, '..') !== false) || // Bucket names cannot contain two, adjacent periods
  675. (strpos($bucket, '-.') !== false) || // Bucket names cannot contain dashes next to periods
  676. (strpos($bucket, '.-') !== false) || // Bucket names cannot contain dashes next to periods
  677. preg_match('/(-|\.)$/', $bucket) || // Bucket names should not end with a dash or period
  678. preg_match('/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/', $bucket) // Must not be formatted as an IP address
  679. ) return false;
  680. return true;
  681. }
  682. /**
  683. * Validates whether or not the specified Amazon S3 bucket name is valid for path-style access. This
  684. * method is leveraged by any method that reads from buckets.
  685. *
  686. * @param string $bucket (Required) The name of the bucket to validate.
  687. * @return boolean Whether or not the bucket name is valid. A value of <code>true</code> means that the bucket name is valid. A value of <code>false</code> means that the bucket name is invalid.
  688. */
  689. public function validate_bucketname_support($bucket)
  690. {
  691. // list_buckets() uses this. Let it pass.
  692. if ($bucket === '') return true;
  693. // Validate
  694. if (
  695. ($bucket === null || $bucket === false) || // Must not be null or false
  696. preg_match('/[^(a-z0-9_\-\.)]/i', $bucket) || // Must be in the Roman alphabet, period, hyphen or underscore
  697. !preg_match('/^([a-z]|\d)/i', $bucket) || // Must start with a number or letter
  698. !(strlen($bucket) >= 3 && strlen($bucket) <= 255) || // Must be between 3 and 255 characters long
  699. preg_match('/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/', $bucket) // Must not be formatted as an IP address
  700. ) return false;
  701. return true;
  702. }
  703. /**
  704. * The callback function that is executed when the cache doesn't exist or has expired. The response of
  705. * this method is cached. Accepts identical parameters as the <authenticate()> method. Never call this
  706. * method directly -- it is used internally by the caching system.
  707. *
  708. * @param string $bucket (Required) The name of the bucket to use.
  709. * @param array $opt (Optional) An associative array of parameters for authenticating. See the individual methods for allowed keys.
  710. * @param string $location (Optional) Used internally by this method when Amazon S3 returns a redirect code and needs to call itself recursively.
  711. * @param integer $redirects (Optional) Used internally by this method when Amazon S3 returns a redirect code and needs to call itself recursively.
  712. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  713. */
  714. public function cache_callback($bucket, $opt = null, $location = null, $redirects = 0)
  715. {
  716. // Disable the cache flow since it's already been handled.
  717. $this->use_cache_flow = false;
  718. // Make the request
  719. $response = $this->authenticate($bucket, $opt, $location, $redirects);
  720. if (isset($response->body) && ($response->body instanceof SimpleXMLElement))
  721. {
  722. $response->body = $response->body->asXML();
  723. }
  724. return $response;
  725. }
  726. /*%******************************************************************************************%*/
  727. // SETTERS
  728. /**
  729. * Sets the region to use for subsequent Amazon S3 operations. This will also reset any prior use of
  730. * <enable_path_style()>.
  731. *
  732. * @param string $region (Required) The region to use for subsequent Amazon S3 operations. [Allowed values: `AmazonS3::REGION_US_E1 `, `AmazonS3::REGION_US_W1`, `AmazonS3::REGION_EU_W1`, `AmazonS3::REGION_APAC_SE1`, `AmazonS3::REGION_APAC_NE1`]
  733. * @return $this A reference to the current instance.
  734. */
  735. public function set_region($region)
  736. {
  737. switch ($region)
  738. {
  739. case self::REGION_US_E1: // Northern Virginia
  740. $this->set_hostname(self::DEFAULT_URL);
  741. $this->enable_path_style(false);
  742. break;
  743. case self::REGION_EU_W1: // Ireland
  744. $this->set_hostname('s3-eu-west-1.amazonaws.com');
  745. $this->enable_path_style(); // Always use path-style access for EU endpoint.
  746. break;
  747. case self::REGION_US_W1: // Northern California
  748. case self::REGION_APAC_SE1: // Singapore
  749. case self::REGION_APAC_NE1: // Japan
  750. default:
  751. $this->set_hostname('s3-' . $region . '.amazonaws.com');
  752. $this->enable_path_style(false);
  753. break;
  754. // @codeCoverageIgnoreStart
  755. }
  756. // @codeCoverageIgnoreEnd
  757. return $this;
  758. }
  759. /**
  760. * Sets the virtual host to use in place of the default `bucket.s3.amazonaws.com` domain.
  761. *
  762. * @param string $vhost (Required) The virtual host to use in place of the default `bucket.s3.amazonaws.com` domain.
  763. * @return $this A reference to the current instance.
  764. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html Virtual Hosting of Buckets
  765. */
  766. public function set_vhost($vhost)
  767. {
  768. $this->vhost = $vhost;
  769. return $this;
  770. }
  771. /**
  772. * Enables the use of the older path-style URI access for all requests.
  773. *
  774. * @param string $style (Optional) Whether or not to enable path-style URI access for all requests. The default value is <code>true</code>.
  775. * @return $this A reference to the current instance.
  776. */
  777. public function enable_path_style($style = true)
  778. {
  779. $this->path_style = $style;
  780. return $this;
  781. }
  782. /*%******************************************************************************************%*/
  783. // BUCKET METHODS
  784. /**
  785. * Creates an Amazon S3 bucket.
  786. *
  787. * Every object stored in Amazon S3 is contained in a bucket. Buckets partition the namespace of
  788. * objects stored in Amazon S3 at the top level. in a bucket, any name can be used for objects.
  789. * However, bucket names must be unique across all of Amazon S3.
  790. *
  791. * @param string $bucket (Required) The name of the bucket to create.
  792. * @param string $region (Required) The preferred geographical location for the bucket. [Allowed values: `AmazonS3::REGION_US_E1 `, `AmazonS3::REGION_US_W1`, `AmazonS3::REGION_EU_W1`, `AmazonS3::REGION_APAC_SE1`, `AmazonS3::REGION_APAC_NE1`]
  793. * @param string $acl (Optional) The ACL settings for the specified bucket. [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. The default value is <ACL_PRIVATE>.
  794. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  795. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  796. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request.</li></ul>
  797. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  798. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/UsingBucket.html Working with Amazon S3 Buckets
  799. */
  800. public function create_bucket($bucket, $region, $acl = self::ACL_PRIVATE, $opt = null)
  801. {
  802. // If the bucket contains uppercase letters...
  803. if (preg_match('/[A-Z]/', $bucket))
  804. {
  805. // Throw a warning
  806. trigger_error('Since DNS-valid bucket names cannot contain uppercase characters, "' . $bucket . '" has been automatically converted to "' . strtolower($bucket) . '"', E_USER_WARNING);
  807. // Force the bucketname to lowercase
  808. $bucket = strtolower($bucket);
  809. }
  810. // Validate the S3 bucket name for creation
  811. if (!$this->validate_bucketname_create($bucket))
  812. {
  813. // @codeCoverageIgnoreStart
  814. throw new S3_Exception('"' . $bucket . '" is not DNS-valid (i.e., <bucketname>.s3.amazonaws.com), and cannot be used as an S3 bucket name. Review "Bucket Restrictions and Limitations" in the S3 Developer Guide for more information.');
  815. // @codeCoverageIgnoreEnd
  816. }
  817. if (!$opt) $opt = array();
  818. $opt['verb'] = 'PUT';
  819. $opt['headers'] = array(
  820. 'Content-Type' => 'application/xml',
  821. 'x-amz-acl' => $acl
  822. );
  823. // Defaults
  824. $this->set_region($region);
  825. $xml = simplexml_load_string($this->base_location_constraint);
  826. switch ($region)
  827. {
  828. case self::REGION_US_E1: // Northern Virginia
  829. $opt['body'] = '';
  830. break;
  831. case self::REGION_EU_W1: // Ireland
  832. $this->enable_path_style(); // DNS-style doesn't seem to work for creation, only in EU. Switch over to path-style.
  833. $xml->LocationConstraint = $region;
  834. $opt['body'] = $xml->asXML();
  835. break;
  836. case self::REGION_US_W1: // Northern California
  837. case self::REGION_APAC_SE1: // Singapore
  838. case self::REGION_APAC_NE1: // Japan
  839. default:
  840. $xml->LocationConstraint = $region;
  841. $opt['body'] = $xml->asXML();
  842. break;
  843. // @codeCoverageIgnoreStart
  844. }
  845. // @codeCoverageIgnoreEnd
  846. $response = $this->authenticate($bucket, $opt);
  847. return $response;
  848. }
  849. /**
  850. * Gets the region in which the specified Amazon S3 bucket is located.
  851. *
  852. * @param string $bucket (Required) The name of the bucket to use.
  853. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  854. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  855. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  856. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  857. */
  858. public function get_bucket_region($bucket, $opt = null)
  859. {
  860. // Add this to our request
  861. if (!$opt) $opt = array();
  862. $opt['verb'] = 'GET';
  863. $opt['sub_resource'] = 'location';
  864. // Authenticate to S3
  865. $response = $this->authenticate($bucket, $opt);
  866. if ($response->isOK())
  867. {
  868. // Handle body
  869. $response->body = (string) $response->body;
  870. }
  871. return $response;
  872. }
  873. /**
  874. * Gets the HTTP headers for the specified Amazon S3 bucket.
  875. *
  876. * @param string $bucket (Required) The name of the bucket to use.
  877. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  878. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  879. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  880. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  881. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  882. */
  883. public function get_bucket_headers($bucket, $opt = null)
  884. {
  885. if (!$opt) $opt = array();
  886. $opt['verb'] = 'HEAD';
  887. return $this->authenticate($bucket, $opt);
  888. }
  889. /**
  890. * Deletes a bucket from an Amazon S3 account. A bucket must be empty before the bucket itself can be deleted.
  891. *
  892. * @param string $bucket (Required) The name of the bucket to use.
  893. * @param boolean $force (Optional) Whether to force-delete the bucket and all of its contents. The default value is <code>false</code>.
  894. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  895. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  896. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  897. * @return mixed A <CFResponse> object if the bucket was deleted successfully. Returns boolean <code>false</code> if otherwise.
  898. */
  899. public function delete_bucket($bucket, $force = false, $opt = null)
  900. {
  901. // Set default value
  902. $success = true;
  903. if ($force)
  904. {
  905. // Delete all of the items from the bucket.
  906. $success = $this->delete_all_object_versions($bucket);
  907. }
  908. // As long as we were successful...
  909. if ($success)
  910. {
  911. if (!$opt) $opt = array();
  912. $opt['verb'] = 'DELETE';
  913. return $this->authenticate($bucket, $opt);
  914. }
  915. // @codeCoverageIgnoreStart
  916. return false;
  917. // @codeCoverageIgnoreEnd
  918. }
  919. /**
  920. * Gets a list of all buckets contained in the caller's Amazon S3 account.
  921. *
  922. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  923. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  924. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  925. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  926. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  927. */
  928. public function list_buckets($opt = null)
  929. {
  930. if (!$opt) $opt = array();
  931. $opt['verb'] = 'GET';
  932. return $this->authenticate('', $opt);
  933. }
  934. /**
  935. * Gets the access control list (ACL) settings for the specified Amazon S3 bucket.
  936. *
  937. * @param string $bucket (Required) The name of the bucket to use.
  938. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  939. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  940. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  941. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  942. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  943. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAccessPolicy.html REST Access Control Policy
  944. */
  945. public function get_bucket_acl($bucket, $opt = null)
  946. {
  947. // Add this to our request
  948. if (!$opt) $opt = array();
  949. $opt['verb'] = 'GET';
  950. $opt['sub_resource'] = 'acl';
  951. // Authenticate to S3
  952. return $this->authenticate($bucket, $opt);
  953. }
  954. /**
  955. * Sets the access control list (ACL) settings for the specified Amazon S3 bucket.
  956. *
  957. * @param string $bucket (Required) The name of the bucket to use.
  958. * @param string $acl (Optional) The ACL settings for the specified bucket. [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. Alternatively, an array of associative arrays. Each associative array contains an `id` and a `permission` key. The default value is <ACL_PRIVATE>.
  959. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  960. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  961. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  962. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  963. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAccessPolicy.html REST Access Control Policy
  964. */
  965. public function set_bucket_acl($bucket, $acl = self::ACL_PRIVATE, $opt = null)
  966. {
  967. // Add this to our request
  968. if (!$opt) $opt = array();
  969. $opt['verb'] = 'PUT';
  970. $opt['sub_resource'] = 'acl';
  971. $opt['headers'] = array(
  972. 'Content-Type' => 'application/xml'
  973. );
  974. // Make sure these are defined.
  975. // @codeCoverageIgnoreStart
  976. if (!defined('AWS_CANONICAL_ID') || !defined('AWS_CANONICAL_NAME'))
  977. {
  978. // Fetch the data live.
  979. $canonical = $this->get_canonical_user_id();
  980. define('AWS_CANONICAL_ID', $canonical['id']);
  981. define('AWS_CANONICAL_NAME', $canonical['display_name']);
  982. }
  983. // @codeCoverageIgnoreEnd
  984. if (is_array($acl))
  985. {
  986. $opt['body'] = $this->generate_access_policy(AWS_CANONICAL_ID, AWS_CANONICAL_NAME, $acl);
  987. }
  988. else
  989. {
  990. $opt['body'] = '';
  991. $opt['headers']['x-amz-acl'] = $acl;
  992. }
  993. // Authenticate to S3
  994. return $this->authenticate($bucket, $opt);
  995. }
  996. /*%******************************************************************************************%*/
  997. // OBJECT METHODS
  998. /**
  999. * Creates an Amazon S3 object. After an Amazon S3 bucket is created, objects can be stored in it.
  1000. *
  1001. * Each standard object can hold up to 5 GB of data. When an object is stored in Amazon S3, the data is streamed
  1002. * to multiple storage servers in multiple data centers. This ensures the data remains available in the
  1003. * event of internal network or hardware failure.
  1004. *
  1005. * @param string $bucket (Required) The name of the bucket to use.
  1006. * @param string $filename (Required) The file name for the object.
  1007. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1008. * <li><code>body</code> - <code>string</code> - Required; Conditional - The data to be stored in the object. Either this parameter or <code>fileUpload</code> must be specified.</li>
  1009. * <li><code>fileUpload</code> - <code>string|resource</code> - Required; Conditional - The URL/path for the file to upload, or an open resource. Either this parameter or <code>body</code> is required.</li>
  1010. * <li><code>acl</code> - <code>string</code> - Optional - The ACL settings for the specified object. [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. The default value is <code>ACL_PRIVATE</code>.</li>
  1011. * <li><code>contentType</code> - <code>string</code> - Optional - The type of content that is being sent in the body. If a file is being uploaded via <code>fileUpload</code> as a file system path, it will attempt to determine the correct mime-type based on the file extension. The default value is <code>application/octet-stream</code>.</li>
  1012. * <li><code>contentType</code> - <code>string</code> - Optional - The type of content that is being sent in the body. If a file is being uploaded via <code>fileUpload</code> as a file system path, it will attempt to determine the correct mime-type based on the file extension. The default value is <code>application/octet-stream</code>.</li>
  1013. * <li><code>encryption</code> - <code>string</code> - Optional - The algorithm to use for encrypting the object. [Allowed values: <code>AES256</code>]</li>
  1014. * <li><code>headers</code> - <code>array</code> - Optional - The standard HTTP headers to send along in the request.</li>
  1015. * <li><code>length</code> - <code>integer</code> - Optional - The size of the object in bytes. For more information, see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13">RFC 2616, section 14.13</a>. The value can also be passed to the <code>header</code> option as <code>Content-Length</code>.</li>
  1016. * <li><code>meta</code> - <code>array</code> - Optional - An associative array of key-value pairs. Represented by <code>x-amz-meta-:</code>. Any header starting with this prefix is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB.</li>
  1017. * <li><code>seekTo</code> - <code>integer</code> - Optional - The starting position in bytes within the file/stream to upload from.</li>
  1018. * <li><code>storage</code> - <code>string</code> - Optional - Whether to use Standard or Reduced Redundancy storage. [Allowed values: <code>AmazonS3::STORAGE_STANDARD</code>, <code>AmazonS3::STORAGE_REDUCED</code>]. The default value is <code>STORAGE_STANDARD</code>.</li>
  1019. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1020. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1021. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1022. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAccessPolicy.html REST Access Control Policy
  1023. */
  1024. public function create_object($bucket, $filename, $opt = null)
  1025. {
  1026. if (!$opt) $opt = array();
  1027. // Add this to our request
  1028. $opt['verb'] = 'PUT';
  1029. $opt['resource'] = $filename;
  1030. // Handle content length. Can also be passed as an HTTP header.
  1031. if (isset($opt['length']))
  1032. {
  1033. $opt['headers']['Content-Length'] = $opt['length'];
  1034. unset($opt['length']);
  1035. }
  1036. // Handle content type. Can also be passed as an HTTP header.
  1037. if (isset($opt['contentType']))
  1038. {
  1039. $opt['headers']['Content-Type'] = $opt['contentType'];
  1040. unset($opt['contentType']);
  1041. }
  1042. // Handle Access Control Lists. Can also be passed as an HTTP header.
  1043. if (isset($opt['acl']))
  1044. {
  1045. $opt['headers']['x-amz-acl'] = $opt['acl'];
  1046. unset($opt['acl']);
  1047. }
  1048. // Handle storage settings. Can also be passed as an HTTP header.
  1049. if (isset($opt['storage']))
  1050. {
  1051. $opt['headers']['x-amz-storage-class'] = $opt['storage'];
  1052. unset($opt['storage']);
  1053. }
  1054. // Handle encryption settings. Can also be passed as an HTTP header.
  1055. if (isset($opt['encryption']))
  1056. {
  1057. $opt['headers']['x-amz-server-side-encryption'] = $opt['encryption'];
  1058. unset($opt['encryption']);
  1059. }
  1060. // Handle meta tags. Can also be passed as an HTTP header.
  1061. if (isset($opt['meta']))
  1062. {
  1063. foreach ($opt['meta'] as $meta_key => $meta_value)
  1064. {
  1065. // e.g., `My Meta Header` is converted to `x-amz-meta-my-meta-header`.
  1066. $opt['headers']['x-amz-meta-' . strtolower(str_replace(' ', '-', $meta_key))] = $meta_value;
  1067. }
  1068. unset($opt['meta']);
  1069. }
  1070. // Authenticate to S3
  1071. return $this->authenticate($bucket, $opt);
  1072. }
  1073. /**
  1074. * Gets the contents of an Amazon S3 object in the specified bucket.
  1075. *
  1076. * @param string $bucket (Required) The name of the bucket to use.
  1077. * @param string $filename (Required) The file name for the object.
  1078. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1079. * <li><code>etag</code> - <code>string</code> - Optional - The <code>ETag</code> header passed in from a previous request. If specified, request <code>LastModified</code> option must be specified as well. Will trigger a <code>304 Not Modified</code> status code if the file hasn't changed.</li>
  1080. * <li><code>fileDownload</code> - <code>string|resource</code> - Optional - The file system location to download the file to, or an open file resource. Must be a server-writable location.</li>
  1081. * <li><code>headers</code> - <code>array</code> - Optional - Standard HTTP headers to send along in the request.</li>
  1082. * <li><code>lastmodified</code> - <code>string</code> - Optional - The <code>LastModified</code> header passed in from a previous request. If specified, request <code>ETag</code> option must be specified as well. Will trigger a <code>304 Not Modified</code> status code if the file hasn't changed.</li>
  1083. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  1084. * <li><code>range</code> - <code>string</code> - Optional - The range of bytes to fetch from the object. Specify this parameter when downloading partial bits or completing incomplete object downloads. The specified range must be notated with a hyphen (e.g., 0-10485759). Defaults to the byte range of the complete Amazon S3 object.</li>
  1085. * <li><code>response</code> - <code>array</code> - Optional - Allows adjustments to specific response headers. Pass an associative array where each key is one of the following: <code>cache-control</code>, <code>content-disposition</code>, <code>content-encoding</code>, <code>content-language</code>, <code>content-type</code>, <code>expires</code>. The <code>expires</code> value should use <php:gmdate()> and be formatted with the <code>DATE_RFC2822</code> constant.</li>
  1086. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object to retrieve. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  1087. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1088. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1089. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1090. */
  1091. public function get_object($bucket, $filename, $opt = null)
  1092. {
  1093. if (!$opt) $opt = array();
  1094. $this->parse_the_response = false;
  1095. // Add this to our request
  1096. $opt['verb'] = 'GET';
  1097. $opt['resource'] = $filename;
  1098. if (!isset($opt['headers']) || !is_array($opt['headers']))
  1099. {
  1100. $opt['headers'] = array();
  1101. }
  1102. if (isset($opt['lastmodified']))
  1103. {
  1104. $opt['headers']['If-Modified-Since'] = $opt['lastmodified'];
  1105. }
  1106. if (isset($opt['etag']))
  1107. {
  1108. $opt['headers']['If-None-Match'] = $opt['etag'];
  1109. }
  1110. // Partial content range
  1111. if (isset($opt['range']))
  1112. {
  1113. $opt['headers']['Range'] = 'bytes=' . $opt['range'];
  1114. }
  1115. // GET responses
  1116. if (isset($opt['response']))
  1117. {
  1118. foreach ($opt['response'] as $key => $value)
  1119. {
  1120. $opt['response-' . $key] = $value;
  1121. unset($opt['response'][$key]);
  1122. }
  1123. }
  1124. // Authenticate to S3
  1125. return $this->authenticate($bucket, $opt);
  1126. }
  1127. /**
  1128. * Gets the HTTP headers for the specified Amazon S3 object.
  1129. *
  1130. * @param string $bucket (Required) The name of the bucket to use.
  1131. * @param string $filename (Required) The file name for the object.
  1132. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1133. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object to retrieve. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  1134. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  1135. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1136. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1137. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1138. */
  1139. public function get_object_headers($bucket, $filename, $opt = null)
  1140. {
  1141. // Add this to our request
  1142. if (!$opt) $opt = array();
  1143. $opt['verb'] = 'HEAD';
  1144. $opt['resource'] = $filename;
  1145. // Authenticate to S3
  1146. return $this->authenticate($bucket, $opt);
  1147. }
  1148. /**
  1149. * Deletes an Amazon S3 object from the specified bucket.
  1150. *
  1151. * @param string $bucket (Required) The name of the bucket to use.
  1152. * @param string $filename (Required) The file name for the object.
  1153. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1154. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object to delete. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  1155. * <li><code>MFASerial</code> - <code>string</code> - Optional - The serial number on the back of the Gemalto device. <code>MFASerial</code> and <code>MFAToken</code> must both be set for MFA to work.</li>
  1156. * <li><code>MFAToken</code> - <code>string</code> - Optional - The current token displayed on the Gemalto device. <code>MFASerial</code> and <code>MFAToken</code> must both be set for MFA to work.</li>
  1157. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1158. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1159. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1160. * @link http://aws.amazon.com/mfa/ Multi-Factor Authentication
  1161. */
  1162. public function delete_object($bucket, $filename, $opt = null)
  1163. {
  1164. // Add this to our request
  1165. if (!$opt) $opt = array();
  1166. $opt['verb'] = 'DELETE';
  1167. $opt['resource'] = $filename;
  1168. // Enable MFA delete?
  1169. // @codeCoverageIgnoreStart
  1170. if (isset($opt['MFASerial']) && isset($opt['MFAToken']))
  1171. {
  1172. $opt['headers'] = array(
  1173. 'x-amz-mfa' => ($opt['MFASerial'] . ' ' . $opt['MFAToken'])
  1174. );
  1175. }
  1176. // @codeCoverageIgnoreEnd
  1177. // Authenticate to S3
  1178. return $this->authenticate($bucket, $opt);
  1179. }
  1180. /**
  1181. * Deletes two or more specified Amazon S3 objects from the specified bucket.
  1182. *
  1183. * @param string $bucket (Required) The name of the bucket to use.
  1184. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1185. * <li><code>objects</code> - <code>array</code> - Required - The object references to delete from the bucket. <ul>
  1186. * <li><code>key</code> - <code>string</code> - Required - The name of the object (e.g., the "key") to delete. This should include the entire file path including all "subdirectories".</li>
  1187. * <li><code>version_id</code> - <code>string</code> - Optional - If the object is versioned, include the version ID to delete.</li>
  1188. * </ul></li>
  1189. * <li><code>quiet</code> - <code>boolean</code> - Optional - Whether or not Amazon S3 should use "Quiet" mode for this operation. A value of <code>true</code> will enable Quiet mode. A value of <code>false</code> will use Verbose mode. The default value is <code>false</code>.</li>
  1190. * <li><code>MFASerial</code> - <code>string</code> - Optional - The serial number on the back of the Gemalto device. <code>MFASerial</code> and <code>MFAToken</code> must both be set for MFA to work.</li>
  1191. * <li><code>MFAToken</code> - <code>string</code> - Optional - The current token displayed on the Gemalto device. <code>MFASerial</code> and <code>MFAToken</code> must both be set for MFA to work.</li>
  1192. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1193. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1194. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1195. * @link http://aws.amazon.com/mfa/ Multi-Factor Authentication
  1196. */
  1197. public function delete_objects($bucket, $opt = null)
  1198. {
  1199. // Add this to our request
  1200. if (!$opt) $opt = array();
  1201. $opt['verb'] = 'POST';
  1202. $opt['sub_resource'] = 'delete';
  1203. $opt['body'] = '';
  1204. // Bail out
  1205. if (!isset($opt['objects']) || !is_array($opt['objects']))
  1206. {
  1207. throw new S3_Exception('The ' . __FUNCTION__ . ' method requires the "objects" option to be set as an array.');
  1208. }
  1209. $xml = new SimpleXMLElement($this->multi_object_delete_xml);
  1210. // Add the objects
  1211. foreach ($opt['objects'] as $object)
  1212. {
  1213. $xobject = $xml->addChild('Object');
  1214. $xobject->addChild('Key', $object['key']);
  1215. if (isset($object['version_id']))
  1216. {
  1217. $xobject->addChild('VersionId', $object['version_id']);
  1218. }
  1219. }
  1220. // Quiet mode?
  1221. if (isset($opt['quiet']))
  1222. {
  1223. $quiet = 'false';
  1224. if (is_bool($opt['quiet'])) // Boolean
  1225. {
  1226. $quiet = $opt['quiet'] ? 'true' : 'false';
  1227. }
  1228. elseif (is_string($opt['quiet'])) // String
  1229. {
  1230. $quiet = ($opt['quiet'] === 'true') ? 'true' : 'false';
  1231. }
  1232. $xml->addChild('Quiet', $quiet);
  1233. }
  1234. // Enable MFA delete?
  1235. // @codeCoverageIgnoreStart
  1236. if (isset($opt['MFASerial']) && isset($opt['MFAToken']))
  1237. {
  1238. $opt['headers'] = array(
  1239. 'x-amz-mfa' => ($opt['MFASerial'] . ' ' . $opt['MFAToken'])
  1240. );
  1241. }
  1242. // @codeCoverageIgnoreEnd
  1243. $opt['body'] = $xml->asXML();
  1244. // Authenticate to S3
  1245. return $this->authenticate($bucket, $opt);
  1246. }
  1247. /**
  1248. * Gets a list of all Amazon S3 objects in the specified bucket.
  1249. *
  1250. * @param string $bucket (Required) The name of the bucket to use.
  1251. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1252. * <li><code>delimiter</code> - <code>string</code> - Optional - Keys that contain the same string between the prefix and the first occurrence of the delimiter will be rolled up into a single result element in the CommonPrefixes collection.</li>
  1253. * <li><code>marker</code> - <code>string</code> - Optional - Restricts the response to contain results that only occur alphabetically after the value of the marker.</li>
  1254. * <li><code>max-keys</code> - <code>string</code> - Optional - The maximum number of results returned by the method call. The returned list will contain no more results than the specified value, but may return less.</li>
  1255. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  1256. * <li><code>prefix</code> - <code>string</code> - Optional - Restricts the response to contain results that begin only with the specified prefix.</li>
  1257. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1258. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1259. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1260. */
  1261. public function list_objects($bucket, $opt = null)
  1262. {
  1263. if (!$opt) $opt = array();
  1264. // Add this to our request
  1265. $opt['verb'] = 'GET';
  1266. foreach (array('delimiter', 'marker', 'max-keys', 'prefix') as $param)
  1267. {
  1268. if (isset($opt[$param]))
  1269. {
  1270. $opt['query_string'][$param] = $opt[$param];
  1271. unset($opt[$param]);
  1272. }
  1273. }
  1274. // Authenticate to S3
  1275. return $this->authenticate($bucket, $opt);
  1276. }
  1277. /**
  1278. * Copies an Amazon S3 object to a new location, whether in the same Amazon S3 region, bucket, or otherwise.
  1279. *
  1280. * @param array $source (Required) The bucket and file name to copy from. The following keys must be set: <ul>
  1281. * <li><code>bucket</code> - <code>string</code> - Required - Specifies the name of the bucket containing the source object.</li>
  1282. * <li><code>filename</code> - <code>string</code> - Required - Specifies the file name of the source object to copy.</li></ul>
  1283. * @param array $dest (Required) The bucket and file name to copy to. The following keys must be set: <ul>
  1284. * <li><code>bucket</code> - <code>string</code> - Required - Specifies the name of the bucket to copy the object to.</li>
  1285. * <li><code>filename</code> - <code>string</code> - Required - Specifies the file name to copy the object to.</li></ul>
  1286. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1287. * <li><code>acl</code> - <code>string</code> - Optional - The ACL settings for the specified object. [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. Alternatively, an array of associative arrays. Each associative array contains an <code>id</code> and a <code>permission</code> key. The default value is <code>ACL_PRIVATE</code>.</li>
  1288. * <li><code>encryption</code> - <code>string</code> - Optional - The algorithm to use for encrypting the object. [Allowed values: <code>AES256</code>]</li>
  1289. * <li><code>storage</code> - <code>string</code> - Optional - Whether to use Standard or Reduced Redundancy storage. [Allowed values: <code>AmazonS3::STORAGE_STANDARD</code>, <code>AmazonS3::STORAGE_REDUCED</code>]. The default value is <code>STORAGE_STANDARD</code>.</li>
  1290. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object to copy. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  1291. * <li><code>ifMatch</code> - <code>string</code> - Optional - The ETag header from a previous request. Copies the object if its entity tag (ETag) matches the specified tag; otherwise, the request returns a <code>412</code> HTTP status code error (precondition failed). Used in conjunction with <code>ifUnmodifiedSince</code>.</li>
  1292. * <li><code>ifUnmodifiedSince</code> - <code>string</code> - Optional - The LastModified header from a previous request. Copies the object if it hasn't been modified since the specified time; otherwise, the request returns a <code>412</code> HTTP status code error (precondition failed). Used in conjunction with <code>ifMatch</code>.</li>
  1293. * <li><code>ifNoneMatch</code> - <code>string</code> - Optional - The ETag header from a previous request. Copies the object if its entity tag (ETag) is different than the specified ETag; otherwise, the request returns a <code>412</code> HTTP status code error (failed condition). Used in conjunction with <code>ifModifiedSince</code>.</li>
  1294. * <li><code>ifModifiedSince</code> - <code>string</code> - Optional - The LastModified header from a previous request. Copies the object if it has been modified since the specified time; otherwise, the request returns a <code>412</code> HTTP status code error (failed condition). Used in conjunction with <code>ifNoneMatch</code>.</li>
  1295. * <li><code>headers</code> - <code>array</code> - Optional - Standard HTTP headers to send along in the request.</li>
  1296. * <li><code>meta</code> - <code>array</code> - Optional - Associative array of key-value pairs. Represented by <code>x-amz-meta-:</code> Any header starting with this prefix is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB.</li>
  1297. * <li><code>metadataDirective</code> - <code>string</code> - Optional - Accepts either COPY or REPLACE. You will likely never need to use this, as it manages itself with no issues.</li>
  1298. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1299. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1300. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1301. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/API/RESTObjectCOPY.html Copying Amazon S3 Objects
  1302. */
  1303. public function copy_object($source, $dest, $opt = null)
  1304. {
  1305. if (!$opt) $opt = array();
  1306. $batch = array();
  1307. // Add this to our request
  1308. $opt['verb'] = 'PUT';
  1309. $opt['resource'] = $dest['filename'];
  1310. $opt['body'] = '';
  1311. // Handle copy source
  1312. if (isset($source['bucket']) && isset($source['filename']))
  1313. {
  1314. $opt['headers']['x-amz-copy-source'] = '/' . $source['bucket'] . '/' . rawurlencode($source['filename'])
  1315. . (isset($opt['versionId']) ? ('?' . 'versionId=' . rawurlencode($opt['versionId'])) : ''); // Append the versionId to copy, if available
  1316. unset($opt['versionId']);
  1317. // Determine if we need to lookup the pre-existing content-type.
  1318. if (
  1319. (!$this->use_batch_flow && !isset($opt['returnCurlHandle'])) &&
  1320. !in_array(strtolower('content-type'), array_map('strtolower', array_keys($opt['headers'])))
  1321. )
  1322. {
  1323. $response = $this->get_object_headers($source['bucket'], $source['filename']);
  1324. if ($response->isOK())
  1325. {
  1326. $opt['headers']['Content-Type'] = $response->header['content-type'];
  1327. }
  1328. }
  1329. }
  1330. // Handle metadata directive
  1331. $opt['headers']['x-amz-metadata-directive'] = 'REPLACE';
  1332. if (isset($opt['metadataDirective']))
  1333. {
  1334. $opt['headers']['x-amz-metadata-directive'] = $opt['metadataDirective'];
  1335. unset($opt['metadataDirective']);
  1336. }
  1337. // Handle Access Control Lists. Can also pass canned ACLs as an HTTP header.
  1338. if (isset($opt['acl']) && is_array($opt['acl']))
  1339. {
  1340. $batch[] = $this->set_object_acl($dest['bucket'], $dest['filename'], $opt['acl'], array(
  1341. 'returnCurlHandle' => true
  1342. ));
  1343. unset($opt['acl']);
  1344. }
  1345. elseif (isset($opt['acl']))
  1346. {
  1347. $opt['headers']['x-amz-acl'] = $opt['acl'];
  1348. unset($opt['acl']);
  1349. }
  1350. // Handle storage settings. Can also be passed as an HTTP header.
  1351. if (isset($opt['storage']))
  1352. {
  1353. $opt['headers']['x-amz-storage-class'] = $opt['storage'];
  1354. unset($opt['storage']);
  1355. }
  1356. // Handle encryption settings. Can also be passed as an HTTP header.
  1357. if (isset($opt['encryption']))
  1358. {
  1359. $opt['headers']['x-amz-server-side-encryption'] = $opt['encryption'];
  1360. unset($opt['encryption']);
  1361. }
  1362. // Handle conditional-copy parameters
  1363. if (isset($opt['ifMatch']))
  1364. {
  1365. $opt['headers']['x-amz-copy-source-if-match'] = $opt['ifMatch'];
  1366. unset($opt['ifMatch']);
  1367. }
  1368. if (isset($opt['ifNoneMatch']))
  1369. {
  1370. $opt['headers']['x-amz-copy-source-if-none-match'] = $opt['ifNoneMatch'];
  1371. unset($opt['ifNoneMatch']);
  1372. }
  1373. if (isset($opt['ifUnmodifiedSince']))
  1374. {
  1375. $opt['headers']['x-amz-copy-source-if-unmodified-since'] = $opt['ifUnmodifiedSince'];
  1376. unset($opt['ifUnmodifiedSince']);
  1377. }
  1378. if (isset($opt['ifModifiedSince']))
  1379. {
  1380. $opt['headers']['x-amz-copy-source-if-modified-since'] = $opt['ifModifiedSince'];
  1381. unset($opt['ifModifiedSince']);
  1382. }
  1383. // Handle meta tags. Can also be passed as an HTTP header.
  1384. if (isset($opt['meta']))
  1385. {
  1386. foreach ($opt['meta'] as $meta_key => $meta_value)
  1387. {
  1388. // e.g., `My Meta Header` is converted to `x-amz-meta-my-meta-header`.
  1389. $opt['headers']['x-amz-meta-' . strtolower(str_replace(' ', '-', $meta_key))] = $meta_value;
  1390. }
  1391. unset($opt['meta']);
  1392. }
  1393. // Authenticate to S3
  1394. $response = $this->authenticate($dest['bucket'], $opt);
  1395. // Attempt to reset ACLs
  1396. $http = new RequestCore();
  1397. $http->send_multi_request($batch);
  1398. return $response;
  1399. }
  1400. /**
  1401. * Updates an Amazon S3 object with new headers or other metadata. To replace the content of the
  1402. * specified Amazon S3 object, call <create_object()> with the same bucket and file name parameters.
  1403. *
  1404. * @param string $bucket (Required) The name of the bucket that contains the source file.
  1405. * @param string $filename (Required) The source file name that you want to update.
  1406. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1407. * <li><code>acl</code> - <code>string</code> - Optional - The ACL settings for the specified object. [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. The default value is <ACL_PRIVATE>.</li>
  1408. * <li><code>headers</code> - <code>array</code> - Optional - The standard HTTP headers to update the Amazon S3 object with.</li>
  1409. * <li><code>meta</code> - <code>array</code> - Optional - An associative array of key-value pairs. Any header with the <code>x-amz-meta-</code> prefix is considered user metadata and is stored with the Amazon S3 object. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB.</li>
  1410. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1411. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1412. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1413. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/API/RESTObjectCOPY.html Copying Amazon S3 Objects
  1414. */
  1415. public function update_object($bucket, $filename, $opt = null)
  1416. {
  1417. if (!$opt) $opt = array();
  1418. $opt['metadataDirective'] = 'REPLACE';
  1419. // Authenticate to S3
  1420. return $this->copy_object(
  1421. array('bucket' => $bucket, 'filename' => $filename),
  1422. array('bucket' => $bucket, 'filename' => $filename),
  1423. $opt
  1424. );
  1425. }
  1426. /*%******************************************************************************************%*/
  1427. // ACCESS CONTROL LISTS
  1428. /**
  1429. * Gets the access control list (ACL) settings for the specified Amazon S3 object.
  1430. *
  1431. * @param string $bucket (Required) The name of the bucket to use.
  1432. * @param string $filename (Required) The file name for the object.
  1433. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1434. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object to retrieve. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  1435. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  1436. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1437. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1438. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1439. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAccessPolicy.html REST Access Control Policy
  1440. */
  1441. public function get_object_acl($bucket, $filename, $opt = null)
  1442. {
  1443. // Add this to our request
  1444. if (!$opt) $opt = array();
  1445. $opt['verb'] = 'GET';
  1446. $opt['resource'] = $filename;
  1447. $opt['sub_resource'] = 'acl';
  1448. // Authenticate to S3
  1449. return $this->authenticate($bucket, $opt);
  1450. }
  1451. /**
  1452. * Sets the access control list (ACL) settings for the specified Amazon S3 object.
  1453. *
  1454. * @param string $bucket (Required) The name of the bucket to use.
  1455. * @param string $filename (Required) The file name for the object.
  1456. * @param string $acl (Optional) The ACL settings for the specified object. Accepts any of the following constants: [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. Alternatively, an array of associative arrays. Each associative array contains an <code>id</code> and a <code>permission</code> key. The default value is <code>ACL_PRIVATE</code>.
  1457. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1458. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1459. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1460. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1461. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAccessPolicy.html REST Access Control Policy
  1462. */
  1463. public function set_object_acl($bucket, $filename, $acl = self::ACL_PRIVATE, $opt = null)
  1464. {
  1465. // Add this to our request
  1466. if (!$opt) $opt = array();
  1467. $opt['verb'] = 'PUT';
  1468. $opt['resource'] = $filename;
  1469. $opt['sub_resource'] = 'acl';
  1470. // Retrieve the original metadata
  1471. $metadata = $this->get_object_metadata($bucket, $filename);
  1472. if ($metadata && $metadata['ContentType'])
  1473. {
  1474. $opt['headers']['Content-Type'] = $metadata['ContentType'];
  1475. }
  1476. if ($metadata && $metadata['StorageClass'])
  1477. {
  1478. $opt['headers']['x-amz-storage-class'] = $metadata['StorageClass'];
  1479. }
  1480. // Make sure these are defined.
  1481. // @codeCoverageIgnoreStart
  1482. if (!defined('AWS_CANONICAL_ID') || !defined('AWS_CANONICAL_NAME'))
  1483. {
  1484. // Fetch the data live.
  1485. $canonical = $this->get_canonical_user_id();
  1486. define('AWS_CANONICAL_ID', $canonical['id']);
  1487. define('AWS_CANONICAL_NAME', $canonical['display_name']);
  1488. }
  1489. // @codeCoverageIgnoreEnd
  1490. if (is_array($acl))
  1491. {
  1492. $opt['body'] = $this->generate_access_policy(AWS_CANONICAL_ID, AWS_CANONICAL_NAME, $acl);
  1493. }
  1494. else
  1495. {
  1496. $opt['body'] = '';
  1497. $opt['headers']['x-amz-acl'] = $acl;
  1498. }
  1499. // Authenticate to S3
  1500. return $this->authenticate($bucket, $opt);
  1501. }
  1502. /**
  1503. * Generates the XML to be used for the Access Control Policy.
  1504. *
  1505. * @param string $canonical_id (Required) The canonical ID for the bucket owner. Use the `AWS_CANONICAL_ID` constant or the `id` return value from <get_canonical_user_id()>.
  1506. * @param string $canonical_name (Required) The canonical display name for the bucket owner. Use the `AWS_CANONICAL_NAME` constant or the `display_name` value from <get_canonical_user_id()>.
  1507. * @param array $users (Optional) An array of associative arrays. Each associative array contains an `id` value and a `permission` value.
  1508. * @return string Access Control Policy XML.
  1509. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_ACLs.html Access Control Lists
  1510. */
  1511. public function generate_access_policy($canonical_id, $canonical_name, $users)
  1512. {
  1513. $xml = simplexml_load_string($this->base_acp_xml);
  1514. $owner = $xml->addChild('Owner');
  1515. $owner->addChild('ID', $canonical_id);
  1516. $owner->addChild('DisplayName', $canonical_name);
  1517. $acl = $xml->addChild('AccessControlList');
  1518. foreach ($users as $user)
  1519. {
  1520. $grant = $acl->addChild('Grant');
  1521. $grantee = $grant->addChild('Grantee');
  1522. switch ($user['id'])
  1523. {
  1524. // Authorized Users
  1525. case self::USERS_AUTH:
  1526. $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance');
  1527. $grantee->addChild('URI', self::USERS_AUTH);
  1528. break;
  1529. // All Users
  1530. case self::USERS_ALL:
  1531. $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance');
  1532. $grantee->addChild('URI', self::USERS_ALL);
  1533. break;
  1534. // The Logging User
  1535. case self::USERS_LOGGING:
  1536. $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance');
  1537. $grantee->addChild('URI', self::USERS_LOGGING);
  1538. break;
  1539. // Email Address or Canonical Id
  1540. default:
  1541. if (strpos($user['id'], '@'))
  1542. {
  1543. $grantee->addAttribute('xsi:type', 'AmazonCustomerByEmail', 'http://www.w3.org/2001/XMLSchema-instance');
  1544. $grantee->addChild('EmailAddress', $user['id']);
  1545. }
  1546. else
  1547. {
  1548. // Assume Canonical Id
  1549. $grantee->addAttribute('xsi:type', 'CanonicalUser', 'http://www.w3.org/2001/XMLSchema-instance');
  1550. $grantee->addChild('ID', $user['id']);
  1551. }
  1552. break;
  1553. }
  1554. $grant->addChild('Permission', $user['permission']);
  1555. }
  1556. return $xml->asXML();
  1557. }
  1558. /*%******************************************************************************************%*/
  1559. // LOGGING METHODS
  1560. /**
  1561. * Gets the access logs associated with the specified Amazon S3 bucket.
  1562. *
  1563. * @param string $bucket (Required) The name of the bucket to use. Pass a `null` value when using the <set_vhost()> method.
  1564. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1565. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  1566. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1567. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1568. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1569. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/ServerLogs.html Server Access Logging
  1570. */
  1571. public function get_logs($bucket, $opt = null)
  1572. {
  1573. // Add this to our request
  1574. if (!$opt) $opt = array();
  1575. $opt['verb'] = 'GET';
  1576. $opt['sub_resource'] = 'logging';
  1577. // Authenticate to S3
  1578. return $this->authenticate($bucket, $opt);
  1579. }
  1580. /**
  1581. * Enables access logging for the specified Amazon S3 bucket.
  1582. *
  1583. * @param string $bucket (Required) The name of the bucket to enable logging for. Pass a `null` value when using the <set_vhost()> method.
  1584. * @param string $target_bucket (Required) The name of the bucket to store the logs in.
  1585. * @param string $target_prefix (Required) The prefix to give to the log file names.
  1586. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1587. * <li><code>users</code> - <code>array</code> - Optional - An array of associative arrays specifying any user to give access to. Each associative array contains an <code>id</code> and <code>permission</code> value.</li>
  1588. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1589. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1590. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1591. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/LoggingAPI.html Server Access Logging Configuration API
  1592. */
  1593. public function enable_logging($bucket, $target_bucket, $target_prefix, $opt = null)
  1594. {
  1595. // Add this to our request
  1596. if (!$opt) $opt = array();
  1597. $opt['verb'] = 'PUT';
  1598. $opt['sub_resource'] = 'logging';
  1599. $opt['headers'] = array(
  1600. 'Content-Type' => 'application/xml'
  1601. );
  1602. $xml = simplexml_load_string($this->base_logging_xml);
  1603. $LoggingEnabled = $xml->addChild('LoggingEnabled');
  1604. $LoggingEnabled->addChild('TargetBucket', $target_bucket);
  1605. $LoggingEnabled->addChild('TargetPrefix', $target_prefix);
  1606. $TargetGrants = $LoggingEnabled->addChild('TargetGrants');
  1607. if (isset($opt['users']) && is_array($opt['users']))
  1608. {
  1609. foreach ($opt['users'] as $user)
  1610. {
  1611. $grant = $TargetGrants->addChild('Grant');
  1612. $grantee = $grant->addChild('Grantee');
  1613. switch ($user['id'])
  1614. {
  1615. // Authorized Users
  1616. case self::USERS_AUTH:
  1617. $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance');
  1618. $grantee->addChild('URI', self::USERS_AUTH);
  1619. break;
  1620. // All Users
  1621. case self::USERS_ALL:
  1622. $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance');
  1623. $grantee->addChild('URI', self::USERS_ALL);
  1624. break;
  1625. // The Logging User
  1626. case self::USERS_LOGGING:
  1627. $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance');
  1628. $grantee->addChild('URI', self::USERS_LOGGING);
  1629. break;
  1630. // Email Address or Canonical Id
  1631. default:
  1632. if (strpos($user['id'], '@'))
  1633. {
  1634. $grantee->addAttribute('xsi:type', 'AmazonCustomerByEmail', 'http://www.w3.org/2001/XMLSchema-instance');
  1635. $grantee->addChild('EmailAddress', $user['id']);
  1636. }
  1637. else
  1638. {
  1639. // Assume Canonical Id
  1640. $grantee->addAttribute('xsi:type', 'CanonicalUser', 'http://www.w3.org/2001/XMLSchema-instance');
  1641. $grantee->addChild('ID', $user['id']);
  1642. }
  1643. break;
  1644. }
  1645. $grant->addChild('Permission', $user['permission']);
  1646. }
  1647. }
  1648. $opt['body'] = $xml->asXML();
  1649. // Authenticate to S3
  1650. return $this->authenticate($bucket, $opt);
  1651. }
  1652. /**
  1653. * Disables access logging for the specified Amazon S3 bucket.
  1654. *
  1655. * @param string $bucket (Required) The name of the bucket to use. Pass `null` if using <set_vhost()>.
  1656. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1657. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1658. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1659. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1660. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/LoggingAPI.html Server Access Logging Configuration API
  1661. */
  1662. public function disable_logging($bucket, $opt = null)
  1663. {
  1664. // Add this to our request
  1665. if (!$opt) $opt = array();
  1666. $opt['verb'] = 'PUT';
  1667. $opt['sub_resource'] = 'logging';
  1668. $opt['headers'] = array(
  1669. 'Content-Type' => 'application/xml'
  1670. );
  1671. $opt['body'] = $this->base_logging_xml;
  1672. // Authenticate to S3
  1673. return $this->authenticate($bucket, $opt);
  1674. }
  1675. /*%******************************************************************************************%*/
  1676. // CONVENIENCE METHODS
  1677. /**
  1678. * Gets whether or not the specified Amazon S3 bucket exists in Amazon S3. This includes buckets
  1679. * that do not belong to the caller.
  1680. *
  1681. * @param string $bucket (Required) The name of the bucket to use.
  1682. * @return boolean A value of <code>true</code> if the bucket exists, or a value of <code>false</code> if it does not.
  1683. */
  1684. public function if_bucket_exists($bucket)
  1685. {
  1686. if ($this->use_batch_flow)
  1687. {
  1688. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1689. }
  1690. $header = $this->get_bucket_headers($bucket);
  1691. return (bool) $header->isOK();
  1692. }
  1693. /**
  1694. * Gets whether or not the specified Amazon S3 object exists in the specified bucket.
  1695. *
  1696. * @param string $bucket (Required) The name of the bucket to use.
  1697. * @param string $filename (Required) The file name for the object.
  1698. * @return boolean A value of <code>true</code> if the object exists, or a value of <code>false</code> if it does not.
  1699. */
  1700. public function if_object_exists($bucket, $filename)
  1701. {
  1702. if ($this->use_batch_flow)
  1703. {
  1704. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1705. }
  1706. $header = $this->get_object_headers($bucket, $filename);
  1707. if ($header->isOK()) { return true; }
  1708. elseif ($header->status === 404) { return false; }
  1709. // @codeCoverageIgnoreStart
  1710. return null;
  1711. // @codeCoverageIgnoreEnd
  1712. }
  1713. /**
  1714. * Gets whether or not the specified Amazon S3 bucket has a bucket policy associated with it.
  1715. *
  1716. * @param string $bucket (Required) The name of the bucket to use.
  1717. * @return boolean A value of <code>true</code> if a bucket policy exists, or a value of <code>false</code> if one does not.
  1718. */
  1719. public function if_bucket_policy_exists($bucket)
  1720. {
  1721. if ($this->use_batch_flow)
  1722. {
  1723. // @codeCoverageIgnoreStart
  1724. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1725. // @codeCoverageIgnoreEnd
  1726. }
  1727. $response = $this->get_bucket_policy($bucket);
  1728. if ($response->isOK()) { return true; }
  1729. elseif ($response->status === 404) { return false; }
  1730. // @codeCoverageIgnoreStart
  1731. return null;
  1732. // @codeCoverageIgnoreEnd
  1733. }
  1734. /**
  1735. * Gets the number of Amazon S3 objects in the specified bucket.
  1736. *
  1737. * @param string $bucket (Required) The name of the bucket to use.
  1738. * @return integer The number of Amazon S3 objects in the bucket.
  1739. */
  1740. public function get_bucket_object_count($bucket)
  1741. {
  1742. if ($this->use_batch_flow)
  1743. {
  1744. // @codeCoverageIgnoreStart
  1745. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1746. // @codeCoverageIgnoreEnd
  1747. }
  1748. return count($this->get_object_list($bucket));
  1749. }
  1750. /**
  1751. * Gets the cumulative file size of the contents of the Amazon S3 bucket.
  1752. *
  1753. * @param string $bucket (Required) The name of the bucket to use.
  1754. * @param boolean $friendly_format (Optional) A value of <code>true</code> will format the return value to 2 decimal points using the largest possible unit (i.e., 3.42 GB). A value of <code>false</code> will format the return value as the raw number of bytes.
  1755. * @return integer|string The number of bytes as an integer, or the friendly format as a string. If the bucket does not exist, the filesize will be 0.
  1756. */
  1757. public function get_bucket_filesize($bucket, $friendly_format = false)
  1758. {
  1759. if ($this->use_batch_flow)
  1760. {
  1761. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1762. }
  1763. $filesize = 0;
  1764. $list = $this->list_objects($bucket);
  1765. foreach ($list->body->Contents as $filename)
  1766. {
  1767. $filesize += (integer) $filename->Size;
  1768. }
  1769. while ((string) $list->body->IsTruncated === 'true')
  1770. {
  1771. $body = (array) $list->body;
  1772. $list = $this->list_objects($bucket, array(
  1773. 'marker' => (string) end($body['Contents'])->Key
  1774. ));
  1775. foreach ($list->body->Contents as $object)
  1776. {
  1777. $filesize += (integer) $object->Size;
  1778. }
  1779. }
  1780. if ($friendly_format)
  1781. {
  1782. $filesize = $this->util->size_readable($filesize);
  1783. }
  1784. return $filesize;
  1785. }
  1786. /**
  1787. * Gets the file size of the specified Amazon S3 object.
  1788. *
  1789. * @param string $bucket (Required) The name of the bucket to use.
  1790. * @param string $filename (Required) The file name for the object.
  1791. * @param boolean $friendly_format (Optional) A value of <code>true</code> will format the return value to 2 decimal points using the largest possible unit (i.e., 3.42 GB). A value of <code>false</code> will format the return value as the raw number of bytes.
  1792. * @return integer|string The number of bytes as an integer, or the friendly format as a string. If the object does not exist, the filesize will be 0.
  1793. */
  1794. public function get_object_filesize($bucket, $filename, $friendly_format = false)
  1795. {
  1796. if ($this->use_batch_flow)
  1797. {
  1798. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1799. }
  1800. $filesize = 0;
  1801. $object = $this->get_object_headers($bucket, $filename);
  1802. if (isset($object->header['content-length']))
  1803. {
  1804. $filesize = (integer) $object->header['content-length'];
  1805. }
  1806. if ($friendly_format)
  1807. {
  1808. $filesize = $this->util->size_readable($filesize);
  1809. }
  1810. return $filesize;
  1811. }
  1812. /**
  1813. * Changes the content type for an existing Amazon S3 object.
  1814. *
  1815. * @param string $bucket (Required) The name of the bucket to use.
  1816. * @param string $filename (Required) The file name for the object.
  1817. * @param string $contentType (Required) The content-type to apply to the object.
  1818. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1819. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1820. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1821. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1822. */
  1823. public function change_content_type($bucket, $filename, $contentType, $opt = null)
  1824. {
  1825. if (!$opt) $opt = array();
  1826. // Retrieve the original metadata
  1827. $metadata = $this->get_object_metadata($bucket, $filename);
  1828. if ($metadata && $metadata['ACL'])
  1829. {
  1830. $opt['acl'] = $metadata['ACL'];
  1831. }
  1832. if ($metadata && $metadata['StorageClass'])
  1833. {
  1834. $opt['headers']['x-amz-storage-class'] = $metadata['StorageClass'];
  1835. }
  1836. // Merge optional parameters
  1837. $opt = array_merge_recursive(array(
  1838. 'headers' => array(
  1839. 'Content-Type' => $contentType
  1840. ),
  1841. 'metadataDirective' => 'REPLACE'
  1842. ), $opt);
  1843. return $this->copy_object(
  1844. array('bucket' => $bucket, 'filename' => $filename),
  1845. array('bucket' => $bucket, 'filename' => $filename),
  1846. $opt
  1847. );
  1848. }
  1849. /**
  1850. * Changes the storage redundancy for an existing object.
  1851. *
  1852. * @param string $bucket (Required) The name of the bucket to use.
  1853. * @param string $filename (Required) The file name for the object.
  1854. * @param string $storage (Required) The storage setting to apply to the object. [Allowed values: <code>AmazonS3::STORAGE_STANDARD</code>, <code>AmazonS3::STORAGE_REDUCED</code>]
  1855. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1856. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1857. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1858. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  1859. */
  1860. public function change_storage_redundancy($bucket, $filename, $storage, $opt = null)
  1861. {
  1862. if (!$opt) $opt = array();
  1863. // Retrieve the original metadata
  1864. $metadata = $this->get_object_metadata($bucket, $filename);
  1865. if ($metadata && $metadata['ACL'])
  1866. {
  1867. $opt['acl'] = $metadata['ACL'];
  1868. }
  1869. if ($metadata && $metadata['ContentType'])
  1870. {
  1871. $opt['headers']['Content-Type'] = $metadata['ContentType'];
  1872. }
  1873. // Merge optional parameters
  1874. $opt = array_merge(array(
  1875. 'storage' => $storage,
  1876. 'metadataDirective' => 'COPY',
  1877. ), $opt);
  1878. return $this->copy_object(
  1879. array('bucket' => $bucket, 'filename' => $filename),
  1880. array('bucket' => $bucket, 'filename' => $filename),
  1881. $opt
  1882. );
  1883. }
  1884. /**
  1885. * Gets a simplified list of bucket names on an Amazon S3 account.
  1886. *
  1887. * @param string $pcre (Optional) A Perl-Compatible Regular Expression (PCRE) to filter the bucket names against.
  1888. * @return array The list of matching bucket names. If there are no results, the method will return an empty array.
  1889. * @link http://php.net/pcre Regular Expressions (Perl-Compatible)
  1890. */
  1891. public function get_bucket_list($pcre = null)
  1892. {
  1893. if ($this->use_batch_flow)
  1894. {
  1895. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1896. }
  1897. // Get a list of buckets.
  1898. $list = $this->list_buckets();
  1899. if ($list = $list->body->query('descendant-or-self::Name'))
  1900. {
  1901. $list = $list->map_string($pcre);
  1902. return $list;
  1903. }
  1904. // @codeCoverageIgnoreStart
  1905. return array();
  1906. // @codeCoverageIgnoreEnd
  1907. }
  1908. /**
  1909. * Gets a simplified list of Amazon S3 object file names contained in a bucket.
  1910. *
  1911. * @param string $bucket (Required) The name of the bucket to use.
  1912. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  1913. * <li><code>delimiter</code> - <code>string</code> - Optional - Keys that contain the same string between the prefix and the first occurrence of the delimiter will be rolled up into a single result element in the CommonPrefixes collection.</li>
  1914. * <li><code>marker</code> - <code>string</code> - Optional - Restricts the response to contain results that only occur alphabetically after the value of the marker.</li>
  1915. * <li><code>max-keys</code> - <code>string</code> - Optional - The maximum number of results returned by the method call. The returned list will contain no more results than the specified value, but may return less.</li>
  1916. * <li><code>pcre</code> - <code>string</code> - Optional - A Perl-Compatible Regular Expression (PCRE) to filter the names against. This is applied only AFTER any native Amazon S3 filtering from specified <code>prefix</code>, <code>marker</code>, <code>max-keys</code>, or <code>delimiter</code> values are applied.</li>
  1917. * <li><code>prefix</code> - <code>string</code> - Optional - Restricts the response to contain results that begin only with the specified prefix.</li>
  1918. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  1919. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  1920. * @return array The list of matching object names. If there are no results, the method will return an empty array.
  1921. * @link http://php.net/pcre Regular Expressions (Perl-Compatible)
  1922. */
  1923. public function get_object_list($bucket, $opt = null)
  1924. {
  1925. if ($this->use_batch_flow)
  1926. {
  1927. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  1928. }
  1929. if (!$opt) $opt = array();
  1930. // Set some default values
  1931. $pcre = isset($opt['pcre']) ? $opt['pcre'] : null;
  1932. $max_keys = isset($opt['max-keys']) ? (integer) $opt['max-keys'] : 'all';
  1933. $objects = array();
  1934. if ($max_keys === 'all')
  1935. {
  1936. do
  1937. {
  1938. $list = $this->list_objects($bucket, $opt);
  1939. if ($keys = $list->body->query('descendant-or-self::Key')->map_string($pcre))
  1940. {
  1941. $objects = array_merge($objects, $keys);
  1942. }
  1943. $body = (array) $list->body;
  1944. $opt = array_merge($opt, array(
  1945. 'marker' => (isset($body['Contents']) && is_array($body['Contents'])) ?
  1946. ((string) end($body['Contents'])->Key) :
  1947. ((string) $list->body->Contents->Key)
  1948. ));
  1949. }
  1950. while ((string) $list->body->IsTruncated === 'true');
  1951. }
  1952. else
  1953. {
  1954. $loops = ceil($max_keys / 1000);
  1955. do
  1956. {
  1957. $list = $this->list_objects($bucket, $opt);
  1958. if ($keys = $list->body->query('descendant-or-self::Key')->map_string($pcre))
  1959. {
  1960. $objects = array_merge($objects, $keys);
  1961. }
  1962. if ($max_keys > 1000)
  1963. {
  1964. $max_keys -= 1000;
  1965. }
  1966. $body = (array) $list->body;
  1967. $opt = array_merge($opt, array(
  1968. 'max-keys' => $max_keys,
  1969. 'marker' => (isset($body['Contents']) && is_array($body['Contents'])) ?
  1970. ((string) end($body['Contents'])->Key) :
  1971. ((string) $list->body->Contents->Key)
  1972. ));
  1973. }
  1974. while (--$loops);
  1975. }
  1976. if (count($objects) > 0)
  1977. {
  1978. return $objects;
  1979. }
  1980. return array();
  1981. }
  1982. /**
  1983. * Deletes all Amazon S3 objects inside the specified bucket.
  1984. *
  1985. * @param string $bucket (Required) The name of the bucket to use.
  1986. * @param string $pcre (Optional) A Perl-Compatible Regular Expression (PCRE) to filter the names against. The default value is <PCRE_ALL>.
  1987. * @return boolean A value of <code>true</code> means that all objects were successfully deleted. A value of <code>false</code> means that at least one object failed to delete.
  1988. * @link http://php.net/pcre Regular Expressions (Perl-Compatible)
  1989. */
  1990. public function delete_all_objects($bucket, $pcre = self::PCRE_ALL)
  1991. {
  1992. // Collect all matches
  1993. $list = $this->get_object_list($bucket, array('pcre' => $pcre));
  1994. // As long as we have at least one match...
  1995. if (count($list) > 0)
  1996. {
  1997. $objects = array();
  1998. foreach ($list as $object)
  1999. {
  2000. $objects[] = array('key' => $object);
  2001. }
  2002. $response = $this->delete_objects($bucket, array(
  2003. 'objects' => $objects
  2004. ));
  2005. return ($response->isOK() && !isset($response->body->Error));
  2006. }
  2007. // If there are no matches, return true
  2008. return true;
  2009. }
  2010. /**
  2011. * Deletes all of the versions of all Amazon S3 objects inside the specified bucket.
  2012. *
  2013. * @param string $bucket (Required) The name of the bucket to use.
  2014. * @param string $pcre (Optional) A Perl-Compatible Regular Expression (PCRE) to filter the names against. The default value is <PCRE_ALL>.
  2015. * @return boolean A value of <code>true</code> means that all object versions were successfully deleted. A value of <code>false</code> means that at least one object/version failed to delete.
  2016. * @link http://php.net/pcre Regular Expressions (Perl-Compatible)
  2017. */
  2018. public function delete_all_object_versions($bucket, $pcre = null)
  2019. {
  2020. // Instantiate
  2021. $versions = $this->list_bucket_object_versions($bucket);
  2022. // Gather all nodes together into a single array
  2023. if ($versions->body->DeleteMarker() && $versions->body->Version())
  2024. {
  2025. $markers = array_merge($versions->body->DeleteMarker()->getArrayCopy(), $versions->body->Version()->getArrayCopy());
  2026. }
  2027. elseif ($versions->body->DeleteMarker())
  2028. {
  2029. $markers = $versions->body->DeleteMarker()->getArrayCopy();
  2030. }
  2031. elseif ($versions->body->Version())
  2032. {
  2033. $markers = $versions->body->Version()->getArrayCopy();
  2034. }
  2035. else
  2036. {
  2037. $markers = array();
  2038. }
  2039. while ((string) $versions->body->IsTruncated === 'true')
  2040. {
  2041. $versions = $this->list_bucket_object_versions($bucket, array(
  2042. 'key-marker' => (string) $versions->body->NextKeyMarker
  2043. ));
  2044. // Gather all nodes together into a single array
  2045. if ($versions->body->DeleteMarker() && $versions->body->Version())
  2046. {
  2047. $markers = array_merge($markers, $versions->body->DeleteMarker()->getArrayCopy(), $versions->body->Version()->getArrayCopy());
  2048. }
  2049. elseif ($versions->body->DeleteMarker())
  2050. {
  2051. $markers = array_merge($markers, $versions->body->DeleteMarker()->getArrayCopy());
  2052. }
  2053. elseif ($versions->body->Version())
  2054. {
  2055. $markers = array_merge($markers, $versions->body->Version()->getArrayCopy());
  2056. }
  2057. }
  2058. $objects = array();
  2059. // Loop through markers
  2060. foreach ($markers as $marker)
  2061. {
  2062. if ($pcre)
  2063. {
  2064. if (preg_match($pcre, (string) $marker->Key))
  2065. {
  2066. $objects[] = array(
  2067. 'key' => (string) $marker->Key,
  2068. 'version_id' => (string) $marker->VersionId
  2069. );
  2070. }
  2071. }
  2072. else
  2073. {
  2074. $objects[] = array(
  2075. 'key' => (string) $marker->Key,
  2076. 'version_id' => (string) $marker->VersionId
  2077. );
  2078. }
  2079. }
  2080. $response = $this->delete_objects($bucket, array(
  2081. 'objects' => $objects
  2082. ));
  2083. return ($response->isOK() && !isset($response->body->Error));
  2084. }
  2085. /**
  2086. * Gets the collective metadata for the given Amazon S3 object.
  2087. *
  2088. * @param string $bucket (Required) The name of the bucket to use.
  2089. * @param string $filename (Required) The file name for the Amazon S3 object.
  2090. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2091. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object to retrieve. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  2092. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2093. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2094. * @return mixed If the object exists, the method returns the collective metadata for the Amazon S3 object. If the object does not exist, the method returns boolean <code>false</code>.
  2095. */
  2096. public function get_object_metadata($bucket, $filename, $opt = null)
  2097. {
  2098. $batch = new CFBatchRequest();
  2099. $this->batch($batch)->get_object_acl($bucket, $filename); // Get ACL info
  2100. $this->batch($batch)->get_object_headers($bucket, $filename); // Get content-type
  2101. $this->batch($batch)->list_objects($bucket, array( // Get other metadata
  2102. 'max-keys' => 1,
  2103. 'prefix' => $filename
  2104. ));
  2105. $response = $this->batch($batch)->send();
  2106. // Fail if any requests were unsuccessful
  2107. if (!$response->areOK())
  2108. {
  2109. return false;
  2110. }
  2111. $data = array(
  2112. 'ACL' => array(),
  2113. 'ContentType' => null,
  2114. 'ETag' => null,
  2115. 'Headers' => null,
  2116. 'Key' => null,
  2117. 'LastModified' => null,
  2118. 'Owner' => array(),
  2119. 'Size' => null,
  2120. 'StorageClass' => null,
  2121. );
  2122. // Add the content type
  2123. $data['ContentType'] = isset($response[1]->header['content-type']) ? (string) $response[1]->header['content-type'] : '';
  2124. // Add the other metadata (including storage type)
  2125. $contents = json_decode(json_encode($response[2]->body->query('descendant-or-self::Contents')->first()), true);
  2126. $data = array_merge($data, (is_array($contents) ? $contents : array()));
  2127. // Add ACL info
  2128. $grants = $response[0]->body->query('descendant-or-self::Grant');
  2129. $max = count($grants);
  2130. // Add raw header info
  2131. $data['Headers'] = $response[1]->header;
  2132. foreach (array('_info', 'x-amz-id-2', 'x-amz-request-id', 'cneonction', 'server', 'content-length', 'content-type', 'etag') as $header)
  2133. {
  2134. unset($data['Headers'][$header]);
  2135. }
  2136. ksort($data['Headers']);
  2137. if (count($grants) > 0)
  2138. {
  2139. foreach ($grants as $grant)
  2140. {
  2141. $dgrant = array(
  2142. 'id' => (string) $this->util->try_these(array('ID', 'URI'), $grant->Grantee),
  2143. 'permission' => (string) $grant->Permission
  2144. );
  2145. $data['ACL'][] = $dgrant;
  2146. }
  2147. }
  2148. return $data;
  2149. }
  2150. /*%******************************************************************************************%*/
  2151. // URLS
  2152. /**
  2153. * Gets the web-accessible URL for the Amazon S3 object or generates a time-limited signed request for
  2154. * a private file.
  2155. *
  2156. * @param string $bucket (Required) The name of the bucket to use.
  2157. * @param string $filename (Required) The file name for the Amazon S3 object.
  2158. * @param integer|string $preauth (Optional) Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.
  2159. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2160. * <li><code>method</code> - <code>string</code> - Optional - The HTTP method to use for the request. Defaults to a value of <code>GET</code>.</li>
  2161. * <li><code>response</code> - <code>array</code> - Optional - Allows adjustments to specific response headers. Pass an associative array where each key is one of the following: <code>cache-control</code>, <code>content-disposition</code>, <code>content-encoding</code>, <code>content-language</code>, <code>content-type</code>, <code>expires</code>. The <code>expires</code> value should use <php:gmdate()> and be formatted with the <code>DATE_RFC2822</code> constant.</li>
  2162. * <li><code>torrent</code> - <code>boolean</code> - Optional - A value of <code>true</code> will return a URL to a torrent of the Amazon S3 object. A value of <code>false</code> will return a non-torrent URL. Defaults to <code>false</code>.</li>
  2163. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  2164. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2165. * @return string The file URL, with authentication and/or torrent parameters if requested.
  2166. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html Using Query String Authentication
  2167. */
  2168. public function get_object_url($bucket, $filename, $preauth = 0, $opt = null)
  2169. {
  2170. // Add this to our request
  2171. if (!$opt) $opt = array();
  2172. $opt['verb'] = isset($opt['method']) ? $opt['method'] : 'GET';
  2173. $opt['resource'] = $filename;
  2174. $opt['preauth'] = $preauth;
  2175. if (isset($opt['torrent']) && $opt['torrent'])
  2176. {
  2177. $opt['sub_resource'] = 'torrent';
  2178. unset($opt['torrent']);
  2179. }
  2180. // GET responses
  2181. if (isset($opt['response']))
  2182. {
  2183. foreach ($opt['response'] as $key => $value)
  2184. {
  2185. $opt['response-' . $key] = $value;
  2186. unset($opt['response'][$key]);
  2187. }
  2188. }
  2189. // Authenticate to S3
  2190. $current_ssl_setting = $this->use_ssl;
  2191. $this->use_ssl = false;
  2192. $response = $this->authenticate($bucket, $opt);
  2193. $this->use_ssl = $current_ssl_setting;
  2194. return $response;
  2195. }
  2196. /**
  2197. * Gets the web-accessible URL to a torrent of the Amazon S3 object. The Amazon S3 object's access
  2198. * control list settings (ACL) MUST be set to <ACL_PUBLIC> for a valid URL to be returned.
  2199. *
  2200. * @param string $bucket (Required) The name of the bucket to use.
  2201. * @param string $filename (Required) The file name for the object.
  2202. * @param integer|string $preauth (Optional) Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.
  2203. * @return string The torrent URL, with authentication parameters if requested.
  2204. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?S3TorrentRetrieve.html Using BitTorrent to Retrieve Objects Stored in Amazon S3
  2205. */
  2206. public function get_torrent_url($bucket, $filename, $preauth = 0)
  2207. {
  2208. return $this->get_object_url($bucket, $filename, $preauth, array(
  2209. 'torrent' => true
  2210. ));
  2211. }
  2212. /*%******************************************************************************************%*/
  2213. // VERSIONING
  2214. /**
  2215. * Enables versioning support for the specified Amazon S3 bucket.
  2216. *
  2217. * @param string $bucket (Required) The name of the bucket to use.
  2218. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2219. * <li><code>MFASerial</code> - string (Optional) The serial number on the back of the Gemalto device. <code>MFASerial</code>, <code>MFAToken</code> and <code>MFAStatus</code> must all be set for MFA to work.</li>
  2220. * <li><code>MFAToken</code> - string (Optional) The current token displayed on the Gemalto device. <code>MFASerial</code>, <code>MFAToken</code> and <code>MFAStatus</code> must all be set for MFA to work.</li>
  2221. * <li><code>MFAStatus</code> - string (Optional) The MFA Delete status. Can be <code>Enabled</code> or <code>Disabled</code>. <code>MFASerial</code>, <code>MFAToken</code> and <code>MFAStatus</code> must all be set for MFA to work.</li>
  2222. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2223. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2224. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2225. * @link http://aws.amazon.com/mfa/ Multi-Factor Authentication
  2226. */
  2227. public function enable_versioning($bucket, $opt = null)
  2228. {
  2229. if (!$opt) $opt = array();
  2230. // Add this to our request
  2231. $opt['verb'] = 'PUT';
  2232. $opt['sub_resource'] = 'versioning';
  2233. $opt['headers'] = array(
  2234. 'Content-Type' => 'application/xml'
  2235. );
  2236. $xml = simplexml_load_string($this->base_versioning_xml);
  2237. $xml->addChild('Status', 'Enabled');
  2238. // Enable MFA delete?
  2239. // @codeCoverageIgnoreStart
  2240. if (isset($opt['MFASerial']) && isset($opt['MFAToken']) && isset($opt['MFAStatus']))
  2241. {
  2242. $xml->addChild('MfaDelete', $opt['MFAStatus']);
  2243. $opt['headers']['x-amz-mfa'] = ($opt['MFASerial'] . ' ' . $opt['MFAToken']);
  2244. }
  2245. // @codeCoverageIgnoreEnd
  2246. $opt['body'] = $xml->asXML();
  2247. // Authenticate to S3
  2248. return $this->authenticate($bucket, $opt);
  2249. }
  2250. /**
  2251. * Disables versioning support for the specified Amazon S3 bucket.
  2252. *
  2253. * @param string $bucket (Required) The name of the bucket to use.
  2254. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2255. * <li><code>MFASerial</code> - <code>string</code> - Optional - The serial number on the back of the Gemalto device. <code>MFASerial</code>, <code>MFAToken</code> and <code>MFAStatus</code> must all be set for MFA to work.</li>
  2256. * <li><code>MFAToken</code> - <code>string</code> - Optional - The current token displayed on the Gemalto device. <code>MFASerial</code>, <code>MFAToken</code> and <code>MFAStatus</code> must all be set for MFA to work.</li>
  2257. * <li><code>MFAStatus</code> - <code>string</code> - Optional - The MFA Delete status. Can be <code>Enabled</code> or <code>Disabled</code>. <code>MFASerial</code>, <code>MFAToken</code> and <code>MFAStatus</code> must all be set for MFA to work.</li>
  2258. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2259. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2260. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2261. * @link http://aws.amazon.com/mfa/ Multi-Factor Authentication
  2262. */
  2263. public function disable_versioning($bucket, $opt = null)
  2264. {
  2265. if (!$opt) $opt = array();
  2266. // Add this to our request
  2267. $opt['verb'] = 'PUT';
  2268. $opt['sub_resource'] = 'versioning';
  2269. $opt['headers'] = array(
  2270. 'Content-Type' => 'application/xml'
  2271. );
  2272. $xml = simplexml_load_string($this->base_versioning_xml);
  2273. $xml->addChild('Status', 'Suspended');
  2274. // Enable MFA delete?
  2275. // @codeCoverageIgnoreStart
  2276. if (isset($opt['MFASerial']) && isset($opt['MFAToken']) && isset($opt['MFAStatus']))
  2277. {
  2278. $xml->addChild('MfaDelete', $opt['MFAStatus']);
  2279. $opt['headers']['x-amz-mfa'] = ($opt['MFASerial'] . ' ' . $opt['MFAToken']);
  2280. }
  2281. // @codeCoverageIgnoreEnd
  2282. $opt['body'] = $xml->asXML();
  2283. // Authenticate to S3
  2284. return $this->authenticate($bucket, $opt);
  2285. }
  2286. /**
  2287. * Gets an Amazon S3 bucket's versioning status.
  2288. *
  2289. * @param string $bucket (Required) The name of the bucket to use.
  2290. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2291. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  2292. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2293. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2294. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2295. */
  2296. public function get_versioning_status($bucket, $opt = null)
  2297. {
  2298. if (!$opt) $opt = array();
  2299. $opt['verb'] = 'GET';
  2300. $opt['sub_resource'] = 'versioning';
  2301. // Authenticate to S3
  2302. return $this->authenticate($bucket, $opt);
  2303. }
  2304. /**
  2305. * Gets a list of all the versions of Amazon S3 objects in the specified bucket.
  2306. *
  2307. * @param string $bucket (Required) The name of the bucket to use.
  2308. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2309. * <li><code>delimiter</code> - <code>string</code> - Optional - Unicode string parameter. Keys that contain the same string between the prefix and the first occurrence of the delimiter will be rolled up into a single result element in the CommonPrefixes collection.</li>
  2310. * <li><code>key-marker</code> - <code>string</code> - Optional - Restricts the response to contain results that only occur alphabetically after the value of the <code>key-marker</code>.</li>
  2311. * <li><code>max-keys</code> - <code>string</code> - Optional - Limits the number of results returned in response to your query. Will return no more than this number of results, but possibly less.</li>
  2312. * <li><code>prefix</code> - <code>string</code> - Optional - Restricts the response to only contain results that begin with the specified prefix.</li>
  2313. * <li><code>version-id-marker</code> - <code>string</code> - Optional - Restricts the response to contain results that only occur alphabetically after the value of the <code>version-id-marker</code>.</li>
  2314. * <li><code>preauth</code> - <code>integer|string</code> - Optional - Specifies that a presigned URL for this request should be returned. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li>
  2315. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2316. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2317. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2318. */
  2319. public function list_bucket_object_versions($bucket, $opt = null)
  2320. {
  2321. if (!$opt) $opt = array();
  2322. $opt['verb'] = 'GET';
  2323. $opt['sub_resource'] = 'versions';
  2324. foreach (array('delimiter', 'key-marker', 'max-keys', 'prefix', 'version-id-marker') as $param)
  2325. {
  2326. if (isset($opt[$param]))
  2327. {
  2328. $opt['query_string'][$param] = $opt[$param];
  2329. unset($opt[$param]);
  2330. }
  2331. }
  2332. // Authenticate to S3
  2333. return $this->authenticate($bucket, $opt);
  2334. }
  2335. /*%******************************************************************************************%*/
  2336. // BUCKET POLICIES
  2337. /**
  2338. * Sets the policy sub-resource for the specified Amazon S3 bucket. The specified policy replaces any
  2339. * policy the bucket already has.
  2340. *
  2341. * To perform this operation, the caller must be authorized to set a policy for the bucket and have
  2342. * PutPolicy permissions. If the caller does not have PutPolicy permissions for the bucket, Amazon S3
  2343. * returns a `403 Access Denied` error. If the caller has the correct permissions but has not been
  2344. * authorized by the bucket owner, Amazon S3 returns a `405 Method Not Allowed` error.
  2345. *
  2346. * @param string $bucket (Required) The name of the bucket to use.
  2347. * @param CFPolicy $policy (Required) The JSON policy to use.
  2348. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2349. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2350. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2351. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2352. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/AccessPolicyLanguage.html Appendix: The Access Policy Language
  2353. */
  2354. public function set_bucket_policy($bucket, CFPolicy $policy, $opt = null)
  2355. {
  2356. if (!$opt) $opt = array();
  2357. $opt['verb'] = 'PUT';
  2358. $opt['sub_resource'] = 'policy';
  2359. $opt['body'] = $policy->get_json();
  2360. // Authenticate to S3
  2361. return $this->authenticate($bucket, $opt);
  2362. }
  2363. /**
  2364. * Gets the policy of the specified Amazon S3 bucket.
  2365. *
  2366. * To use this operation, the caller must have GetPolicy permissions for the specified bucket and must be
  2367. * the bucket owner. If the caller does not have GetPolicy permissions, this method will generate a
  2368. * `403 Access Denied` error. If the caller has the correct permissions but is not the bucket owner, this
  2369. * method will generate a `405 Method Not Allowed` error. If the bucket does not have a policy defined for
  2370. * it, this method will generate a `404 Policy Not Found` error.
  2371. *
  2372. * @param string $bucket (Required) The name of the bucket to use.
  2373. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2374. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2375. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2376. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2377. */
  2378. public function get_bucket_policy($bucket, $opt = null)
  2379. {
  2380. if (!$opt) $opt = array();
  2381. $opt['verb'] = 'GET';
  2382. $opt['sub_resource'] = 'policy';
  2383. // Authenticate to S3
  2384. return $this->authenticate($bucket, $opt);
  2385. }
  2386. /**
  2387. * Deletes the bucket policy for the specified Amazon S3 bucket. To delete the policy, the caller must
  2388. * be the bucket owner and have `DeletePolicy` permissions for the specified bucket.
  2389. *
  2390. * @param string $bucket (Required) The name of the bucket to use.
  2391. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2392. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2393. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2394. * @return CFResponse A <CFResponse> object containing a parsed HTTP response. If you do not have `DeletePolicy` permissions, Amazon S3 returns a `403 Access Denied` error. If you have the correct permissions, but are not the bucket owner, Amazon S3 returns a `405 Method Not Allowed` error. If the bucket doesn't have a policy, Amazon S3 returns a `204 No Content` error.
  2395. */
  2396. public function delete_bucket_policy($bucket, $opt = null)
  2397. {
  2398. if (!$opt) $opt = array();
  2399. $opt['verb'] = 'DELETE';
  2400. $opt['sub_resource'] = 'policy';
  2401. // Authenticate to S3
  2402. return $this->authenticate($bucket, $opt);
  2403. }
  2404. /*%******************************************************************************************%*/
  2405. // BUCKET NOTIFICATIONS
  2406. /**
  2407. * Enables notifications of specified events for an Amazon S3 bucket. Currently, the
  2408. * `s3:ReducedRedundancyLostObject` event is the only event supported for notifications. The
  2409. * `s3:ReducedRedundancyLostObject` event is triggered when Amazon S3 detects that it has lost all
  2410. * copies of an Amazon S3 object and can no longer service requests for that object.
  2411. *
  2412. * If the bucket owner and Amazon SNS topic owner are the same, the bucket owner has permission to
  2413. * publish notifications to the topic by default. Otherwise, the owner of the topic must create a
  2414. * policy to enable the bucket owner to publish to the topic.
  2415. *
  2416. * By default, only the bucket owner can configure notifications on a bucket. However, bucket owners
  2417. * can use bucket policies to grant permission to other users to set this configuration with the
  2418. * `s3:PutBucketNotification` permission.
  2419. *
  2420. * After a PUT operation is called to configure notifications on a bucket, Amazon S3 publishes a test
  2421. * notification to ensure that the topic exists and that the bucket owner has permission to publish
  2422. * to the specified topic. If the notification is successfully published to the SNS topic, the PUT
  2423. * operation updates the bucket configuration and returns the 200 OK responses with a
  2424. * `x-amz-sns-test-message-id` header containing the message ID of the test notification sent to topic.
  2425. *
  2426. * @param string $bucket (Required) The name of the bucket to create bucket notifications for.
  2427. * @param string $topic_arn (Required) The SNS topic ARN to send notifications to.
  2428. * @param string $event (Required) The event type to listen for.
  2429. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2430. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2431. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2432. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2433. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/NotificationHowTo.html Setting Up Notification of Bucket Events
  2434. */
  2435. public function create_bucket_notification($bucket, $topic_arn, $event, $opt = null)
  2436. {
  2437. if (!$opt) $opt = array();
  2438. $opt['verb'] = 'PUT';
  2439. $opt['sub_resource'] = 'notification';
  2440. $opt['headers'] = array(
  2441. 'Content-Type' => 'application/xml'
  2442. );
  2443. $xml = simplexml_load_string($this->base_notification_xml);
  2444. $topic_config = $xml->addChild('TopicConfiguration');
  2445. $topic_config->addChild('Topic', $topic_arn);
  2446. $topic_config->addChild('Event', $event);
  2447. $opt['body'] = $xml->asXML();
  2448. // Authenticate to S3
  2449. return $this->authenticate($bucket, $opt);
  2450. }
  2451. /**
  2452. * Gets the notification configuration of a bucket. Currently, the `s3:ReducedRedundancyLostObject` event
  2453. * is the only event supported for notifications. The `s3:ReducedRedundancyLostObject` event is triggered
  2454. * when Amazon S3 detects that it has lost all replicas of a Reduced Redundancy Storage object and can no
  2455. * longer service requests for that object.
  2456. *
  2457. * If notifications are not enabled on the bucket, the operation returns an empty
  2458. * `NotificatonConfiguration` element.
  2459. *
  2460. * By default, you must be the bucket owner to read the notification configuration of a bucket. However,
  2461. * the bucket owner can use a bucket policy to grant permission to other users to read this configuration
  2462. * with the `s3:GetBucketNotification` permission.
  2463. *
  2464. * @param string $bucket (Required) The name of the bucket to use.
  2465. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2466. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2467. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2468. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2469. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/NotificationHowTo.html Setting Up Notification of Bucket Events
  2470. */
  2471. public function get_bucket_notifications($bucket, $opt = null)
  2472. {
  2473. if (!$opt) $opt = array();
  2474. $opt['verb'] = 'GET';
  2475. $opt['sub_resource'] = 'notification';
  2476. // Authenticate to S3
  2477. return $this->authenticate($bucket, $opt);
  2478. }
  2479. /**
  2480. * Empties the list of SNS topics to send notifications to.
  2481. *
  2482. * @param string $bucket (Required) The name of the bucket to use.
  2483. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2484. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2485. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2486. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2487. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/NotificationHowTo.html Setting Up Notification of Bucket Events
  2488. */
  2489. public function delete_bucket_notification($bucket, $opt = null)
  2490. {
  2491. if (!$opt) $opt = array();
  2492. $opt['verb'] = 'PUT';
  2493. $opt['sub_resource'] = 'notification';
  2494. $opt['body'] = $this->base_notification_xml;
  2495. // Authenticate to S3
  2496. return $this->authenticate($bucket, $opt);
  2497. }
  2498. /*%******************************************************************************************%*/
  2499. // MULTIPART UPLOAD
  2500. /**
  2501. * Calculates the correct values for sequentially reading a file for multipart upload. This method should
  2502. * be used in conjunction with <upload_part()>.
  2503. *
  2504. * @param integer $filesize (Required) The size in bytes of the entire file.
  2505. * @param integer $part_size (Required) The size in bytes of the part of the file to send.
  2506. * @return array An array containing key-value pairs. The keys are `seekTo` and `length`.
  2507. */
  2508. public function get_multipart_counts($filesize, $part_size)
  2509. {
  2510. $i = 0;
  2511. $sizecount = $filesize;
  2512. $values = array();
  2513. while ($sizecount > 0)
  2514. {
  2515. $sizecount -= $part_size;
  2516. $values[] = array(
  2517. 'seekTo' => ($part_size * $i),
  2518. 'length' => (($sizecount > 0) ? $part_size : ($sizecount + $part_size)),
  2519. );
  2520. $i++;
  2521. }
  2522. return $values;
  2523. }
  2524. /**
  2525. * Initiates a multipart upload and returns an `UploadId`.
  2526. *
  2527. * @param string $bucket (Required) The name of the bucket to use.
  2528. * @param string $filename (Required) The file name for the object.
  2529. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2530. * <li><code>acl</code> - <code>string</code> - Optional - The ACL settings for the specified object. [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. The default value is <code>ACL_PRIVATE</code>.</li>
  2531. * <li><code>contentType</code> - <code>string</code> - Optional - The type of content that is being sent. The default value is <code>application/octet-stream</code>.</li>
  2532. * <li><code>encryption</code> - <code>string</code> - Optional - The algorithm to use for encrypting the object. [Allowed values: <code>AES256</code>]</li>
  2533. * <li><code>headers</code> - <code>array</code> - Optional - The standard HTTP headers to send along in the request.</li>
  2534. * <li><code>meta</code> - <code>array</code> - Optional - An associative array of key-value pairs. Any header starting with <code>x-amz-meta-:</code> is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB.</li>
  2535. * <li><code>storage</code> - <code>string</code> - Optional - Whether to use Standard or Reduced Redundancy storage. [Allowed values: <code>AmazonS3::STORAGE_STANDARD</code>, <code>AmazonS3::STORAGE_REDUCED</code>]. The default value is <code>STORAGE_STANDARD</code>.</li>
  2536. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2537. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2538. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2539. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAccessPolicy.html REST Access Control Policy
  2540. */
  2541. public function initiate_multipart_upload($bucket, $filename, $opt = null)
  2542. {
  2543. if (!$opt) $opt = array();
  2544. // Add this to our request
  2545. $opt['verb'] = 'POST';
  2546. $opt['resource'] = $filename;
  2547. $opt['sub_resource'] = 'uploads';
  2548. $opt['body'] = '';
  2549. // Handle content type. Can also be passed as an HTTP header.
  2550. if (isset($opt['contentType']))
  2551. {
  2552. $opt['headers']['Content-Type'] = $opt['contentType'];
  2553. unset($opt['contentType']);
  2554. }
  2555. // Set a default content type.
  2556. if (!isset($opt['headers']['Content-Type']))
  2557. {
  2558. $opt['headers']['Content-Type'] = 'application/octet-stream';
  2559. }
  2560. // Handle Access Control Lists. Can also be passed as an HTTP header.
  2561. if (isset($opt['acl']))
  2562. {
  2563. $opt['headers']['x-amz-acl'] = $opt['acl'];
  2564. unset($opt['acl']);
  2565. }
  2566. // Handle storage settings. Can also be passed as an HTTP header.
  2567. if (isset($opt['storage']))
  2568. {
  2569. $opt['headers']['x-amz-storage-class'] = $opt['storage'];
  2570. unset($opt['storage']);
  2571. }
  2572. // Handle encryption settings. Can also be passed as an HTTP header.
  2573. if (isset($opt['encryption']))
  2574. {
  2575. $opt['headers']['x-amz-server-side-encryption'] = $opt['encryption'];
  2576. unset($opt['encryption']);
  2577. }
  2578. // Handle meta tags. Can also be passed as an HTTP header.
  2579. if (isset($opt['meta']))
  2580. {
  2581. foreach ($opt['meta'] as $meta_key => $meta_value)
  2582. {
  2583. // e.g., `My Meta Header` is converted to `x-amz-meta-my-meta-header`.
  2584. $opt['headers']['x-amz-meta-' . strtolower(str_replace(' ', '-', $meta_key))] = $meta_value;
  2585. }
  2586. unset($opt['meta']);
  2587. }
  2588. // Authenticate to S3
  2589. return $this->authenticate($bucket, $opt);
  2590. }
  2591. /**
  2592. * Uploads a single part of a multipart upload. The part size cannot be smaller than 5 MB
  2593. * or larger than 5 TB. A multipart upload can have no more than 10,000 parts.
  2594. *
  2595. * Amazon S3 charges for storage as well as requests to the service. Smaller part sizes (and more
  2596. * requests) allow for faster failures and better upload reliability. Larger part sizes (and fewer
  2597. * requests) costs slightly less but has lower upload reliability.
  2598. *
  2599. * @param string $bucket (Required) The name of the bucket to use.
  2600. * @param string $filename (Required) The file name for the object.
  2601. * @param string $upload_id (Required) The upload ID identifying the multipart upload whose parts are being listed. The upload ID is retrieved from a call to <initiate_multipart_upload()>.
  2602. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2603. * <li><code>fileUpload</code> - <code>string|resource</code> - Required - The URL/path for the file to upload or an open resource.</li>
  2604. * <li><code>partNumber</code> - <code>integer</code> - Required - The part number order of the multipart upload.</li>
  2605. * <li><code>expect</code> - <code>string</code> - Optional - Specifies that the SDK not send the request body until it receives an acknowledgement. If the message is rejected based on the headers, the body of the message is not sent. For more information, see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20">RFC 2616, section 14.20</a>. The value can also be passed to the <code>header</code> option as <code>Expect</code>. [Allowed values: <code>100-continue</code>]</li>
  2606. * <li><code>headers</code> - <code>array</code> - Optional - The standard HTTP headers to send along in the request.</li>
  2607. * <li><code>length</code> - <code>integer</code> - Optional - The size of the part in bytes. For more information, see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13">RFC 2616, section 14.13</a>. The value can also be passed to the <code>header</code> option as <code>Content-Length</code>.</li>
  2608. * <li><code>md5</code> - <code>string</code> - Optional - The base64 encoded 128-bit MD5 digest of the part data. This header can be used as a message integrity check to verify that the part data is the same data that was originally sent. Although it is optional, we recommend using this mechanism as an end-to-end integrity check. For more information, see <a href="http://www.ietf.org/rfc/rfc1864.txt">RFC 1864</a>. The value can also be passed to the <code>header</code> option as <code>Content-MD5</code>.</li>
  2609. * <li><code>seekTo</code> - <code>integer</code> - Optional - The starting position in bytes for the piece of the file/stream to upload.</li>
  2610. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2611. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2612. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2613. */
  2614. public function upload_part($bucket, $filename, $upload_id, $opt = null)
  2615. {
  2616. if (!$opt) $opt = array();
  2617. // Add this to our request
  2618. $opt['verb'] = 'PUT';
  2619. $opt['resource'] = $filename;
  2620. $opt['uploadId'] = $upload_id;
  2621. if (!isset($opt['fileUpload']) || !isset($opt['partNumber']))
  2622. {
  2623. throw new S3_Exception('The `fileUpload` and `partNumber` options are both required in ' . __FUNCTION__ . '().');
  2624. }
  2625. // Handle expectation. Can also be passed as an HTTP header.
  2626. if (isset($opt['expect']))
  2627. {
  2628. $opt['headers']['Expect'] = $opt['expect'];
  2629. unset($opt['expect']);
  2630. }
  2631. // Handle content length. Can also be passed as an HTTP header.
  2632. if (isset($opt['length']))
  2633. {
  2634. $opt['headers']['Content-Length'] = $opt['length'];
  2635. unset($opt['length']);
  2636. }
  2637. // Handle content md5. Can also be passed as an HTTP header.
  2638. if (isset($opt['md5']))
  2639. {
  2640. $opt['headers']['Content-MD5'] = $opt['md5'];
  2641. unset($opt['md5']);
  2642. }
  2643. // Authenticate to S3
  2644. return $this->authenticate($bucket, $opt);
  2645. }
  2646. /**
  2647. * Lists the completed parts of an in-progress multipart upload.
  2648. *
  2649. * @param string $bucket (Required) The name of the bucket to use.
  2650. * @param string $filename (Required) The file name for the object.
  2651. * @param string $upload_id (Required) The upload ID identifying the multipart upload whose parts are being listed. The upload ID is retrieved from a call to <initiate_multipart_upload()>.
  2652. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2653. * <li><code>max-parts</code> - <code>integer</code> - Optional - The maximum number of parts to return in the response body.</li>
  2654. * <li><code>part-number-marker</code> - <code>string</code> - Optional - Restricts the response to contain results that only occur numerically after the value of the <code>part-number-marker</code>.</li>
  2655. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2656. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2657. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2658. */
  2659. public function list_parts($bucket, $filename, $upload_id, $opt = null)
  2660. {
  2661. if (!$opt) $opt = array();
  2662. // Add this to our request
  2663. $opt['verb'] = 'GET';
  2664. $opt['resource'] = $filename;
  2665. $opt['uploadId'] = $upload_id;
  2666. $opt['query_string'] = array();
  2667. foreach (array('max-parts', 'part-number-marker') as $param)
  2668. {
  2669. if (isset($opt[$param]))
  2670. {
  2671. $opt['query_string'][$param] = $opt[$param];
  2672. unset($opt[$param]);
  2673. }
  2674. }
  2675. // Authenticate to S3
  2676. return $this->authenticate($bucket, $opt);
  2677. }
  2678. /**
  2679. * Aborts an in-progress multipart upload. This operation cannot be reversed.
  2680. *
  2681. * @param string $bucket (Required) The name of the bucket to use.
  2682. * @param string $filename (Required) The file name for the object.
  2683. * @param string $upload_id (Required) The upload ID identifying the multipart upload whose parts are being listed. The upload ID is retrieved from a call to <initiate_multipart_upload()>.
  2684. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2685. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2686. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2687. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2688. */
  2689. public function abort_multipart_upload($bucket, $filename, $upload_id, $opt = null)
  2690. {
  2691. if (!$opt) $opt = array();
  2692. // Add this to our request
  2693. $opt['verb'] = 'DELETE';
  2694. $opt['resource'] = $filename;
  2695. $opt['uploadId'] = $upload_id;
  2696. // Authenticate to S3
  2697. return $this->authenticate($bucket, $opt);
  2698. }
  2699. /**
  2700. * Completes an in-progress multipart upload. A multipart upload is completed by describing the part
  2701. * numbers and corresponding ETag values in order, and submitting that data to Amazon S3 as an XML document.
  2702. *
  2703. * @param string $bucket (Required) The name of the bucket to use.
  2704. * @param string $filename (Required) The file name for the object.
  2705. * @param string $upload_id (Required) The upload ID identifying the multipart upload whose parts are being listed. The upload ID is retrieved from a call to <initiate_multipart_upload()>.
  2706. * @param string|array|SimpleXMLElement|CFResponse $parts (Required) The completion XML document. This document can be provided in multiple ways; as a string of XML, as a <php:SimpleXMLElement> object representing the XML document, as an indexed array of associative arrays where the keys are <code>PartNumber</code> and <code>ETag</code>, or as a <CFResponse> object returned by <list_parts()>.
  2707. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2708. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2709. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2710. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2711. */
  2712. public function complete_multipart_upload($bucket, $filename, $upload_id, $parts, $opt = null)
  2713. {
  2714. if (!$opt) $opt = array();
  2715. // Add this to our request
  2716. $opt['verb'] = 'POST';
  2717. $opt['resource'] = $filename;
  2718. $opt['uploadId'] = $upload_id;
  2719. $opt['headers'] = array(
  2720. 'Content-Type' => 'application/xml'
  2721. );
  2722. // Disable Content-MD5 calculation for this operation
  2723. $opt['NoContentMD5'] = true;
  2724. if (is_string($parts))
  2725. {
  2726. // Assume it's the intended XML.
  2727. $opt['body'] = $parts;
  2728. }
  2729. elseif ($parts instanceof SimpleXMLElement)
  2730. {
  2731. // Assume it's a SimpleXMLElement object representing the XML.
  2732. $opt['body'] = $parts->asXML();
  2733. }
  2734. elseif (is_array($parts) || $parts instanceof CFResponse)
  2735. {
  2736. $xml = simplexml_load_string($this->complete_mpu_xml);
  2737. if (is_array($parts))
  2738. {
  2739. // Generate the appropriate XML.
  2740. foreach ($parts as $node)
  2741. {
  2742. $part = $xml->addChild('Part');
  2743. $part->addChild('PartNumber', $node['PartNumber']);
  2744. $part->addChild('ETag', $node['ETag']);
  2745. }
  2746. }
  2747. elseif ($parts instanceof CFResponse)
  2748. {
  2749. // Assume it's a response from list_parts().
  2750. foreach ($parts->body->Part as $node)
  2751. {
  2752. $part = $xml->addChild('Part');
  2753. $part->addChild('PartNumber', (string) $node->PartNumber);
  2754. $part->addChild('ETag', (string) $node->ETag);
  2755. }
  2756. }
  2757. $opt['body'] = $xml->asXML();
  2758. }
  2759. // Authenticate to S3
  2760. return $this->authenticate($bucket, $opt);
  2761. }
  2762. /**
  2763. * Lists the in-progress multipart uploads.
  2764. *
  2765. * @param string $bucket (Required) The name of the bucket to use.
  2766. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2767. * <li><code>delimiter</code> - <code>string</code> - Optional - Keys that contain the same string between the prefix and the first occurrence of the delimiter will be rolled up into a single result element in the CommonPrefixes collection.</li>
  2768. * <li><code>key-marker</code> - <code>string</code> - Optional - Restricts the response to contain results that only occur alphabetically after the value of the <code>key-marker</code>. If used in conjunction with <code>upload-id-marker</code>, the results will be filtered to include keys whose upload ID is alphabetically after the value of <code>upload-id-marker</code>.</li>
  2769. * <li><code>upload-id-marker</code> - <code>string</code> - Optional - Restricts the response to contain results that only occur alphabetically after the value of the <code>upload-id-marker</code>. Must be used in conjunction with <code>key-marker</code>.</li>
  2770. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2771. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2772. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2773. */
  2774. public function list_multipart_uploads($bucket, $opt = null)
  2775. {
  2776. if (!$opt) $opt = array();
  2777. // Add this to our request
  2778. $opt['verb'] = 'GET';
  2779. $opt['sub_resource'] = 'uploads';
  2780. foreach (array('key-marker', 'max-uploads', 'upload-id-marker') as $param)
  2781. {
  2782. if (isset($opt[$param]))
  2783. {
  2784. $opt['query_string'][$param] = $opt[$param];
  2785. unset($opt[$param]);
  2786. }
  2787. }
  2788. // Authenticate to S3
  2789. return $this->authenticate($bucket, $opt);
  2790. }
  2791. /**
  2792. * Since Amazon S3's standard <copy_object()> operation only supports copying objects that are smaller than
  2793. * 5 GB, the ability to copy large objects (greater than 5 GB) requires the use of "Multipart Copy".
  2794. *
  2795. * Copying large objects requires the developer to initiate a new multipart "upload", copy pieces of the
  2796. * large object (specifying a range of bytes up to 5 GB from the large source file), then complete the
  2797. * multipart "upload".
  2798. *
  2799. * NOTE: <strong>This is a synchronous operation</strong>, not an <em>asynchronous</em> operation, which means
  2800. * that Amazon S3 will not return a response for this operation until the copy has completed across the Amazon
  2801. * S3 server fleet. Copying objects within a single region will complete more quickly than copying objects
  2802. * <em>across</em> regions. The synchronous nature of this operation is different from other services where
  2803. * responses are typically returned immediately, even if the operation itself has not yet been completed on
  2804. * the server-side.
  2805. *
  2806. * @param array $source (Required) The bucket and file name to copy from. The following keys must be set: <ul>
  2807. * <li><code>bucket</code> - <code>string</code> - Required - Specifies the name of the bucket containing the source object.</li>
  2808. * <li><code>filename</code> - <code>string</code> - Required - Specifies the file name of the source object to copy.</li></ul>
  2809. * @param array $dest (Required) The bucket and file name to copy to. The following keys must be set: <ul>
  2810. * <li><code>bucket</code> - <code>string</code> - Required - Specifies the name of the bucket to copy the object to.</li>
  2811. * <li><code>filename</code> - <code>string</code> - Required - Specifies the file name to copy the object to.</li></ul>
  2812. * @param string $upload_id (Required) The upload ID identifying the multipart upload whose parts are being listed. The upload ID is retrieved from a call to <initiate_multipart_upload()>.
  2813. * @param integer $part_number (Required) A part number uniquely identifies a part and defines its position within the destination object. When you complete a multipart upload, a complete object is created by concatenating parts in ascending order based on part number. If you copy a new part using the same part number as a previously copied/uploaded part, the previously written part is overwritten.
  2814. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2815. * <li><code>ifMatch</code> - <code>string</code> - Optional - The ETag header from a previous request. Copies the object if its entity tag (ETag) matches the specified tag; otherwise, the request returns a <code>412</code> HTTP status code error (precondition failed). Used in conjunction with <code>ifUnmodifiedSince</code>.</li>
  2816. * <li><code>ifUnmodifiedSince</code> - <code>string</code> - Optional - The LastModified header from a previous request. Copies the object if it hasn't been modified since the specified time; otherwise, the request returns a <code>412</code> HTTP status code error (precondition failed). Used in conjunction with <code>ifMatch</code>.</li>
  2817. * <li><code>ifNoneMatch</code> - <code>string</code> - Optional - The ETag header from a previous request. Copies the object if its entity tag (ETag) is different than the specified ETag; otherwise, the request returns a <code>412</code> HTTP status code error (failed condition). Used in conjunction with <code>ifModifiedSince</code>.</li>
  2818. * <li><code>ifModifiedSince</code> - <code>string</code> - Optional - The LastModified header from a previous request. Copies the object if it has been modified since the specified time; otherwise, the request returns a <code>412</code> HTTP status code error (failed condition). Used in conjunction with <code>ifNoneMatch</code>.</li>
  2819. * <li><code>range</code> - <code>string</code> - Optional - The range of bytes to copy from the object. Specify this parameter when copying partial bits. The specified range must be notated with a hyphen (e.g., 0-10485759). Defaults to the byte range of the complete Amazon S3 object.</li>
  2820. * <li><code>versionId</code> - <code>string</code> - Optional - The version of the object to copy. Version IDs are returned in the <code>x-amz-version-id</code> header of any previous object-related request.</li>
  2821. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2822. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2823. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2824. */
  2825. public function copy_part($source, $dest, $upload_id, $part_number, $opt = null)
  2826. {
  2827. if (!$opt) $opt = array();
  2828. // Add this to our request
  2829. $opt['verb'] = 'PUT';
  2830. $opt['resource'] = $dest['filename'];
  2831. $opt['uploadId'] = $upload_id;
  2832. $opt['partNumber'] = $part_number;
  2833. // Handle copy source
  2834. if (isset($source['bucket']) && isset($source['filename']))
  2835. {
  2836. $opt['headers']['x-amz-copy-source'] = '/' . $source['bucket'] . '/' . rawurlencode($source['filename'])
  2837. . (isset($opt['versionId']) ? ('?' . 'versionId=' . rawurlencode($opt['versionId'])) : ''); // Append the versionId to copy, if available
  2838. unset($opt['versionId']);
  2839. }
  2840. // Handle conditional-copy parameters
  2841. if (isset($opt['ifMatch']))
  2842. {
  2843. $opt['headers']['x-amz-copy-source-if-match'] = $opt['ifMatch'];
  2844. unset($opt['ifMatch']);
  2845. }
  2846. if (isset($opt['ifNoneMatch']))
  2847. {
  2848. $opt['headers']['x-amz-copy-source-if-none-match'] = $opt['ifNoneMatch'];
  2849. unset($opt['ifNoneMatch']);
  2850. }
  2851. if (isset($opt['ifUnmodifiedSince']))
  2852. {
  2853. $opt['headers']['x-amz-copy-source-if-unmodified-since'] = $opt['ifUnmodifiedSince'];
  2854. unset($opt['ifUnmodifiedSince']);
  2855. }
  2856. if (isset($opt['ifModifiedSince']))
  2857. {
  2858. $opt['headers']['x-amz-copy-source-if-modified-since'] = $opt['ifModifiedSince'];
  2859. unset($opt['ifModifiedSince']);
  2860. }
  2861. // Partial content range
  2862. if (isset($opt['range']))
  2863. {
  2864. $opt['headers']['x-amz-copy-source-range'] = 'bytes=' . $opt['range'];
  2865. }
  2866. // Authenticate to S3
  2867. return $this->authenticate($dest['bucket'], $opt);
  2868. }
  2869. /**
  2870. * Creates an Amazon S3 object using the multipart upload APIs. It is analogous to <create_object()>.
  2871. *
  2872. * While each individual part of a multipart upload can hold up to 5 GB of data, this method limits the
  2873. * part size to a maximum of 500 MB. The combined size of all parts can not exceed 5 TB of data. When an
  2874. * object is stored in Amazon S3, the data is streamed to multiple storage servers in multiple data
  2875. * centers. This ensures the data remains available in the event of internal network or hardware failure.
  2876. *
  2877. * Amazon S3 charges for storage as well as requests to the service. Smaller part sizes (and more
  2878. * requests) allow for faster failures and better upload reliability. Larger part sizes (and fewer
  2879. * requests) costs slightly less but has lower upload reliability.
  2880. *
  2881. * In certain cases with large objects, it's possible for this method to attempt to open more file system
  2882. * connections than allowed by the OS. In this case, either
  2883. * <a href="https://forums.aws.amazon.com/thread.jspa?threadID=70216">increase the number of connections
  2884. * allowed</a> or increase the value of the <code>partSize</code> parameter to use a larger part size.
  2885. *
  2886. * @param string $bucket (Required) The name of the bucket to use.
  2887. * @param string $filename (Required) The file name for the object.
  2888. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  2889. * <li><code>fileUpload</code> - <code>string|resource</code> - Required - The URL/path for the file to upload, or an open resource.</li>
  2890. * <li><code>acl</code> - <code>string</code> - Optional - The ACL settings for the specified object. [Allowed values: <code>AmazonS3::ACL_PRIVATE</code>, <code>AmazonS3::ACL_PUBLIC</code>, <code>AmazonS3::ACL_OPEN</code>, <code>AmazonS3::ACL_AUTH_READ</code>, <code>AmazonS3::ACL_OWNER_READ</code>, <code>AmazonS3::ACL_OWNER_FULL_CONTROL</code>]. The default value is <code>ACL_PRIVATE</code>.</li>
  2891. * <li><code>contentType</code> - <code>string</code> - Optional - The type of content that is being sent in the body. The default value is <code>application/octet-stream</code>.</li>
  2892. * <li><code>headers</code> - <code>array</code> - Optional - The standard HTTP headers to send along in the request.</li>
  2893. * <li><code>length</code> - <code>integer</code> - Optional - The size of the object in bytes. For more information, see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13">RFC 2616, section 14.13</a>. The value can also be passed to the <code>header</code> option as <code>Content-Length</code>.</li>
  2894. * <li><code>limit</code> - <code>integer</code> - Optional - The maximum number of concurrent uploads done by cURL. Gets passed to <code>CFBatchRequest</code>.</li>
  2895. * <li><code>meta</code> - <code>array</code> - Optional - An associative array of key-value pairs. Any header starting with <code>x-amz-meta-:</code> is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB.</li>
  2896. * <li><code>partSize</code> - <code>integer</code> - Optional - The size of an individual part. The size may not be smaller than 5 MB or larger than 500 MB. The default value is 50 MB.</li>
  2897. * <li><code>seekTo</code> - <code>integer</code> - Optional - The starting position in bytes for the first piece of the file/stream to upload.</li>
  2898. * <li><code>storage</code> - <code>string</code> - Optional - Whether to use Standard or Reduced Redundancy storage. [Allowed values: <code>AmazonS3::STORAGE_STANDARD</code>, <code>AmazonS3::STORAGE_REDUCED</code>]. The default value is <code>STORAGE_STANDARD</code>.</li>
  2899. * <li><code>uploadId</code> - <code>string</code> - Optional - An upload ID identifying an existing multipart upload to use. If this option is not set, one will be created automatically.</li>
  2900. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  2901. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  2902. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  2903. * @link http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAccessPolicy.html REST Access Control Policy
  2904. */
  2905. public function create_mpu_object($bucket, $filename, $opt = null)
  2906. {
  2907. if ($this->use_batch_flow)
  2908. {
  2909. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  2910. }
  2911. if (!$opt) $opt = array();
  2912. // Handle content length. Can also be passed as an HTTP header.
  2913. if (isset($opt['length']))
  2914. {
  2915. $opt['headers']['Content-Length'] = $opt['length'];
  2916. unset($opt['length']);
  2917. }
  2918. if (!isset($opt['fileUpload']))
  2919. {
  2920. throw new S3_Exception('The `fileUpload` option is required in ' . __FUNCTION__ . '().');
  2921. }
  2922. elseif (is_resource($opt['fileUpload']))
  2923. {
  2924. $opt['limit'] = 1; // We can only read from this one resource.
  2925. $upload_position = isset($opt['seekTo']) ? (integer) $opt['seekTo'] : ftell($opt['fileUpload']);
  2926. $upload_filesize = isset($opt['headers']['Content-Length']) ? (integer) $opt['headers']['Content-Length'] : null;
  2927. if (!isset($upload_filesize) && $upload_position !== false)
  2928. {
  2929. $stats = fstat($opt['fileUpload']);
  2930. if ($stats && $stats['size'] >= 0)
  2931. {
  2932. $upload_filesize = $stats['size'] - $upload_position;
  2933. }
  2934. }
  2935. }
  2936. else
  2937. {
  2938. $upload_position = isset($opt['seekTo']) ? (integer) $opt['seekTo'] : 0;
  2939. if (isset($opt['headers']['Content-Length']))
  2940. {
  2941. $upload_filesize = (integer) $opt['headers']['Content-Length'];
  2942. }
  2943. else
  2944. {
  2945. $upload_filesize = filesize($opt['fileUpload']);
  2946. if ($upload_filesize !== false)
  2947. {
  2948. $upload_filesize -= $upload_position;
  2949. }
  2950. }
  2951. }
  2952. if ($upload_position === false || !isset($upload_filesize) || $upload_filesize === false || $upload_filesize < 0)
  2953. {
  2954. throw new S3_Exception('The size of `fileUpload` cannot be determined in ' . __FUNCTION__ . '().');
  2955. }
  2956. // Handle part size
  2957. if (isset($opt['partSize']))
  2958. {
  2959. // If less that 5 MB...
  2960. if ((integer) $opt['partSize'] < 5242880)
  2961. {
  2962. $opt['partSize'] = 5242880; // 5 MB
  2963. }
  2964. // If more than 500 MB...
  2965. elseif ((integer) $opt['partSize'] > 524288000)
  2966. {
  2967. $opt['partSize'] = 524288000; // 500 MB
  2968. }
  2969. }
  2970. else
  2971. {
  2972. $opt['partSize'] = 52428800; // 50 MB
  2973. }
  2974. // If the upload size is smaller than the piece size, failover to create_object().
  2975. if ($upload_filesize < $opt['partSize'] && !isset($opt['uploadId']))
  2976. {
  2977. return $this->create_object($bucket, $filename, $opt);
  2978. }
  2979. // Initiate multipart upload
  2980. if (isset($opt['uploadId']))
  2981. {
  2982. $upload_id = $opt['uploadId'];
  2983. }
  2984. else
  2985. {
  2986. // Compose options for initiate_multipart_upload().
  2987. $_opt = array();
  2988. foreach (array('contentType', 'acl', 'storage', 'headers', 'meta') as $param)
  2989. {
  2990. if (isset($opt[$param]))
  2991. {
  2992. $_opt[$param] = $opt[$param];
  2993. }
  2994. }
  2995. $upload = $this->initiate_multipart_upload($bucket, $filename, $_opt);
  2996. if (!$upload->isOK())
  2997. {
  2998. return $upload;
  2999. }
  3000. // Fetch the UploadId
  3001. $upload_id = (string) $upload->body->UploadId;
  3002. }
  3003. // Get the list of pieces
  3004. $pieces = $this->get_multipart_counts($upload_filesize, (integer) $opt['partSize']);
  3005. // Queue batch requests
  3006. $batch = new CFBatchRequest(isset($opt['limit']) ? (integer) $opt['limit'] : null);
  3007. foreach ($pieces as $i => $piece)
  3008. {
  3009. $this->batch($batch)->upload_part($bucket, $filename, $upload_id, array(
  3010. 'expect' => '100-continue',
  3011. 'fileUpload' => $opt['fileUpload'],
  3012. 'partNumber' => ($i + 1),
  3013. 'seekTo' => $upload_position + (integer) $piece['seekTo'],
  3014. 'length' => (integer) $piece['length'],
  3015. ));
  3016. }
  3017. // Send batch requests
  3018. $batch_responses = $this->batch($batch)->send();
  3019. if (!$batch_responses->areOK())
  3020. {
  3021. return $batch_responses;
  3022. }
  3023. // Compose completion XML
  3024. $parts = array();
  3025. foreach ($batch_responses as $i => $response)
  3026. {
  3027. $parts[] = array('PartNumber' => ($i + 1), 'ETag' => $response->header['etag']);
  3028. }
  3029. return $this->complete_multipart_upload($bucket, $filename, $upload_id, $parts);
  3030. }
  3031. /**
  3032. * Aborts all multipart uploads initiated before the specified date. This operation cannot be reversed.
  3033. *
  3034. * @param string $bucket (Required) The name of the bucket to use.
  3035. * @param string|integer $when (Optional) The time and date to use for comparison. Accepts any value that <php:strtotime()> understands.
  3036. * @return CFArray A <CFArray> containing a series of 0 or more <CFResponse> objects, containing a parsed HTTP response.
  3037. */
  3038. public function abort_multipart_uploads_by_date($bucket, $when = null)
  3039. {
  3040. if ($this->use_batch_flow)
  3041. {
  3042. // @codeCoverageIgnoreStart
  3043. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  3044. // @codeCoverageIgnoreEnd
  3045. }
  3046. $when = $when ? $when : time();
  3047. $handles = array();
  3048. $data = $this->list_multipart_uploads($bucket)->body;
  3049. $when = is_int($when) ? $when : strtotime($when);
  3050. if (!($data instanceof CFSimpleXML))
  3051. {
  3052. return false;
  3053. }
  3054. $list = $data->query('descendant-or-self::Upload/Initiated');
  3055. foreach ($list as $node)
  3056. {
  3057. if (strtotime((string) $node) < $when)
  3058. {
  3059. $q = new CFBatchRequest();
  3060. $parent = $node->parent();
  3061. $upload_id = $parent
  3062. ->query('descendant-or-self::UploadId')
  3063. ->first()
  3064. ->to_string();
  3065. $filename = $parent
  3066. ->query('descendant-or-self::Key')
  3067. ->first()
  3068. ->to_string();
  3069. $handles[] = $this->abort_multipart_upload($bucket, $filename, $upload_id, array(
  3070. 'returnCurlHandle' => true
  3071. ));
  3072. }
  3073. }
  3074. $http = new CFRequest();
  3075. $responses = $http->send_multi_request($handles);
  3076. return new CFArray($responses);
  3077. }
  3078. /*%******************************************************************************************%*/
  3079. // WEBSITE CONFIGURATION
  3080. /**
  3081. * Enables and configures an Amazon S3 website using the corresponding bucket as the content source.
  3082. * The website will have one default domain name associated with it, which is the bucket name. If you
  3083. * attempt to configure an Amazon S3 website for a bucket whose name is not compatible with DNS,
  3084. * Amazon S3 returns an <code>InvalidBucketName</code> error. For more information on bucket names and DNS,
  3085. * refer to <a href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/BucketRestrictions.html">Bucket Restrictions and Limitations.</a>
  3086. *
  3087. * To visit the bucket as a website a new endpoint is created in the following pattern:
  3088. * <code>http://&lt;bucketName&gt;.s3-website-&lt;region&gt;.amazonaws.com</code>. This is a sample URL
  3089. * for a bucket called <code>example-bucket</code> in the <code>us-east-1</code> region.
  3090. * (e.g., <code>http://example-bucket.s3-website-us-east-1.amazonaws.com</code>)
  3091. *
  3092. * @param string $bucket (Required) The name of the bucket to use.
  3093. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  3094. * <li><code>indexDocument</code> - <code>string</code> - Optional - The file path to use as the root document. The default value is <code>index.html</code>.</li>
  3095. * <li><code>errorDocument</code> - <code>string</code> - Optional - The file path to use as the error document. The default value is <code>error.html</code>.</li>
  3096. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  3097. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  3098. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  3099. */
  3100. public function create_website_config($bucket, $opt = null)
  3101. {
  3102. if (!$opt) $opt = array();
  3103. $opt['verb'] = 'PUT';
  3104. $opt['sub_resource'] = 'website';
  3105. $xml = simplexml_load_string($this->website_config_xml);
  3106. if (isset($opt['indexDocument']))
  3107. {
  3108. $xml->IndexDocument->Suffix = $opt['indexDocument'];
  3109. }
  3110. if (isset($opt['errorDocument']))
  3111. {
  3112. $xml->ErrorDocument->Key = $opt['errorDocument'];
  3113. }
  3114. $opt['body'] = $xml->asXML();
  3115. // Authenticate to S3
  3116. return $this->authenticate($bucket, $opt);
  3117. }
  3118. /**
  3119. * Retrieves the website configuration for a bucket. The contents of this response are identical to the
  3120. * content submitted by the user during the website creation operation. If a website configuration has
  3121. * never been set, Amazon S3 will return a 404 error.
  3122. *
  3123. * @param string $bucket (Required) The name of the bucket to use.
  3124. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  3125. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  3126. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  3127. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  3128. */
  3129. public function get_website_config($bucket, $opt = null)
  3130. {
  3131. if (!$opt) $opt = array();
  3132. $opt['verb'] = 'GET';
  3133. $opt['sub_resource'] = 'website';
  3134. $opt['headers'] = array(
  3135. 'Content-Type' => 'application/xml'
  3136. );
  3137. // Authenticate to S3
  3138. return $this->authenticate($bucket, $opt);
  3139. }
  3140. /**
  3141. * Removes the website configuration for a bucket.
  3142. *
  3143. * @param string $bucket (Required) The name of the bucket to use.
  3144. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
  3145. * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
  3146. * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
  3147. * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
  3148. */
  3149. public function delete_website_config($bucket, $opt = null)
  3150. {
  3151. if (!$opt) $opt = array();
  3152. $opt['verb'] = 'DELETE';
  3153. $opt['sub_resource'] = 'website';
  3154. // Authenticate to S3
  3155. return $this->authenticate($bucket, $opt);
  3156. }
  3157. /*%******************************************************************************************%*/
  3158. // MISCELLANEOUS
  3159. /**
  3160. * Gets the canonical user ID and display name from the Amazon S3 server.
  3161. *
  3162. * @return array An associative array containing the `id` and `display_name` values.
  3163. */
  3164. public function get_canonical_user_id()
  3165. {
  3166. if ($this->use_batch_flow)
  3167. {
  3168. throw new S3_Exception(__FUNCTION__ . '() cannot be batch requested');
  3169. }
  3170. $id = $this->list_buckets();
  3171. return array(
  3172. 'id' => (string) $id->body->Owner->ID,
  3173. 'display_name' => (string) $id->body->Owner->DisplayName
  3174. );
  3175. }
  3176. }