-
Notifications
You must be signed in to change notification settings - Fork 22
/
StreamWrapper.php
426 lines (376 loc) · 11 KB
/
StreamWrapper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
<?php
namespace Drupal\amazons3;
use Capgemini\Cache\DrupalDoctrineCache;
use Guzzle\Cache\DoctrineCacheAdapter;
use \Aws\S3\S3Client as AwsS3Client;
/**
* @file
* Drupal stream wrapper implementation for Amazon S3
*
* Implements DrupalStreamWrapperInterface to provide an Amazon S3 wrapper with
* the s3:// prefix.
*/
class StreamWrapper extends \Aws\S3\StreamWrapper implements \DrupalStreamWrapperInterface {
use DrupalAdapter\Common;
use DrupalAdapter\FileMimetypes;
/**
* The path to the image style generation callback.
*
* If this is changed, be sure to update amazons3_menu() as well.
*
* @const string
*/
const stylesCallback = 'amazons3/image-derivative';
/**
* The name of the S3Client class to use.
*
* @var string
*/
protected static $s3ClientClass = '\Drupal\amazons3\S3Client';
/**
* Default configuration used when constructing a new stream wrapper.
*
* @var \Drupal\amazons3\StreamWrapperConfiguration
*/
protected static $defaultConfig;
/**
* Configuration for this stream wrapper.
*
* @var \Drupal\amazons3\StreamWrapperConfiguration
*/
protected $config;
/**
* Instance URI referenced as "s3://bucket/key"
*
* @var S3Url
*/
protected $uri;
/**
* The URL associated with the S3 object.
*
* @var S3URL
*/
protected $s3Url;
/**
* Set default configuration to use when constructing a new stream wrapper.
*
* @param \Drupal\amazons3\StreamWrapperConfiguration $config
*/
public static function setDefaultConfig(StreamWrapperConfiguration $config) {
static::$defaultConfig = $config;
}
/**
* Return the default configuration.
*
* @return \Drupal\amazons3\StreamWrapperConfiguration
*/
public static function getDefaultConfig() {
return static::$defaultConfig;
}
/**
* Set the name of the S3Client class to use.
*
* @param string $client
*/
public static function setS3ClientClass($client) {
static::$s3ClientClass = $client;
}
/**
* Construct a new stream wrapper.
*
* @param \Drupal\amazons3\StreamWrapperConfiguration $config
* (optional) A specific configuration to use for this wrapper.
*/
public function __construct(StreamWrapperConfiguration $config = NULL) {
if (!$config) {
if (static::$defaultConfig) {
$config = static::$defaultConfig;
}
else {
// @codeCoverageIgnoreStart
$config = StreamWrapperConfiguration::fromDrupalVariables();
// @codeCoverageIgnoreEnd
}
}
$this->config = $config;
if (!$this->getClient()) {
/** @var S3Client $name */
$name = static::$s3ClientClass;
$this->setClient($name::factory());
}
// @todo Add a static cache.
if ($this->config->isCaching() && !static::$cache) {
$cache = new Cache();
static::attachCache(
new DoctrineCacheAdapter($cache),
$this->config->getCacheLifetime()
);
}
}
/**
* Get the client associated with this stream wrapper.
*
* @return \Aws\S3\S3Client
*/
public static function getClient() {
return self::$client;
}
/**
* Set the client associated with this stream wrapper.
*
* Note that all stream wrapper instances share a global client.
*
* @param \Aws\S3\S3Client $client
* The client to use. Set to NULL to remove an existing client.
*/
public static function setClient(AwsS3Client $client = NULL) {
self::$client = $client;
}
/**
* Support for flock().
*
* S3 has no support for file locking. If it's needed, it has to be
* implemented at the application layer.
*
* @todo Investigate supporting stream_lock() with Drupal's lock API.
*
* @link https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
*
* @param string $operation
* One of the following:
* - LOCK_SH to acquire a shared lock (reader).
* - LOCK_EX to acquire an exclusive lock (writer).
* - LOCK_UN to release a lock (shared or exclusive).
* - LOCK_NB if you don't want flock() to block while locking (not
* supported on Windows).
*
* @return bool
* returns TRUE if lock was successful
*
* @link http://php.net/manual/en/streamwrapper.stream-lock.php
*
* @codeCoverageIgnore
*/
public function stream_lock($operation) {
return FALSE;
}
/**
* {@inheritdoc}
*/
function setUri($uri) {
// file_stream_wrapper_get_instance_by_scheme() assumes that all schemes
// can work without a directory, but S3 requires a bucket. If a raw scheme
// is passed in, we append our default bucket.
if ($uri == 's3://') {
$uri = 's3://' . $this->config->getBucket();
}
$this->uri = S3Url::factory($uri);
}
/**
* {@inheritdoc}
*/
public function getUri() {
return (string) $this->uri;
}
/**
* {@inheritdoc}
*/
public function getExternalUrl() {
if (!isset($this->uri)) {
throw new \LogicException('A URI must be set before calling getExternalUrl().');
}
$path_segments = $this->uri->getPathSegments();
$args = array();
// Image styles support
// Delivers the first request to an image from the private file system
// otherwise it returns an external URL to an image that has not been
// created yet.
if ($path_segments[0] === 'styles' && !file_exists((string) $this->uri)) {
return $this->url($this::stylesCallback . '/' . $this->uri->getBucket() . $this->uri->getPath(), array('absolute' => TRUE));
}
// Allow other modules to change the download link type.
// @todo Rather than passing an info array and a path, we should look into
// replacing the commandFactory and then letting it call a hook on any S3
// operation.
// $args = array_merge($args, module_invoke_all('amazons3_url_info', $local_path, $args));
// UI overrides.
// Presigned URLs.
// @todo Presigned URLs are now createPresignedUrl
/**
$timeout = $args['presigned_url'] ? time() + $args['presigned_url_timeout'] : 0;
foreach ($this->presignedUrls as $path => $timeout) {
if ($path === '*' || preg_match('#' . strtr($path, '#', '\#') . '#', $local_path)) {
$args['presigned_url'] = TRUE;
$args['presigned_url_timeout'] = $timeout;
break;
}
}**/
// Save as.
$expiry = NULL;
if ($this->forceDownload()) {
$args['ResponseContentDisposition'] = $this->getContentDispositionAttachment();
$expiry = time() + 60 * 60 * 24;
}
// Torrent URLs.
$path = $this->getLocalPath();
if ($this->useTorrent()) {
$path .= '?torrent';
}
// Generate a standard URL.
$url = static::$client->getObjectUrl($this->uri->getBucket(), $path, $expiry, $args);
return $url;
}
/**
* {@inheritdoc}
*/
public static function getMimeType($uri, $mapping = NULL) {
// Load the default file map.
// @codeCoverageIgnoreStart
if (!$mapping) {
$mapping = static::file_mimetype_mapping();
}
// @codeCoverageIgnoreEnd
$extension = '';
$file_parts = explode('.', basename($uri));
// Remove the first part: a full filename should not match an extension.
array_shift($file_parts);
// Iterate over the file parts, trying to find a match.
// For my.awesome.image.jpeg, we try:
// jpeg
// image.jpeg, and
// awesome.image.jpeg
while ($additional_part = array_pop($file_parts)) {
$extension = strtolower($additional_part . ($extension ? '.' . $extension : ''));
if (isset($mapping['extensions'][$extension])) {
return $mapping['mimetypes'][$mapping['extensions'][$extension]];
}
// @codeCoverageIgnoreStart
}
// @codeCoverageIgnoreEnd
return 'application/octet-stream';
}
/**
* {@inheritdoc}
*
* @codeCoverageIgnore
*/
public function chmod($mode) {
// TODO: Implement chmod() method.
return TRUE;
}
/**
* @return bool
* FALSE, as this stream wrapper does not support realpath().
*
* @codeCoverageIgnore
*/
public function realpath() {
return FALSE;
}
/**
* {@inheritdoc}
*/
public function dirname($uri = NULL) {
// drupal_dirname() doesn't call setUri() before calling. That lead our URI
// to be stuck at the default 's3://'' that is set by
// file_stream_wrapper_get_instance_by_scheme().
if ($uri) {
$this->setUri($uri);
}
$s3url = S3Url::factory($uri, $this->config);
$s3url->normalizePath();
$pathSegments = $s3url->getPathSegments();
array_pop($pathSegments);
$s3url->setPath($pathSegments);
return trim((string) $s3url, '/');
}
/**
* Return the local filesystem path.
*
* @return string
* The local path.
*/
protected function getLocalPath() {
$path = $this->uri->getPath();
$path = trim($path, '/');
return $path;
}
/**
* Override register() to force using hook_stream_wrappers().
*
* @param \Aws\S3\S3Client $client
*/
public static function register(AwsS3Client $client) {
throw new \LogicException('Drupal handles registration of stream wrappers. Implement hook_stream_wrappers() instead.');
}
/**
* Override getOptions() to default all files to be publicly readable.
*
* @return array
*/
public function getOptions() {
$options = parent::getOptions();
$options['ACL'] = 'public-read';
return $options;
}
/**
* Return the basename for this URI.
*
* @return string
* The basename of the URI.
*/
public function getBasename() {
if (!isset($this->uri)) {
throw new \LogicException('A URI must be set before calling getBasename().');
}
return basename($this->getLocalPath());
}
/**
* Return a string to use as a Content-Disposition header.
*
* @return string
* The header value.
*/
protected function getContentDispositionAttachment() {
// Encode the filename according to RFC2047.
return 'attachment; filename="' . mb_encode_mimeheader($this->getBasename()) . '"';
}
/**
* Find if this URI should force a download.
*
* @return bool
* TRUE if the local path of the stream URI should force a download. FALSE
* otherwise.
*/
protected function forceDownload() {
return $this->matchPathRegex($this->getLocalPath(), $this->config->getSaveAsPaths());
}
/**
* Find if a path matches a set of patterns.
*
* @param string $path
* The path to test against $patterns.
* @param array $patterns
* An array of regular expression patterns, without start and end markers.
*
* @return bool
* TRUE if $path matches at least one pattern, FALSE otherwise.
*/
protected static function matchPathRegex($path, array $patterns) {
foreach ($patterns as $pattern) {
if ($pattern === '*' || preg_match('#' . strtr($pattern, '#', '\#') . '#', $path)) {
return TRUE;
}
}
return FALSE;
}
/**
* Find if the URI should be returned as a torrent.
*
* @return bool
* TRUE if a torrent should be served, FALSE otherwise.
*/
protected function useTorrent() {
return $this->matchPathRegex($this->getLocalPath(), $this->config->getTorrentPaths());
}
}