-
-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathMediaManager.php
More file actions
1404 lines (1190 loc) · 41.3 KB
/
MediaManager.php
File metadata and controls
1404 lines (1190 loc) · 41.3 KB
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace Backend\Widgets;
use Str;
use Lang;
use Input;
use Event;
use Config;
use Backend;
use ApplicationException;
use Backend\Classes\WidgetBase;
use System\Classes\ImageResizer;
use System\Classes\MediaLibrary;
use System\Classes\MediaLibraryItem;
use System\Models\Parameter;
/**
* Media Manager widget.
*
* @package winter\wn-backend-module
* @author Alexey Bobkov, Samuel Georges
*/
class MediaManager extends WidgetBase
{
use \Backend\Traits\UploadableWidget;
use \Backend\Traits\PreferenceMaker;
const FOLDER_ROOT = '/';
const VIEW_MODE_GRID = 'grid';
const VIEW_MODE_LIST = 'list';
const VIEW_MODE_TILES = 'tiles';
const SELECTION_MODE_NORMAL = 'normal';
const SELECTION_MODE_FIXED_RATIO = 'fixed-ratio';
const SELECTION_MODE_FIXED_SIZE = 'fixed-size';
const FILTER_ALL = 'all';
/**
* @var boolean Determines whether the widget is in readonly mode or not.
*/
public $readOnly = false;
/**
* @var boolean Determines whether the bottom toolbar is visible.
*/
public $bottomToolbar = false;
/**
* @var boolean Determines whether the Crop & Insert button is visible.
*/
public $cropAndInsertButton = false;
/**
* @var boolean Determines whether the Display filters are visible.
*/
public bool $filterDisplay = true;
/**
* Constructor.
*/
public function __construct($controller, $alias, $readOnly = false)
{
$this->alias = $alias;
$this->readOnly = $readOnly;
parent::__construct($controller, []);
}
/**
* Adds widget specific asset files. Use $this->addJs() and $this->addCss()
* to register new assets to include on the page.
* @return void
*/
protected function loadAssets()
{
$this->addCss('css/mediamanager.css', 'core');
if (Config::get('develop.decompileBackendAssets', false)) {
$scripts = Backend::decompileAsset($this->getAssetPath('js/mediamanager-browser.js'));
foreach ($scripts as $script) {
$this->addJs($script, 'core');
}
} else {
$this->addJs('js/mediamanager-browser-min.js', 'core');
}
}
/**
* Abort the request with an access-denied code if readOnly mode is active
*/
protected function abortIfReadOnly(): void
{
if ($this->readOnly) {
abort(403);
}
}
/**
* Renders the widget.
*/
public function render(): string
{
$this->prepareVars();
return $this->makePartial('body');
}
//
// AJAX handlers
//
/**
* Perform a search with the query specified in the request ("search")
*/
public function onSearch(): array
{
$this->setSearchTerm(Input::get('search'));
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list'),
'#' . $this->getId('folder-path') => $this->makePartial('folder-path')
];
}
/**
* Go to the path specified in the request ("path")
*/
public function onGoToFolder(): array
{
$path = Input::get('path');
if (Input::get('clearCache')) {
MediaLibrary::instance()->resetCache();
}
if (Input::get('resetSearch')) {
$this->setSearchTerm(null);
}
$this->setCurrentFolder($path);
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list'),
'#' . $this->getId('folder-path') => $this->makePartial('folder-path')
];
}
/**
* Generate thumbnails for the provided array of thumbnail info ("batch")
*/
public function onGenerateThumbnails(): array
{
$batch = Input::get('batch');
if (!is_array($batch)) {
return [];
}
$result = [];
foreach ($batch as $thumbnailInfo) {
$result[] = $this->generateThumbnail($thumbnailInfo);
}
return [
'generatedThumbnails' => $result
];
}
/**
* Get the thumbnail for the provided path ("path") and lastModified date ("lastModified")
*
* @throws ApplicationException if the lastModified date is invalid
*/
public function onGetSidebarThumbnail(): array
{
$path = MediaLibrary::validatePath(Input::get('path'));
$lastModified = Input::get('lastModified');
if (!is_numeric($lastModified)) {
throw new ApplicationException('Invalid input data');
}
$thumbnailParams = $this->getThumbnailParams();
$thumbnailParams['width'] = 300;
$thumbnailParams['height'] = 255;
$thumbnailParams['mode'] = 'auto';
$thumbnailInfo = $thumbnailParams;
$thumbnailInfo['path'] = $path;
$thumbnailInfo['lastModified'] = $lastModified;
$thumbnailInfo['id'] = 'sidebar-thumbnail';
return $this->generateThumbnail($thumbnailInfo, $thumbnailParams);
}
/**
* Render the view for the provided "path" and "view" mode from the request
*/
public function onChangeView(): array
{
$viewMode = Input::get('view');
$path = Input::get('path');
$this->setViewMode($viewMode);
$this->setCurrentFolder($path);
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list'),
'#' . $this->getId('folder-path') => $this->makePartial('folder-path'),
'#' . $this->getId('view-mode-buttons') => $this->makePartial('view-mode-buttons')
];
}
/**
* Set the current filter from the request ("filter")
*/
public function onSetFilter(): array
{
$filter = Input::get('filter');
$path = Input::get('path');
$this->setFilter($filter);
$this->setCurrentFolder($path);
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list'),
'#' . $this->getId('folder-path') => $this->makePartial('folder-path'),
'#' . $this->getId('filters') => $this->makePartial('filters')
];
}
/**
* Set the current sorting configuration from the request ("sortBy", "sortDirection")
*/
public function onSetSorting(): array
{
$sortBy = Input::get('sortBy', $this->getSortBy());
$sortDirection = Input::get('sortDirection', $this->getSortDirection());
$path = Input::get('path');
$this->setSortBy($sortBy);
$this->setSortDirection($sortDirection);
$this->setCurrentFolder($path);
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list'),
'#' . $this->getId('folder-path') => $this->makePartial('folder-path')
];
}
/**
* Deletes the provided paths from the request ("paths")
*
* @throws ApplicationException if the paths input is invalid
* @todo Move media events to the MediaLibary class instead.
*/
public function onDeleteItem(): array
{
$this->abortIfReadOnly();
$paths = Input::get('paths');
if (!is_array($paths)) {
throw new ApplicationException('Invalid input data');
}
$library = MediaLibrary::instance();
$filesToDelete = [];
foreach ($paths as $pathInfo) {
$path = array_get($pathInfo, 'path');
$type = array_get($pathInfo, 'type');
if (!$path || !$type) {
throw new ApplicationException('Invalid input data');
}
if ($type === MediaLibraryItem::TYPE_FILE) {
/*
* Add to bulk collection
*/
$filesToDelete[] = $path;
} elseif ($type === MediaLibraryItem::TYPE_FOLDER) {
/*
* Delete single folder
*/
$library->deleteFolder($path);
/**
* @event media.folder.delete
* Called after a folder is deleted
*
* Example usage:
*
* Event::listen('media.folder.delete', function ((\Backend\Widgets\MediaManager) $mediaWidget, (string) $path) {
* \Log::info($path . " was deleted");
* });
*
* Or
*
* $mediaWidget->bindEvent('folder.delete', function ((string) $path) {
* \Log::info($path . " was deleted");
* });
*
*/
$this->fireSystemEvent('media.folder.delete', [$path]);
}
}
if (count($filesToDelete) > 0) {
/*
* Delete collection of files
*/
$library->deleteFiles($filesToDelete);
/*
* Extensibility
*/
foreach ($filesToDelete as $path) {
/**
* @event media.file.delete
* Called after a file is deleted
*
* Example usage:
*
* Event::listen('media.file.delete', function ((\Backend\Widgets\MediaManager) $mediaWidget, (string) $path) {
* \Log::info($path . " was deleted");
* });
*
* Or
*
* $mediaWidget->bindEvent('file.delete', function ((string) $path) {
* \Log::info($path . " was deleted");
* });
*
*/
$this->fireSystemEvent('media.file.delete', [$path]);
}
}
$library->resetCache();
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list')
];
}
/**
* Render the rename popup for the provided "path" from the request
*/
public function onLoadRenamePopup(): string
{
$this->abortIfReadOnly();
$path = Input::get('path');
$path = MediaLibrary::validatePath($path);
$this->vars['originalPath'] = $path;
$this->vars['name'] = basename($path);
$this->vars['listId'] = Input::get('listId');
$this->vars['type'] = Input::get('type');
return $this->makePartial('rename-form');
}
/**
* Rename the provided path from the request ("originalPath") to the new name ("name")
*
* @throws ApplicationException if the new name is invalid
* @todo Move media events to the MediaLibary class instead.
*/
public function onApplyName(): void
{
$this->abortIfReadOnly();
$newName = trim(Input::get('name'));
if (!strlen($newName)) {
throw new ApplicationException(Lang::get('cms::lang.asset.name_cant_be_empty'));
}
if (!$this->validateFileName($newName)) {
throw new ApplicationException(Lang::get('cms::lang.asset.invalid_name'));
}
$originalPath = Input::get('originalPath');
$originalPath = MediaLibrary::validatePath($originalPath);
$newPath = dirname($originalPath) . '/' . $newName;
$type = Input::get('type');
if ($type == MediaLibraryItem::TYPE_FILE) {
/*
* Validate extension
*/
if (!$this->validateFileType($newName)) {
throw new ApplicationException(Lang::get('backend::lang.media.type_blocked'));
}
/*
* Move single file
*/
MediaLibrary::instance()->moveFile($originalPath, $newPath);
/**
* @event media.file.rename
* Called after a file is renamed / moved
*
* Example usage:
*
* Event::listen('media.file.rename', function ((\Backend\Widgets\MediaManager) $mediaWidget, (string) $originalPath, (string) $newPath) {
* \Log::info($originalPath . " was moved to " . $path);
* });
*
* Or
*
* $mediaWidget->bindEvent('file.rename', function ((string) $originalPath, (string) $newPath) {
* \Log::info($originalPath . " was moved to " . $path);
* });
*
*/
$this->fireSystemEvent('media.file.rename', [$originalPath, $newPath]);
} else {
/*
* Move single folder
*/
MediaLibrary::instance()->moveFolder($originalPath, $newPath);
/**
* @event media.folder.rename
* Called after a folder is renamed / moved
*
* Example usage:
*
* Event::listen('media.folder.rename', function ((\Backend\Widgets\MediaManager) $mediaWidget, (string) $originalPath, (string) $newPath) {
* \Log::info($originalPath . " was moved to " . $path);
* });
*
* Or
*
* $mediaWidget->bindEvent('folder.rename', function ((string) $originalPath, (string) $newPath) {
* \Log::info($originalPath . " was moved to " . $path);
* });
*
*/
$this->fireSystemEvent('media.folder.rename', [$originalPath, $newPath]);
}
MediaLibrary::instance()->resetCache();
}
/**
* Create a new folder ("name") in the provided "path" from the request
*
* @throws ApplicationException If the requested folder already exists or is otherwise invalid
*/
public function onCreateFolder(): array
{
$this->abortIfReadOnly();
$name = trim(Input::get('name'));
if (!strlen($name)) {
throw new ApplicationException(Lang::get('cms::lang.asset.name_cant_be_empty'));
}
if (!$this->validateFileName($name)) {
throw new ApplicationException(Lang::get('cms::lang.asset.invalid_name'));
}
$path = Input::get('path');
$path = MediaLibrary::validatePath($path);
$newFolderPath = $path . '/' . $name;
$library = MediaLibrary::instance();
if ($library->folderExists($newFolderPath)) {
throw new ApplicationException(Lang::get('backend::lang.media.folder_or_file_exist'));
}
/*
* Create the new folder
*/
if (!$library->makeFolder($newFolderPath)) {
throw new ApplicationException(Lang::get('backend::lang.media.error_creating_folder'));
}
/**
* @event media.folder.create
* Called after a folder is created
*
* Example usage:
*
* Event::listen('media.folder.create', function ((\Backend\Widgets\MediaManager) $mediaWidget, (string) $newFolderPath) {
* \Log::info($newFolderPath . " was created");
* });
*
* Or
*
* $mediaWidget->bindEvent('folder.create', function ((string) $newFolderPath) {
* \Log::info($newFolderPath . " was created");
* });
*
*/
$this->fireSystemEvent('media.folder.create', [$newFolderPath]);
$library->resetCache();
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list')
];
}
/**
* Render the move popup with a list of folders to move the selected items to excluding the provided paths in the request ("exclude")
*
* @throws ApplicationException If the exclude input data is not an array
*/
public function onLoadMovePopup(): string
{
$this->abortIfReadOnly();
$exclude = Input::get('exclude', []);
if (!is_array($exclude)) {
throw new ApplicationException('Invalid input data');
}
$folders = MediaLibrary::instance()->listAllDirectories($exclude);
$folderList = [];
foreach ($folders as $folder) {
$path = $folder;
if ($folder == '/') {
$name = Lang::get('backend::lang.media.library');
} else {
$segments = explode('/', $folder);
$name = str_repeat(' ', (count($segments) - 1) * 4) . basename($folder);
}
$folderList[$path] = $name;
}
$this->vars['folders'] = $folderList;
$this->vars['originalPath'] = Input::get('path');
return $this->makePartial('move-form');
}
/**
* Move the selected items ("files", "folders") to the provided destination path from the request ("dest")
*
* @throws ApplicationException if the input data is invalid
*/
public function onMoveItems(): array
{
$this->abortIfReadOnly();
$dest = trim(Input::get('dest'));
if (!strlen($dest)) {
throw new ApplicationException(Lang::get('backend::lang.media.please_select_move_dest'));
}
$dest = MediaLibrary::validatePath($dest);
if ($dest == Input::get('originalPath')) {
throw new ApplicationException(Lang::get('backend::lang.media.move_dest_src_match'));
}
$files = Input::get('files', []);
if (!is_array($files)) {
throw new ApplicationException('Invalid input data');
}
$folders = Input::get('folders', []);
if (!is_array($folders)) {
throw new ApplicationException('Invalid input data');
}
$library = MediaLibrary::instance();
foreach ($files as $path) {
/*
* Move a single file
*/
$library->moveFile($path, $dest . '/' . basename($path));
/**
* @event media.file.move
* Called after a file is moved
*
* Example usage:
*
* Event::listen('media.file.move', function ((\Backend\Widgets\MediaManager) $mediaWidget, (string) $path, (string) $dest) {
* \Log::info($path . " was moved to " . $dest);
* });
*
* Or
*
* $mediaWidget->bindEvent('file.rename', function ((string) $path, (string) $dest) {
* \Log::info($path . " was moved to " . $dest);
* });
*
*/
$this->fireSystemEvent('media.file.move', [$path, $dest]);
}
foreach ($folders as $path) {
/*
* Move a single folder
*/
$library->moveFolder($path, $dest . '/' . basename($path));
/**
* @event media.folder.move
* Called after a folder is moved
*
* Example usage:
*
* Event::listen('media.folder.move', function ((\Backend\Widgets\MediaManager) $mediaWidget, (string) $path, (string) $dest) {
* \Log::info($path . " was moved to " . $dest);
* });
*
* Or
*
* $mediaWidget->bindEvent('folder.rename', function ((string) $path, (string) $dest) {
* \Log::info($path . " was moved to " . $dest);
* });
*
*/
$this->fireSystemEvent('media.folder.move', [$path, $dest]);
}
$library->resetCache();
$this->prepareVars();
return [
'#' . $this->getId('item-list') => $this->makePartial('item-list')
];
}
/**
* Sets the sidebar visibility state from the request ("visible")
*/
public function onSetSidebarVisible(): void
{
$visible = (bool) Input::get('visible');
$this->setSidebarVisible($visible);
}
/**
* Renders the widget in a popup body (options include "bottomToolbar" and "cropAndInsertButton")
*/
public function onLoadPopup(): string
{
$this->bottomToolbar = Input::get('bottomToolbar', $this->bottomToolbar);
$this->cropAndInsertButton = Input::get('cropAndInsertButton', $this->cropAndInsertButton);
if ($mode = Input::get('mode')) {
$this->setFilter($mode);
if ($mode !== static::FILTER_ALL) {
$this->setFilterDisplay(false);
}
}
return $this->makePartial('popup-body');
}
/**
* Prepares & renders the image crop popup body
*/
public function onLoadImageCropPopup(): string
{
$this->abortIfReadOnly();
$path = Input::get('path');
$path = MediaLibrary::validatePath($path);
$selectionParams = $this->getSelectionParams();
$url = MediaLibrary::url($path);
// @TODO: Improve support non-local disks
if (Str::startsWith($url, '/')) {
$localPath = base_path(implode("/", array_map("rawurldecode", explode("/", $url))));
$dimensions = getimagesize($localPath);
} else {
$dimensions = getimagesize($url);
}
$width = $dimensions[0];
$height = $dimensions[1] ?: 1;
$this->vars['currentSelectionMode'] = $selectionParams['mode'];
$this->vars['currentSelectionWidth'] = $selectionParams['width'];
$this->vars['currentSelectionHeight'] = $selectionParams['height'];
$this->vars['imageUrl'] = $url;
$this->vars['dimensions'] = $dimensions;
$this->vars['originalRatio'] = round($width / $height, 5);
$this->vars['path'] = $path;
return $this->makePartial('image-crop-popup-body');
}
/**
* Crop image AJAX handler
*
* @throws ApplicationException if the input data is invalid
*/
public function onCropImage(): array
{
$this->abortIfReadOnly();
$selectionData = Input::get('selection');
$sourceImageUrl = Input::get('img');
$mediaItemPath = Input::get('path');
if (!is_array($selectionData)) {
throw new ApplicationException('Invalid input data');
}
foreach (['x', 'y', 'w', 'h'] as $key) {
if (!isset($selectionData[$key]) || !is_numeric($selectionData[$key])) {
throw new ApplicationException('Invalid selection data.');
}
$selectionData[$key] = (int) $selectionData[$key];
}
if ($selectionData['h'] === 0 || $selectionData['w'] === 0) {
throw new ApplicationException('You must define a crop size before inserting');
}
// Initialize the ImageResizer
$resizer = new ImageResizer(
$sourceImageUrl,
$selectionData['w'],
$selectionData['h'],
[
'mode' => 'exact',
'offset' => [
$selectionData['x'],
$selectionData['y'],
],
],
);
// Crop the image
$resizer->crop();
// Get the path to the cropped image
$croppedPath = $resizer->getPathToResizedImage();
// Generate the target path for the cropped image
$targetPath = $this->deduplicatePath($mediaItemPath, '_cropped');
// Move the cropped image to the target path
MediaLibrary::instance()->put(
$targetPath,
ImageResizer::getDefaultDisk()->get($croppedPath)
);
$result = [
'publicUrl' => MediaLibrary::url($targetPath),
'documentType' => MediaLibraryItem::FILE_TYPE_IMAGE,
'itemType' => MediaLibraryItem::TYPE_FILE,
'path' => $targetPath,
'title' => basename($targetPath),
'folder' => dirname($targetPath),
];
$selectionMode = Input::get('selectionMode');
$selectionWidth = Input::get('selectionWidth');
$selectionHeight = Input::get('selectionHeight');
$this->setSelectionParams($selectionMode, $selectionWidth, $selectionHeight);
return $result;
}
/**
* Handles resizing the provided image and returns the URL to the resized image
* Used by the Crop & Insert popup to resize the image being cropped on the canvas
* before cropping it.
*
* @throws ApplicationException if the provided input data is invalid
*/
public function onResizeImage(): array
{
$this->abortIfReadOnly();
$width = trim(Input::get('width'));
if (!strlen($width) || !ctype_digit($width)) {
throw new ApplicationException('Invalid input data');
}
$height = trim(Input::get('height'));
if (!strlen($height) || !ctype_digit($height)) {
throw new ApplicationException('Invalid input data');
}
$path = Input::get('path');
$path = MediaLibrary::validatePath($path);
// Initialize the ImageResizer
$resizer = new ImageResizer(
MediaLibrary::url($path),
$width,
$height,
[
'mode' => 'exact',
],
);
// Process the resize
$resizer->resize();
// Get the URL to the resized image
$resizedUrl = $resizer->getResizedUrl();
return [
'url' => $resizedUrl,
'dimensions' => [$width, $height]
];
}
/**
* Executed when the media library has not yet been scanned, or the user opts to manually re-scan the media library.
*
* @return void
*/
public function onScan()
{
return $this->makePartial('scan-popup');
}
public function onScanExecute()
{
MediaLibrary::instance()->scan();
$this->prepareVars();
return [
'#'.$this->getId('item-list') => $this->makePartial('item-list'),
'#'.$this->getId('folder-path') => $this->makePartial('folder-path'),
'#'.$this->getId('filters') => $this->makePartial('filters')
];
}
//
// Methods for internal use
//
/**
* Internal method to prepare view variables.
*/
protected function prepareVars()
{
clearstatcache();
$folder = $this->getCurrentFolder();
$viewMode = $this->getViewMode();
$filter = $this->getFilter();
$sortBy = $this->getSortBy();
$sortDirection = $this->getSortDirection();
$searchTerm = $this->getSearchTerm();
$searchMode = strlen($searchTerm) > 0;
if (!$searchMode) {
$this->vars['items'] = $this->listFolderItems($folder, $filter, ['by' => $sortBy, 'direction' => $sortDirection]);
}
else {
$this->vars['items'] = $this->findFiles($searchTerm, $filter, ['by' => $sortBy, 'direction' => $sortDirection]);
}
$this->vars['isScanned'] = !is_null(Parameter::get('media::scan.last_scanned'));
$this->vars['currentFolder'] = $folder;
$this->vars['isRootFolder'] = $folder == self::FOLDER_ROOT;
$this->vars['pathSegments'] = $this->splitPathToSegments($folder);
$this->vars['viewMode'] = $viewMode;
$this->vars['thumbnailParams'] = $this->getThumbnailParams($viewMode);
$this->vars['currentFilter'] = $filter;
$this->vars['sortBy'] = $sortBy;
$this->vars['sortDirection'] = $sortDirection;
$this->vars['searchMode'] = $searchMode;
$this->vars['searchTerm'] = $searchTerm;
$this->vars['sidebarVisible'] = $this->getSidebarVisible();
}
/**
* Returns a list of folders and files in a Library folder.
*
* @param string $searchTerm
* @param string $filter
* @param string $sortBy
* @return array[System\Classes\MediaLibraryItem]
*/
protected function listFolderItems($folder, $filter, $sortBy)
{
$filter = $filter !== self::FILTER_ALL ? $filter : null;
return MediaLibrary::instance()->listFolderContents($folder, $sortBy, $filter);
}
/**
* Finds files from within the media library based on supplied criteria,
* returns an array of MediaLibraryItem objects.
*
* @param string $searchTerm
* @param string $filter
* @param string $sortBy
* @return array[System\Classes\MediaLibraryItem]
*/
protected function findFiles($searchTerm, $filter, $sortBy)
{
$filter = $filter !== self::FILTER_ALL ? $filter : null;
return MediaLibrary::instance()->findFiles($searchTerm, $sortBy, $filter);
}
/**
* Sets the provided path as the current folder in the session
*/
protected function setCurrentFolder(string $path): void
{
$path = MediaLibrary::validatePath($path);
$this->putSession('media_folder', $path);
}
/**
* Gets the user's current folder from the session
*/
protected function getCurrentFolder(): string
{
return $this->getSession('media_folder', self::FOLDER_ROOT);
}
/**
* Sets the user filter from the session
*/
protected function setFilter(string $filter): void
{
if (!in_array($filter, [
self::FILTER_ALL,
MediaLibraryItem::FILE_TYPE_IMAGE,
MediaLibraryItem::FILE_TYPE_AUDIO,
MediaLibraryItem::FILE_TYPE_DOCUMENT,
MediaLibraryItem::FILE_TYPE_VIDEO
])) {
throw new ApplicationException('Invalid input data');
}
$this->putSession('media_filter', $filter);
}
/**
* Sets the filter display option for the request
*/
protected function setFilterDisplay(bool $status): void
{
$this->filterDisplay = $status;
}
/**
* Gets the filter display option for the request
*/
protected function getFilterDisplay(): bool
{
return $this->filterDisplay;
}
/**
* Gets the user filter from the session state
*
* @return string
*/
protected function getFilter()
{
return $this->getSession('media_filter', self::FILTER_ALL);
}
/**
* Sets the user search term from the session state
*
* @param string $searchTerm
*/
protected function setSearchTerm($searchTerm): void
{
$this->putSession('media_search', trim($searchTerm));