PageRenderTime 71ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/sdk-1.5.5/services/s3.class.php

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