S3Client.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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\CacheInterface;
  8. use Aws\ClientResolver;
  9. use Aws\Command;
  10. use Aws\Exception\AwsException;
  11. use Aws\HandlerList;
  12. use Aws\InputValidationMiddleware;
  13. use Aws\Middleware;
  14. use Aws\Retry\QuotaManager;
  15. use Aws\RetryMiddleware;
  16. use Aws\ResultInterface;
  17. use Aws\CommandInterface;
  18. use Aws\RetryMiddlewareV2;
  19. use Aws\S3\UseArnRegion\Configuration;
  20. use Aws\S3\UseArnRegion\ConfigurationInterface;
  21. use Aws\S3\UseArnRegion\ConfigurationProvider as UseArnRegionConfigurationProvider;
  22. use Aws\S3\RegionalEndpoint\ConfigurationProvider;
  23. use GuzzleHttp\Exception\RequestException;
  24. use GuzzleHttp\Promise\Promise;
  25. use GuzzleHttp\Promise\PromiseInterface;
  26. use Psr\Http\Message\RequestInterface;
  27. /**
  28. * Client used to interact with **Amazon Simple Storage Service (Amazon S3)**.
  29. *
  30. * @method \Aws\Result abortMultipartUpload(array $args = [])
  31. * @method \GuzzleHttp\Promise\Promise abortMultipartUploadAsync(array $args = [])
  32. * @method \Aws\Result completeMultipartUpload(array $args = [])
  33. * @method \GuzzleHttp\Promise\Promise completeMultipartUploadAsync(array $args = [])
  34. * @method \Aws\Result copyObject(array $args = [])
  35. * @method \GuzzleHttp\Promise\Promise copyObjectAsync(array $args = [])
  36. * @method \Aws\Result createBucket(array $args = [])
  37. * @method \GuzzleHttp\Promise\Promise createBucketAsync(array $args = [])
  38. * @method \Aws\Result createMultipartUpload(array $args = [])
  39. * @method \GuzzleHttp\Promise\Promise createMultipartUploadAsync(array $args = [])
  40. * @method \Aws\Result deleteBucket(array $args = [])
  41. * @method \GuzzleHttp\Promise\Promise deleteBucketAsync(array $args = [])
  42. * @method \Aws\Result deleteBucketAnalyticsConfiguration(array $args = [])
  43. * @method \GuzzleHttp\Promise\Promise deleteBucketAnalyticsConfigurationAsync(array $args = [])
  44. * @method \Aws\Result deleteBucketCors(array $args = [])
  45. * @method \GuzzleHttp\Promise\Promise deleteBucketCorsAsync(array $args = [])
  46. * @method \Aws\Result deleteBucketEncryption(array $args = [])
  47. * @method \GuzzleHttp\Promise\Promise deleteBucketEncryptionAsync(array $args = [])
  48. * @method \Aws\Result deleteBucketIntelligentTieringConfiguration(array $args = [])
  49. * @method \GuzzleHttp\Promise\Promise deleteBucketIntelligentTieringConfigurationAsync(array $args = [])
  50. * @method \Aws\Result deleteBucketInventoryConfiguration(array $args = [])
  51. * @method \GuzzleHttp\Promise\Promise deleteBucketInventoryConfigurationAsync(array $args = [])
  52. * @method \Aws\Result deleteBucketLifecycle(array $args = [])
  53. * @method \GuzzleHttp\Promise\Promise deleteBucketLifecycleAsync(array $args = [])
  54. * @method \Aws\Result deleteBucketMetricsConfiguration(array $args = [])
  55. * @method \GuzzleHttp\Promise\Promise deleteBucketMetricsConfigurationAsync(array $args = [])
  56. * @method \Aws\Result deleteBucketOwnershipControls(array $args = [])
  57. * @method \GuzzleHttp\Promise\Promise deleteBucketOwnershipControlsAsync(array $args = [])
  58. * @method \Aws\Result deleteBucketPolicy(array $args = [])
  59. * @method \GuzzleHttp\Promise\Promise deleteBucketPolicyAsync(array $args = [])
  60. * @method \Aws\Result deleteBucketReplication(array $args = [])
  61. * @method \GuzzleHttp\Promise\Promise deleteBucketReplicationAsync(array $args = [])
  62. * @method \Aws\Result deleteBucketTagging(array $args = [])
  63. * @method \GuzzleHttp\Promise\Promise deleteBucketTaggingAsync(array $args = [])
  64. * @method \Aws\Result deleteBucketWebsite(array $args = [])
  65. * @method \GuzzleHttp\Promise\Promise deleteBucketWebsiteAsync(array $args = [])
  66. * @method \Aws\Result deleteObject(array $args = [])
  67. * @method \GuzzleHttp\Promise\Promise deleteObjectAsync(array $args = [])
  68. * @method \Aws\Result deleteObjectTagging(array $args = [])
  69. * @method \GuzzleHttp\Promise\Promise deleteObjectTaggingAsync(array $args = [])
  70. * @method \Aws\Result deleteObjects(array $args = [])
  71. * @method \GuzzleHttp\Promise\Promise deleteObjectsAsync(array $args = [])
  72. * @method \Aws\Result deletePublicAccessBlock(array $args = [])
  73. * @method \GuzzleHttp\Promise\Promise deletePublicAccessBlockAsync(array $args = [])
  74. * @method \Aws\Result getBucketAccelerateConfiguration(array $args = [])
  75. * @method \GuzzleHttp\Promise\Promise getBucketAccelerateConfigurationAsync(array $args = [])
  76. * @method \Aws\Result getBucketAcl(array $args = [])
  77. * @method \GuzzleHttp\Promise\Promise getBucketAclAsync(array $args = [])
  78. * @method \Aws\Result getBucketAnalyticsConfiguration(array $args = [])
  79. * @method \GuzzleHttp\Promise\Promise getBucketAnalyticsConfigurationAsync(array $args = [])
  80. * @method \Aws\Result getBucketCors(array $args = [])
  81. * @method \GuzzleHttp\Promise\Promise getBucketCorsAsync(array $args = [])
  82. * @method \Aws\Result getBucketEncryption(array $args = [])
  83. * @method \GuzzleHttp\Promise\Promise getBucketEncryptionAsync(array $args = [])
  84. * @method \Aws\Result getBucketIntelligentTieringConfiguration(array $args = [])
  85. * @method \GuzzleHttp\Promise\Promise getBucketIntelligentTieringConfigurationAsync(array $args = [])
  86. * @method \Aws\Result getBucketInventoryConfiguration(array $args = [])
  87. * @method \GuzzleHttp\Promise\Promise getBucketInventoryConfigurationAsync(array $args = [])
  88. * @method \Aws\Result getBucketLifecycle(array $args = [])
  89. * @method \GuzzleHttp\Promise\Promise getBucketLifecycleAsync(array $args = [])
  90. * @method \Aws\Result getBucketLifecycleConfiguration(array $args = [])
  91. * @method \GuzzleHttp\Promise\Promise getBucketLifecycleConfigurationAsync(array $args = [])
  92. * @method \Aws\Result getBucketLocation(array $args = [])
  93. * @method \GuzzleHttp\Promise\Promise getBucketLocationAsync(array $args = [])
  94. * @method \Aws\Result getBucketLogging(array $args = [])
  95. * @method \GuzzleHttp\Promise\Promise getBucketLoggingAsync(array $args = [])
  96. * @method \Aws\Result getBucketMetricsConfiguration(array $args = [])
  97. * @method \GuzzleHttp\Promise\Promise getBucketMetricsConfigurationAsync(array $args = [])
  98. * @method \Aws\Result getBucketNotification(array $args = [])
  99. * @method \GuzzleHttp\Promise\Promise getBucketNotificationAsync(array $args = [])
  100. * @method \Aws\Result getBucketNotificationConfiguration(array $args = [])
  101. * @method \GuzzleHttp\Promise\Promise getBucketNotificationConfigurationAsync(array $args = [])
  102. * @method \Aws\Result getBucketOwnershipControls(array $args = [])
  103. * @method \GuzzleHttp\Promise\Promise getBucketOwnershipControlsAsync(array $args = [])
  104. * @method \Aws\Result getBucketPolicy(array $args = [])
  105. * @method \GuzzleHttp\Promise\Promise getBucketPolicyAsync(array $args = [])
  106. * @method \Aws\Result getBucketPolicyStatus(array $args = [])
  107. * @method \GuzzleHttp\Promise\Promise getBucketPolicyStatusAsync(array $args = [])
  108. * @method \Aws\Result getBucketReplication(array $args = [])
  109. * @method \GuzzleHttp\Promise\Promise getBucketReplicationAsync(array $args = [])
  110. * @method \Aws\Result getBucketRequestPayment(array $args = [])
  111. * @method \GuzzleHttp\Promise\Promise getBucketRequestPaymentAsync(array $args = [])
  112. * @method \Aws\Result getBucketTagging(array $args = [])
  113. * @method \GuzzleHttp\Promise\Promise getBucketTaggingAsync(array $args = [])
  114. * @method \Aws\Result getBucketVersioning(array $args = [])
  115. * @method \GuzzleHttp\Promise\Promise getBucketVersioningAsync(array $args = [])
  116. * @method \Aws\Result getBucketWebsite(array $args = [])
  117. * @method \GuzzleHttp\Promise\Promise getBucketWebsiteAsync(array $args = [])
  118. * @method \Aws\Result getObject(array $args = [])
  119. * @method \GuzzleHttp\Promise\Promise getObjectAsync(array $args = [])
  120. * @method \Aws\Result getObjectAcl(array $args = [])
  121. * @method \GuzzleHttp\Promise\Promise getObjectAclAsync(array $args = [])
  122. * @method \Aws\Result getObjectLegalHold(array $args = [])
  123. * @method \GuzzleHttp\Promise\Promise getObjectLegalHoldAsync(array $args = [])
  124. * @method \Aws\Result getObjectLockConfiguration(array $args = [])
  125. * @method \GuzzleHttp\Promise\Promise getObjectLockConfigurationAsync(array $args = [])
  126. * @method \Aws\Result getObjectRetention(array $args = [])
  127. * @method \GuzzleHttp\Promise\Promise getObjectRetentionAsync(array $args = [])
  128. * @method \Aws\Result getObjectTagging(array $args = [])
  129. * @method \GuzzleHttp\Promise\Promise getObjectTaggingAsync(array $args = [])
  130. * @method \Aws\Result getObjectTorrent(array $args = [])
  131. * @method \GuzzleHttp\Promise\Promise getObjectTorrentAsync(array $args = [])
  132. * @method \Aws\Result getPublicAccessBlock(array $args = [])
  133. * @method \GuzzleHttp\Promise\Promise getPublicAccessBlockAsync(array $args = [])
  134. * @method \Aws\Result headBucket(array $args = [])
  135. * @method \GuzzleHttp\Promise\Promise headBucketAsync(array $args = [])
  136. * @method \Aws\Result headObject(array $args = [])
  137. * @method \GuzzleHttp\Promise\Promise headObjectAsync(array $args = [])
  138. * @method \Aws\Result listBucketAnalyticsConfigurations(array $args = [])
  139. * @method \GuzzleHttp\Promise\Promise listBucketAnalyticsConfigurationsAsync(array $args = [])
  140. * @method \Aws\Result listBucketIntelligentTieringConfigurations(array $args = [])
  141. * @method \GuzzleHttp\Promise\Promise listBucketIntelligentTieringConfigurationsAsync(array $args = [])
  142. * @method \Aws\Result listBucketInventoryConfigurations(array $args = [])
  143. * @method \GuzzleHttp\Promise\Promise listBucketInventoryConfigurationsAsync(array $args = [])
  144. * @method \Aws\Result listBucketMetricsConfigurations(array $args = [])
  145. * @method \GuzzleHttp\Promise\Promise listBucketMetricsConfigurationsAsync(array $args = [])
  146. * @method \Aws\Result listBuckets(array $args = [])
  147. * @method \GuzzleHttp\Promise\Promise listBucketsAsync(array $args = [])
  148. * @method \Aws\Result listMultipartUploads(array $args = [])
  149. * @method \GuzzleHttp\Promise\Promise listMultipartUploadsAsync(array $args = [])
  150. * @method \Aws\Result listObjectVersions(array $args = [])
  151. * @method \GuzzleHttp\Promise\Promise listObjectVersionsAsync(array $args = [])
  152. * @method \Aws\Result listObjects(array $args = [])
  153. * @method \GuzzleHttp\Promise\Promise listObjectsAsync(array $args = [])
  154. * @method \Aws\Result listObjectsV2(array $args = [])
  155. * @method \GuzzleHttp\Promise\Promise listObjectsV2Async(array $args = [])
  156. * @method \Aws\Result listParts(array $args = [])
  157. * @method \GuzzleHttp\Promise\Promise listPartsAsync(array $args = [])
  158. * @method \Aws\Result putBucketAccelerateConfiguration(array $args = [])
  159. * @method \GuzzleHttp\Promise\Promise putBucketAccelerateConfigurationAsync(array $args = [])
  160. * @method \Aws\Result putBucketAcl(array $args = [])
  161. * @method \GuzzleHttp\Promise\Promise putBucketAclAsync(array $args = [])
  162. * @method \Aws\Result putBucketAnalyticsConfiguration(array $args = [])
  163. * @method \GuzzleHttp\Promise\Promise putBucketAnalyticsConfigurationAsync(array $args = [])
  164. * @method \Aws\Result putBucketCors(array $args = [])
  165. * @method \GuzzleHttp\Promise\Promise putBucketCorsAsync(array $args = [])
  166. * @method \Aws\Result putBucketEncryption(array $args = [])
  167. * @method \GuzzleHttp\Promise\Promise putBucketEncryptionAsync(array $args = [])
  168. * @method \Aws\Result putBucketIntelligentTieringConfiguration(array $args = [])
  169. * @method \GuzzleHttp\Promise\Promise putBucketIntelligentTieringConfigurationAsync(array $args = [])
  170. * @method \Aws\Result putBucketInventoryConfiguration(array $args = [])
  171. * @method \GuzzleHttp\Promise\Promise putBucketInventoryConfigurationAsync(array $args = [])
  172. * @method \Aws\Result putBucketLifecycle(array $args = [])
  173. * @method \GuzzleHttp\Promise\Promise putBucketLifecycleAsync(array $args = [])
  174. * @method \Aws\Result putBucketLifecycleConfiguration(array $args = [])
  175. * @method \GuzzleHttp\Promise\Promise putBucketLifecycleConfigurationAsync(array $args = [])
  176. * @method \Aws\Result putBucketLogging(array $args = [])
  177. * @method \GuzzleHttp\Promise\Promise putBucketLoggingAsync(array $args = [])
  178. * @method \Aws\Result putBucketMetricsConfiguration(array $args = [])
  179. * @method \GuzzleHttp\Promise\Promise putBucketMetricsConfigurationAsync(array $args = [])
  180. * @method \Aws\Result putBucketNotification(array $args = [])
  181. * @method \GuzzleHttp\Promise\Promise putBucketNotificationAsync(array $args = [])
  182. * @method \Aws\Result putBucketNotificationConfiguration(array $args = [])
  183. * @method \GuzzleHttp\Promise\Promise putBucketNotificationConfigurationAsync(array $args = [])
  184. * @method \Aws\Result putBucketOwnershipControls(array $args = [])
  185. * @method \GuzzleHttp\Promise\Promise putBucketOwnershipControlsAsync(array $args = [])
  186. * @method \Aws\Result putBucketPolicy(array $args = [])
  187. * @method \GuzzleHttp\Promise\Promise putBucketPolicyAsync(array $args = [])
  188. * @method \Aws\Result putBucketReplication(array $args = [])
  189. * @method \GuzzleHttp\Promise\Promise putBucketReplicationAsync(array $args = [])
  190. * @method \Aws\Result putBucketRequestPayment(array $args = [])
  191. * @method \GuzzleHttp\Promise\Promise putBucketRequestPaymentAsync(array $args = [])
  192. * @method \Aws\Result putBucketTagging(array $args = [])
  193. * @method \GuzzleHttp\Promise\Promise putBucketTaggingAsync(array $args = [])
  194. * @method \Aws\Result putBucketVersioning(array $args = [])
  195. * @method \GuzzleHttp\Promise\Promise putBucketVersioningAsync(array $args = [])
  196. * @method \Aws\Result putBucketWebsite(array $args = [])
  197. * @method \GuzzleHttp\Promise\Promise putBucketWebsiteAsync(array $args = [])
  198. * @method \Aws\Result putObject(array $args = [])
  199. * @method \GuzzleHttp\Promise\Promise putObjectAsync(array $args = [])
  200. * @method \Aws\Result putObjectAcl(array $args = [])
  201. * @method \GuzzleHttp\Promise\Promise putObjectAclAsync(array $args = [])
  202. * @method \Aws\Result putObjectLegalHold(array $args = [])
  203. * @method \GuzzleHttp\Promise\Promise putObjectLegalHoldAsync(array $args = [])
  204. * @method \Aws\Result putObjectLockConfiguration(array $args = [])
  205. * @method \GuzzleHttp\Promise\Promise putObjectLockConfigurationAsync(array $args = [])
  206. * @method \Aws\Result putObjectRetention(array $args = [])
  207. * @method \GuzzleHttp\Promise\Promise putObjectRetentionAsync(array $args = [])
  208. * @method \Aws\Result putObjectTagging(array $args = [])
  209. * @method \GuzzleHttp\Promise\Promise putObjectTaggingAsync(array $args = [])
  210. * @method \Aws\Result putPublicAccessBlock(array $args = [])
  211. * @method \GuzzleHttp\Promise\Promise putPublicAccessBlockAsync(array $args = [])
  212. * @method \Aws\Result restoreObject(array $args = [])
  213. * @method \GuzzleHttp\Promise\Promise restoreObjectAsync(array $args = [])
  214. * @method \Aws\Result selectObjectContent(array $args = [])
  215. * @method \GuzzleHttp\Promise\Promise selectObjectContentAsync(array $args = [])
  216. * @method \Aws\Result uploadPart(array $args = [])
  217. * @method \GuzzleHttp\Promise\Promise uploadPartAsync(array $args = [])
  218. * @method \Aws\Result uploadPartCopy(array $args = [])
  219. * @method \GuzzleHttp\Promise\Promise uploadPartCopyAsync(array $args = [])
  220. */
  221. class S3Client extends AwsClient implements S3ClientInterface
  222. {
  223. use S3ClientTrait;
  224. /** @var array */
  225. private static $mandatoryAttributes = ['Bucket', 'Key'];
  226. public static function getArguments()
  227. {
  228. $args = parent::getArguments();
  229. $args['retries']['fn'] = [__CLASS__, '_applyRetryConfig'];
  230. $args['api_provider']['fn'] = [__CLASS__, '_applyApiProvider'];
  231. return $args + [
  232. 'bucket_endpoint' => [
  233. 'type' => 'config',
  234. 'valid' => ['bool'],
  235. 'doc' => 'Set to true to send requests to a hardcoded '
  236. . 'bucket endpoint rather than create an endpoint as a '
  237. . 'result of injecting the bucket into the URL. This '
  238. . 'option is useful for interacting with CNAME endpoints.',
  239. ],
  240. 'use_arn_region' => [
  241. 'type' => 'config',
  242. 'valid' => [
  243. 'bool',
  244. Configuration::class,
  245. CacheInterface::class,
  246. 'callable'
  247. ],
  248. 'doc' => 'Set to true to allow passed in ARNs to override'
  249. . ' client region. Accepts...',
  250. 'fn' => [__CLASS__, '_apply_use_arn_region'],
  251. 'default' => [UseArnRegionConfigurationProvider::class, 'defaultProvider'],
  252. ],
  253. 'use_accelerate_endpoint' => [
  254. 'type' => 'config',
  255. 'valid' => ['bool'],
  256. 'doc' => 'Set to true to send requests to an S3 Accelerate'
  257. . ' endpoint by default. Can be enabled or disabled on'
  258. . ' individual operations by setting'
  259. . ' \'@use_accelerate_endpoint\' to true or false. Note:'
  260. . ' you must enable S3 Accelerate on a bucket before it can'
  261. . ' be accessed via an Accelerate endpoint.',
  262. 'default' => false,
  263. ],
  264. 'use_dual_stack_endpoint' => [
  265. 'type' => 'config',
  266. 'valid' => ['bool'],
  267. 'doc' => 'Set to true to send requests to an S3 Dual Stack'
  268. . ' endpoint by default, which enables IPv6 Protocol.'
  269. . ' Can be enabled or disabled on individual operations by setting'
  270. . ' \'@use_dual_stack_endpoint\' to true or false.',
  271. 'default' => false,
  272. ],
  273. 'use_path_style_endpoint' => [
  274. 'type' => 'config',
  275. 'valid' => ['bool'],
  276. 'doc' => 'Set to true to send requests to an S3 path style'
  277. . ' endpoint by default.'
  278. . ' Can be enabled or disabled on individual operations by setting'
  279. . ' \'@use_path_style_endpoint\' to true or false.',
  280. 'default' => false,
  281. ],
  282. ];
  283. }
  284. /**
  285. * {@inheritdoc}
  286. *
  287. * In addition to the options available to
  288. * {@see Aws\AwsClient::__construct}, S3Client accepts the following
  289. * options:
  290. *
  291. * - bucket_endpoint: (bool) Set to true to send requests to a
  292. * hardcoded bucket endpoint rather than create an endpoint as a result
  293. * of injecting the bucket into the URL. This option is useful for
  294. * interacting with CNAME endpoints.
  295. * - calculate_md5: (bool) Set to false to disable calculating an MD5
  296. * for all Amazon S3 signed uploads.
  297. * - s3_us_east_1_regional_endpoint:
  298. * (Aws\S3\RegionalEndpoint\ConfigurationInterface|Aws\CacheInterface\|callable|string|array)
  299. * Specifies whether to use regional or legacy endpoints for the us-east-1
  300. * region. Provide an Aws\S3\RegionalEndpoint\ConfigurationInterface object, an
  301. * instance of Aws\CacheInterface, a callable configuration provider used
  302. * to create endpoint configuration, a string value of `legacy` or
  303. * `regional`, or an associative array with the following keys:
  304. * endpoint_types: (string) Set to `legacy` or `regional`, defaults to
  305. * `legacy`
  306. * - use_accelerate_endpoint: (bool) Set to true to send requests to an S3
  307. * Accelerate endpoint by default. Can be enabled or disabled on
  308. * individual operations by setting '@use_accelerate_endpoint' to true or
  309. * false. Note: you must enable S3 Accelerate on a bucket before it can be
  310. * accessed via an Accelerate endpoint.
  311. * - use_arn_region: (Aws\S3\UseArnRegion\ConfigurationInterface,
  312. * Aws\CacheInterface, bool, callable) Set to true to enable the client
  313. * to use the region from a supplied ARN argument instead of the client's
  314. * region. Provide an instance of Aws\S3\UseArnRegion\ConfigurationInterface,
  315. * an instance of Aws\CacheInterface, a callable that provides a promise for
  316. * a Configuration object, or a boolean value. Defaults to false (i.e.
  317. * the SDK will not follow the ARN region if it conflicts with the client
  318. * region and instead throw an error).
  319. * - use_dual_stack_endpoint: (bool) Set to true to send requests to an S3
  320. * Dual Stack endpoint by default, which enables IPv6 Protocol.
  321. * Can be enabled or disabled on individual operations by setting
  322. * '@use_dual_stack_endpoint\' to true or false. Note:
  323. * you cannot use it together with an accelerate endpoint.
  324. * - use_path_style_endpoint: (bool) Set to true to send requests to an S3
  325. * path style endpoint by default.
  326. * Can be enabled or disabled on individual operations by setting
  327. * '@use_path_style_endpoint\' to true or false. Note:
  328. * you cannot use it together with an accelerate endpoint.
  329. *
  330. * @param array $args
  331. */
  332. public function __construct(array $args)
  333. {
  334. if (
  335. !isset($args['s3_us_east_1_regional_endpoint'])
  336. || $args['s3_us_east_1_regional_endpoint'] instanceof CacheInterface
  337. ) {
  338. $args['s3_us_east_1_regional_endpoint'] = ConfigurationProvider::defaultProvider($args);
  339. }
  340. parent::__construct($args);
  341. $stack = $this->getHandlerList();
  342. $stack->appendInit(SSECMiddleware::wrap($this->getEndpoint()->getScheme()), 's3.ssec');
  343. $stack->appendBuild(ApplyChecksumMiddleware::wrap($this->getApi()), 's3.checksum');
  344. $stack->appendBuild(
  345. Middleware::contentType(['PutObject', 'UploadPart'],$args['Content-Type']),
  346. 's3.content_type'
  347. );
  348. // Use the bucket style middleware when using a "bucket_endpoint" (for cnames)
  349. if ($this->getConfig('bucket_endpoint')) {
  350. $stack->appendBuild(BucketEndpointMiddleware::wrap(), 's3.bucket_endpoint');
  351. } else {
  352. $stack->appendBuild(
  353. S3EndpointMiddleware::wrap(
  354. $this->getRegion(),
  355. $this->getConfig('endpoint_provider'),
  356. [
  357. 'dual_stack' => $this->getConfig('use_dual_stack_endpoint'),
  358. 'accelerate' => $this->getConfig('use_accelerate_endpoint'),
  359. 'path_style' => $this->getConfig('use_path_style_endpoint')
  360. ]
  361. ),
  362. 's3.endpoint_middleware'
  363. );
  364. }
  365. $stack->appendBuild(
  366. BucketEndpointArnMiddleware::wrap(
  367. $this->getApi(),
  368. $this->getRegion(),
  369. [
  370. 'use_arn_region' => $this->getConfig('use_arn_region'),
  371. 'dual_stack' => $this->getConfig('use_dual_stack_endpoint'),
  372. 'accelerate' => $this->getConfig('use_accelerate_endpoint'),
  373. 'path_style' => $this->getConfig('use_path_style_endpoint'),
  374. 'endpoint' => isset($args['endpoint'])
  375. ? $args['endpoint']
  376. : null
  377. ]
  378. ),
  379. 's3.bucket_endpoint_arn'
  380. );
  381. $stack->appendValidate(
  382. InputValidationMiddleware::wrap($this->getApi(), self::$mandatoryAttributes),
  383. 'input_validation_middleware'
  384. );
  385. $stack->appendSign(PutObjectUrlMiddleware::wrap(), 's3.put_object_url');
  386. $stack->appendSign(PermanentRedirectMiddleware::wrap(), 's3.permanent_redirect');
  387. $stack->appendInit(Middleware::sourceFile($this->getApi()), 's3.source_file');
  388. $stack->appendInit($this->getSaveAsParameter(), 's3.save_as');
  389. $stack->appendInit($this->getLocationConstraintMiddleware(), 's3.location');
  390. $stack->appendInit($this->getEncodingTypeMiddleware(), 's3.auto_encode');
  391. $stack->appendInit($this->getHeadObjectMiddleware(), 's3.head_object');
  392. }
  393. /**
  394. * Determine if a string is a valid name for a DNS compatible Amazon S3
  395. * bucket.
  396. *
  397. * DNS compatible bucket names can be used as a subdomain in a URL (e.g.,
  398. * "<bucket>.s3.amazonaws.com").
  399. *
  400. * @param string $bucket Bucket name to check.
  401. *
  402. * @return bool
  403. */
  404. public static function isBucketDnsCompatible($bucket)
  405. {
  406. $bucketLen = strlen($bucket);
  407. return ($bucketLen >= 3 && $bucketLen <= 63) &&
  408. // Cannot look like an IP address
  409. !filter_var($bucket, FILTER_VALIDATE_IP) &&
  410. preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket);
  411. }
  412. public static function _apply_use_arn_region($value, array &$args, HandlerList $list)
  413. {
  414. if ($value instanceof CacheInterface) {
  415. $value = UseArnRegionConfigurationProvider::defaultProvider($args);
  416. }
  417. if (is_callable($value)) {
  418. $value = $value();
  419. }
  420. if ($value instanceof PromiseInterface) {
  421. $value = $value->wait();
  422. }
  423. if ($value instanceof ConfigurationInterface) {
  424. $args['use_arn_region'] = $value;
  425. } else {
  426. // The Configuration class itself will validate other inputs
  427. $args['use_arn_region'] = new Configuration($value);
  428. }
  429. }
  430. public function createPresignedRequest(CommandInterface $command, $expires, array $options = [])
  431. {
  432. $command = clone $command;
  433. $command->getHandlerList()->remove('signer');
  434. /** @var \Aws\Signature\SignatureInterface $signer */
  435. $signer = call_user_func(
  436. $this->getSignatureProvider(),
  437. $this->getConfig('signature_version'),
  438. $this->getConfig('signing_name'),
  439. $this->getConfig('signing_region')
  440. );
  441. return $signer->presign(
  442. \Aws\serialize($command),
  443. $this->getCredentials()->wait(),
  444. $expires,
  445. $options
  446. );
  447. }
  448. /**
  449. * Returns the URL to an object identified by its bucket and key.
  450. *
  451. * The URL returned by this method is not signed nor does it ensure that the
  452. * bucket and key given to the method exist. If you need a signed URL, then
  453. * use the {@see \Aws\S3\S3Client::createPresignedRequest} method and get
  454. * the URI of the signed request.
  455. *
  456. * @param string $bucket The name of the bucket where the object is located
  457. * @param string $key The key of the object
  458. *
  459. * @return string The URL to the object
  460. */
  461. public function getObjectUrl($bucket, $key)
  462. {
  463. $command = $this->getCommand('GetObject', [
  464. 'Bucket' => $bucket,
  465. 'Key' => $key
  466. ]);
  467. return (string) \Aws\serialize($command)->getUri();
  468. }
  469. /**
  470. * Raw URL encode a key and allow for '/' characters
  471. *
  472. * @param string $key Key to encode
  473. *
  474. * @return string Returns the encoded key
  475. */
  476. public static function encodeKey($key)
  477. {
  478. return str_replace('%2F', '/', rawurlencode($key));
  479. }
  480. /**
  481. * Provides a middleware that removes the need to specify LocationConstraint on CreateBucket.
  482. *
  483. * @return \Closure
  484. */
  485. private function getLocationConstraintMiddleware()
  486. {
  487. $region = $this->getRegion();
  488. return static function (callable $handler) use ($region) {
  489. return function (Command $command, $request = null) use ($handler, $region) {
  490. if ($command->getName() === 'CreateBucket') {
  491. $locationConstraint = isset($command['CreateBucketConfiguration']['LocationConstraint'])
  492. ? $command['CreateBucketConfiguration']['LocationConstraint']
  493. : null;
  494. if ($locationConstraint === 'us-east-1') {
  495. unset($command['CreateBucketConfiguration']);
  496. } elseif ('us-east-1' !== $region && empty($locationConstraint)) {
  497. $command['CreateBucketConfiguration'] = ['LocationConstraint' => $region];
  498. }
  499. }
  500. return $handler($command, $request);
  501. };
  502. };
  503. }
  504. /**
  505. * Provides a middleware that supports the `SaveAs` parameter.
  506. *
  507. * @return \Closure
  508. */
  509. private function getSaveAsParameter()
  510. {
  511. return static function (callable $handler) {
  512. return function (Command $command, $request = null) use ($handler) {
  513. if ($command->getName() === 'GetObject' && isset($command['SaveAs'])) {
  514. $command['@http']['sink'] = $command['SaveAs'];
  515. unset($command['SaveAs']);
  516. }
  517. return $handler($command, $request);
  518. };
  519. };
  520. }
  521. /**
  522. * Provides a middleware that disables content decoding on HeadObject
  523. * commands.
  524. *
  525. * @return \Closure
  526. */
  527. private function getHeadObjectMiddleware()
  528. {
  529. return static function (callable $handler) {
  530. return function (
  531. CommandInterface $command,
  532. RequestInterface $request = null
  533. ) use ($handler) {
  534. if ($command->getName() === 'HeadObject'
  535. && !isset($command['@http']['decode_content'])
  536. ) {
  537. $command['@http']['decode_content'] = false;
  538. }
  539. return $handler($command, $request);
  540. };
  541. };
  542. }
  543. /**
  544. * Provides a middleware that autopopulates the EncodingType parameter on
  545. * ListObjects commands.
  546. *
  547. * @return \Closure
  548. */
  549. private function getEncodingTypeMiddleware()
  550. {
  551. return static function (callable $handler) {
  552. return function (Command $command, $request = null) use ($handler) {
  553. $autoSet = false;
  554. if ($command->getName() === 'ListObjects'
  555. && empty($command['EncodingType'])
  556. ) {
  557. $command['EncodingType'] = 'url';
  558. $autoSet = true;
  559. }
  560. return $handler($command, $request)
  561. ->then(function (ResultInterface $result) use ($autoSet) {
  562. if ($result['EncodingType'] === 'url' && $autoSet) {
  563. static $topLevel = [
  564. 'Delimiter',
  565. 'Marker',
  566. 'NextMarker',
  567. 'Prefix',
  568. ];
  569. static $nested = [
  570. ['Contents', 'Key'],
  571. ['CommonPrefixes', 'Prefix'],
  572. ];
  573. foreach ($topLevel as $key) {
  574. if (isset($result[$key])) {
  575. $result[$key] = urldecode($result[$key]);
  576. }
  577. }
  578. foreach ($nested as $steps) {
  579. if (isset($result[$steps[0]])) {
  580. foreach ($result[$steps[0]] as $key => $part) {
  581. if (isset($part[$steps[1]])) {
  582. $result[$steps[0]][$key][$steps[1]]
  583. = urldecode($part[$steps[1]]);
  584. }
  585. }
  586. }
  587. }
  588. }
  589. return $result;
  590. });
  591. };
  592. };
  593. }
  594. /** @internal */
  595. public static function _applyRetryConfig($value, $args, HandlerList $list)
  596. {
  597. if ($value) {
  598. $config = \Aws\Retry\ConfigurationProvider::unwrap($value);
  599. if ($config->getMode() === 'legacy') {
  600. $maxRetries = $config->getMaxAttempts() - 1;
  601. $decider = RetryMiddleware::createDefaultDecider($maxRetries);
  602. $decider = function ($retries, $command, $request, $result, $error) use ($decider, $maxRetries) {
  603. $maxRetries = null !== $command['@retries']
  604. ? $command['@retries']
  605. : $maxRetries;
  606. if ($decider($retries, $command, $request, $result, $error)) {
  607. return true;
  608. }
  609. if ($error instanceof AwsException
  610. && $retries < $maxRetries
  611. ) {
  612. if ($error->getResponse()
  613. && $error->getResponse()->getStatusCode() >= 400
  614. ) {
  615. return strpos(
  616. $error->getResponse()->getBody(),
  617. 'Your socket connection to the server'
  618. ) !== false;
  619. }
  620. if ($error->getPrevious() instanceof RequestException) {
  621. // All commands except CompleteMultipartUpload are
  622. // idempotent and may be retried without worry if a
  623. // networking error has occurred.
  624. return $command->getName() !== 'CompleteMultipartUpload';
  625. }
  626. }
  627. return false;
  628. };
  629. $delay = [RetryMiddleware::class, 'exponentialDelay'];
  630. $list->appendSign(Middleware::retry($decider, $delay), 'retry');
  631. } else {
  632. $defaultDecider = RetryMiddlewareV2::createDefaultDecider(
  633. new QuotaManager(),
  634. $config->getMaxAttempts()
  635. );
  636. $list->appendSign(
  637. RetryMiddlewareV2::wrap(
  638. $config,
  639. [
  640. 'collect_stats' => $args['stats']['retries'],
  641. 'decider' => function(
  642. $attempts,
  643. CommandInterface $cmd,
  644. $result
  645. ) use ($defaultDecider, $config) {
  646. $isRetryable = $defaultDecider($attempts, $cmd, $result);
  647. if (!$isRetryable
  648. && $result instanceof AwsException
  649. && $attempts < $config->getMaxAttempts()
  650. ) {
  651. if (!empty($result->getResponse())
  652. && strpos(
  653. $result->getResponse()->getBody(),
  654. 'Your socket connection to the server'
  655. ) !== false
  656. ) {
  657. $isRetryable = false;
  658. }
  659. if ($result->getPrevious() instanceof RequestException
  660. && $cmd->getName() !== 'CompleteMultipartUpload'
  661. ) {
  662. $isRetryable = true;
  663. }
  664. }
  665. return $isRetryable;
  666. }
  667. ]
  668. ),
  669. 'retry'
  670. );
  671. }
  672. }
  673. }
  674. /** @internal */
  675. public static function _applyApiProvider($value, array &$args, HandlerList $list)
  676. {
  677. ClientResolver::_apply_api_provider($value, $args);
  678. $args['parser'] = new GetBucketLocationParser(
  679. new AmbiguousSuccessParser(
  680. new RetryableMalformedResponseParser(
  681. $args['parser'],
  682. $args['exception_class']
  683. ),
  684. $args['error_parser'],
  685. $args['exception_class']
  686. )
  687. );
  688. }
  689. /**
  690. * @internal
  691. * @codeCoverageIgnore
  692. */
  693. public static function applyDocFilters(array $api, array $docs)
  694. {
  695. $b64 = '<div class="alert alert-info">This value will be base64 encoded on your behalf.</div>';
  696. $opt = '<div class="alert alert-info">This value will be computed for you it is not supplied.</div>';
  697. // Add a note on the CopyObject docs
  698. $s3ExceptionRetryMessage = "<p>Additional info on response behavior: if there is"
  699. . " an internal error in S3 after the request was successfully recieved,"
  700. . " a 200 response will be returned with an <code>S3Exception</code> embedded"
  701. . " in it; this will still be caught and retried by"
  702. . " <code>RetryMiddleware.</code></p>";
  703. $docs['operations']['CopyObject'] .= $s3ExceptionRetryMessage;
  704. $docs['operations']['CompleteMultipartUpload'] .= $s3ExceptionRetryMessage;
  705. $docs['operations']['UploadPartCopy'] .= $s3ExceptionRetryMessage;
  706. $docs['operations']['UploadPart'] .= $s3ExceptionRetryMessage;
  707. // Add the SourceFile parameter.
  708. $docs['shapes']['SourceFile']['base'] = 'The path to a file on disk to use instead of the Body parameter.';
  709. $api['shapes']['SourceFile'] = ['type' => 'string'];
  710. $api['shapes']['PutObjectRequest']['members']['SourceFile'] = ['shape' => 'SourceFile'];
  711. $api['shapes']['UploadPartRequest']['members']['SourceFile'] = ['shape' => 'SourceFile'];
  712. // Add the ContentSHA256 parameter.
  713. $docs['shapes']['ContentSHA256']['base'] = 'A SHA256 hash of the body content of the request.';
  714. $api['shapes']['ContentSHA256'] = ['type' => 'string'];
  715. $api['shapes']['PutObjectRequest']['members']['ContentSHA256'] = ['shape' => 'ContentSHA256'];
  716. $api['shapes']['UploadPartRequest']['members']['ContentSHA256'] = ['shape' => 'ContentSHA256'];
  717. unset($api['shapes']['PutObjectRequest']['members']['ContentMD5']);
  718. unset($api['shapes']['UploadPartRequest']['members']['ContentMD5']);
  719. $docs['shapes']['ContentSHA256']['append'] = $opt;
  720. // Add the SaveAs parameter.
  721. $docs['shapes']['SaveAs']['base'] = 'The path to a file on disk to save the object data.';
  722. $api['shapes']['SaveAs'] = ['type' => 'string'];
  723. $api['shapes']['GetObjectRequest']['members']['SaveAs'] = ['shape' => 'SaveAs'];
  724. // Several SSECustomerKey documentation updates.
  725. $docs['shapes']['SSECustomerKey']['append'] = $b64;
  726. $docs['shapes']['CopySourceSSECustomerKey']['append'] = $b64;
  727. $docs['shapes']['SSECustomerKeyMd5']['append'] = $opt;
  728. // Add the ObjectURL to various output shapes and documentation.
  729. $docs['shapes']['ObjectURL']['base'] = 'The URI of the created object.';
  730. $api['shapes']['ObjectURL'] = ['type' => 'string'];
  731. $api['shapes']['PutObjectOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
  732. $api['shapes']['CopyObjectOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
  733. $api['shapes']['CompleteMultipartUploadOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
  734. // Fix references to Location Constraint.
  735. unset($api['shapes']['CreateBucketRequest']['payload']);
  736. $api['shapes']['BucketLocationConstraint']['enum'] = [
  737. "ap-northeast-1",
  738. "ap-southeast-2",
  739. "ap-southeast-1",
  740. "cn-north-1",
  741. "eu-central-1",
  742. "eu-west-1",
  743. "us-east-1",
  744. "us-west-1",
  745. "us-west-2",
  746. "sa-east-1",
  747. ];
  748. // Add a note that the ContentMD5 is optional.
  749. $docs['shapes']['ContentMD5']['append'] = '<div class="alert alert-info">The value will be computed on '
  750. . 'your behalf.</div>';
  751. return [
  752. new Service($api, ApiProvider::defaultProvider()),
  753. new DocModel($docs)
  754. ];
  755. }
  756. /**
  757. * @internal
  758. * @codeCoverageIgnore
  759. */
  760. public static function addDocExamples($examples)
  761. {
  762. $getObjectExample = [
  763. 'input' => [
  764. 'Bucket' => 'arn:aws:s3:us-east-1:123456789012:accesspoint:myaccesspoint',
  765. 'Key' => 'my-key'
  766. ],
  767. 'output' => [
  768. 'Body' => 'class GuzzleHttp\Psr7\Stream#208 (7) {...}',
  769. 'ContentLength' => '11',
  770. 'ContentType' => 'application/octet-stream',
  771. ],
  772. 'comments' => [
  773. 'input' => '',
  774. 'output' => 'Simplified example output'
  775. ],
  776. 'description' => 'The following example retrieves an object by referencing the bucket via an S3 accesss point ARN. Result output is simplified for the example.',
  777. 'id' => '',
  778. 'title' => 'To get an object via an S3 access point ARN'
  779. ];
  780. if (isset($examples['GetObject'])) {
  781. $examples['GetObject'] []= $getObjectExample;
  782. } else {
  783. $examples['GetObject'] = [$getObjectExample];
  784. }
  785. $putObjectExample = [
  786. 'input' => [
  787. 'Bucket' => 'arn:aws:s3:us-east-1:123456789012:accesspoint:myaccesspoint',
  788. 'Key' => 'my-key',
  789. 'Body' => 'my-body',
  790. ],
  791. 'output' => [
  792. 'ObjectURL' => 'https://my-bucket.s3.us-east-1.amazonaws.com/my-key'
  793. ],
  794. 'comments' => [
  795. 'input' => '',
  796. 'output' => 'Simplified example output'
  797. ],
  798. 'description' => 'The following example uploads an object by referencing the bucket via an S3 accesss point ARN. Result output is simplified for the example.',
  799. 'id' => '',
  800. 'title' => 'To upload an object via an S3 access point ARN'
  801. ];
  802. if (isset($examples['PutObject'])) {
  803. $examples['PutObject'] []= $putObjectExample;
  804. } else {
  805. $examples['PutObject'] = [$putObjectExample];
  806. }
  807. return $examples;
  808. }
  809. }