-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputfieldFileS3.module
373 lines (313 loc) · 10.5 KB
/
InputfieldFileS3.module
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
<?php namespace ProcessWire;
use Aws\S3\S3Client;
/**
* An Inputfield for handling file uploads to AWS S3
*
*/
class InputfieldFileS3 extends InputfieldFile implements Module {
public static function getModuleInfo() {
return array(
'title' => __('InputfieldFileS3', __FILE__), // Module Title
'summary' => __('One or more file uploads (sortable)', __FILE__), // Module Summary
'version' => 005,
'autoload' => true,
);
}
public function init() {
parent::init();
$this->addHook('Pagefile::s3url', $this, 's3url');
if($this->cf){
$this->addHookProperty('Pagefile::cfurl', $this, 'cloudFrontUrl');
}
$this->addHookProperty("Pagefile::s3url", $this, "s3url");
}
/**
* Render markup for a file item
*
* @param Pagefile $pagefile
* @param string $id
* @param int $n
* @return string
*
*/
protected function ___renderItem($pagefile, $id, $n) {
$displayName = $this->getDisplayBasename($pagefile);
$deleteLabel = $this->labels['delete'];
$url = ($this->localStorage) ? $pagefile->url : $pagefile->s3url();
$out =
"<p class='InputfieldFileInfo InputfieldItemHeader ui-state-default ui-widget-header'>" .
wireIconMarkupFile($pagefile->basename, "fa-fw HideIfEmpty") .
"<a class='InputfieldFileName' title='$pagefile->basename' target='_blank' href='{$url}'>$displayName</a> " .
"<span class='InputfieldFileStats'>" . str_replace(' ', ' ', wireBytesStr($pagefile->fSize)) . "</span> ";
if(!$this->renderValueMode) $out .=
"<label class='InputfieldFileDelete'>" .
"<input type='checkbox' name='delete_$id' value='1' title='$deleteLabel' />" .
"<i class='fa fa-fw fa-trash'></i></label>";
$out .=
"</p>" .
"<div class='InputfieldFileData description ui-widget-content'>" .
$this->renderItemDescriptionField($pagefile, $id, $n);
if(!$this->renderValueMode) $out .=
"<input class='InputfieldFileSort' type='text' name='sort_$id' value='$n' />";
$out .=
"</div>";
return $out;
}
protected function ___fileAdded(Pagefile $pagefile) {
if($this->noUpload) return;
$isValid = $this->wire('sanitizer')->validateFile($pagefile->filename(), array(
'pagefile' => $pagefile
));
if($isValid === false) {
$errors = $this->wire('sanitizer')->errors('clear array');
throw new WireException(
$this->_('File failed validation') .
(count($errors) ? ": " . implode(', ', $errors) : "")
);
} else if($isValid === null) {
// there was no validator available for this file type
}
$message = $this->_('Added file:') . " {$pagefile->basename}"; // Label that precedes an added filename
if($this->isAjax && !$this->noAjax) {
if(!$this->localStorage) {
$this->uploadFileToS3($pagefile, $this->input->get->id);
}
$pagefile->fSize = @filesize($pagefile->filename);
$n = count($this->value);
if($n) $n--; // for sorting
$this->currentItem = $pagefile;
$markup = $this->fileAddedGetMarkup($pagefile, $n);
$this->ajaxResponse(false, $message, $pagefile->url, $pagefile->fSize, $markup);
} else {
$this->message($message);
}
}
/**
* @param string $filename
* @throws WireException
*
*/
protected function ___processInputAddFile($filename) {
$total = count($this->value);
$metadata = array();
$rm = null;
if($this->maxFiles > 1 && $total >= $this->maxFiles) return;
// allow replacement of file if maxFiles is 1
if($this->maxFiles == 1 && $total) {
$pagefile = $this->value->first();
$metadata = $this->extractMetadata($pagefile, $metadata);
$rm = true;
if($filename == $pagefile->basename) {
// use overwrite mode rather than replace mode when single file and same filename
if($this->overwrite) $rm = false;
}
if($rm) {
if($this->overwrite) $this->processInputDeleteFile($pagefile);
$this->singleFileReplacement = true;
}
}
if($this->overwrite) {
$pagefile = $this->value->get($filename);
clearstatcache();
if($pagefile) {
// already have a file of the same name
if($pagefile instanceof Pageimage) $pagefile->removeVariations();
$metadata = $this->extractMetadata($pagefile, $metadata);
} else {
// we don't have a file with the same name as the one that was uploaded
// file must be in another files field on the same page, that could be problematic
$ul = $this->getWireUpload();
// see if any files were overwritten that weren't part of our field
// if so, we need to restore them and issue an error
$err = false;
foreach($ul->getOverwrittenFiles() as $bakFile => $newFile) {
if(basename($newFile) != $filename) continue;
unlink($newFile);
rename($bakFile, $newFile); // restore
$ul->error(sprintf($this->_('Refused file %s because it is already on the file system and owned by a different field.'), $filename));
$err = true;
}
if($err) return;
}
}
$this->value->add($filename);
/** @var Pagefile $item */
$item = $this->value->last();
try {
foreach($metadata as $key => $val) {
if($val) $item->$key = $val;
}
// items saved in ajax or uploadOnly mode are temporary till saved in non-ajax/non-uploadOnly
if($this->isAjax && !$this->overwrite && $this->localStorage) $item->isTemp(true);
$this->fileAdded($item);
} catch(\Exception $e) {
$item->unlink();
$this->value->remove($item);
throw new WireException($e->getMessage());
}
}
protected function ___processInputDeleteFile(Pagefile $pagefile) {
$this->message($this->_("Deleted file:") . " $pagefile"); // Label that precedes a deleted filename
$this->value->delete($pagefile);
$this->trackChange('value');
if(!$this->localStorage) {
$this->deleteFileFromS3($pagefile, $this->input->get->id);
}
}
public function ___processInput(WireInputData $input) {
if(is_null($this->value)) $this->value = $this->wire(new Pagefiles($this->wire('page')));
if(!$this->destinationPath) $this->destinationPath = $this->value->path();
if(!$this->destinationPath || !is_dir($this->destinationPath)) return $this->error($this->_("destinationPath is empty or does not exist"));
if(!is_writable($this->destinationPath)) return $this->error($this->_("destinationPath is not writable"));
$changed = false;
$total = count($this->value);
if(!$this->noUpload) {
if($this->maxFiles <= 1 || $total < $this->maxFiles) {
$ul = $this->getWireUpload();
$ul->setName($this->attr('name'));
$ul->setDestinationPath($this->destinationPath);
$ul->setOverwrite($this->overwrite);
$ul->setAllowAjax($this->noAjax ? false : true);
if($this->maxFilesize) $ul->setMaxFileSize($this->maxFilesize);
if($this->maxFiles == 1) {
$ul->setMaxFiles(1);
} else if($this->maxFiles) {
$maxFiles = $this->maxFiles - $total;
$ul->setMaxFiles($maxFiles);
} else if($this->unzip) {
$ul->setExtractArchives(true);
}
$ul->setValidExtensions(explode(' ', trim($this->extensions)));
foreach($ul->execute() as $filename) {
$this->processInputAddFile($filename);
$changed = true;
}
if($this->isAjax && !$this->noAjax) foreach($ul->getErrors() as $error) {
$this->ajaxResponse(true, $error);
}
} else if($this->maxFiles) {
// over the limit
$this->ajaxResponse(true, $this->_("Max file upload limit reached"));
}
}
$n = 0;
foreach($this->value as $pagefile) {
if($this->processInputFile($input, $pagefile, $n)) $changed = true;
if(!$this->localStorage && !$this->isAjax){
@unlink($pagefile->filename);
}
$n++;
}
if($changed) {
$this->value->sort('sort');
$this->trackChange('value');
}
if(count($this->ajaxResponses) && $this->isAjax) {
echo json_encode($this->ajaxResponses);
}
return $this;
}
// File url
protected function s3url($event) {
if($this->localStorage) {
$event->return = $event->object->url;
}
else {
$ssl = ($this->useSSL) ? 'https' : 'http';
$domain = $this->domain();
$event->return = "{$ssl}://{$domain}/" . $event->object->page . "/" . $event->object->name;
}
}
protected function cloudFrontUrl($event) {
if($this->localStorage) {
$event->return = $event->object->url;
}
else {
$ssl = ($this->useSSL) ? 'https' : 'http';
$domain = $this->domain();
$event->return = "{$ssl}://". $this->cfurl ."/" . $event->object->page . "/" . $event->object->name;
}
}
protected function domain() {
switch ($this->region) {
case 'us-east-1':
$endpoint = 's3.amazonaws.com';
break;
case 'us-east-2':
$endpoint = 's3.us-east-2.amazonaws.com';
break;
case 'us-west-1':
$endpoint = 's3-us-west-1.amazonaws.com';
break;
case 'us-west-2':
$endpoint = 's3-us-west-2.amazonaws.com';
break;
case 'ca-central-1':
$endpoint = 's3-ca-central-1.amazonaws.com';
break;
case 'eu-west-1':
$endpoint = 's3-eu-west-1.amazonaws.com';
break;
case 'eu-west-2':
$endpoint = 's3-eu-west-2.amazonaws.com';
break;
case 'eu-central-1':
$endpoint = 's3-eu-central-1.amazonaws.com';
break;
case 'ap-south-1':
$endpoint = 's3-ap-south-1.amazonaws.com';
break;
case 'ap-southeast-1':
$endpoint = 's3-ap-southeast-1.amazonaws.com';
break;
case 'ap-southeast-2':
$endpoint = 's3-ap-southeast-2.amazonaws.com';
break;
case 'ap-northeast-1':
$endpoint = 's3-ap-northeast-1.amazonaws.com';
break;
case 'ap-northeast-2':
$endpoint = 's3-ap-northeast-2.amazonaws.com';
break;
case 'sa-east-1':
$endpoint = 's3-sa-east-1.amazonaws.com';
break;
default:
$endpoint = 's3.amazonaws.com';
break;
}
return ($this->useMyDomain) ? $this->bucket : "{$endpoint}/{$this->bucket}";
}
protected function uploadFileToS3($pagefile, $pageID) {
$this->setS3Client();
$s3args = [
"ACL" => $this->ACL,
"Bucket" => $this->bucket,
"Key" => "{$pageID}/{$pagefile->name}",
"SourceFile" => $pagefile->filename,
"ContentType" => mime_content_type($pagefile->filename)
];
if($this->cacheHeader){
$s3args['CacheControl'] = 'max-age=' . $this->cacheHeader;
}
$this->s3->PutObject($s3args);
}
protected function deleteFileFromS3($pagefile, $pageID) {
$this->setS3Client();
$this->s3->deleteObject([
"Bucket" => $this->bucket,
"Key" => "{$pageID}/{$pagefile->name}",
]);
}
// Instantiate S3 client
protected function setS3Client() {
//require_once("aws-sdk/aws-autoloader.php");
$this->s3 = new S3Client([
"version" => "latest",
"region" => $this->region,
"credentials" => [
"key" => $this->key,
"secret" => $this->secret
]]);
}
}