]> git.mxchange.org Git - friendica-addons.git/blob - s3_storage/vendor/akeeba/s3/README.md
eb3c5b531e6777d1b67a9725118e4ccdddd7648c
[friendica-addons.git] / s3_storage / vendor / akeeba / s3 / README.md
1 # Akeeba Amazon S3 Connector
2
3 A compact, dependency-less Amazon S3 API client implementing the most commonly used features
4
5 ## Why reinvent the wheel
6
7 After having a lot of impossible to debug problems with Amazon's Guzzle-based AWS SDK we decided to roll our own connector for Amazon S3. This is by no means a complete implementation, just a small subset of S3's features which are required by our software. The design goals are simplicity, no external dependencies and a low memory footprint.
8
9 This code was originally based on [S3.php written by Donovan Schonknecht](http://undesigned.org.za/2007/10/22/amazon-s3-php-class) which is available under a BSD-like license. This repository no longer reflects the original author's work and should not be confused with it.
10
11 This software is distributed under the GNU General Public License version 3 or, at your option, any later version published by the Free Software Foundation (FSF). In short, it's GPL-3.0-or-later, as noted in composer.json.
12
13 ## Important notes about version 2
14
15 ### PHP version support since 2.0
16
17 Akeeba Amazon S3 Connector version 2 has dropped support for PHP 5.3 to 7.0 inclusive.
18
19 The most significant change in this version is that all methods use scalar type hints for parameters and return values. This _may_ break existing consumers which relied on implicit type conversion.
20
21 ### Namespace change since 2.3
22
23 Up to and including version 2.2 of the library, the namespace was `\Akeeba\Engine\Postproc\Connector\S3v4`. From version 2.3 of the library the namespace has changed to `\Akeeba\S3`.
24
25 The library automatically registers aliases of the old classes to the new ones, thus ensuring updating the library will not introduce backwards incompatible changes. This is why it's not a major version update. Aliases will remain in place until at least version 3.0 of the library.
26
27 ## Using the connector
28
29 You need to define a constant before using or referencing any class in the library:
30
31 ```php
32 defined('AKEEBAENGINE') or define('AKEEBAENGINE', 1);
33 ```
34
35 All library files have a line similar to
36
37 ```php
38 defined('AKEEBAENGINE') or die();
39 ```
40
41 to prevent direct access to the libraries files. This is intentional. The primary use case for this library is mass-distributed software which gets installed in a publicly accessible subdirectory of the web root. This line prevents any accidental path disclosure from PHP error messages if someone were to access these files directly on misconfigured servers.
42
43 If you are writing a Joomla extension, especially a plugin or module, please _always_ check if the constant has already been defined before defining it yourself. Thank you! 
44
45 ### Get a connector object
46
47 ```php
48 $configuration = new \Akeeba\S3\Configuration(
49         'YourAmazonAccessKey',
50         'YourAmazonSecretKey'
51 );
52
53 $connector = new \Akeeba\S3\Connector($configuration);
54 ```
55
56 If you are running inside an Amazon EC2 instance you can fetch temporary credentials from the instance's metadata
57 server using the IAM Role attached to the EC2 instance. In this case you need to do this (169.254.169.254 is a fixed
58 IP hosting the instance's metadata cache service):
59
60 ```php
61 $role = file_get_contents('http://169.254.169.254/latest/meta-data/iam/security-credentials/');
62 $jsonCredentials = file_get_contents('http://169.254.169.254/latest/meta-data/iam/security-credentials/' . $role);
63 $credentials = json_decode($jsonCredentials, true);
64 $configuration = new \Akeeba\S3\Configuration(
65         $credentials['AccessKeyId'],
66         $credentials['SecretAccessKey'],
67         'v4',
68         $yourRegion
69 );
70 $configuration->setToken($credentials['Token']);
71
72 $connector = new \Akeeba\S3\Connector($configuration);
73 ```
74
75 where `$yourRegion` is the AWS region of your bucket, e.g. `us-east-1`. Please note that we are passing the security
76 token (`$credentials['Token']`) to the Configuration object. This is REQUIRED. The temporary credentials returned by
77 the metadata service won't work without it.
78
79 Another point worth noting is that the temporary credentials don't last forever. Check the `$credentials['Expiration']` to see
80 when they are about to expire. Amazon recommends that you retry fetching new credentials from the metadata service
81 10 minutes before your cached credentials are set to expire. The metadata service is guaranteed to provision fresh
82 temporary credentials by that time. 
83
84 ### Listing buckets
85
86 ```php
87 $listing = $connector->listBuckets(true);
88 ```
89
90 Returns an array like this:
91
92 ```
93 array(2) {
94   'owner' =>
95   array(2) {
96     'id' =>
97     string(64) "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
98     'name' =>
99     string(8) "someUserName"
100   }
101   'buckets' =>
102   array(3) {
103     [0] =>
104     array(2) {
105       'name' =>
106       string(10) "mybucket"
107       'time' =>
108       int(1267730711)
109     }
110     [1] =>
111     array(2) {
112       'name' =>
113       string(10) "anotherbucket"
114       'time' =>
115       int(1269516249)
116     }
117     [2] =>
118     array(2) {
119       'name' =>
120       string(11) "differentbucket"
121       'time' =>
122       int(1354458048)
123     }
124   }
125 }
126 ```
127
128 ### Listing bucket contents
129
130 ```php
131 $listing = $connector->getBucket('mybucket', 'path/to/list/');
132 ```
133
134 If you want to list "subdirectories" you need to do
135  
136 ```php
137 $listing = $connector->getBucket('mybucket', 'path/to/list/', null, null, '/', true);
138 ```
139
140 The last parameter (common prefixes) controls the listing of "subdirectories"
141
142 ### Uploading (small) files
143
144 From a file:
145
146 ```php
147 $input = \Akeeba\S3\Input::createFromFile($sourceFile);   
148 $connector->putObject($input, 'mybucket', 'path/to/myfile.txt');
149 ```
150
151 From a string:
152
153 ```php
154 $input = \Akeeba\S3\Input::createFromData($sourceString);   
155 $connector->putObject($input, 'mybucket', 'path/to/myfile.txt');
156 ```
157
158 From a stream resource:
159
160 ```php
161 $input = \Akeeba\S3\Input::createFromResource($streamHandle, false);   
162 $connector->putObject($input, 'mybucket', 'path/to/myfile.txt');
163 ```
164
165 In all cases the entirety of the file has to be loaded in memory.
166
167 ### Uploading large file with multipart (chunked) uploads
168
169 Files are uploaded in 5Mb chunks.
170
171 ```php
172 $input = \Akeeba\S3\Input::createFromFile($sourceFile);
173 $uploadId = $connector->startMultipart($input, 'mybucket', 'mypath/movie.mov');
174
175 $eTags = array();
176 $eTag = null;
177 $partNumber = 0;
178
179 do
180 {
181         // IMPORTANT: You MUST create the input afresh before each uploadMultipart call
182         $input = \Akeeba\S3\Input::createFromFile($sourceFile);
183         $input->setUploadID($uploadId);
184         $input->setPartNumber(++$partNumber);
185         
186         $eTag = $connector->uploadMultipart($input, 'mybucket', 'mypath/movie.mov');
187
188         if (!is_null($eTag))
189         {
190                 $eTags[] = $eTag;
191         }
192 }
193 while (!is_null($eTag));
194
195 // IMPORTANT: You MUST create the input afresh before finalising the multipart upload
196 $input = \Akeeba\S3\Input::createFromFile($sourceFile);
197 $input->setUploadID($uploadId);
198 $input->setEtags($eTags);
199
200 $connector->finalizeMultipart($input, 'mybucket', 'mypath/movie.mov');
201 ```
202
203 As long as you keep track of the UploadId, PartNumber and ETags you can have each uploadMultipart call in a separate
204 page load to prevent timeouts.
205
206 ### Get presigned URLs
207
208 Allows browsers to download files directly without exposing your credentials and without going through your server:
209
210 ```php
211 $preSignedURL = $connector->getAuthenticatedURL('mybucket', 'path/to/file.jpg', 60);
212 ```
213
214 The last parameter controls how many seconds into the future this URL will be valid.
215
216 ### Download
217
218 To a file with absolute path `$targetFile`
219
220 ```php
221 $connector->getObject('mybucket', 'path/to/file.jpg', $targetFile);
222 ```
223
224 To a string
225
226 ```php
227 $content = $connector->getObject('mybucket', 'path/to/file.jpg', false);
228 ```
229
230 ### Delete an object
231
232 ```php
233 $connector->deleteObject('mybucket', 'path/to/file.jpg');
234 ```
235
236 ### Test if an object exists
237
238 ```php
239 try
240 {
241     $headers = $connector->headObject('mybucket', 'path/to/file.jpg');
242     $exists  = true;
243 }
244 catch (\Akeeba\S3\Exception\CannotGetFile $e)
245 {
246     $headers = [];
247     $exists  = false;
248 }
249 ```
250
251 The `$headers` variable contains an array with the S3 headers returned by the [HeadObject(https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html) API call. The header keys are always in lowercase. Please note that _not all_ of the headers Amazon describes in their documentation are returned in every request.
252
253 ## Configuration options
254
255 The Configuration option has optional methods which can be used to enable some useful features in the connector.
256
257 You need to execute these methods against the Configuration object before passing it to the Connector's constructor. For example:
258
259 ```php
260 $configuration = new \Akeeba\S3\Configuration(
261         'YourAmazonAccessKey',
262         'YourAmazonSecretKey'
263 );
264
265 // Use v4 signatures and Dualstack URLs
266 $configuration->setSignatureMethod('v4');
267 $configuration->setUseDualstackUrl(true);
268
269 $connector = new \Akeeba\S3\Connector($configuration);
270 ```
271
272 ### HTTPS vs plain HTTP
273
274 **It is not recommended to use plain HTTP connections to Amazon S3**. If, however, you have no other option you can tell the Configuration object to use plain HTTP URLs:
275
276 ```php
277 $configuration->setSSL(false);
278 ```  
279
280 ### Custom endpoint
281
282 You can use the Akeeba Amazon S3 Connector library with S3-compatible APIs such as DigitalOcean's Spaces by changing the endpoint URL.
283
284 Please note that if the S3-compatible APi uses v4 signatures you need to enter the region-specific endpoint domain name and the region when initializing the object, e.g.:
285
286 ```php
287 // DigitalOcean Spaces using v4 signatures
288 // The access credentials are those used in the example at https://developers.digitalocean.com/documentation/spaces/
289 $configuration = new \Akeeba\S3\Configuration(
290         '532SZONTQ6ALKBCU94OU',
291         'zCkY83KVDXD8u83RouEYPKEm/dhPSPB45XsfnWj8fxQ',
292     'v4',
293     'nyc3'
294 );
295 $configuration->setEndpoint('nyc3.digitaloceanspaces.com');
296
297 $connector = new \Akeeba\S3\Connector($configuration);
298 ```
299
300 If your S3-compatible API uses v2 signatures you do not need to specify a region.
301
302 ```php
303 // DigitalOcean Spaces using v2 signatures
304 // The access credentials are those used in the example at https://developers.digitalocean.com/documentation/spaces/
305 $configuration = new \Akeeba\S3\Configuration(
306         '532SZONTQ6ALKBCU94OU',
307         'zCkY83KVDXD8u83RouEYPKEm/dhPSPB45XsfnWj8fxQ',
308     'v2'
309 );
310 $configuration->setEndpoint('nyc3.digitaloceanspaces.com');
311
312 $connector = new \Akeeba\S3\Connector($configuration);
313 ```
314
315 ### Legacy path-style access
316
317 The S3 API calls made by this library will use by default the subdomain-style access. That is to say, the endpoint will be prefixed with the name of the bucket. For example, a bucket called `example` in the `eu-west-1` region will be accessed using the endpoint URL `example.s3.eu-west-1.amazonaws.com`.
318
319 If you have buckets with characters that are invalid in the context of DNS (most notably dots and uppercase characters) this will fail. You will need to use the legacy path style instead. In this case the endpoint used is the generic region specific one (`s3.eu-west-1.amazonaws.com` in our example above) and the API URL will be prefixed with the bucket name.
320
321 You need to do:
322 ```php
323 $configuration->setUseLegacyPathStyle(true);
324 ```
325
326 Caveat: this will not work with v2 signatures if you are using Amazon AWS S3 proper. It will very likely work with the v2 signatures if you are using a custom endpoint, though.
327
328 ### Dualstack (IPv4 and IPv6) support
329
330 Amazon S3 supports dual-stack URLs which resolve to both IPv4 and IPv6 addresses. By default they are _not_ used. If you want to enable this feature you need to do:
331
332 ```php
333 $connector->setUseDualstackUrl(true);
334 ```
335
336 Caveat: this option only takes effect if you are using Amazon S3 proper. It will _not_ have any effect with custom endpoints.