-
Notifications
You must be signed in to change notification settings - Fork 56
/
BaseFileSystemStorage.php
949 lines (844 loc) · 34.5 KB
/
BaseFileSystemStorage.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
<?php
namespace luya\admin\storage;
use Yii;
use yii\db\Query;
use yii\helpers\Inflector;
use yii\base\Component;
use luya\Exception;
use luya\helpers\FileHelper;
use luya\admin\helpers\Storage;
use luya\admin\models\StorageFile;
use luya\admin\models\StorageImage;
use luya\admin\models\StorageFilter;
use luya\admin\models\StorageFolder;
use luya\traits\CacheableTrait;
use luya\web\Request;
use luya\admin\filters\TinyCrop;
use luya\admin\filters\MediumThumbnail;
use yii\helpers\VarDumper;
/**
* Storage Container for reading, saving and holding files.
*
* Create images, files, manipulate, foreach and get details. The storage container will be the singleton similar instance containing all the loaded images and files.
*
* The base storage system is implemented by filesystems:
*
* + {{luya\admin\filesystem\LocalStorage}} (Default system for the admin module)
* + {{luya\admin\filesystem\S3}}
*
* As files, images and folders implement the same traits you can also read more about enhanced usage:
*
* + Querying Data with {{\luya\admin\storage\QueryTrait}}
* + Where conditions {{\luya\admin\storage\QueryTrait::where()}}
*
* ## Handling Files
*
* First adding a new file to the Storage system using the {{\luya\admin\storage\BaseFileSystemStorage::addFile()}} method.
*
* ```php
* Yii::$app->storage->addFile('/the/path/to/File.jpg', 'File.jpg', 0, 1);
* ```
*
* The response of the add file method is an {{\luya\admin\file\Item}} Object.
*
* Get an array of files based on search parameters (When not passing any arguments all files would be returned.):
*
* ```php
* Yii::$app->storage->findFiles(['is_hidden' => 0, 'is_deleted' => 0]);
* ```
*
* In order to get a single file object based on its ID use:
*
* ```php
* Yii::$app->storage->getFile(5);
* ```
*
* To find a file based on other where arguments instead of the id use findFile:
*
* ```php
* Yii::$app->storage->findFile(['name' => 'MyFile.jpg']);
* ```
*
* ### Handling Images
*
* An image object is always based on the {{\luya\admin\file\Item}} object and a {{luya\admin\base\Filter}}. In order to add an image you already need a fileId and filterId. If the filterId is 0, it means no additional filter will be applied.
*
* ```php
* Yii::$app->storage->addImage(123, 0); // create an image from file object id 123 without filter.
* ```
*
* The newly created image will return a {{luya\admin\image\Item}} object.
*
* In order to find one image:
*
* ```php
* Yii::$app->storage->findImage(['id' => 123]);
* ```
*
* or find one image by its ID:
*
* ```php
* Yii::$app->storage->getImage(123);
* ```
*
* To get an array of images based on where conditions use:
*
* ```php
* Yii::$app->storage->findImages(['file_id' => 1, 'filter_id' => 0]);
* ```
*
* @property string $serverPath Get the server path (for php) to the storage folder.
* @property array $filesArray An array containing all files
* @property array $imagesArray An array containg all images
* @property array $foldersArray An array containing all folders
* @property array $filtersArray An array with all filters
*
* @author Basil Suter <basil@nadar.io>
* @since 1.0.0
*/
abstract class BaseFileSystemStorage extends Component
{
use CacheableTrait;
/**
* Return the http path for a given file on the file system.
*
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
* @since 1.2.0
*/
abstract public function fileHttpPath($fileName);
/**
* Return the absolute http path for a given file on the file system.
*
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
* @since 1.2.0
*/
abstract public function fileAbsoluteHttpPath($fileName);
/**
* Returns the path internal server path to the given file on the file system.
*
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
*/
abstract public function fileServerPath($fileName);
/**
* Check if the file exists on the given file system.
*
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
* @since 1.2.0
*/
abstract public function fileSystemExists($fileName);
/**
* Get the content of the file on the given file system.
*
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
* @since 1.2.0
*/
abstract public function fileSystemContent($fileName);
/**
* Save the given file source as a new file with the given fileName on the filesystem.
*
* @param string $source The absolute file source path and filename, like `/tmp/upload/myfile.jpg`.
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
* @return boolean Whether the file has been stored or not.
*/
abstract public function fileSystemSaveFile($source, $fileName);
/**
* Replace an existing file source with a new one on the filesystem.
*
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
* @param string $newSource The absolute file source path and filename, like `/tmp/upload/myfile.jpg`.
* @return boolean Whether the file has replaced stored or not.
*/
abstract public function fileSystemReplaceFile($fileName, $newSource);
/**
* Delete a given file source on the filesystem.
*
* @param string $fileName The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem.
* @return boolean Whether the file has been deleted or not.
*/
abstract public function fileSystemDeleteFile($fileName);
/**
* @var string File cache key.
*/
const CACHE_KEY_FILE = 'storage_fileCacheKey';
/**
* @var string Image cache key.
*/
const CACHE_KEY_IMAGE = 'storage_imageCacheKey';
/**
* @var string Folder cache key.
*/
const CACHE_KEY_FOLDER = 'storage_folderCacheKey';
/**
* @var string Filter cache key.
*/
const CACHE_KEY_FILTER = 'storage_filterCacheKey';
/**
* @var array The mime types which will be rejected.
*/
public $dangerousMimeTypes = [
'application/x-msdownload',
'application/x-msdos-program',
'application/x-msdos-windows',
'application/x-download',
'application/bat',
'application/x-bat',
'application/com',
'application/x-com',
'application/exe',
'application/x-exe',
'application/x-winexe',
'application/x-winhlp',
'application/x-winhelp',
'application/x-javascript',
'application/hta',
'application/x-ms-shortcut',
'application/octet-stream',
'vms/exe',
'text/javascript',
'text/scriptlet',
'text/x-php',
'text/plain',
'application/x-spss',
];
/**
* @var array The extension which will be rejected.
*/
public $dangerousExtensions = [
'html', 'php', 'phtml', 'php3', 'exe', 'bat', 'js',
];
/**
* @var array a list of mime types which are indicating images
* @since 1.2.2.1
*/
public $imageMimeTypes = [
'image/gif', 'image/jpeg', 'image/png', 'image/jpg',
];
/**
* @var boolean Whether secure file upload is enabled or not. If enabled dangerous mime types and extensions will
* be rejected and the file mime type needs to be verified by phps `fileinfo` extension.
*/
public $secureFileUpload = true;
/**
* @var array The mime types inside this array are whitelistet and will be stored whether validation failes or not. For example if mime
* type 'text/plain' is given for a 'csv' extension, the valid extensions would be 'txt' or 'log', this would throw an exception, therefore
* you can whitelist the 'text/plain' mime type. This can be usefull when uploading csv files.
* @since 1.1.0
*/
public $whitelistMimeTypes = [];
/**
* @var array An array with extensions which are whitelisted. This can be very dangerous as it will skip the check whether the mime type is
* matching the extension types. If an extensions in {{$dangerousExtensions}} and {{$whitelistExtensions}} it will still throw an exception as
* {{$dangerousExtensions}} take precedence over {{$$whitelistExtensions}}.
* @since 1.2.2
*/
public $whitelistExtensions = [];
/**
* @var \luya\web\Request Request object resolved by the Dependency Injector.
*/
public $request;
/**
* @var boolean When enabled the storage component will try to recreated missing images when {{luya\admin\image\Item::getSource()}} of an
* image is called but the `getFileExists()` does return false, which means that the source file has been deleted.
* So in those cases the storage component will automatiaccly try to recreated this image based on the filterId and
* fileId.
*/
public $autoFixMissingImageSources = true;
/**
* Consturctor resolveds Request component from DI container
*
* @param \luya\web\Request $request The request component class resolved by the Dependency Injector.
* @param array $config
*/
public function __construct(Request $request, array $config = [])
{
$this->request = $request;
parent::__construct($config);
}
private $_filesArray;
/**
* Get all storage files as an array from database.
*
* This method is used to retrieve all files from the database and indexed by file key.
*
* @return array An array with all storage files indexed by the file id.
*/
public function getFilesArray()
{
if ($this->_filesArray === null) {
$this->_filesArray = $this->getQueryCacheHelper((new Query())->from('admin_storage_file')->select(['id', 'is_hidden', 'is_deleted', 'folder_id', 'name_original', 'name_new', 'name_new_compound', 'mime_type', 'extension', 'hash_name', 'hash_file', 'upload_timestamp', 'file_size', 'upload_user_id', 'caption'])->indexBy('id'), self::CACHE_KEY_FILE);
}
return $this->_filesArray;
}
/**
* Setter method for fiels array.
*
* This is mainly used when working with unit tests.
*
* @param array $files
*/
public function setFilesArray(array $files)
{
$this->_filesArray = $files;
}
/**
* Get a single file by file id from the files array.
*
* @param integer $fileId The file id to find.
* @return boolean|array The file array or false if not found.
*/
public function getFilesArrayItem($fileId)
{
return isset($this->filesArray[$fileId]) ? $this->filesArray[$fileId] : false;
}
private $_imagesArray;
/**
* Get all storage images as an array from database.
*
* This method is used to retrieve all images from the database and indexed by image key.
*
* @return array An array with all storage images indexed by the image id.
*/
public function getImagesArray()
{
if ($this->_imagesArray === null) {
$this->_imagesArray = $this->getQueryCacheHelper((new Query())->from('admin_storage_image')->select(['id', 'file_id', 'filter_id', 'resolution_width', 'resolution_height'])->indexBy('id'), self::CACHE_KEY_IMAGE);
}
return $this->_imagesArray;
}
/**
* Setter method for images array.
*
* This is mainly used when working with unit tests.
*
* @param array $images
*/
public function setImagesArray(array $images)
{
$this->_imagesArray = $images;
}
/**
* Get a single image by image id from the files array.
*
* @param integer $imageId The image id to find.
* @return boolean|array The image array or false if not found.
*/
public function getImagesArrayItem($imageId)
{
return isset($this->imagesArray[$imageId]) ? $this->imagesArray[$imageId] : false;
}
/**
* Get an array with all files based on a where condition.
*
* This method returns an array with files matching there $args array condition. If no argument is provided all files will be returned.
*
* See {{\luya\admin\storage\QueryTrait::where}} for condition informations.
*
* @param array $args An array with conditions to match e.g. `['is_hidden' => 1, 'is_deleted' => 0]`.
* @return \luya\admin\file\Iterator An iterator object containing all files found for the condition provided.
*/
public function findFiles(array $args = [])
{
return (new \luya\admin\file\Query())->where($args)->all();
}
/**
* Get a single file based on a where condition.
*
* This method returns a single file matching the where condition, if the multiple results match the condition the first one will be picked.
*
* See {{\luya\admin\storage\QueryTrait::where}} for condition informations.
*
* @param array $args An array with conditions to match e.g. `['is_hidden' => 1, 'is_deleted' => 0]`.
* @return \luya\admin\file\Item The file item object.
*/
public function findFile(array $args)
{
return (new \luya\admin\file\Query())->where($args)->one();
}
/**
* Get a single file based on the the ID.
*
* If not found false is returned.
*
* @param integer $fileId The requested storage file id.
* @return \luya\admin\file\Item|boolean The file object or false if not found.
*/
public function getFile($fileId)
{
return (new \luya\admin\file\Query())->findOne($fileId);
}
/**
* Ensure a file uploads and return relevant file infos.
*
* @param string $fileSource The file on the server ($_FILES['tmp'])
* @param string $fileName Original upload name of the file ($_FILES['name'])
* @throws Exception
* @return array Returns an array with the following KeywordPatch
* + fileInfo:
* + mimeType:
* + fileName:
* + secureFileName: The file name with all insecure chars removed
* + fileSource:
* + extension: jpg, png, etc.
* + hashName: a short hash name for the given file, not the md5 sum.
*/
public function ensureFileUpload($fileSource, $fileName)
{
// throw exception if source or name is empty
if (empty($fileSource) || empty($fileName)) {
throw new Exception("Filename and source can not be empty.");
}
// if filename is blob, its a paste event from the browser, therefore generate the filename from the file source.
// @TODO: move out of ensureFileUpload
if ($fileName == 'blob') {
$ext = FileHelper::getExtensionsByMimeType(FileHelper::getMimeType($fileSource));
$fileName = 'paste-'.date("Y-m-d-H-i").'.'.$ext[0];
}
// get file informations from the name
$fileInfo = FileHelper::getFileInfo($fileName);
// get the mimeType from the fileSource, if $secureFileUpload is disabled, the mime type will be extracted from the file extensions
// instead of using the fileinfo extension, therefore this is not recommend.
$mimeType = FileHelper::getMimeType($fileSource, null, !$this->secureFileUpload);
// empty mime type indicates a wrong file upload.
if (empty($mimeType)) {
throw new Exception("Unable to find mimeType for the given file, make sure the php extension 'fileinfo' is installed.");
}
$extensionsFromMimeType = FileHelper::getExtensionsByMimeType($mimeType);
if (empty($extensionsFromMimeType) && empty($this->whitelistExtensions)) {
throw new Exception("Unable to find extension for given mimeType \"{$mimeType}\" or it contains insecure data.");
}
if (!empty($this->whitelistExtensions)) {
$extensionsFromMimeType = array_merge($extensionsFromMimeType, $this->whitelistExtensions);
}
// check if the file extension is matching the entries from FileHelper::getExtensionsByMimeType array.
if (!in_array($fileInfo->extension, $extensionsFromMimeType) && !in_array($mimeType, $this->whitelistMimeTypes)) {
throw new Exception("The given file extension \"{$fileInfo->extension}\" for file with mimeType \"{$mimeType}\" is not matching any valid extension: ".VarDumper::dumpAsString($extensionsFromMimeType).".");
}
foreach ($extensionsFromMimeType as $extension) {
if (in_array($extension, $this->dangerousExtensions)) {
throw new Exception("The file extension '{$extension}' seems to be dangerous and can not be stored.");
}
}
// check whether a mimetype is in the dangerousMimeTypes list and not whitelisted in whitelistMimeTypes.
if (in_array($mimeType, $this->dangerousMimeTypes) && !in_array($mimeType, $this->whitelistMimeTypes)) {
throw new Exception("The file mimeType '{$mimeType}' seems to be dangerous and can not be stored.");
}
return [
'fileInfo' => $fileInfo,
'mimeType' => $mimeType,
'fileName' => $fileName,
'secureFileName' => Inflector::slug(str_replace('_', '-', $fileInfo->name), '-'),
'fileSource' => $fileSource,
'fileSize' => filesize($fileSource),
'extension' => $fileInfo->extension,
'hashName' => FileHelper::hashName($fileName),
];
}
/**
* Add a new file based on the source to the storage system.
*
* When using the $_FILES array you can also make usage of the file helper methods:
*
* + {{luya\admin\helpers\Storage::uploadFromFiles}}
* + {{luya\admin\helpers\Storage::uploadFromFileArray}}
*
* When not using the $_FILES array:
*
* ```php
* Yii::$app->storage->addFile('/the/path/to/File.jpg', 'File.jpg', 0, 1);
* ```
*
* @param string $fileSource Path to the file source where the file should be created from
* @param string $fileName The name of this file (must contain data type suffix).
* @param integer $folderId The id of the folder where the file should be stored in.
* @param boolean $isHidden Should the file visible in the filemanager or not.
* @return bool|\luya\admin\file\Item|Exception Returns the item object, if an error happens an exception is thrown.
* @throws Exception
*/
public function addFile($fileSource, $fileName, $folderId = 0, $isHidden = false)
{
$fileData = $this->ensureFileUpload($fileSource, $fileName);
$fileHash = FileHelper::md5sum($fileSource);
$newName = implode([$fileData['secureFileName'].'_'.$fileData['hashName'], $fileData['extension']], '.');
if (!$this->fileSystemSaveFile($fileSource, $newName)) {
return false;
}
$model = new StorageFile();
$model->setAttributes([
'name_original' => $fileName,
'name_new' => $fileData['secureFileName'],
'name_new_compound' => $newName,
'mime_type' => $fileData['mimeType'],
'extension' => $fileData['extension'],
'folder_id' => (int) $folderId,
'hash_file' => $fileHash,
'hash_name' => $fileData['hashName'],
'is_hidden' => $isHidden ? true : false,
'is_deleted' => false,
'file_size' => $fileData['fileSize'],
'caption' => null,
]);
if ($model->validate()) {
if ($model->save()) {
$this->deleteHasCache(self::CACHE_KEY_FILE);
$this->_filesArray[$model->id] = $model->toArray();
return $this->getFile($model->id);
}
}
return false;
}
/**
* Get an array with all images based on a where condition.
*
* This method returns an array with images matching there $args array condition. If no argument is provided all images will be returned.
*
* See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
*
* @param array $args An array with conditions to match e.g. `['is_hidden' => 1, 'is_deleted' => 0]`.
* @return \luya\admin\image\Iterator An iterator object containing all image found for the condition provided.
*/
public function findImages(array $args = [])
{
return (new \luya\admin\image\Query())->where($args)->all();
}
/**
* Get a single image based on a where condition.
*
* This method returns a single image matching the where condition, if the multiple results match the condition the first one will be picked.
*
* See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
*
* @param array $args An array with conditions to match e.g. `['is_hidden' => 1, 'is_deleted' => 0]`.
* @return \luya\admin\image\Item The file item object.
*/
public function findImage(array $args = [])
{
return (new \luya\admin\image\Query())->where($args)->one();
}
/**
* Get a single image based on the the ID.
*
* If not found false is returned.
*
* @param integer $imageId The requested storage image id.
* @return \luya\admin\image\Item|boolean The image object or false if not found.
*/
public function getImage($imageId)
{
return (new \luya\admin\image\Query())->findOne($imageId);
}
/**
* Add a new image based an existing file Id.
*
* The storage system uses the same file base, for images and files. The difference between a file and an image is the filter which is applied.
*
* Only files of the type image can be used (or added) as an image.
*
* An image object is always based on the {{\luya\admin\file\Item}} object and a {{luya\admin\base\Filter}}.
*
* ```php
* Yii::$app->storage->addImage(123, 0); // create an image from file object id 123 without filter.
* ```
*
* @param integer $fileId The id of the file where image should be created from.
* @param integer $filterId The id of the filter which should be applied to, if filter is 0, no filter will be added. Filter can new also be the string name of the filter like `tiny-crop`.
* @param boolean $throwException Whether the addImage should throw an exception or just return boolean
* @return bool|\luya\admin\image\Item|Exception Returns the item object, if an error happens and $throwException is off `false` is returned otherwhise an exception is thrown.
* @throws \luya\Exception
*/
public function addImage($fileId, $filterId = 0, $throwException = false)
{
try {
// if the filterId is provded as a string the filter will be looked up by its name in the get filters array list.
if (is_string($filterId) && !is_numeric($filterId)) {
$filterLookup = $this->getFiltersArrayItem($filterId);
if (!$filterLookup) {
throw new Exception("The provided filter name " . $filterId . " does not exist.");
}
$filterId = $filterLookup['id'];
}
$query = (new \luya\admin\image\Query())->where(['file_id' => $fileId, 'filter_id' => $filterId])->one();
if ($query && $query->fileExists) {
return $query;
}
$fileQuery = $this->getFile($fileId);
if (!$fileQuery || !$fileQuery->fileExists) {
if ($fileQuery !== false) {
throw new Exception("Unable to create image, the base file server source '{$fileQuery->serverSource}' does not exist.");
}
throw new Exception("Unable to find the file with id '{$fileId}', image can not be created.");
}
$model = $this->createImage($fileId, $filterId);
if (!$model) {
throw new Exception("Unable to create the image on the filesystem.");
}
$this->_imagesArray[$model->id] = $model->toArray();
$this->deleteHasCache(self::CACHE_KEY_IMAGE);
return $this->getImage($model->id);
} catch (\Exception $err) {
if ($throwException) {
throw $err;
}
}
return false;
}
/**
* Just creating the image based on input informations without usage of storage files or images list.
*
* @since 1.2.2.1
* @return \luya\admin\models\StorageImage|false Returns the storage image model on success, otherwise false.
*/
public function createImage($fileId, $filterId)
{
$image = StorageImage::find()->where(['file_id' => $fileId, 'filter_id' => $filterId])->one();
// the image exists already in the database and the file system
if ($image && $image->fileExists) {
return $image;
}
$file = StorageFile::findOne($fileId);
if (!$file) {
return false;
}
// create the new image name
$fileName = $filterId.'_'.$file->name_new_compound;
// create a temp file
$tempFile = tempnam(sys_get_temp_dir(), 'prefix');
$tempFile.= $fileName;
// there is no filter, which means we create an image version for a given file.
if (empty($filterId)) {
@copy($file->serverSource, $tempFile);
} else {
$filter = StorageFilter::findOne($filterId);
if (!$filter) {
throw new Exception("Could not find the provided filter id '$filterId'.");
}
if (!$filter->applyFilterChain($file->serverSource, $tempFile)) {
throw new Exception("Unable to create and save image '".$tempFile."'.");
}
}
$resolution = Storage::getImageResolution($tempFile);
// now copy the file to the storage system
$this->fileSystemSaveFile($tempFile, $fileName);
unlink($tempFile);
$this->flushImageArray();
// ensure the existing of the model
if ($image) {
$image->resolution_height = $resolution['height'];
$image->resolution_width = $resolution['width'];
$image->save();
return $image;
}
$image = new StorageImage();
$image->file_id = $fileId;
$image->filter_id = $filterId;
$image->resolution_height = $resolution['height'];
$image->resolution_width = $resolution['width'];
$image->save();
return $image;
}
private $_foldersArray;
/**
* Get all storage folders as an array from database.
*
* This method is used to retrieve all folders from the database and indexed by folder key.
*
* @return array An array with all storage folders indexed by the folder id.
*/
public function getFoldersArray()
{
if ($this->_foldersArray === null) {
$query = (new Query())
->from('admin_storage_folder as folder')
->select(['folder.id', 'name', 'parent_id', 'timestamp_create', 'COUNT(file.id) filesCount'])
->where(['folder.is_deleted' => false])
->orderBy(['name' => 'ASC'])
->leftJoin('admin_storage_file as file', 'folder.id=file.folder_id AND file.is_deleted = 0')
->groupBy(['folder.id'])
->indexBy(['id']);
$this->_foldersArray = $this->getQueryCacheHelper($query, self::CACHE_KEY_FOLDER);
}
return $this->_foldersArray;
}
/**
* Get a single folder by folder id from the folders array.
*
* @param integer $folderId The folder id to find.
* @return boolean|array The folder array or false if not found.
*/
public function getFoldersArrayItem($folderId)
{
return (isset($this->foldersArray[$folderId])) ? $this->foldersArray[$folderId] : false;
}
/**
* Get an array with all folders based on a where condition.
*
* If no argument is provided all images will be returned.
*
* See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
*
* @param array $args An array with conditions to match e.g. `['is_hidden' => 1, 'is_deleted' => 0]`.
* @return \luya\admin\folder\Iterator An iterator object containing all image found for the condition provided.
*/
public function findFolders(array $args = [])
{
return (new \luya\admin\folder\Query())->where($args)->all();
}
/**
* Get a single folder based on a where condition.
*
* This method returns a single fpöder matching the where condition, if the multiple results match the condition the first one will be picked.
*
* See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
*
* @param array $args An array with conditions to match e.g. `['is_hidden' => 1, 'is_deleted' => 0]`.
* @return \luya\admin\folder\Item The folder item object.
*/
public function findFolder(array $args = [])
{
return (new \luya\admin\folder\Query())->where($args)->one();
}
/**
* Get a single folder based on the the ID.
*
* If not found false is returned.
*
* @param integer $folderId The requested storage folder id.
* @return \luya\admin\folder\Item|boolean The folder object or false if not found.
*/
public function getFolder($folderId)
{
return (new \luya\admin\folder\Query())->where(['id' => $folderId])->one();
}
/**
* Add new folder to the storage system.
*
* @param string $folderName The name of the new folder
* @param integer $parentFolderId If its a subfolder the id of the parent folder must be provided.
* @return boolean|integer Returns the folder id or false if something went wrong.
*/
public function addFolder($folderName, $parentFolderId = 0)
{
$model = new StorageFolder();
$model->name = $folderName;
$model->parent_id = $parentFolderId;
$model->timestamp_create = time();
$this->deleteHasCache(self::CACHE_KEY_FOLDER);
if ($model->save(false)) {
return $model->id;
}
return false;
}
private $_filtersArray;
/**
* Get all storage filters as an array from database.
*
* This method is used to retrieve all filters from the database and indexed by filter identifier key.
*
* @return array An array with all storage filters indexed by the filter identifier.
*/
public function getFiltersArray()
{
if ($this->_filtersArray === null) {
$this->_filtersArray = $this->getQueryCacheHelper((new Query())->from('admin_storage_filter')->select(['id', 'identifier', 'name'])->indexBy('identifier')->orderBy(['name' => SORT_ASC]), self::CACHE_KEY_FILTER);
}
return $this->_filtersArray;
}
/**
* Setter method for filters array.
*
* This is mainly used when working with unit tests.
*
* @param array $filters
*/
public function setFiltersArray(array $filters)
{
$this->_filtersArray = $filters;
}
/**
* Get a single filter by filter identifier from the filters array.
*
* @param integer $filterIdentifier The filter identifier to find use {{luya\admin\base\Filter::identifier()}} method.
* @return boolean|array The filter array or false if not found.
*/
public function getFiltersArrayItem($filterIdentifier)
{
return isset($this->filtersArray[$filterIdentifier]) ? $this->filtersArray[$filterIdentifier] : false;
}
/**
* Get the filter id based on the identifier.
*
* This is a short hand method as its used very often
*
* @param string $identifier
* @return integer
* @since 1.2.2.1
*/
public function getFilterId($identifier)
{
$filter = $this->getFiltersArrayItem($identifier);
return $filter ? (int) $filter['id'] : false;
}
/**
* Caching helper method.
*
* @param \yii\db\Query $query
* @param string|array $key
* @return mixed|boolean
*/
private function getQueryCacheHelper(\yii\db\Query $query, $key)
{
$data = $this->getHasCache($key);
if ($data === false) {
$data = $query->all();
$this->setHasCache($key, $data);
}
return $data;
}
/**
* Will force to refresh all container arrays and clean up the cache
*/
public function flushArrays()
{
$this->_filesArray = null;
$this->_imagesArray = null;
$this->_foldersArray = null;
$this->_filtersArray = null;
$this->deleteHasCache(self::CACHE_KEY_FILE);
$this->deleteHasCache(self::CACHE_KEY_IMAGE);
$this->deleteHasCache(self::CACHE_KEY_FOLDER);
$this->deleteHasCache(self::CACHE_KEY_FILTER);
}
/**
* Flush only images array and image cache.
*
* @since 1.2.3
*/
public function flushImageArray()
{
$this->_imagesArray = null;
$this->deleteHasCache(self::CACHE_KEY_IMAGE);
}
/**
* This method allwos you to generate all thumbnails for the file manager, you can trigger this process when
* importing or creating several images at once, so the user does not have to create the thumbnails
*
* @return boolean
*/
public function processThumbnails()
{
foreach ($this->findFiles(['is_hidden' => false, 'is_deleted' => false]) as $file) {
if ($file->isImage) {
// create tiny thumbnail
$this->createImage($file->id, $this->getFilterId(TinyCrop::identifier()));
$this->createImage($file->id, $this->getFilterId(MediumThumbnail::identifier()));
}
}
// force auto fix
$this->autoFixMissingImageSources = true;
foreach ($this->findImages() as $image) {
if (!empty($image->file) && !$image->file->isHidden && !$image->file->isDeleted) {
$image->source; // which forces to recreate missing sources.
}
}
return true;
}
}