-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
MediaFiles.php
415 lines (353 loc) · 16.2 KB
/
MediaFiles.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
<?php
declare(strict_types=1);
/**
* Flextype (https://flextype.org)
* Founded by Sergey Romanenko and maintained by Flextype Community.
*/
namespace Flextype\Foundation\Media;
use Atomastic\Arrays\Arrays;
use Atomastic\Macroable\Macroable;
use ErrorException;
use Intervention\Image\ImageManagerStatic as Image;
use RuntimeException;
use Slim\Http\Environment;
use Slim\Http\Uri;
use function arrays;
use function basename;
use function chmod;
use function exif_read_data;
use function explode;
use function filesystem;
use function filter;
use function flextype;
use function getimagesize;
use function in_array;
use function is_dir;
use function is_uploaded_file;
use function is_writable;
use function ltrim;
use function mime_content_type;
use function move_uploaded_file;
use function pathinfo;
use function realpath;
use function str_replace;
use function strings;
use function strpos;
use function strrpos;
use function strstr;
use function strtolower;
use function substr;
use function time;
use const DIRECTORY_SEPARATOR;
use const PATHINFO_EXTENSION;
use const UPLOAD_ERR_INI_SIZE;
use const UPLOAD_ERR_OK;
class MediaFiles
{
use Macroable;
/**
* Create a Media Files Meta instance.
*/
public function meta(): MediaFilesMeta
{
return new MediaFilesMeta();
}
/**
* Upload media file
*
* @param array $file Raw file data (multipart/form-data).
* @param string $folder The folder you're targetting.
*
* @access public
*/
public function upload(array $file, string $folder)
{
$uploadFolder = PATH['project'] . '/media/' . $folder . '/';
$uploadMetadataFolder = PATH['project'] . '/media/.meta/' . $folder . '/';
if (! filesystem()->directory($uploadFolder)->exists()) {
filesystem()->directory($uploadFolder)->create(0755, true);
}
if (! filesystem()->directory($uploadMetadataFolder)->exists()) {
filesystem()->directory($uploadMetadataFolder)->create(0755, true);
}
$acceptFileTypes = registry()->get('flextype.settings.media.accept_file_types');
$maxFileSize = registry()->get('flextype.settings.media.max_file_size');
$safeNames = registry()->get('flextype.settings.media.safe_names');
$maxImageWidth = registry()->get('flextype.settings.media.images.max_image_width');
$maxImageHeight = registry()->get('flextype.settings.media.images.max_image_height');
$exact = false;
$chmod = 0644;
$filename = null;
$exifData = [];
// Tests if a successful upload has been made.
if (
isset($file['error'])
and isset($file['tmp_name'])
and $file['error'] === UPLOAD_ERR_OK
and is_uploaded_file($file['tmp_name'])
) {
// Tests if upload data is valid, even if no file was uploaded.
if (
isset($file['error'])
and isset($file['name'])
and isset($file['type'])
and isset($file['tmp_name'])
and isset($file['size'])
) {
// Test if an uploaded file is an allowed file type, by extension.
if (strpos($acceptFileTypes, strtolower(pathinfo($file['name'], PATHINFO_EXTENSION))) !== false) {
// Validation rule to test if an uploaded file is allowed by file size.
if (
($file['error'] !== UPLOAD_ERR_INI_SIZE)
and ($file['error'] === UPLOAD_ERR_OK)
and ($file['size'] <= $maxFileSize)
) {
// Validation rule to test if an upload is an image and, optionally, is the correct size.
if (in_array(mime_content_type($file['tmp_name']), ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'])) {
if ($this->validateImage($file, $maxImageWidth, $maxImageHeight, $exact) === false) {
return false;
}
}
if (! isset($file['tmp_name']) or ! is_uploaded_file($file['tmp_name'])) {
// Ignore corrupted uploads
return false;
}
if ($filename === null) {
// Use the default filename
$filename = $file['name'];
}
if ($safeNames === true) {
// Remove spaces from the filename
$filename = flextype('slugify')->slugify(pathinfo($filename)['filename']) . '.' . pathinfo($filename)['extension'];
}
if (! is_dir($uploadFolder) or ! is_writable(realpath($uploadFolder))) {
throw new RuntimeException("Directory {$uploadFolder} must be writable");
}
// Make the filename into a complete path
$filename = realpath($uploadFolder) . DIRECTORY_SEPARATOR . $filename;
if (move_uploaded_file($file['tmp_name'], $filename)) {
// Set permissions on filename
chmod($filename, $chmod);
if (in_array(mime_content_type($filename), ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'])) {
// open an image file
$img = Image::make($filename);
// now you are able to resize the instance
if (registry()->get('flextype.settings.media.images.image_width') > 0 && registry()->get('flextype.settings.media.images.image_height') > 0) {
$img->resize(registry()->get('flextype.settings.media.images.image_width'), registry()->get('flextype.settings.media.images.image_height'), static function ($constraint): void {
$constraint->aspectRatio();
$constraint->upsize();
});
} elseif (registry()->get('flextype.settings.media.images.image_width') > 0) {
$img->resize(registry()->get('flextype.settings.media.images.image_width'), null, static function ($constraint): void {
$constraint->aspectRatio();
$constraint->upsize();
});
} elseif (registry()->get('flextype.settings.media.images.image_height') > 0) {
$img->resize(null, registry()->get('flextype.settings.media.images.image_height'), static function ($constraint): void {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// finally we save the image as a new file
$img->save($filename, registry()->get('flextype.settings.media.images.image_quality'));
// destroy
$img->destroy();
$exifData = [];
try {
$headers = @exif_read_data($filename);
if ($headers !== false) {
foreach ($headers['COMPUTED'] as $header => $value) {
$exifData[$header] = $value;
}
}
} catch (RuntimeException $e) {
// catch... @todo
}
}
$metadata = [
'title' => substr(basename($filename), 0, strrpos(basename($filename), '.')),
'description' => '',
'type' => mime_content_type($filename),
'filesize' => filesystem()->file($filename)->size(),
'uploaded_on' => time(),
'exif' => $exifData,
];
filesystem()
->file($uploadMetadataFolder . basename($filename) . '.yaml')
->put(serializers()->yaml()->encode($metadata));
// Return new file path
return $filename;
}
}
}
}
}
return false;
}
/**
* Fetch.
*
* @param string $id The path to file.
* @param array $options Options array.
*
* @return Arrays Returns instance of The Arrays class.
*
* @access public
*/
public function fetch(string $id, array $options = []): Arrays
{
// Run event: onEntriesFetch
emitter()->emit('onMediaFilesFetch');
if (
isset($options['collection']) &&
strings($options['collection'])->isTrue()
) {
$result = [];
foreach (filesystem()->find()->files()->depth(0)->in(flextype('media')->folders()->meta()->getDirectoryMetaLocation($id)) as $file) {
$basename = $file->getBasename('.' . $file->getExtension());
$result[$basename] = serializers()->yaml()->decode(filesystem()->file($file->getPathname())->get());
$result[$basename]['filename'] = pathinfo(str_replace('/.meta', '', flextype('media')->files()->meta()->getFileMetaLocation($basename)))['filename'];
$result[$basename]['basename'] = explode('.', basename(flextype('media')->files()->meta()->getFileMetaLocation($basename)))[0];
$result[$basename]['extension'] = ltrim(strstr($basename, '.'), '.');
$result[$basename]['dirname'] = pathinfo(str_replace('/.meta', '', $file->getPathname()))['dirname'];
$result[$basename]['url'] = 'project/media/' . $id . '/' . $basename;
if (registry()->has('flextype.settings.url') && registry()->get('flextype.settings.url') !== '') {
$fullUrl = registry()->get('flextype.settings.url');
} else {
$fullUrl = Uri::createFromEnvironment(new Environment($_SERVER))->getBaseUrl();
}
$result[$basename]['path'] = $id;
$result[$basename]['full_url'] = $fullUrl . '/project/media/' . $id . '/' . $basename;
}
$result = filter($result, $options);
return arrays($result);
}
$result = [];
if (filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($id))->exists()) {
$result = serializers()->yaml()->decode(filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($id))->get());
$result['filename'] = pathinfo(str_replace('/.meta', '', flextype('media')->files()->meta()->getFileMetaLocation($id)))['filename'];
$result['basename'] = explode('.', basename(flextype('media')->files()->meta()->getFileMetaLocation($id)))[0];
$result['extension'] = ltrim(strstr($id, '.'), '.');
$result['dirname'] = pathinfo(str_replace('/.meta', '', flextype('media')->files()->meta()->getFileMetaLocation($id)))['dirname'];
$result['url'] = 'project/media/' . $id;
$result['path'] = $id;
if (registry()->has('flextype.settings.url') && registry()->get('flextype.settings.url') !== '') {
$fullUrl = registry()->get('flextype.settings.url');
} else {
$fullUrl = Uri::createFromEnvironment(new Environment($_SERVER))->getBaseUrl();
}
$result['full_url'] = $fullUrl . '/project/media/' . $id;
}
$result = filter($result, $options);
return arrays($result);
}
/**
* Move file
*
* @param string $id Unique identifier of the file.
* @param string $newID New Unique identifier of the file.
*
* @return bool True on success, false on failure.
*
* @access public
*/
public function move(string $id, string $newID): bool
{
if (! filesystem()->file($this->getFileLocation($newID))->exists() && ! filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($newID))->exists()) {
return filesystem()->file($this->getFileLocation($id))->move($this->getFileLocation($newID)) &&
filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($id))->move(flextype('media')->files()->meta()->getFileMetaLocation($newID));
}
return false;
}
/**
* Delete file
*
* @param string $id Unique identifier of the file.
*
* @return bool True on success, false on failure.
*
* @access public
*/
public function delete(string $id): bool
{
return filesystem()->file($this->getFileLocation($id))->delete() &&
filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($id))->delete();
}
/**
* Check whether a file exists.
*
* @param string $id Unique identifier of the file.
*
* @return bool True on success, false on failure.
*
* @access public
*/
public function has(string $id): bool
{
return filesystem()->file($this->getFileLocation($id))->exists() &&
filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($id))->exists();
}
/**
* Copy file
*
* @param string $id Unique identifier of the file.
* @param string $newID New Unique identifier of the file.
*
* @return bool True on success, false on failure.
*
* @access public
*/
public function copy(string $id, string $newID): bool
{
if (! filesystem()->file($this->getFileLocation($newID))->exists() && ! filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($newID))->exists()) {
filesystem()->file($this->getFileLocation($id))->copy($this->getFileLocation($newID));
filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($id))->copy(flextype('media')->files()->meta()->getFileMetaLocation($newID));
return filesystem()->file($this->getFileLocation($newID))->exists() &&
filesystem()->file(flextype('media')->files()->meta()->getFileMetaLocation($newID))->exists();
}
return false;
}
/**
* Get file location
*
* @param string $id Unique identifier of the file.
*
* @return string entry file location
*
* @access public
*/
public function getFileLocation(string $id): string
{
return PATH['project'] . '/media/' . $id;
}
/**
* Validate Image
*/
protected function validateImage($file, $maxImageWidth, $maxImageHeight, $exact)
{
try {
// Get the width and height from the uploaded image
[$width, $height] = getimagesize($file['tmp_name']);
} catch (ErrorException $e) {
// Ignore read errors
}
if (empty($width) or empty($height)) {
// Cannot get image size, cannot validate
return false;
}
if (! $maxImageWidth) {
// No limit, use the image width
$maxImageWidth = $width;
}
if (! $maxImageHeight) {
// No limit, use the image height
$maxImageHeight = $height;
}
if ($exact) {
// Check if dimensions match exactly
return $width === $maxImageWidth and $height === $maxImageHeight;
}
// Check if size is within maximum dimensions
return $width <= $maxImageWidth and $height <= $maxImageHeight;
}
}