S3Client.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <?php
  2. namespace Aws\S3;
  3. use Aws\Api\ApiProvider;
  4. use Aws\Api\DocModel;
  5. use Aws\Api\Service;
  6. use Aws\AwsClient;
  7. use Aws\ClientResolver;
  8. use Aws\Command;
  9. use Aws\Exception\AwsException;
  10. use Aws\HandlerList;
  11. use Aws\Middleware;
  12. use Aws\RetryMiddleware;
  13. use Aws\ResultInterface;
  14. use Aws\CommandInterface;
  15. use GuzzleHttp\Exception\RequestException;
  16. use GuzzleHttp\Promise;
  17. use GuzzleHttp\Psr7;
  18. use Psr\Http\Message\RequestInterface;
  19. /**
  20. * Client used to interact with **Amazon Simple Storage Service (Amazon S3)**.
  21. *
  22. * @method \Aws\Result abortMultipartUpload(array $args = [])
  23. * @method \GuzzleHttp\Promise\Promise abortMultipartUploadAsync(array $args = [])
  24. * @method \Aws\Result completeMultipartUpload(array $args = [])
  25. * @method \GuzzleHttp\Promise\Promise completeMultipartUploadAsync(array $args = [])
  26. * @method \Aws\Result copyObject(array $args = [])
  27. * @method \GuzzleHttp\Promise\Promise copyObjectAsync(array $args = [])
  28. * @method \Aws\Result createBucket(array $args = [])
  29. * @method \GuzzleHttp\Promise\Promise createBucketAsync(array $args = [])
  30. * @method \Aws\Result createMultipartUpload(array $args = [])
  31. * @method \GuzzleHttp\Promise\Promise createMultipartUploadAsync(array $args = [])
  32. * @method \Aws\Result deleteBucket(array $args = [])
  33. * @method \GuzzleHttp\Promise\Promise deleteBucketAsync(array $args = [])
  34. * @method \Aws\Result deleteBucketAnalyticsConfiguration(array $args = [])
  35. * @method \GuzzleHttp\Promise\Promise deleteBucketAnalyticsConfigurationAsync(array $args = [])
  36. * @method \Aws\Result deleteBucketCors(array $args = [])
  37. * @method \GuzzleHttp\Promise\Promise deleteBucketCorsAsync(array $args = [])
  38. * @method \Aws\Result deleteBucketInventoryConfiguration(array $args = [])
  39. * @method \GuzzleHttp\Promise\Promise deleteBucketInventoryConfigurationAsync(array $args = [])
  40. * @method \Aws\Result deleteBucketLifecycle(array $args = [])
  41. * @method \GuzzleHttp\Promise\Promise deleteBucketLifecycleAsync(array $args = [])
  42. * @method \Aws\Result deleteBucketMetricsConfiguration(array $args = [])
  43. * @method \GuzzleHttp\Promise\Promise deleteBucketMetricsConfigurationAsync(array $args = [])
  44. * @method \Aws\Result deleteBucketPolicy(array $args = [])
  45. * @method \GuzzleHttp\Promise\Promise deleteBucketPolicyAsync(array $args = [])
  46. * @method \Aws\Result deleteBucketReplication(array $args = [])
  47. * @method \GuzzleHttp\Promise\Promise deleteBucketReplicationAsync(array $args = [])
  48. * @method \Aws\Result deleteBucketTagging(array $args = [])
  49. * @method \GuzzleHttp\Promise\Promise deleteBucketTaggingAsync(array $args = [])
  50. * @method \Aws\Result deleteBucketWebsite(array $args = [])
  51. * @method \GuzzleHttp\Promise\Promise deleteBucketWebsiteAsync(array $args = [])
  52. * @method \Aws\Result deleteObject(array $args = [])
  53. * @method \GuzzleHttp\Promise\Promise deleteObjectAsync(array $args = [])
  54. * @method \Aws\Result deleteObjectTagging(array $args = [])
  55. * @method \GuzzleHttp\Promise\Promise deleteObjectTaggingAsync(array $args = [])
  56. * @method \Aws\Result deleteObjects(array $args = [])
  57. * @method \GuzzleHttp\Promise\Promise deleteObjectsAsync(array $args = [])
  58. * @method \Aws\Result getBucketAccelerateConfiguration(array $args = [])
  59. * @method \GuzzleHttp\Promise\Promise getBucketAccelerateConfigurationAsync(array $args = [])
  60. * @method \Aws\Result getBucketAcl(array $args = [])
  61. * @method \GuzzleHttp\Promise\Promise getBucketAclAsync(array $args = [])
  62. * @method \Aws\Result getBucketAnalyticsConfiguration(array $args = [])
  63. * @method \GuzzleHttp\Promise\Promise getBucketAnalyticsConfigurationAsync(array $args = [])
  64. * @method \Aws\Result getBucketCors(array $args = [])
  65. * @method \GuzzleHttp\Promise\Promise getBucketCorsAsync(array $args = [])
  66. * @method \Aws\Result getBucketInventoryConfiguration(array $args = [])
  67. * @method \GuzzleHttp\Promise\Promise getBucketInventoryConfigurationAsync(array $args = [])
  68. * @method \Aws\Result getBucketLifecycle(array $args = [])
  69. * @method \GuzzleHttp\Promise\Promise getBucketLifecycleAsync(array $args = [])
  70. * @method \Aws\Result getBucketLifecycleConfiguration(array $args = [])
  71. * @method \GuzzleHttp\Promise\Promise getBucketLifecycleConfigurationAsync(array $args = [])
  72. * @method \Aws\Result getBucketLocation(array $args = [])
  73. * @method \GuzzleHttp\Promise\Promise getBucketLocationAsync(array $args = [])
  74. * @method \Aws\Result getBucketLogging(array $args = [])
  75. * @method \GuzzleHttp\Promise\Promise getBucketLoggingAsync(array $args = [])
  76. * @method \Aws\Result getBucketMetricsConfiguration(array $args = [])
  77. * @method \GuzzleHttp\Promise\Promise getBucketMetricsConfigurationAsync(array $args = [])
  78. * @method \Aws\Result getBucketNotification(array $args = [])
  79. * @method \GuzzleHttp\Promise\Promise getBucketNotificationAsync(array $args = [])
  80. * @method \Aws\Result getBucketNotificationConfiguration(array $args = [])
  81. * @method \GuzzleHttp\Promise\Promise getBucketNotificationConfigurationAsync(array $args = [])
  82. * @method \Aws\Result getBucketPolicy(array $args = [])
  83. * @method \GuzzleHttp\Promise\Promise getBucketPolicyAsync(array $args = [])
  84. * @method \Aws\Result getBucketReplication(array $args = [])
  85. * @method \GuzzleHttp\Promise\Promise getBucketReplicationAsync(array $args = [])
  86. * @method \Aws\Result getBucketRequestPayment(array $args = [])
  87. * @method \GuzzleHttp\Promise\Promise getBucketRequestPaymentAsync(array $args = [])
  88. * @method \Aws\Result getBucketTagging(array $args = [])
  89. * @method \GuzzleHttp\Promise\Promise getBucketTaggingAsync(array $args = [])
  90. * @method \Aws\Result getBucketVersioning(array $args = [])
  91. * @method \GuzzleHttp\Promise\Promise getBucketVersioningAsync(array $args = [])
  92. * @method \Aws\Result getBucketWebsite(array $args = [])
  93. * @method \GuzzleHttp\Promise\Promise getBucketWebsiteAsync(array $args = [])
  94. * @method \Aws\Result getObject(array $args = [])
  95. * @method \GuzzleHttp\Promise\Promise getObjectAsync(array $args = [])
  96. * @method \Aws\Result getObjectAcl(array $args = [])
  97. * @method \GuzzleHttp\Promise\Promise getObjectAclAsync(array $args = [])
  98. * @method \Aws\Result getObjectTagging(array $args = [])
  99. * @method \GuzzleHttp\Promise\Promise getObjectTaggingAsync(array $args = [])
  100. * @method \Aws\Result getObjectTorrent(array $args = [])
  101. * @method \GuzzleHttp\Promise\Promise getObjectTorrentAsync(array $args = [])
  102. * @method \Aws\Result headBucket(array $args = [])
  103. * @method \GuzzleHttp\Promise\Promise headBucketAsync(array $args = [])
  104. * @method \Aws\Result headObject(array $args = [])
  105. * @method \GuzzleHttp\Promise\Promise headObjectAsync(array $args = [])
  106. * @method \Aws\Result listBucketAnalyticsConfigurations(array $args = [])
  107. * @method \GuzzleHttp\Promise\Promise listBucketAnalyticsConfigurationsAsync(array $args = [])
  108. * @method \Aws\Result listBucketInventoryConfigurations(array $args = [])
  109. * @method \GuzzleHttp\Promise\Promise listBucketInventoryConfigurationsAsync(array $args = [])
  110. * @method \Aws\Result listBucketMetricsConfigurations(array $args = [])
  111. * @method \GuzzleHttp\Promise\Promise listBucketMetricsConfigurationsAsync(array $args = [])
  112. * @method \Aws\Result listBuckets(array $args = [])
  113. * @method \GuzzleHttp\Promise\Promise listBucketsAsync(array $args = [])
  114. * @method \Aws\Result listMultipartUploads(array $args = [])
  115. * @method \GuzzleHttp\Promise\Promise listMultipartUploadsAsync(array $args = [])
  116. * @method \Aws\Result listObjectVersions(array $args = [])
  117. * @method \GuzzleHttp\Promise\Promise listObjectVersionsAsync(array $args = [])
  118. * @method \Aws\Result listObjects(array $args = [])
  119. * @method \GuzzleHttp\Promise\Promise listObjectsAsync(array $args = [])
  120. * @method \Aws\Result listObjectsV2(array $args = [])
  121. * @method \GuzzleHttp\Promise\Promise listObjectsV2Async(array $args = [])
  122. * @method \Aws\Result listParts(array $args = [])
  123. * @method \GuzzleHttp\Promise\Promise listPartsAsync(array $args = [])
  124. * @method \Aws\Result putBucketAccelerateConfiguration(array $args = [])
  125. * @method \GuzzleHttp\Promise\Promise putBucketAccelerateConfigurationAsync(array $args = [])
  126. * @method \Aws\Result putBucketAcl(array $args = [])
  127. * @method \GuzzleHttp\Promise\Promise putBucketAclAsync(array $args = [])
  128. * @method \Aws\Result putBucketAnalyticsConfiguration(array $args = [])
  129. * @method \GuzzleHttp\Promise\Promise putBucketAnalyticsConfigurationAsync(array $args = [])
  130. * @method \Aws\Result putBucketCors(array $args = [])
  131. * @method \GuzzleHttp\Promise\Promise putBucketCorsAsync(array $args = [])
  132. * @method \Aws\Result putBucketInventoryConfiguration(array $args = [])
  133. * @method \GuzzleHttp\Promise\Promise putBucketInventoryConfigurationAsync(array $args = [])
  134. * @method \Aws\Result putBucketLifecycle(array $args = [])
  135. * @method \GuzzleHttp\Promise\Promise putBucketLifecycleAsync(array $args = [])
  136. * @method \Aws\Result putBucketLifecycleConfiguration(array $args = [])
  137. * @method \GuzzleHttp\Promise\Promise putBucketLifecycleConfigurationAsync(array $args = [])
  138. * @method \Aws\Result putBucketLogging(array $args = [])
  139. * @method \GuzzleHttp\Promise\Promise putBucketLoggingAsync(array $args = [])
  140. * @method \Aws\Result putBucketMetricsConfiguration(array $args = [])
  141. * @method \GuzzleHttp\Promise\Promise putBucketMetricsConfigurationAsync(array $args = [])
  142. * @method \Aws\Result putBucketNotification(array $args = [])
  143. * @method \GuzzleHttp\Promise\Promise putBucketNotificationAsync(array $args = [])
  144. * @method \Aws\Result putBucketNotificationConfiguration(array $args = [])
  145. * @method \GuzzleHttp\Promise\Promise putBucketNotificationConfigurationAsync(array $args = [])
  146. * @method \Aws\Result putBucketPolicy(array $args = [])
  147. * @method \GuzzleHttp\Promise\Promise putBucketPolicyAsync(array $args = [])
  148. * @method \Aws\Result putBucketReplication(array $args = [])
  149. * @method \GuzzleHttp\Promise\Promise putBucketReplicationAsync(array $args = [])
  150. * @method \Aws\Result putBucketRequestPayment(array $args = [])
  151. * @method \GuzzleHttp\Promise\Promise putBucketRequestPaymentAsync(array $args = [])
  152. * @method \Aws\Result putBucketTagging(array $args = [])
  153. * @method \GuzzleHttp\Promise\Promise putBucketTaggingAsync(array $args = [])
  154. * @method \Aws\Result putBucketVersioning(array $args = [])
  155. * @method \GuzzleHttp\Promise\Promise putBucketVersioningAsync(array $args = [])
  156. * @method \Aws\Result putBucketWebsite(array $args = [])
  157. * @method \GuzzleHttp\Promise\Promise putBucketWebsiteAsync(array $args = [])
  158. * @method \Aws\Result putObject(array $args = [])
  159. * @method \GuzzleHttp\Promise\Promise putObjectAsync(array $args = [])
  160. * @method \Aws\Result putObjectAcl(array $args = [])
  161. * @method \GuzzleHttp\Promise\Promise putObjectAclAsync(array $args = [])
  162. * @method \Aws\Result putObjectTagging(array $args = [])
  163. * @method \GuzzleHttp\Promise\Promise putObjectTaggingAsync(array $args = [])
  164. * @method \Aws\Result restoreObject(array $args = [])
  165. * @method \GuzzleHttp\Promise\Promise restoreObjectAsync(array $args = [])
  166. * @method \Aws\Result uploadPart(array $args = [])
  167. * @method \GuzzleHttp\Promise\Promise uploadPartAsync(array $args = [])
  168. * @method \Aws\Result uploadPartCopy(array $args = [])
  169. * @method \GuzzleHttp\Promise\Promise uploadPartCopyAsync(array $args = [])
  170. */
  171. class S3Client extends AwsClient implements S3ClientInterface
  172. {
  173. use S3ClientTrait;
  174. public static function getArguments()
  175. {
  176. $args = parent::getArguments();
  177. $args['retries']['fn'] = [__CLASS__, '_applyRetryConfig'];
  178. $args['api_provider']['fn'] = [__CLASS__, '_applyApiProvider'];
  179. return $args + [
  180. 'bucket_endpoint' => [
  181. 'type' => 'config',
  182. 'valid' => ['bool'],
  183. 'doc' => 'Set to true to send requests to a hardcoded '
  184. . 'bucket endpoint rather than create an endpoint as a '
  185. . 'result of injecting the bucket into the URL. This '
  186. . 'option is useful for interacting with CNAME endpoints.',
  187. ],
  188. 'use_accelerate_endpoint' => [
  189. 'type' => 'config',
  190. 'valid' => ['bool'],
  191. 'doc' => 'Set to true to send requests to an S3 Accelerate'
  192. . ' endpoint by default. Can be enabled or disabled on'
  193. . ' individual operations by setting'
  194. . ' \'@use_accelerate_endpoint\' to true or false. Note:'
  195. . ' you must enable S3 Accelerate on a bucket before it can'
  196. . ' be accessed via an Accelerate endpoint.',
  197. 'default' => false,
  198. ],
  199. 'use_dual_stack_endpoint' => [
  200. 'type' => 'config',
  201. 'valid' => ['bool'],
  202. 'doc' => 'Set to true to send requests to an S3 Dual Stack'
  203. . ' endpoint by default, which enables IPv6 Protocol.'
  204. . ' Can be enabled or disabled on individual operations by setting'
  205. . ' \'@use_dual_stack_endpoint\' to true or false.',
  206. 'default' => false,
  207. ],
  208. 'use_path_style_endpoint' => [
  209. 'type' => 'config',
  210. 'valid' => ['bool'],
  211. 'doc' => 'Set to true to send requests to an S3 path style'
  212. . ' endpoint by default.'
  213. . ' Can be enabled or disabled on individual operations by setting'
  214. . ' \'@use_path_style_endpoint\' to true or false.',
  215. 'default' => false,
  216. ],
  217. ];
  218. }
  219. /**
  220. * {@inheritdoc}
  221. *
  222. * In addition to the options available to
  223. * {@see Aws\AwsClient::__construct}, S3Client accepts the following
  224. * options:
  225. *
  226. * - bucket_endpoint: (bool) Set to true to send requests to a
  227. * hardcoded bucket endpoint rather than create an endpoint as a result
  228. * of injecting the bucket into the URL. This option is useful for
  229. * interacting with CNAME endpoints.
  230. * - calculate_md5: (bool) Set to false to disable calculating an MD5
  231. * for all Amazon S3 signed uploads.
  232. * - use_accelerate_endpoint: (bool) Set to true to send requests to an S3
  233. * Accelerate endpoint by default. Can be enabled or disabled on
  234. * individual operations by setting '@use_accelerate_endpoint' to true or
  235. * false. Note: you must enable S3 Accelerate on a bucket before it can be
  236. * accessed via an Accelerate endpoint.
  237. * - use_dual_stack_endpoint: (bool) Set to true to send requests to an S3
  238. * Dual Stack endpoint by default, which enables IPv6 Protocol.
  239. * Can be enabled or disabled on individual operations by setting
  240. * '@use_dual_stack_endpoint\' to true or false. Note:
  241. * you cannot use it together with an accelerate endpoint.
  242. * - use_path_style_endpoint: (bool) Set to true to send requests to an S3
  243. * path style endpoint by default.
  244. * Can be enabled or disabled on individual operations by setting
  245. * '@use_path_style_endpoint\' to true or false. Note:
  246. * you cannot use it together with an accelerate endpoint.
  247. *
  248. * @param array $args
  249. */
  250. public function __construct(array $args)
  251. {
  252. parent::__construct($args);
  253. $stack = $this->getHandlerList();
  254. $stack->appendInit(SSECMiddleware::wrap($this->getEndpoint()->getScheme()), 's3.ssec');
  255. $stack->appendBuild(ApplyChecksumMiddleware::wrap(), 's3.checksum');
  256. $stack->appendBuild(
  257. Middleware::contentType(['PutObject', 'UploadPart']),
  258. 's3.content_type'
  259. );
  260. // Use the bucket style middleware when using a "bucket_endpoint" (for cnames)
  261. if ($this->getConfig('bucket_endpoint')) {
  262. $stack->appendBuild(BucketEndpointMiddleware::wrap(), 's3.bucket_endpoint');
  263. } else {
  264. $stack->appendBuild(
  265. S3EndpointMiddleware::wrap(
  266. $this->getRegion(),
  267. [
  268. 'dual_stack' => $this->getConfig('use_dual_stack_endpoint'),
  269. 'accelerate' => $this->getConfig('use_accelerate_endpoint'),
  270. 'path_style' => $this->getConfig('use_path_style_endpoint')
  271. ]
  272. ),
  273. 's3.endpoint_middleware'
  274. );
  275. }
  276. $stack->appendSign(PutObjectUrlMiddleware::wrap(), 's3.put_object_url');
  277. $stack->appendSign(PermanentRedirectMiddleware::wrap(), 's3.permanent_redirect');
  278. $stack->appendInit(Middleware::sourceFile($this->getApi()), 's3.source_file');
  279. $stack->appendInit($this->getSaveAsParameter(), 's3.save_as');
  280. $stack->appendInit($this->getLocationConstraintMiddleware(), 's3.location');
  281. $stack->appendInit($this->getEncodingTypeMiddleware(), 's3.auto_encode');
  282. $stack->appendInit($this->getHeadObjectMiddleware(), 's3.head_object');
  283. }
  284. /**
  285. * Determine if a string is a valid name for a DNS compatible Amazon S3
  286. * bucket.
  287. *
  288. * DNS compatible bucket names can be used as a subdomain in a URL (e.g.,
  289. * "<bucket>.s3.amazonaws.com").
  290. *
  291. * @param string $bucket Bucket name to check.
  292. *
  293. * @return bool
  294. */
  295. public static function isBucketDnsCompatible($bucket)
  296. {
  297. $bucketLen = strlen($bucket);
  298. return ($bucketLen >= 3 && $bucketLen <= 63) &&
  299. // Cannot look like an IP address
  300. !filter_var($bucket, FILTER_VALIDATE_IP) &&
  301. preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket);
  302. }
  303. public function createPresignedRequest(CommandInterface $command, $expires)
  304. {
  305. $command = clone $command;
  306. $command->getHandlerList()->remove('signer');
  307. /** @var \Aws\Signature\SignatureInterface $signer */
  308. $signer = call_user_func(
  309. $this->getSignatureProvider(),
  310. $this->getConfig('signature_version'),
  311. $this->getConfig('signing_name'),
  312. $this->getConfig('signing_region')
  313. );
  314. return $signer->presign(
  315. \Aws\serialize($command),
  316. $this->getCredentials()->wait(),
  317. $expires
  318. );
  319. }
  320. public function getObjectUrl($bucket, $key)
  321. {
  322. $command = $this->getCommand('GetObject', [
  323. 'Bucket' => $bucket,
  324. 'Key' => $key
  325. ]);
  326. return (string) \Aws\serialize($command)->getUri();
  327. }
  328. /**
  329. * Raw URL encode a key and allow for '/' characters
  330. *
  331. * @param string $key Key to encode
  332. *
  333. * @return string Returns the encoded key
  334. */
  335. public static function encodeKey($key)
  336. {
  337. return str_replace('%2F', '/', rawurlencode($key));
  338. }
  339. /**
  340. * Provides a middleware that removes the need to specify LocationConstraint on CreateBucket.
  341. *
  342. * @return \Closure
  343. */
  344. private function getLocationConstraintMiddleware()
  345. {
  346. $region = $this->getRegion();
  347. return static function (callable $handler) use ($region) {
  348. return function (Command $command, $request = null) use ($handler, $region) {
  349. if ($command->getName() === 'CreateBucket') {
  350. $locationConstraint = isset($command['CreateBucketConfiguration']['LocationConstraint'])
  351. ? $command['CreateBucketConfiguration']['LocationConstraint']
  352. : null;
  353. if ($locationConstraint === 'us-east-1') {
  354. unset($command['CreateBucketConfiguration']);
  355. } elseif ('us-east-1' !== $region && empty($locationConstraint)) {
  356. $command['CreateBucketConfiguration'] = ['LocationConstraint' => $region];
  357. }
  358. }
  359. return $handler($command, $request);
  360. };
  361. };
  362. }
  363. /**
  364. * Provides a middleware that supports the `SaveAs` parameter.
  365. *
  366. * @return \Closure
  367. */
  368. private function getSaveAsParameter()
  369. {
  370. return static function (callable $handler) {
  371. return function (Command $command, $request = null) use ($handler) {
  372. if ($command->getName() === 'GetObject' && isset($command['SaveAs'])) {
  373. $command['@http']['sink'] = $command['SaveAs'];
  374. unset($command['SaveAs']);
  375. }
  376. return $handler($command, $request);
  377. };
  378. };
  379. }
  380. /**
  381. * Provides a middleware that disables content decoding on HeadObject
  382. * commands.
  383. *
  384. * @return \Closure
  385. */
  386. private function getHeadObjectMiddleware()
  387. {
  388. return static function (callable $handler) {
  389. return function (
  390. CommandInterface $command,
  391. RequestInterface $request = null
  392. ) use ($handler) {
  393. if ($command->getName() === 'HeadObject'
  394. && !isset($command['@http']['decode_content'])
  395. ) {
  396. $command['@http']['decode_content'] = false;
  397. }
  398. return $handler($command, $request);
  399. };
  400. };
  401. }
  402. /**
  403. * Provides a middleware that autopopulates the EncodingType parameter on
  404. * ListObjects commands.
  405. *
  406. * @return \Closure
  407. */
  408. private function getEncodingTypeMiddleware()
  409. {
  410. return static function (callable $handler) {
  411. return function (Command $command, $request = null) use ($handler) {
  412. $autoSet = false;
  413. if ($command->getName() === 'ListObjects'
  414. && empty($command['EncodingType'])
  415. ) {
  416. $command['EncodingType'] = 'url';
  417. $autoSet = true;
  418. }
  419. return $handler($command, $request)
  420. ->then(function (ResultInterface $result) use ($autoSet) {
  421. if ($result['EncodingType'] === 'url' && $autoSet) {
  422. static $topLevel = [
  423. 'Delimiter',
  424. 'Marker',
  425. 'NextMarker',
  426. 'Prefix',
  427. ];
  428. static $nested = [
  429. ['Contents', 'Key'],
  430. ['CommonPrefixes', 'Prefix'],
  431. ];
  432. foreach ($topLevel as $key) {
  433. if (isset($result[$key])) {
  434. $result[$key] = urldecode($result[$key]);
  435. }
  436. }
  437. foreach ($nested as $steps) {
  438. if (isset($result[$steps[0]])) {
  439. foreach ($result[$steps[0]] as $key => $part) {
  440. if (isset($part[$steps[1]])) {
  441. $result[$steps[0]][$key][$steps[1]]
  442. = urldecode($part[$steps[1]]);
  443. }
  444. }
  445. }
  446. }
  447. }
  448. return $result;
  449. });
  450. };
  451. };
  452. }
  453. /** @internal */
  454. public static function _applyRetryConfig($value, $_, HandlerList $list)
  455. {
  456. if (!$value) {
  457. return;
  458. }
  459. $decider = RetryMiddleware::createDefaultDecider($value);
  460. $decider = function ($retries, $command, $request, $result, $error) use ($decider, $value) {
  461. $maxRetries = null !== $command['@retries']
  462. ? $command['@retries']
  463. : $value;
  464. if ($decider($retries, $command, $request, $result, $error)) {
  465. return true;
  466. } elseif ($error instanceof AwsException
  467. && $retries < $maxRetries
  468. ) {
  469. if (
  470. $error->getResponse()
  471. && $error->getResponse()->getStatusCode() >= 400
  472. ) {
  473. return strpos(
  474. $error->getResponse()->getBody(),
  475. 'Your socket connection to the server'
  476. ) !== false;
  477. } elseif ($error->getPrevious() instanceof RequestException) {
  478. // All commands except CompleteMultipartUpload are
  479. // idempotent and may be retried without worry if a
  480. // networking error has occurred.
  481. return $command->getName() !== 'CompleteMultipartUpload';
  482. }
  483. }
  484. return false;
  485. };
  486. $delay = [RetryMiddleware::class, 'exponentialDelay'];
  487. $list->appendSign(Middleware::retry($decider, $delay), 'retry');
  488. }
  489. /** @internal */
  490. public static function _applyApiProvider($value, array &$args, HandlerList $list)
  491. {
  492. ClientResolver::_apply_api_provider($value, $args, $list);
  493. $args['parser'] = new GetBucketLocationParser(
  494. new AmbiguousSuccessParser(
  495. new RetryableMalformedResponseParser(
  496. $args['parser'],
  497. $args['exception_class']
  498. ),
  499. $args['error_parser'],
  500. $args['exception_class']
  501. )
  502. );
  503. }
  504. /**
  505. * @internal
  506. * @codeCoverageIgnore
  507. */
  508. public static function applyDocFilters(array $api, array $docs)
  509. {
  510. $b64 = '<div class="alert alert-info">This value will be base64 encoded on your behalf.</div>';
  511. $opt = '<div class="alert alert-info">This value will be computed for you it is not supplied.</div>';
  512. // Add the SourceFile parameter.
  513. $docs['shapes']['SourceFile']['base'] = 'The path to a file on disk to use instead of the Body parameter.';
  514. $api['shapes']['SourceFile'] = ['type' => 'string'];
  515. $api['shapes']['PutObjectRequest']['members']['SourceFile'] = ['shape' => 'SourceFile'];
  516. $api['shapes']['UploadPartRequest']['members']['SourceFile'] = ['shape' => 'SourceFile'];
  517. // Add the ContentSHA256 parameter.
  518. $docs['shapes']['ContentSHA256']['base'] = 'A SHA256 hash of the body content of the request.';
  519. $api['shapes']['ContentSHA256'] = ['type' => 'string'];
  520. $api['shapes']['PutObjectRequest']['members']['ContentSHA256'] = ['shape' => 'ContentSHA256'];
  521. $api['shapes']['UploadPartRequest']['members']['ContentSHA256'] = ['shape' => 'ContentSHA256'];
  522. unset($api['shapes']['PutObjectRequest']['members']['ContentMD5']);
  523. unset($api['shapes']['UploadPartRequest']['members']['ContentMD5']);
  524. $docs['shapes']['ContentSHA256']['append'] = $opt;
  525. // Add the SaveAs parameter.
  526. $docs['shapes']['SaveAs']['base'] = 'The path to a file on disk to save the object data.';
  527. $api['shapes']['SaveAs'] = ['type' => 'string'];
  528. $api['shapes']['GetObjectRequest']['members']['SaveAs'] = ['shape' => 'SaveAs'];
  529. // Several SSECustomerKey documentation updates.
  530. $docs['shapes']['SSECustomerKey']['append'] = $b64;
  531. $docs['shapes']['CopySourceSSECustomerKey']['append'] = $b64;
  532. $docs['shapes']['SSECustomerKeyMd5']['append'] = $opt;
  533. // Add the ObjectURL to various output shapes and documentation.
  534. $docs['shapes']['ObjectURL']['base'] = 'The URI of the created object.';
  535. $api['shapes']['ObjectURL'] = ['type' => 'string'];
  536. $api['shapes']['PutObjectOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
  537. $api['shapes']['CopyObjectOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
  538. $api['shapes']['CompleteMultipartUploadOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
  539. // Fix references to Location Constraint.
  540. unset($api['shapes']['CreateBucketRequest']['payload']);
  541. $api['shapes']['BucketLocationConstraint']['enum'] = [
  542. "ap-northeast-1",
  543. "ap-southeast-2",
  544. "ap-southeast-1",
  545. "cn-north-1",
  546. "eu-central-1",
  547. "eu-west-1",
  548. "us-east-1",
  549. "us-west-1",
  550. "us-west-2",
  551. "sa-east-1",
  552. ];
  553. // Add a note that the ContentMD5 is optional.
  554. $docs['shapes']['ContentMD5']['append'] = '<div class="alert alert-info">The value will be computed on '
  555. . 'your behalf.</div>';
  556. return [
  557. new Service($api, ApiProvider::defaultProvider()),
  558. new DocModel($docs)
  559. ];
  560. }
  561. }