PageRenderTime 60ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/vendors/aws-sdk/services/s3.class.php

http://github.com/joebeeson/amazon
PHP | 3637 lines | 1508 code | 394 blank | 1735 comment | 241 complexity | c27938cdc812a42fe8018ad9cde9286e MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * Copyright 2010 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. * File: AmazonS3
  18. * Amazon S3 is a web service that enables you to store data in the cloud. You can then download the data
  19. * or use the data with other AWS services, such as Amazon Elastic Cloud Computer (EC2).
  20. *
  21. * Amazon Simple Storage Service (Amazon S3) is storage for the Internet. You can use Amazon S3 to store
  22. * and retrieve any amount of data at any time, from anywhere on the web. You can accomplish these tasks
  23. * using the AWS Management Console, which is a simple and intuitive web interface.
  24. *
  25. * To get the most out of Amazon S3, you need to understand a few simple concepts. Amazon S3 stores data
  26. * as objects in buckets. An object is comprised of a file and optionally any metadata that describes
  27. * that file.
  28. *
  29. * To store an object in Amazon S3, you upload the file you want to store to a bucket. When you upload a
  30. * file, you can set permissions on the object as well as any metadata.
  31. *
  32. * Buckets are the containers for objects. You can have one or more buckets. For each bucket, you can control
  33. * access to the bucket (who can create, delete, and list objects in the bucket), view access logs for the
  34. * bucket and its objects, and choose the geographical region where Amazon S3 will store the bucket and its
  35. * contents.
  36. *
  37. * Visit <http://aws.amazon.com/s3/> for more information.
  38. *
  39. * Version:
  40. * 2010.12.02
  41. *
  42. * License and Copyright:
  43. * See the included NOTICE.md file for more information.
  44. *
  45. * See Also:
  46. * [Amazon Simple Storage Service](http://aws.amazon.com/s3/)
  47. * [Amazon Simple Storage Service documentation](http://aws.amazon.com/documentation/s3/)
  48. */
  49. /*%******************************************************************************************%*/
  50. // EXCEPTIONS
  51. /**
  52. * Exception: S3_Exception
  53. * Default S3 Exception.
  54. */
  55. class S3_Exception extends Exception {}
  56. /*%******************************************************************************************%*/
  57. // MAIN CLASS
  58. /**
  59. * Class: AmazonS3
  60. * Container for all Amazon S3-related methods. Inherits additional methods from CFRuntime.
  61. */
  62. class AmazonS3 extends CFRuntime
  63. {
  64. /*%******************************************************************************************%*/
  65. // CLASS CONSTANTS
  66. /**
  67. * Constant: DEFAULT_URL
  68. * The default endpoint.
  69. */
  70. const DEFAULT_URL = 's3.amazonaws.com';
  71. /**
  72. * Constant: REGION_US_E1
  73. * Specify the queue URL for the US-East (Northern Virginia) Region.
  74. */
  75. const REGION_US_E1 = '';
  76. /**
  77. * Constant: REGION_US_W1
  78. * Specify the queue URL for the US-West (Northern California) Region.
  79. */
  80. const REGION_US_W1 = 'us-west-1';
  81. /**
  82. * Constant: REGION_EU_W1
  83. * Specify the queue URL for the EU (Ireland) Region.
  84. */
  85. const REGION_EU_W1 = 'EU';
  86. /**
  87. * Constant: REGION_APAC_SE1
  88. * Specify the queue URL for the Asia Pacific (Singapore) Region.
  89. */
  90. const REGION_APAC_SE1 = 'ap-southeast-1';
  91. /**
  92. * Constant: ACL_PRIVATE
  93. * ACL: Owner-only read/write.
  94. */
  95. const ACL_PRIVATE = 'private';
  96. /**
  97. * Constant: ACL_PUBLIC
  98. * ACL: Owner read/write, public read.
  99. */
  100. const ACL_PUBLIC = 'public-read';
  101. /**
  102. * Constant: ACL_OPEN
  103. * ACL: Public read/write.
  104. */
  105. const ACL_OPEN = 'public-read-write';
  106. /**
  107. * Constant: ACL_AUTH_READ
  108. * ACL: Owner read/write, authenticated read.
  109. */
  110. const ACL_AUTH_READ = 'authenticated-read';
  111. /**
  112. * Constant: ACL_OWNER_READ
  113. * ACL: Bucket owner read.
  114. */
  115. const ACL_OWNER_READ = 'bucket-owner-read';
  116. /**
  117. * Constant: ACL_OWNER_FULL_CONTROL
  118. * ACL: Bucket owner full control.
  119. */
  120. const ACL_OWNER_FULL_CONTROL = 'bucket-owner-full-control';
  121. /**
  122. * Constant: GRANT_READ
  123. * When applied to a bucket, grants permission to list the bucket. When applied to an object, this
  124. * grants permission to read the object data and/or metadata.
  125. */
  126. const GRANT_READ = 'READ';
  127. /**
  128. * Constant: GRANT_WRITE
  129. * When applied to a bucket, grants permission to create, overwrite, and delete any object in the
  130. * bucket. This permission is not supported for objects.
  131. */
  132. const GRANT_WRITE = 'WRITE';
  133. /**
  134. * Constant: GRANT_READ_ACP
  135. * Grants permission to read the ACL for the applicable bucket or object. The owner of a bucket or
  136. * object always has this permission implicitly.
  137. */
  138. const GRANT_READ_ACP = 'READ_ACP';
  139. /**
  140. * Constant: GRANT_WRITE_ACP
  141. * Gives permission to overwrite the ACP for the applicable bucket or object. The owner of a bucket
  142. * or object always has this permission implicitly. Granting this permission is equivalent to granting
  143. * FULL_CONTROL because the grant recipient can make any changes to the ACP.
  144. */
  145. const GRANT_WRITE_ACP = 'WRITE_ACP';
  146. /**
  147. * Constant: GRANT_FULL_CONTROL
  148. * Provides READ, WRITE, READ_ACP, and WRITE_ACP permissions. It does not convey additional rights and
  149. * is provided only for convenience.
  150. */
  151. const GRANT_FULL_CONTROL = 'FULL_CONTROL';
  152. /**
  153. * Constant: USERS_AUTH
  154. * The "AuthenticatedUsers" group for access control policies.
  155. */
  156. const USERS_AUTH = 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers';
  157. /**
  158. * Constant: USERS_ALL
  159. * The "AllUsers" group for access control policies.
  160. */
  161. const USERS_ALL = 'http://acs.amazonaws.com/groups/global/AllUsers';
  162. /**
  163. * Constant: USERS_LOGGING
  164. * The "LogDelivery" group for access control policies.
  165. */
  166. const USERS_LOGGING = 'http://acs.amazonaws.com/groups/s3/LogDelivery';
  167. /**
  168. * Constant: PCRE_ALL
  169. * PCRE: Match all items
  170. */
  171. const PCRE_ALL = '/.*/i';
  172. /**
  173. * Constant: STORAGE_STANDARD
  174. * Standard storage redundancy.
  175. */
  176. const STORAGE_STANDARD = 'STANDARD';
  177. /**
  178. * Constant: STORAGE_REDUCED
  179. * Reduced storage redundancy.
  180. */
  181. const STORAGE_REDUCED = 'REDUCED_REDUNDANCY';
  182. /*%******************************************************************************************%*/
  183. // PROPERTIES
  184. /**
  185. * Property: request_url
  186. * The request URL.
  187. */
  188. public $request_url;
  189. /**
  190. * Property: vhost
  191. * The virtual host setting.
  192. */
  193. public $vhost;
  194. /**
  195. * Property: base_acp_xml
  196. * The base XML elements to use for access control policy methods.
  197. */
  198. public $base_acp_xml;
  199. /**
  200. * Property: base_logging_xml
  201. * The base XML elements to use for logging methods.
  202. */
  203. public $base_logging_xml;
  204. /**
  205. * Property: base_notification_xml
  206. * The base XML elements to use for notifications.
  207. */
  208. public $base_notification_xml;
  209. /**
  210. * Property: base_versioning_xml
  211. * The base XML elements to use for versioning.
  212. */
  213. public $base_versioning_xml;
  214. /**
  215. * Property: complete_mpu_xml
  216. * The base XML elements to use for completing a multipart upload.
  217. */
  218. public $complete_mpu_xml;
  219. /**
  220. * Property: path_style
  221. * The DNS vs. Path-style setting.
  222. */
  223. public $path_style = false;
  224. /*%******************************************************************************************%*/
  225. // CONSTRUCTOR
  226. /**
  227. * Method: __construct()
  228. * Constructs a new instance of <AmazonS3>.
  229. *
  230. * Access:
  231. * public
  232. *
  233. * Parameters:
  234. * $key - _string_ (Optional) Amazon API Key. If blank, the <AWS_KEY> constant is used.
  235. * $secret_key - _string_ (Optional) Amazon API Secret Key. If blank, the <AWS_SECRET_KEY> constant is used.
  236. *
  237. * Returns:
  238. * _boolean_ A value of `false` if no valid values are set, otherwise `true`.
  239. */
  240. public function __construct($key = null, $secret_key = null)
  241. {
  242. $this->vhost = null;
  243. $this->api_version = '2006-03-01';
  244. $this->hostname = self::DEFAULT_URL;
  245. $this->base_acp_xml = '<?xml version="1.0" encoding="UTF-8"?><AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/latest/"></AccessControlPolicy>';
  246. $this->base_location_constraint = '<?xml version="1.0" encoding="UTF-8"?><CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint></LocationConstraint></CreateBucketConfiguration>';
  247. $this->base_logging_xml = '<?xml version="1.0" encoding="utf-8"?><BucketLoggingStatus xmlns="http://doc.s3.amazonaws.com/' . $this->api_version . '"></BucketLoggingStatus>';
  248. $this->base_notification_xml = '<?xml version="1.0" encoding="utf-8"?><NotificationConfiguration></NotificationConfiguration>';
  249. $this->base_versioning_xml = '<?xml version="1.0" encoding="utf-8"?><VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"></VersioningConfiguration>';
  250. $this->complete_mpu_xml = '<?xml version="1.0" encoding="utf-8"?><CompleteMultipartUpload></CompleteMultipartUpload>';
  251. if (!$key && !defined('AWS_KEY'))
  252. {
  253. throw new S3_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.');
  254. }
  255. if (!$secret_key && !defined('AWS_SECRET_KEY'))
  256. {
  257. throw new S3_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.');
  258. }
  259. return parent::__construct($key, $secret_key);
  260. }
  261. /*%******************************************************************************************%*/
  262. // AUTHENTICATION
  263. /**
  264. * Method: authenticate()
  265. * Authenticates a connection to Amazon S3. Do not use directly unless implementing custom methods for
  266. * this class.
  267. *
  268. * Access:
  269. * public
  270. *
  271. * Parameters:
  272. * $bucket - _string_ (Required) The name of the bucket to use.
  273. * $opt - _array_ (Optional) An associative array of parameters for authenticating. See the individual methods for allowed keys.
  274. * $location - _string_ (Do Not Use) Used internally by this function on occasions when Amazon S3 returns a redirect code and it needs to call itself recursively.
  275. * $redirects - _integer_ (Do Not Use) Used internally by this function on occasions when Amazon S3 returns a redirect code and it needs to call itself recursively.
  276. *
  277. * Returns:
  278. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  279. *
  280. * See Also:
  281. * [REST authentication](http://docs.amazonwebservices.com/AmazonS3/latest/RESTAuthentication.html)
  282. */
  283. public function authenticate($bucket, $opt = null, $location = null, $redirects = 0, $nothing = null)
  284. {
  285. /*
  286. * Overriding or extending this class? You can pass the following "magic" keys into $opt.
  287. *
  288. * ## verb, resource, sub_resource and query_string ##
  289. * <verb> /<resource>?<sub_resource>&<query_string>
  290. * GET /filename.txt?versions&prefix=abc&max-items=1
  291. *
  292. * ## versionId, uploadId, partNumber ##
  293. * These don't follow the same rules as above, in that the they needs to be signed, while
  294. * other query_string values do not.
  295. *
  296. * ## curlopts ##
  297. * These values get passed directly to the cURL methods in RequestCore.
  298. *
  299. * ## fileUpload, fileDownload, seekTo, length ##
  300. * These are slightly modified and then passed to the cURL methods in RequestCore.
  301. *
  302. * ## headers ##
  303. * $opt['headers'] is an array, whose keys are HTTP headers to be sent.
  304. *
  305. * ## body ##
  306. * This is the request body that is sent to the server via PUT/POST.
  307. *
  308. * ## preauth ##
  309. * This is a hook that tells authenticate() to generate a pre-authenticated URL.
  310. *
  311. * ## returnCurlHandle ##
  312. * Tells authenticate() to return the cURL handle for the request instead of executing it.
  313. */
  314. /**
  315. * @todo: Handle duplicate headers with different values.
  316. */
  317. // Validate the S3 bucket name
  318. if (!$this->validate_bucketname_support($bucket))
  319. {
  320. 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.');
  321. }
  322. // Die if $opt isn't set.
  323. if (!$opt) return false;
  324. $method_arguments = func_get_args();
  325. // Use the caching flow to determine if we need to do a round-trip to the server.
  326. if ($this->use_cache_flow)
  327. {
  328. // Generate an identifier specific to this particular set of arguments.
  329. $cache_id = $this->key . '_' . get_class($this) . '_' . $bucket . '_' . sha1(serialize($method_arguments));
  330. // Instantiate the appropriate caching object.
  331. $this->cache_object = new $this->cache_class($cache_id, $this->cache_location, $this->cache_expires, $this->cache_compress);
  332. if ($this->delete_cache)
  333. {
  334. $this->use_cache_flow = false;
  335. $this->delete_cache = false;
  336. return $this->cache_object->delete();
  337. }
  338. // Invoke the cache callback function to determine whether to pull data from the cache or make a fresh request.
  339. $data = $this->cache_object->response_manager(array($this, 'cache_callback'), $method_arguments);
  340. // Parse the XML body
  341. $data = $this->parse_callback($data);
  342. // End!
  343. return $data;
  344. }
  345. // If we haven't already set a resource prefix...
  346. if (!$this->resource_prefix || $this->path_style)
  347. {
  348. // And if the bucket name isn't DNS-valid...
  349. if (!$this->validate_bucketname_create($bucket) || $this->path_style)
  350. {
  351. // Fall back to the older path-style URI
  352. $this->set_resource_prefix('/' . $bucket);
  353. }
  354. }
  355. // Determine hostname
  356. $scheme = $this->use_ssl ? 'https://' : 'http://';
  357. if ($this->resource_prefix || $this->path_style) // Use bucket-in-path method.
  358. {
  359. $hostname = $this->hostname . $this->resource_prefix . (($bucket === '' || $this->resource_prefix === '/' . $bucket) ? '' : ('/' . $bucket));
  360. }
  361. else
  362. {
  363. $hostname = $this->vhost ? $this->vhost : (($bucket === '') ? $this->hostname : ($bucket . '.') . $this->hostname);
  364. }
  365. // Get the UTC timestamp in RFC 2616 format
  366. $date = gmdate($this->util->konst($this->util, 'DATE_FORMAT_RFC2616'), (time() + (integer) $this->adjust_offset));
  367. // Storage for request parameters.
  368. $resource = '';
  369. $sub_resource = '';
  370. $query_string_params = array();
  371. $signable_query_string_params = array();
  372. $string_to_sign = '';
  373. $headers = array(
  374. 'Content-MD5' => '',
  375. 'Content-Type' => 'application/x-www-form-urlencoded',
  376. 'Date' => $date
  377. );
  378. /*%******************************************************************************************%*/
  379. // Handle specific resources
  380. if (isset($opt['resource']))
  381. {
  382. $resource .= $opt['resource'];
  383. }
  384. // Merge query string values
  385. if (isset($opt['query_string']))
  386. {
  387. $query_string_params = array_merge($query_string_params, $opt['query_string']);
  388. }
  389. $query_string = $this->util->to_query_string($query_string_params);
  390. // Merge the signable query string values. Must be alphabetical.
  391. if (isset($opt['partNumber']))
  392. {
  393. $signable_query_string_params['partNumber'] = rawurlencode($opt['partNumber']);
  394. }
  395. if (isset($opt['uploadId']))
  396. {
  397. $signable_query_string_params['uploadId'] = rawurlencode($opt['uploadId']);
  398. }
  399. if (isset($opt['versionId']))
  400. {
  401. $signable_query_string_params['versionId'] = rawurlencode($opt['versionId']);
  402. }
  403. // ksort($signable_query_string_params);
  404. $signable_query_string = $this->util->to_query_string($signable_query_string_params);
  405. // Merge the HTTP headers
  406. if (isset($opt['headers']))
  407. {
  408. $headers = array_merge($headers, $opt['headers']);
  409. }
  410. // Compile the URI to request
  411. $conjunction = '?';
  412. $signable_resource = '/' . rawurlencode($resource);
  413. $non_signable_resource = '';
  414. if (isset($opt['sub_resource']))
  415. {
  416. $signable_resource .= $conjunction . rawurlencode($opt['sub_resource']);
  417. $conjunction = '&';
  418. }
  419. if ($signable_query_string !== '')
  420. {
  421. $signable_resource .= $conjunction . $signable_query_string;
  422. $conjunction = '&';
  423. }
  424. if ($query_string !== '')
  425. {
  426. $non_signable_resource .= $conjunction . $query_string;
  427. $conjunction = '&';
  428. }
  429. $this->request_url = $scheme . $hostname . $signable_resource . $non_signable_resource;
  430. // Instantiate the request class
  431. $request = new $this->request_class($this->request_url, $this->proxy);
  432. // Update RequestCore settings
  433. $request->request_class = $this->request_class;
  434. $request->response_class = $this->response_class;
  435. // Streaming uploads
  436. if (isset($opt['fileUpload']))
  437. {
  438. if (is_resource($opt['fileUpload']))
  439. {
  440. $request->set_read_stream($opt['fileUpload'], isset($opt['length']) ? $opt['length'] : -1);
  441. if ($headers['Content-Type'] === 'application/x-www-form-urlencoded')
  442. {
  443. $headers['Content-Type'] = 'application/octet-stream';
  444. }
  445. }
  446. else
  447. {
  448. $request->set_read_file($opt['fileUpload']);
  449. // Attempt to guess the correct mime-type
  450. if ($headers['Content-Type'] === 'application/x-www-form-urlencoded')
  451. {
  452. $extension = explode('.', $opt['fileUpload']);
  453. $extension = array_pop($extension);
  454. $mime_type = CFMimeTypes::get_mimetype($extension);
  455. $headers['Content-Type'] = $mime_type;
  456. }
  457. }
  458. $headers['Content-Length'] = $request->read_stream_size;
  459. $curlopts[CURLOPT_INFILESIZE] = $headers['Content-Length'];
  460. $headers['Content-MD5'] = '';
  461. }
  462. // Streaming downloads
  463. if (isset($opt['fileDownload']))
  464. {
  465. if (is_resource($opt['fileDownload']))
  466. {
  467. $request->set_write_stream($opt['fileDownload']);
  468. }
  469. else
  470. {
  471. $request->set_write_file($opt['fileDownload']);
  472. }
  473. }
  474. $curlopts = array();
  475. // Set custom CURLOPT settings
  476. if (isset($opt['curlopts']))
  477. {
  478. $curlopts = $opt['curlopts'];
  479. unset($opt['curlopts']);
  480. }
  481. // Debug mode
  482. if ($this->debug_mode)
  483. {
  484. $curlopts[CURLOPT_VERBOSE] = true;
  485. }
  486. // Handle streaming file offsets
  487. if (isset($opt['seekTo']))
  488. {
  489. // Pass the seek position to RequestCore
  490. $request->set_seek_position((integer) $opt['seekTo']);
  491. $headers['Content-Length'] = (!is_resource($opt['fileUpload']) ? (filesize($opt['fileUpload']) - (integer) $opt['seekTo']) : -1);
  492. $curlopts[CURLOPT_INFILESIZE] = $headers['Content-Length'];
  493. }
  494. // Override the content length
  495. if (isset($opt['length']))
  496. {
  497. $headers['Content-Length'] = (integer) $opt['length'];
  498. $curlopts[CURLOPT_INFILESIZE] = $headers['Content-Length'];
  499. }
  500. // Set the curl options.
  501. if (count($curlopts))
  502. {
  503. $request->set_curlopts($curlopts);
  504. }
  505. // Do we have a verb?
  506. if (isset($opt['verb']))
  507. {
  508. $request->set_method($opt['verb']);
  509. $string_to_sign .= $opt['verb'] . "\n";
  510. }
  511. // Add headers and content when we have a body
  512. if (isset($opt['body']))
  513. {
  514. $request->set_body($opt['body']);
  515. $headers['Content-Length'] = strlen($opt['body']);
  516. if ($headers['Content-Type'] === 'application/x-www-form-urlencoded')
  517. {
  518. $headers['Content-Type'] = 'application/octet-stream';
  519. }
  520. if (!isset($opt['NoContentMD5']) || $opt['NoContentMD5'] !== true)
  521. {
  522. $headers['Content-MD5'] = $this->util->hex_to_base64(md5($opt['body']));
  523. }
  524. }
  525. // Handle query-string authentication
  526. if (isset($opt['preauth']) && (integer) $opt['preauth'] > 0)
  527. {
  528. unset($headers['Date']);
  529. $headers['Content-Type'] = '';
  530. $headers['Expires'] = strtotime($opt['preauth']);
  531. }
  532. // Sort headers
  533. uksort($headers, 'strnatcasecmp');
  534. // Add headers to request and compute the string to sign
  535. foreach ($headers as $header_key => $header_value)
  536. {
  537. // Strip linebreaks from header values as they're illegal and can allow for security issues
  538. $header_value = str_replace(array("\r", "\n"), '', $header_value);
  539. // Add the header if it has a value
  540. if ($header_value !== '')
  541. {
  542. $request->add_header($header_key, $header_value);
  543. }
  544. // Generate the string to sign
  545. if (
  546. strtolower($header_key) === 'content-md5' ||
  547. strtolower($header_key) === 'content-type' ||
  548. strtolower($header_key) === 'date' ||
  549. (strtolower($header_key) === 'expires' && isset($opt['preauth']) && (integer) $opt['preauth'] > 0)
  550. )
  551. {
  552. $string_to_sign .= $header_value . "\n";
  553. }
  554. elseif (substr(strtolower($header_key), 0, 6) === 'x-amz-')
  555. {
  556. $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n";
  557. }
  558. }
  559. // Add the signable resource location
  560. $string_to_sign .= ($this->resource_prefix ? $this->resource_prefix : '');
  561. $string_to_sign .= (($bucket === '' || $this->resource_prefix === '/' . $bucket) ? '' : ('/' . $bucket)) . $signable_resource;
  562. // Hash the AWS secret key and generate a signature for the request.
  563. $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->secret_key, true));
  564. $request->add_header('Authorization', 'AWS ' . $this->key . ':' . $signature);
  565. // If we're generating a URL, return certain data to the calling method.
  566. if (isset($opt['preauth']) && (integer) $opt['preauth'] > 0)
  567. {
  568. return $this->request_url . (isset($opt['sub_resource']) ? '&' : '?') . 'AWSAccessKeyId=' . $this->key . '&Expires=' . $headers['Expires'] . '&Signature=' . rawurlencode($signature);
  569. }
  570. elseif (isset($opt['preauth']))
  571. {
  572. return $this->request_url;
  573. }
  574. /*%******************************************************************************************%*/
  575. // Manage the (newer) batch request API or the (older) returnCurlHandle setting.
  576. if ($this->use_batch_flow)
  577. {
  578. $handle = $request->prep_request();
  579. $this->batch_object->add($handle);
  580. $this->use_batch_flow = false;
  581. return $handle;
  582. }
  583. elseif (isset($opt['returnCurlHandle']) && $opt['returnCurlHandle'] === true)
  584. {
  585. return $request->prep_request();
  586. }
  587. // Send!
  588. $request->send_request();
  589. // Prepare the response
  590. $headers = $request->get_response_header();
  591. $headers['x-aws-request-url'] = $this->request_url;
  592. $headers['x-aws-redirects'] = $redirects;
  593. $headers['x-aws-stringtosign'] = $string_to_sign;
  594. $headers['x-aws-requestheaders'] = $request->request_headers;
  595. // Did we have a request body?
  596. if (isset($opt['body']))
  597. {
  598. $headers['x-aws-requestbody'] = $opt['body'];
  599. }
  600. $data = new $this->response_class($headers, $this->parse_callback($request->get_response_body()), $request->get_response_code());
  601. // Did Amazon tell us to redirect? Typically happens for multiple rapid requests EU datacenters.
  602. // @see: http://docs.amazonwebservices.com/AmazonS3/latest/Redirects.html
  603. if ((integer) $request->get_response_code() === 307) // Temporary redirect to new endpoint.
  604. {
  605. $data = $this->authenticate($bucket, $opt, $headers['location'], ++$redirects);
  606. }
  607. // Was it Amazon's fault the request failed? Retry the request until we reach $max_retries.
  608. elseif ((integer) $request->get_response_code() === 500 || (integer) $request->get_response_code() === 503)
  609. {
  610. if ($redirects <= $this->max_retries)
  611. {
  612. // Exponential backoff
  613. $delay = (integer) (pow(4, $redirects) * 100000);
  614. usleep($delay);
  615. $data = $this->authenticate($bucket, $opt, null, ++$redirects);
  616. }
  617. }
  618. // Return!
  619. return $data;
  620. }
  621. /**
  622. * Method: validate_bucketname_create()
  623. * Validates whether or not the specified Amazon S3 bucket name is valid for DNS-style access. This
  624. * method is leveraged by any method that creates buckets.
  625. *
  626. * Access:
  627. * public
  628. *
  629. * Parameters:
  630. * $bucket - _string_ (Required) The name of the bucket to validate.
  631. *
  632. * Returns:
  633. * _boolean_ Whether or not the specified Amazon S3 bucket name is valid for DNS-style access. A value of `true` means that the bucket name is valid. A value of `false` means that the bucket name is invalid.
  634. */
  635. public function validate_bucketname_create($bucket)
  636. {
  637. // list_buckets() uses this. Let it pass.
  638. if ($bucket === '') return true;
  639. if (
  640. ($bucket === null || $bucket === false) || // Must not be null or false
  641. preg_match('/[^(a-z0-9\-\.)]/', $bucket) || // Must be in the lowercase Roman alphabet, period or hyphen
  642. !preg_match('/^([a-z]|\d)/', $bucket) || // Must start with a number or letter
  643. !(strlen($bucket) >= 3 && strlen($bucket) <= 63) || // Must be between 3 and 63 characters long
  644. (strpos($bucket, '..') !== false) || // Bucket names cannot contain two, adjacent periods
  645. (strpos($bucket, '-.') !== false) || // Bucket names cannot contain dashes next to periods
  646. (strpos($bucket, '.-') !== false) || // Bucket names cannot contain dashes next to periods
  647. preg_match('/(-|\.)$/', $bucket) || // Bucket names should not end with a dash or period
  648. preg_match('/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/', $bucket) // Must not be formatted as an IP address
  649. ) return false;
  650. return true;
  651. }
  652. /**
  653. * Method: validate_bucketname_support()
  654. * Validates whether or not the specified Amazon S3 bucket name is valid for path-style access. This
  655. * method is leveraged by any method that reads from buckets.
  656. *
  657. * Access:
  658. * public
  659. *
  660. * Parameters:
  661. * $bucket - _string_ (Required) The name of the bucket to validate.
  662. *
  663. * Returns:
  664. * _boolean_ Whether or not the bucket name is valid. A value of `true` means that the bucket name is valid. A valuf of `false` means that the bucket name is invalid.
  665. */
  666. public function validate_bucketname_support($bucket)
  667. {
  668. // list_buckets() uses this. Let it pass.
  669. if ($bucket === '') return true;
  670. // Validate
  671. if (
  672. ($bucket === null || $bucket === false) || // Must not be null or false
  673. preg_match('/[^(a-z0-9_\-\.)]/i', $bucket) || // Must be in the Roman alphabet, period, hyphen or underscore
  674. !preg_match('/^([a-z]|\d)/i', $bucket) || // Must start with a number or letter
  675. !(strlen($bucket) >= 3 && strlen($bucket) <= 255) || // Must be between 3 and 255 characters long
  676. preg_match('/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/', $bucket) // Must not be formatted as an IP address
  677. ) return false;
  678. return true;
  679. }
  680. /**
  681. * Method: cache_callback()
  682. * The callback function that is executed when the cache doesn't exist or has expired. The response of
  683. * this method is cached. Accepts identical parameters as the <authenticate()> method. Never call this
  684. * method directly -- it is used internally by the caching system.
  685. *
  686. * Access:
  687. * public
  688. *
  689. * Parameters:
  690. * $bucket - _string_ (Required) The name of the bucket to use.
  691. * $opt - _array_ (Optional) An associative array of parameters for authenticating. See the individual methods for allowed keys.
  692. * $location - _string_ (Optional) Used internally by this method when Amazon S3 returns a redirect code and needs to call itself recursively.
  693. * $redirects - _integer_ (Optional) Used internally by this method when Amazon S3 returns a redirect code and needs to call itself recursively.
  694. *
  695. * Returns:
  696. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  697. */
  698. public function cache_callback($bucket, $opt = null, $location = null, $redirects = 0)
  699. {
  700. // Disable the cache flow since it's already been handled.
  701. $this->use_cache_flow = false;
  702. // Make the request
  703. $response = $this->authenticate($bucket, $opt, $location, $redirects);
  704. if (isset($response->body) && ($response->body instanceof SimpleXMLElement))
  705. {
  706. $response->body = $response->body->asXML();
  707. }
  708. return $response;
  709. }
  710. /*%******************************************************************************************%*/
  711. // SETTERS
  712. /**
  713. * Method: set_region()
  714. * Sets the region to use for subsequent Amazon S3 operations. This will also reset any prior use of
  715. * <enable_path_style()>.
  716. *
  717. * Access:
  718. * public
  719. *
  720. * Parameters:
  721. * $region - _string_ (Required) The region to use for subsequent Amazon S3 operations. [Allowed values: `AmazonS3::REGION_US_E1 `, `AmazonS3::REGION_US_W1`, `AmazonS3::REGION_EU_W1`, `AmazonS3::REGION_APAC_SE1`]
  722. *
  723. * Returns:
  724. * `$this` A reference to the current instance.
  725. */
  726. public function set_region($region)
  727. {
  728. switch ($region)
  729. {
  730. case self::REGION_US_W1: // Northern California
  731. case self::REGION_APAC_SE1: // Singapore
  732. $this->set_hostname('s3-' . $region . '.amazonaws.com');
  733. $this->enable_path_style(false);
  734. break;
  735. case self::REGION_EU_W1: // Ireland
  736. $this->set_hostname('s3-eu-west-1.amazonaws.com');
  737. $this->enable_path_style(); // Always use path-style access for EU endpoint.
  738. break;
  739. default:
  740. // REGION_US_E1 // Northern Virginia
  741. $this->set_hostname(self::DEFAULT_URL);
  742. $this->enable_path_style(false);
  743. break;
  744. }
  745. return $this;
  746. }
  747. /**
  748. * Method: set_vhost()
  749. * Sets the virtual host to use in place of the default `bucket.s3.amazonaws.com` domain.
  750. *
  751. * Access:
  752. * public
  753. *
  754. * Parameters:
  755. * $vhost - _string_ (Required) The virtual host to use in place of the default `bucket.s3.amazonaws.com` domain.
  756. *
  757. * Returns:
  758. * `$this` A reference to the current instance.
  759. *
  760. * See Also:
  761. * [Virtual Hosting of Buckets](http://docs.amazonwebservices.com/AmazonS3/latest/VirtualHosting.html)
  762. */
  763. public function set_vhost($vhost)
  764. {
  765. $this->vhost = $vhost;
  766. return $this;
  767. }
  768. /**
  769. * Method: enable_path_style()
  770. * Enables the use of the older path-style URI access for all requests.
  771. *
  772. * Access:
  773. * public
  774. *
  775. * Parameters:
  776. * $style - _string_ (Optional) Whether or not to enable path-style URI access for all requests. The default value is `true`.
  777. *
  778. * Returns:
  779. * `$this` A reference to the current instance.
  780. */
  781. public function enable_path_style($style = true)
  782. {
  783. $this->path_style = $style;
  784. return $this;
  785. }
  786. /*%******************************************************************************************%*/
  787. // BUCKET METHODS
  788. /**
  789. * Method: create_bucket()
  790. * Creates an Amazon S3 bucket.
  791. *
  792. * Every object stored in Amazon S3 is contained in a bucket. Buckets partition the namespace of
  793. * objects stored in Amazon S3 at the top level. in a bucket, any name can be used for objects.
  794. * However, bucket names must be unique across all of Amazon S3.
  795. *
  796. * Access:
  797. * public
  798. *
  799. * Parameters:
  800. * $bucket - _string_ (Required) The name of the bucket to create.
  801. * $region - _string_ (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`]
  802. * $acl - _string_ (Optional) The ACL settings for the specified bucket. [Allowed values: `AmazonS3::ACL_PRIVATE`, `AmazonS3::ACL_PUBLIC`, `AmazonS3::ACL_OPEN`, `AmazonS3::ACL_AUTH_READ`, `AmazonS3::ACL_OWNER_READ`, `AmazonS3::ACL_OWNER_FULL_CONTROL`]. The default value is <ACL_PRIVATE>.
  803. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  804. *
  805. * Keys for the $opt parameter:
  806. * returnCurlHandle - _boolean_ (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.
  807. *
  808. * Returns:
  809. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  810. *
  811. * See Also:
  812. * * [Working with Amazon S3 Buckets](http://docs.amazonwebservices.com/AmazonS3/latest/UsingBucket.html)
  813. */
  814. public function create_bucket($bucket, $region, $acl = self::ACL_PRIVATE, $opt = null)
  815. {
  816. // If the bucket contains uppercase letters...
  817. if (preg_match('/[A-Z]/', $bucket))
  818. {
  819. // Throw a warning
  820. trigger_error('Since DNS-valid bucket names cannot contain uppercase characters, "' . $bucket . '" has been automatically converted to "' . strtolower($bucket) . '"', E_USER_WARNING);
  821. // Force the bucketname to lowercase
  822. $bucket = strtolower($bucket);
  823. }
  824. // Validate the S3 bucket name for creation
  825. if (!$this->validate_bucketname_create($bucket))
  826. {
  827. 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.');
  828. }
  829. if (!$opt) $opt = array();
  830. $opt['verb'] = 'PUT';
  831. $opt['headers'] = array(
  832. 'Content-Type' => 'application/xml',
  833. 'x-amz-acl' => $acl
  834. );
  835. // Defaults
  836. $this->set_region($region);
  837. $xml = simplexml_load_string($this->base_location_constraint);
  838. switch ($region)
  839. {
  840. case self::REGION_US_W1: // Northern California
  841. case self::REGION_APAC_SE1: // Singapore
  842. $xml->LocationConstraint = $region;
  843. $opt['body'] = $xml->asXML();
  844. break;
  845. case self::REGION_EU_W1: // Ireland
  846. $this->enable_path_style(); // DNS-style doesn't seem to work for creation, only in EU. Switch over to path-style.
  847. $xml->LocationConstraint = $region;
  848. $opt['body'] = $xml->asXML();
  849. break;
  850. default: // REGION_US_E1 // Northern Virginia
  851. $opt['body'] = '';
  852. break;
  853. }
  854. $response = $this->authenticate($bucket, $opt);
  855. return $response;
  856. }
  857. /**
  858. * Method: get_bucket_region()
  859. * Gets the region in which the specified Amazon S3 bucket is located.
  860. *
  861. * Access:
  862. * public
  863. *
  864. * Parameters:
  865. * $bucket - _string_ (Required) The name of the bucket to use.
  866. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  867. *
  868. * Keys for the $opt parameter:
  869. * preauth - _integer_|_string_ (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 `strtotime()`.
  870. * returnCurlHandle - _boolean_ (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.
  871. *
  872. * Returns:
  873. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  874. */
  875. public function get_bucket_region($bucket, $opt = null)
  876. {
  877. // Add this to our request
  878. if (!$opt) $opt = array();
  879. $opt['verb'] = 'GET';
  880. $opt['sub_resource'] = 'location';
  881. // Authenticate to S3
  882. $response = $this->authenticate($bucket, $opt);
  883. if ($response->isOK())
  884. {
  885. // Handle body
  886. $response->body = (string) $response->body;
  887. }
  888. return $response;
  889. }
  890. /**
  891. * Method: get_bucket_headers()
  892. * Gets the HTTP headers for the specified Amazon S3 bucket.
  893. *
  894. * Access:
  895. * public
  896. *
  897. * Parameters:
  898. * $bucket - _string_ (Required) The name of the bucket to use.
  899. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  900. *
  901. * Keys for the $opt parameter:
  902. * preauth - _integer_|_string_ (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 `strtotime()`.
  903. * returnCurlHandle - _boolean_ (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.
  904. *
  905. * Returns:
  906. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  907. */
  908. public function get_bucket_headers($bucket, $opt = null)
  909. {
  910. if (!$opt) $opt = array();
  911. $opt['verb'] = 'HEAD';
  912. return $this->authenticate($bucket, $opt);
  913. }
  914. /**
  915. * Method: delete_bucket()
  916. * Deletes a bucket from an Amazon S3 account. A bucket must be empty before the bucket itself can be
  917. * deleted.
  918. *
  919. * Access:
  920. * public
  921. *
  922. * Parameters:
  923. * $bucket - _string_ (Required) The name of the bucket to use.
  924. * $force - _boolean_ (Optional) Whether to force-delete the bucket and all of its contents. The default value is `false`.
  925. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  926. *
  927. * Keys for the $opt parameter:
  928. * returnCurlHandle - _boolean_ (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.
  929. *
  930. * Returns:
  931. * _mixed_ A <CFResponse> object if the bucket was deleted successfully. Returns _boolean_ `false` if otherwise.
  932. */
  933. public function delete_bucket($bucket, $force = false, $opt = null)
  934. {
  935. // Set default value
  936. $success = true;
  937. if ($force)
  938. {
  939. // Delete all of the items from the bucket.
  940. $success = $this->delete_all_object_versions($bucket);
  941. }
  942. // As long as we were successful...
  943. if ($success)
  944. {
  945. if (!$opt) $opt = array();
  946. $opt['verb'] = 'DELETE';
  947. return $this->authenticate($bucket, $opt);
  948. }
  949. return false;
  950. }
  951. /**
  952. * Method: list_buckets()
  953. * Gets a list of all buckets contained in the caller's Amazon S3 account.
  954. *
  955. * Access:
  956. * public
  957. *
  958. * Parameters:
  959. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  960. *
  961. * Keys for the $opt parameter:
  962. * preauth - _integer_|_string_ (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 `strtotime()`.
  963. * returnCurlHandle - _boolean_ (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.
  964. *
  965. * Returns:
  966. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  967. */
  968. public function list_buckets($opt = null)
  969. {
  970. if (!$opt) $opt = array();
  971. $opt['verb'] = 'GET';
  972. return $this->authenticate('', $opt);
  973. }
  974. /**
  975. * Method: get_bucket_acl()
  976. * Gets the access control list (ACL) settings for the specified Amazon S3 bucket.
  977. *
  978. * Access:
  979. * public
  980. *
  981. * Parameters:
  982. * $bucket - _string_ (Required) The name of the bucket to use.
  983. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  984. *
  985. * Keys for the $opt parameter:
  986. * preauth - _integer_|_string_ (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 `strtotime()`.
  987. * returnCurlHandle - _boolean_ (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.
  988. *
  989. * Returns:
  990. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  991. *
  992. * See Also:
  993. * [REST Access Control Policy](http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html)
  994. */
  995. public function get_bucket_acl($bucket, $opt = null)
  996. {
  997. // Add this to our request
  998. if (!$opt) $opt = array();
  999. $opt['verb'] = 'GET';
  1000. $opt['sub_resource'] = 'acl';
  1001. // Authenticate to S3
  1002. return $this->authenticate($bucket, $opt);
  1003. }
  1004. /**
  1005. * Method: set_bucket_acl()
  1006. * Sets the access control list (ACL) settings for the specified Amazon S3 bucket.
  1007. *
  1008. * Access:
  1009. * public
  1010. *
  1011. * Parameters:
  1012. * $bucket - _string_ (Required) The name of the bucket to use.
  1013. * $acl - _string_ (Optional) The ACL settings for the specified bucket. [Allowed values: `AmazonS3::ACL_PRIVATE`, `AmazonS3::ACL_PUBLIC`, `AmazonS3::ACL_OPEN`, `AmazonS3::ACL_AUTH_READ`, `AmazonS3::ACL_OWNER_READ`, `AmazonS3::ACL_OWNER_FULL_CONTROL`]. Alternatively, an array of associative arrays. Each associative array contains an `id` and a `permission` key. The default value is <ACL_PRIVATE>.
  1014. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  1015. *
  1016. * Keys for the $opt parameter:
  1017. * returnCurlHandle - _boolean_ (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.
  1018. *
  1019. * Returns:
  1020. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  1021. *
  1022. * See Also:
  1023. * [REST Access Control Policy](http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html)
  1024. */
  1025. public function set_bucket_acl($bucket, $acl = self::ACL_PRIVATE, $opt = null)
  1026. {
  1027. // Add this to our request
  1028. if (!$opt) $opt = array();
  1029. $opt['verb'] = 'PUT';
  1030. $opt['sub_resource'] = 'acl';
  1031. $opt['headers'] = array(
  1032. 'Content-Type' => 'application/xml'
  1033. );
  1034. // Make sure these are defined.
  1035. if (!defined('AWS_CANONICAL_ID') || !defined('AWS_CANONICAL_NAME'))
  1036. {
  1037. // Fetch the data live.
  1038. $canonical = $this->get_canonical_user_id();
  1039. define('AWS_CANONICAL_ID', $canonical['id']);
  1040. define('AWS_CANONICAL_NAME', $canonical['display_name']);
  1041. }
  1042. if (is_array($acl))
  1043. {
  1044. $opt['body'] = $this->generate_access_policy(AWS_CANONICAL_ID, AWS_CANONICAL_NAME, $acl);
  1045. }
  1046. else
  1047. {
  1048. $opt['headers']['x-amz-acl'] = $acl;
  1049. }
  1050. // Authenticate to S3
  1051. return $this->authenticate($bucket, $opt);
  1052. }
  1053. /*%******************************************************************************************%*/
  1054. // OBJECT METHODS
  1055. /**
  1056. * Method: create_object()
  1057. * Creates an Amazon S3 object. After an Amazon S3 bucket is created, objects can be stored in it.
  1058. *
  1059. * Each object can hold up to 5 GB of data. When an object is stored in Amazon S3, the data is streamed
  1060. * to multiple storage servers in multiple data centers. This ensures the data remains available in the
  1061. * event of internal network or hardware failure.
  1062. *
  1063. * Access:
  1064. * public
  1065. *
  1066. * Parameters:
  1067. * $bucket - _string_ (Required) The name of the bucket to use.
  1068. * $filename - _string_ (Required) The file name for the object.
  1069. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  1070. *
  1071. * Keys for the $opt parameter:
  1072. * body - _string_ (Required; Conditional) The data to be stored in the object. Either this parameter or `fileUpload` must be specified.
  1073. * fileUpload - _string_|_resource_ (Required; Conditional) The file system path for the local file to upload, or an open file resource. Either this parameter or `body` is required.
  1074. * acl - _string_ (Optional) The ACL settings for the specified object. [Allowed values: `AmazonS3::ACL_PRIVATE`, `AmazonS3::ACL_PUBLIC`, `AmazonS3::ACL_OPEN`, `AmazonS3::ACL_AUTH_READ`, `AmazonS3::ACL_OWNER_READ`, `AmazonS3::ACL_OWNER_FULL_CONTROL`]. The default value is <ACL_PRIVATE>.
  1075. * contentType - _string_ (Optional) The type of content that is being sent in the body. If a file is being uploaded via `fileUpload` as a file system path, it will attempt to determine the correct mime-type based on the file extension. The default value is `application/octet-stream`.
  1076. * headers - _array_ (Optional) The standard HTTP headers to send along in the request.
  1077. * meta - _array_ (Optional) An associative array of key-value pairs. Represented by `x-amz-meta-:` 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.
  1078. * storage - _string_ (Optional) Whether to use Standard or Reduced Redundancy storage. [Allowed values: `AmazonS3::STORAGE_STANDARD`, `AmazonS3::STORAGE_REDUCED`]. The default value is <STORAGE_STANDARD>.
  1079. * returnCurlHandle - _boolean_ (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.
  1080. *
  1081. * Returns:
  1082. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  1083. *
  1084. * See Also:
  1085. * [REST Access Control Policy](http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html)
  1086. */
  1087. public function create_object($bucket, $filename, $opt = null)
  1088. {
  1089. if (!$opt) $opt = array();
  1090. // Add this to our request
  1091. $opt['verb'] = 'PUT';
  1092. $opt['resource'] = $filename;
  1093. // Handle content type. Can also be passed as an HTTP header.
  1094. if (isset($opt['contentType']))
  1095. {
  1096. $opt['headers']['Content-Type'] = $opt['contentType'];
  1097. unset($opt['contentType']);
  1098. }
  1099. // Handle Access Control Lists. Can also be passed as an HTTP header.
  1100. if (isset($opt['acl']))
  1101. {
  1102. $opt['headers']['x-amz-acl'] = $opt['acl'];
  1103. unset($opt['acl']);
  1104. }
  1105. // Handle storage settings. Can also be passed as an HTTP header.
  1106. if (isset($opt['storage']))
  1107. {
  1108. $opt['headers']['x-amz-storage-class'] = $opt['storage'];
  1109. unset($opt['storage']);
  1110. }
  1111. // Handle meta tags. Can also be passed as an HTTP header.
  1112. if (isset($opt['meta']))
  1113. {
  1114. foreach ($opt['meta'] as $meta_key => $meta_value)
  1115. {
  1116. // e.g., `My Meta Header` is converted to `x-amz-meta-my-meta-header`.
  1117. $opt['headers']['x-amz-meta-' . strtolower(str_replace(' ', '-', $meta_key))] = $meta_value;
  1118. }
  1119. unset($opt['meta']);
  1120. }
  1121. // Authenticate to S3
  1122. return $this->authenticate($bucket, $opt);
  1123. }
  1124. /**
  1125. * Method: get_object()
  1126. * Gets the contents of an Amazon S3 object in the specified bucket.
  1127. *
  1128. * Access:
  1129. * public
  1130. *
  1131. * Parameters:
  1132. * $bucket - _string_ (Required) The name of the bucket to use.
  1133. * $filename - _string_ (Required) The file name for the object.
  1134. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  1135. *
  1136. * Keys for the $opt parameter:
  1137. * etag - _string_ (Optional) The `ETag` header passed in from a previous request. If specified, request `lastmodified` option must be specified as well. Will trigger a `304 Not Modified` status code if the file hasn't changed.
  1138. * fileDownload - _string_|_resource_ (Optional) The file system location to download the file to, or an open file resource. Must be a server-writable location.
  1139. * headers - _array_ (Optional) Standard HTTP headers to send along in the request.
  1140. * lastmodified - _string_ (Optional) The `LastModified` header passed in from a previous request. If specified, request `etag` option must be specified as well. Will trigger a `304 Not Modified` status code if the file hasn't changed.
  1141. * preauth - _integer_|_string_ (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 `strtotime()`.
  1142. * range - _string_ (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.
  1143. * versionId - _string_ (Optional) The version of the object to retrieve. Version IDs are returned in the `x-amz-version-id` header of any previous object-related request.
  1144. * returnCurlHandle - _boolean_ (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.
  1145. *
  1146. * Returns:
  1147. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  1148. */
  1149. public function get_object($bucket, $filename, $opt = null)
  1150. {
  1151. if (!$opt) $opt = array();
  1152. // Add this to our request
  1153. $opt['verb'] = 'GET';
  1154. $opt['resource'] = $filename;
  1155. if (!isset($opt['headers']) || !is_array($opt['headers']))
  1156. {
  1157. $opt['headers'] = array();
  1158. }
  1159. // Are we checking for changes?
  1160. if (isset($opt['lastmodified']) && isset($opt['etag']))
  1161. {
  1162. $opt['headers']['If-Modified-Since'] = $opt['lastmodified'];
  1163. $opt['headers']['If-None-Match'] = $opt['etag'];
  1164. }
  1165. // Partial content range
  1166. if (isset($opt['range']))
  1167. {
  1168. $opt['headers']['Range'] = 'bytes=' . $opt['range'];
  1169. }
  1170. // Authenticate to S3
  1171. return $this->authenticate($bucket, $opt);
  1172. }
  1173. /**
  1174. * Method: get_object_headers()
  1175. * Gets the HTTP headers for the specified Amazon S3 object.
  1176. *
  1177. * Access:
  1178. * public
  1179. *
  1180. * Parameters:
  1181. * $bucket - _string_ (Required) The name of the bucket to use.
  1182. * $filename - _string_ (Required) The file name for the object.
  1183. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  1184. *
  1185. * Keys for the $opt parameter:
  1186. * versionId - _string_ (Optional) The version of the object to retrieve. Version IDs are returned in the `x-amz-version-id` header of any previous object-related request.
  1187. * preauth - _integer_|_string_ (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 `strtotime()`.
  1188. * returnCurlHandle - _boolean_ (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.
  1189. *
  1190. * Returns:
  1191. * _CFResponse_ A <CFResponse> object containing a parsed HTTP response.
  1192. */
  1193. public function get_object_headers($bucket, $filename, $opt = null)
  1194. {
  1195. // Add this to our request
  1196. if (!$opt) $opt = array();
  1197. $opt['verb'] = 'HEAD';
  1198. $opt['resource'] = $filename;
  1199. // Authenticate to S3
  1200. return $this->authenticate($bucket, $opt);
  1201. }
  1202. /**
  1203. * Method: delete_object()
  1204. * Deletes an Amazon S3 object from the specified bucket.
  1205. *
  1206. * Access:
  1207. * public
  1208. *
  1209. * Parameters:
  1210. * $bucket - _string_ (Required) The name of the bucket to use.
  1211. * $filename - _string_ (Required) The file name for the object.
  1212. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section.
  1213. *
  1214. * Keys for the $opt parameter:
  1215. * versionId - _string_ (Optional) The version of the object to delete. Version IDs are returned in the `x-amz-version-id` header of any previous object-related request.
  1216. * MFASerial - _string_ (Optional) The serial number on the back of the Gemalto device. `MFASerial` and `MFAToken` must both be set for MFA to work.
  1217. * MFAToken - _string_ (Opt…

Large files files are truncated, but you can click here to view the full file