This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
/
S3AccessWrapper.php
442 lines (412 loc) · 15.3 KB
/
S3AccessWrapper.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
<?php
/*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*
*/
namespace Pydio\Access\Driver\StreamProvider\S3;
use Pydio\Access\Core\Model\AJXP_Node;
use Pydio\Access\Driver\StreamProvider\FS\FsAccessWrapper;
use Pydio\Core\Model\ContextInterface;
use Pydio\Core\Services\ApplicationState;
use Pydio\Core\Utils\FileHelper;
use Pydio\Core\Utils\Vars\UrlUtils;
use Pydio\Log\Core\Logger;
defined('AJXP_EXEC') or die('Access not allowed');
require_once(AJXP_INSTALL_PATH . "/plugins/access.fs/FsAccessWrapper.php");
/**
* Encapsulation of the PEAR webDAV client
* @package AjaXplorer_Plugins
* @subpackage Access
*/
class S3AccessWrapper extends FsAccessWrapper
{
public static $lastException;
protected static $clients = [];
/**
* @param AJXP_Node $node
* @return array
*/
public static function getResolvedOptionsForNode($node)
{
$context = $node->getContext();
$repository = $node->getRepository();
$options = [
"TYPE" => "s3"
];
$optKeys = ["API_KEY", "SECRET_KEY", "CONTAINER", "PATH", "SIGNATURE_VERSION", "STORAGE_URL", "REGION", "PROXY", "API_VERSION", "VHOST_NOT_SUPPORTED"];
foreach($optKeys as $key){
$options[$key] = $repository->getContextOption($context, $key);
}
if(empty($options["API_VERSION"])) {
$options["API_VERSION"] = "latest";
}
return $options;
}
/**
* @param ContextInterface $ctx
* @param boolean $registerStream
* @return S3Client
*/
public static function getClientForContext(ContextInterface $ctx, $registerStream = true)
{
$repoObject = $ctx->getRepository();
if (!isSet(self::$clients[$repoObject->getId()])) {
// Get a client
$options = array(
'key' => $repoObject->getContextOption($ctx, "API_KEY"),
'secret' => $repoObject->getContextOption($ctx, "SECRET_KEY")
);
$signatureVersion = $repoObject->getContextOption($ctx, "SIGNATURE_VERSION");
if (!empty($signatureVersion)) {
$options['signature'] = $signatureVersion;
}
$apiVersion = $repoObject->getContextOption($ctx, "API_VERSION");
if ($apiVersion === "") {
$apiVersion = "latest";
}
$config = [
"version" => $apiVersion,
"credentials" => $options
];
$region = $repoObject->getContextOption($ctx, "REGION");
if (!empty($region)) {
$config["region"] = $region;
}
$proxy = $repoObject->getContextOption($ctx, "PROXY");
if (!empty($proxy)) {
$config['http'] = array('proxy' => $proxy);
}
$baseURL = $repoObject->getContextOption($ctx, "STORAGE_URL");
if (!empty($baseURL)) {
$config["endpoint"] = $baseURL;
$config["use_path_style_endpoint"] = true;
}
require_once("S3Client.php");
$s3Client = new S3Client($config, $repoObject->getId());
$s3Client->registerStreamWrapper();
self::$clients[$repoObject->getId()] = $s3Client;
}
return self::$clients[$repoObject->getId()];
}
/**
* Initialize the stream from the given path.
* Concretely, transform ajxp.s3:// into s3://
*
* @param string $path
* @param $streamType
* @param bool $storeOpenContext
* @param bool $skipZip
* @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path
* @throws \Exception
*/
protected static function initPath($path, $streamType, $storeOpenContext = false, $skipZip = false)
{
$url = UrlUtils::mbParseUrl($path);
$node = new AJXP_Node($path);
$repoId = $node->getRepositoryId();
$repoObject = $node->getRepository();
if (!isSet($repoObject)) {
$e = new \Exception("Cannot find repository with id " . $repoId);
self::$lastException = $e;
throw $e;
}
// Make sure to register s3:// wrapper
$client = self::getClientForContext($node->getContext(), true);
$protocol = "s3://";
if ($client instanceof S3Client) {
$protocol = "s3." . $repoId . "://";
}
$basePath = $repoObject->getContextOption($node->getContext(), "PATH");
$baseContainer = $repoObject->getContextOption($node->getContext(), "CONTAINER");
if (!empty($basePath)) {
$baseContainer .= "/".trim($basePath, "/");
}
$p = $protocol . $baseContainer . str_replace("//", "/", $url["path"]);
return $p;
}
/**
* Opens the stream
* Diff with parent class : do not "securePath", as it removes double slash
*
* @param String $path Maybe in the form "ajxp.fs://repositoryId/pathToFile"
* @param String $mode
* @param string $options
* @param resource $context
* @return resource|bool
* @internal param string $opened_path
*/
public function stream_open($path, $mode, $options, &$context)
{
try {
$this->realPath = $this->initPath($path, "file");
} catch (\Exception $e) {
Logger::error(__CLASS__, "stream_open", "Error while opening stream $path");
return false;
}
if ($this->realPath == -1) {
$this->fp = -1;
return true;
} else {
$this->fp = fopen($this->realPath, $mode, $options);
return ($this->fp !== false);
}
}
/**
* Stats the given path.
* Fix PEAR by adding S_ISREG mask when file case.
*
* @param string $path
* @param integer $flags
* @return array
*/
public function url_stat($path, $flags)
{
// File and zip case
// AJXP_Logger::debug(__CLASS__,__FUNCTION__,"Stating $path");
$stat = @stat($this->initPath($path, "file"));
if ($stat == null) return null;
if ($stat["mode"] == 0666) {
$stat[2] = $stat["mode"] |= 0100000; // S_ISREG
}
if($stat["mode"] === 0040777){
$node = new AJXP_Node($path);
$ctx = $node->getContext();
$repoObject = $node->getRepository();
$basePath = $repoObject->getContextOption($ctx, "PATH");
$result = $this->getClientForContext($ctx)->listObjects([
'Bucket' => $repoObject->getContextOption($ctx, "CONTAINER"),
'Prefix' => ltrim( trim($basePath, "/") ."/". ltrim($node->getPath(), "/"), '/') . '/',
'MaxKeys' => 1
]);
if (isSet($result['Contents']) && isSet($result['Contents'][0]['LastModified'])) {
$stat = $this->statForDir($result['Contents'][0]['LastModified']);
}
}
return $stat;
}
/**
* @param $lastModified
* @return array
*/
protected function statForDir($lastModified){
$time = strtotime($lastModified);
return [
0 => 0, 'dev' => 0,
1 => 0, 'ino' => 0,
2 => 0040777, 'mode' => 0040777,
3 => 0, 'nlink' => 0,
4 => 0, 'uid' => 0,
5 => 0, 'gid' => 0,
6 => -1, 'rdev' => -1,
7 => 0, 'size' => 0,
8 => $time, 'atime' => $time,
9 => $time, 'mtime' => $time,
10 => $time, 'ctime' => $time,
11 => -1, 'blksize' => -1,
12 => -1, 'blocks' => -1,
];
}
/**
* Opens a handle to the dir
* Fix PEAR by being sure it ends up with "/", to avoid
* adding the current dir to the children list.
*
* @param string $path
* @param string $options
* @return resource|bool
*/
public function dir_opendir($path, $options)
{
$this->realPath = $this->initPath($path, "dir", true);
if ($this->realPath[strlen($this->realPath) - 1] != "/") {
$this->realPath .= "/";
}
if (is_string($this->realPath)) {
$this->dH = @opendir($this->realPath);
} else if ($this->realPath == -1) {
$this->dH = -1;
}
return $this->dH !== false;
}
/**
* @param string $path
* @param int $mode
* @param int $options
* @return bool
* @throws \Exception
*/
public function mkdir($path, $mode, $options){
$node = new AJXP_Node($path);
$repoId = $node->getRepositoryId();
$repoObject = $node->getRepository();
if (!isSet($repoObject)) {
$e = new \Exception("Cannot find repository with id " . $repoId);
self::$lastException = $e;
throw $e;
}
$folderEmptyFile = $repoObject->getContextOption($node->getContext(), "S3_FOLDER_EMPTY_FILE");
if(!empty($folderEmptyFile)){
$s3path = $this->initPath($path, "file") . "/" . $folderEmptyFile;
file_put_contents($s3path, " ");
return true;
}else{
return mkdir($this->initPath($path, "file"), $mode);
}
}
/**
* DUPLICATE STATIC FUNCTIONS TO BE SURE
* NOT TO MESS WITH self:: CALLS
* @param $tmpDir
* @param $tmpFile
*/
public static function removeTmpFile($tmpDir, $tmpFile)
{
if (is_file($tmpFile)) unlink($tmpFile);
if (is_dir($tmpDir)) rmdir($tmpDir);
}
/**
* @inheritdoc
*/
public static function getRealFSReference($path, $persistent = false)
{
$tmpFile = ApplicationState::getTemporaryFolder() . "/" . md5(time()) . "." . pathinfo($path, PATHINFO_EXTENSION);
$tmpHandle = fopen($tmpFile, "wb");
self::copyFileInStream($path, $tmpHandle);
fclose($tmpHandle);
if (!$persistent) {
register_shutdown_function(function () use ($tmpFile) {
FileHelper::silentUnlink($tmpFile);
});
}
return $tmpFile;
}
/**
* @inheritdoc
*/
public static function isRemote($url)
{
return true;
}
/**
* @inheritdoc
*/
public static function copyFileInStream($path, $stream)
{
Logger::debug(__CLASS__, __FUNCTION__, "Should load " . $path);
$fp = fopen($path, "r");
if (!is_resource($fp)) return;
while (!feof($fp)) {
$data = fread($fp, 4096);
fwrite($stream, $data, strlen($data));
}
fclose($fp);
}
/**
* @inheritdoc
*/
public static function changeMode($path, $chmodValue)
{
}
/**
* @inheritdoc
*/
public function rename($from, $to)
{
$node = new AJXP_Node($from);
$ctx = $node->getContext();
$repoObject = $node->getRepository();
if (!isSet($repoObject)) {
$e = new \Exception("Cannot find repository with id " . $node->getRepositoryId());
self::$lastException = $e;
throw $e;
}
$isViPR = $repoObject->getContextOption($ctx, "IS_VIPR");
$isDir = false;
if ($isViPR === true) {
if (is_dir($from . "/")) {
$from .= '/';
$to .= '/';
$isDir = true;
}
}
if ($isDir === true || is_dir($from)) {
Logger::debug(__CLASS__, __FUNCTION__, "S3 Renaming dir $from to $to");
$s3Client = self::getClientForContext($node->getContext(), false);
$bucket = $repoObject->getContextOption($ctx, "CONTAINER");
$basePath = $repoObject->getContextOption($ctx, "PATH");
$fromKeyname = trim(str_replace("//", "/", $basePath . UrlUtils::mbParseUrl($from, PHP_URL_PATH)), '/');
$toKeyname = trim(str_replace("//", "/", $basePath . UrlUtils::mbParseUrl($to, PHP_URL_PATH)), '/');
if ($isViPR) {
$toKeyname .= '/';
$parts = explode('/', $bucket);
$bucket = $parts[0];
if (isset($parts[1])) {
$fromKeyname = $parts[1] . "/" . $fromKeyname;
}
}
// Perform a batch of CopyObject operations.
$batch = array();
$failed = array();
$iterator = $s3Client->getIterator('ListObjects', array(
'Bucket' => $bucket,
'Prefix' => $fromKeyname . "/"
));
$toDelete = array();
Logger::debug(__CLASS__, __FUNCTION__, "S3 Got iterator looking for prefix " . $fromKeyname . "/ , and toKeyName=" . $toKeyname);
foreach ($iterator as $object) {
$currentFrom = $object['Key'];
$currentTo = $toKeyname . substr($currentFrom, strlen($fromKeyname));
if ($isViPR) {
if (isset($parts[1])) {
$currentTo = $parts[1] . "/" . $currentTo;
}
}
Logger::debug(__CLASS__, __FUNCTION__, "S3 Should move one object " . $currentFrom . " to new key :" . $currentTo);
$batch[] = $s3Client->getCommand('CopyObject', array(
'Bucket' => $bucket,
'Key' => "{$currentTo}",
'CopySource' => "{$bucket}/" . rawurlencode($currentFrom),
));
$toDelete[] = $currentFrom;
}
Logger::debug(__CLASS__, __FUNCTION__, "S3 Execute batch on " . count($batch) . " objects");
foreach ($batch as $command) {
$successful = $s3Client->execute($command);
}
//We must delete the "/" in $fromKeyname because we want to delete the folder
$clear = \Aws\S3\BatchDelete::fromIterator($s3Client, $bucket, $s3Client->getIterator('ListObjects', array(
'Bucket' => $bucket,
'Prefix' => $fromKeyname
)), ['batch_size' => 5]);
$clear->delete();
if (count($failed)) {
foreach ($failed as $c) {
// $c is a Aws\S3\Command\S3Command
Logger::error("S3Wrapper", __FUNCTION__, "Error while copying: " . $c->getOperation()->getServiceDescription());
}
self::$lastException = new \Exception("Failed moving folder: " . count($failed));
return false;
}
return true;
} else {
Logger::debug(__CLASS__, __FUNCTION__, "S3 Execute standard rename on " . $from . " to " . $to);
return parent::rename($from, $to);
}
}
}