PageRenderTime 73ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/backupbuddy/destinations/stash/lib/aws-sdk/services/s3.class.php

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