-
Notifications
You must be signed in to change notification settings - Fork 611
/
AssetsController.php
1401 lines (1173 loc) · 50.4 KB
/
AssetsController.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
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
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\controllers;
use Craft;
use craft\assetpreviews\Image as ImagePreview;
use craft\base\Element;
use craft\base\LocalFsInterface;
use craft\elements\Asset;
use craft\elements\conditions\ElementCondition;
use craft\errors\AssetException;
use craft\errors\DeprecationException;
use craft\errors\ElementNotFoundException;
use craft\errors\FsException;
use craft\errors\UploadFailedException;
use craft\errors\VolumeException;
use craft\fields\Assets as AssetsField;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\Assets;
use craft\helpers\Db;
use craft\helpers\FileHelper;
use craft\helpers\ImageTransforms;
use craft\helpers\StringHelper;
use craft\helpers\UrlHelper;
use craft\i18n\Formatter;
use craft\imagetransforms\ImageTransformer;
use craft\models\ImageTransform;
use craft\models\VolumeFolder;
use craft\web\Controller;
use craft\web\UploadedFile;
use Throwable;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\InvalidRouteException;
use yii\base\NotSupportedException;
use yii\base\UserException;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\RangeNotSatisfiableHttpException;
use yii\web\Response;
use yii\web\ServerErrorHttpException;
use ZipArchive;
/** @noinspection ClassOverridesFieldOfSuperClassInspection */
/**
* The AssetsController class is a controller that handles various actions related to asset tasks, such as uploading
* files and creating/deleting/renaming files and folders.
* Note that all actions in the controller except for [[actionGenerateTransform()]] and [[actionGenerateThumb()]]
* require an authenticated Craft session via [[allowAnonymous]].
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class AssetsController extends Controller
{
use AssetsControllerTrait;
/**
* @inheritdoc
*/
protected array|bool|int $allowAnonymous = ['generate-thumb', 'generate-transform'];
/**
* Displays the Assets index page.
*
* @return Response
* @since 4.4.0
*/
public function actionIndex(string $defaultSource = null)
{
$this->requireCpRequest();
$variables = [];
if ($defaultSource) {
$defaultSourcePath = ArrayHelper::filterEmptyStringsFromArray(explode('/', $defaultSource));
$volumesService = Craft::$app->getVolumes();
$volume = $volumesService->getVolumeByHandle(array_shift($defaultSourcePath));
if ($volume) {
$assetsService = Craft::$app->getAssets();
$variables['defaultSource'] = "volume:$volume->uid";
if (!empty($defaultSourcePath)) {
$subfolder = $assetsService->findFolder([
'volumeId' => $volume->id,
'path' => sprintf('%s/', implode('/', $defaultSourcePath)),
]);
if ($subfolder) {
$sourcePath = [];
/** @var VolumeFolder[] $folders */
$folders = [];
while ($subfolder) {
array_unshift($folders, $subfolder);
$subfolder = $subfolder->getParent();
}
foreach ($folders as $i => $folder) {
if ($i < count($folders) - 1) {
$folder->setHasChildren(true);
}
$sourcePath[] = $folder->getSourcePathInfo();
}
$variables['defaultSourcePath'] = $sourcePath;
}
}
}
}
return $this->renderTemplate('assets/_index', $variables);
}
/**
* Returns an updated preview image for an asset.
*
* @return Response
* @throws BadRequestHttpException
* @throws NotSupportedException
* @since 3.4.0
*/
public function actionPreviewThumb(): Response
{
$this->requireCpRequest();
$assetId = $this->request->getRequiredParam('assetId');
$width = $this->request->getRequiredParam('width');
$height = $this->request->getRequiredParam('height');
$asset = Asset::findOne($assetId);
if ($asset === null) {
throw new BadRequestHttpException("Invalid asset ID: $assetId");
}
return $this->asJson([
'img' => $asset->getPreviewThumbImg($width, $height),
]);
}
/**
* Saves an asset.
*
* @return Response|null
* @throws BadRequestHttpException
* @throws Exception
* @throws ForbiddenHttpException
* @throws InvalidConfigException
* @throws VolumeException
* @throws Throwable
* @throws DeprecationException
* @throws ElementNotFoundException
* @throws InvalidRouteException
* @since 3.4.0
* @deprecated in 4.0.0
*/
public function actionSaveAsset(): ?Response
{
if (UploadedFile::getInstanceByName('assets-upload') !== null) {
Craft::$app->getDeprecator()->log(__METHOD__, 'Uploading new files via `assets/save-asset` has been deprecated. Use `assets/upload` instead.');
return $this->runAction('upload');
}
$assetId = $this->request->getBodyParam('sourceId') ?? $this->request->getRequiredParam('assetId');
$siteId = $this->request->getBodyParam('siteId');
$assetVariable = $this->request->getValidatedBodyParam('assetVariable') ?? 'asset';
/** @var Asset|null $asset */
$asset = Asset::find()
->id($assetId)
->siteId($siteId)
->one();
if ($asset === null) {
throw new BadRequestHttpException("Invalid asset ID: $assetId");
}
$this->requireVolumePermissionByAsset('saveAssets', $asset);
$this->requirePeerVolumePermissionByAsset('savePeerAssets', $asset);
if (Craft::$app->getIsMultiSite()) {
// Make sure they have access to this site
$this->requirePermission('editSite:' . $asset->getSite()->uid);
}
$asset->title = $this->request->getParam('title') ?? $asset->title;
$asset->newFilename = $this->request->getParam('filename');
$fieldsLocation = $this->request->getParam('fieldsLocation') ?? 'fields';
$asset->setFieldValuesFromRequest($fieldsLocation);
// Save the asset
$asset->setScenario(Element::SCENARIO_LIVE);
if (!Craft::$app->getElements()->saveElement($asset)) {
return $this->asModelFailure(
$asset,
Craft::t('app', 'Couldn’t save {type}.', [
'type' => Asset::lowerDisplayName(),
]),
$assetVariable
);
}
return $this->asModelSuccess(
$asset,
Craft::t('app', '{type} saved.', [
'type' => Asset::displayName(),
]),
data: [
'id' => $asset->id,
'title' => $asset->title,
'url' => $asset->getUrl(),
'cpEditUrl' => $asset->getCpEditUrl(),
],
);
}
/**
* Handles a file upload.
*
* @return Response
* @throws BadRequestHttpException
* @since 3.4.0
*/
public function actionUpload(): Response
{
$this->requireAcceptsJson();
$elementsService = Craft::$app->getElements();
$uploadedFile = UploadedFile::getInstanceByName('assets-upload');
if (!$uploadedFile) {
throw new BadRequestHttpException('No file was uploaded');
}
$folderId = (int)$this->request->getBodyParam('folderId') ?: null;
$fieldId = (int)$this->request->getBodyParam('fieldId') ?: null;
if (!$folderId && !$fieldId) {
throw new BadRequestHttpException('No target destination provided for uploading');
}
$assets = Craft::$app->getAssets();
$tempPath = $this->_getUploadedFileTempPath($uploadedFile);
if (empty($folderId)) {
/** @var AssetsField|null $field */
$field = Craft::$app->getFields()->getFieldById((int)$fieldId);
if (!$field instanceof AssetsField) {
throw new BadRequestHttpException('The field provided is not an Assets field');
}
if ($elementId = $this->request->getBodyParam('elementId')) {
$siteId = $this->request->getBodyParam('siteId') ?: null;
$element = $elementsService->getElementById($elementId, null, $siteId);
} else {
$element = null;
}
$folderId = $field->resolveDynamicPathToFolderId($element);
$selectionCondition = $field->getSelectionCondition();
if ($selectionCondition instanceof ElementCondition) {
$selectionCondition->referenceElement = $element;
}
} else {
$selectionCondition = null;
}
if (empty($folderId)) {
throw new BadRequestHttpException('The target destination provided for uploading is not valid');
}
$folder = $assets->findFolder(['id' => $folderId]);
if (!$folder) {
throw new BadRequestHttpException('The target folder provided for uploading is not valid');
}
// Check the permissions to upload in the resolved folder.
$this->requireVolumePermissionByFolder('saveAssets', $folder);
$filename = Assets::prepareAssetName($uploadedFile->name);
if ($selectionCondition) {
$tempFolder = Craft::$app->getAssets()->getUserTemporaryUploadFolder();
if ($folder->id !== $tempFolder->id) {
// upload to the user's temp folder initially, with a temp name
$originalFolder = $folder;
$originalFilename = $filename;
$folder = $tempFolder;
$filename = uniqid('asset', true) . '.' . pathinfo($filename, PATHINFO_EXTENSION);
}
}
$asset = new Asset();
$asset->tempFilePath = $tempPath;
$asset->setFilename($filename);
$asset->newFolderId = $folder->id;
$asset->setVolumeId($folder->volumeId);
$asset->uploaderId = Craft::$app->getUser()->getId();
$asset->avoidFilenameConflicts = true;
if (isset($originalFilename)) {
$asset->title = Assets::filename2Title(pathinfo($originalFilename, PATHINFO_FILENAME));
}
$asset->setScenario(Asset::SCENARIO_CREATE);
$result = $elementsService->saveElement($asset);
// In case of error, let user know about it.
if (!$result) {
return $this->asModelFailure($asset);
}
if ($selectionCondition) {
if (!$selectionCondition->matchElement($asset)) {
// delete and reject it
$elementsService->deleteElement($asset, true);
return $this->asFailure(Craft::t('app', '{filename} isn’t selectable for this field.', [
'filename' => $uploadedFile->name,
]));
}
if (isset($originalFilename, $originalFolder)) {
// move it into the original target destination
$asset->newFilename = $originalFilename;
$asset->newFolderId = $originalFolder->id;
$asset->setScenario(Asset::SCENARIO_MOVE);
if (!$elementsService->saveElement($asset)) {
return $this->asModelFailure($asset);
}
}
}
if ($asset->conflictingFilename !== null) {
$conflictingAsset = Asset::findOne(['folderId' => $folder->id, 'filename' => $asset->conflictingFilename]);
return $this->asJson([
'conflict' => Craft::t('app', 'A file with the name “{filename}” already exists.', ['filename' => $asset->conflictingFilename]),
'assetId' => $asset->id,
'filename' => $asset->conflictingFilename,
'conflictingAssetId' => $conflictingAsset->id ?? null,
'suggestedFilename' => $asset->suggestedFilename,
'conflictingAssetUrl' => ($conflictingAsset && $conflictingAsset->getVolume()->getFs()->hasUrls) ? $conflictingAsset->getUrl() : null,
]);
}
return $this->asSuccess(data: [
'filename' => $asset->getFilename(),
'assetId' => $asset->id,
]);
}
/**
* Replaces a file.
*
* @return Response
* @throws BadRequestHttpException if incorrect combination of parameters passed.
* @throws ForbiddenHttpException
* @throws InvalidConfigException
* @throws NotFoundHttpException if the asset can’t be found
* @throws VolumeException
*/
public function actionReplaceFile(): Response
{
$this->requireAcceptsJson();
$assetId = $this->request->getBodyParam('assetId');
$sourceAssetId = $this->request->getBodyParam('sourceAssetId');
$targetFilename = $this->request->getBodyParam('targetFilename');
$uploadedFile = UploadedFile::getInstanceByName('replaceFile');
$assets = Craft::$app->getAssets();
// Must have at least one existing asset (source or target).
// Must have either target asset or target filename.
// Must have either uploaded file or source asset.
if ((empty($assetId) && empty($sourceAssetId)) ||
(empty($assetId) && empty($targetFilename)) ||
($uploadedFile === null && empty($sourceAssetId))
) {
throw new BadRequestHttpException('Incorrect combination of parameters.');
}
$sourceAsset = null;
$assetToReplace = null;
if ($assetId && !$assetToReplace = $assets->getAssetById($assetId)) {
throw new NotFoundHttpException('Asset not found.');
}
if ($sourceAssetId && !$sourceAsset = $assets->getAssetById($sourceAssetId)) {
throw new NotFoundHttpException('Asset not found.');
}
$this->requireVolumePermissionByAsset('replaceFiles', $assetToReplace ?: $sourceAsset);
$this->requirePeerVolumePermissionByAsset('replacePeerFiles', $assetToReplace ?: $sourceAsset);
// Handle the Element Action
if ($assetToReplace !== null && $uploadedFile) {
$tempPath = $this->_getUploadedFileTempPath($uploadedFile);
$filename = Assets::prepareAssetName($uploadedFile->name);
$assets->replaceAssetFile($assetToReplace, $tempPath, $filename);
} elseif ($sourceAsset !== null) {
// Or replace using an existing Asset
// See if we can find an Asset to replace.
if ($assetToReplace === null) {
// Make sure the extension didn't change
if (pathinfo($targetFilename, PATHINFO_EXTENSION) !== $sourceAsset->getExtension()) {
throw new Exception($targetFilename . ' doesn\'t have the original file extension.');
}
/** @var Asset|null $assetToReplace */
$assetToReplace = Asset::find()
->select(['elements.id'])
->folderId($sourceAsset->folderId)
->filename(Db::escapeParam($targetFilename))
->one();
}
// If we have an actual asset for which to replace the file, just do it.
if (!empty($assetToReplace)) {
$tempPath = $sourceAsset->getCopyOfFile();
$assets->replaceAssetFile($assetToReplace, $tempPath, $assetToReplace->getFilename());
Craft::$app->getElements()->deleteElement($sourceAsset);
} else {
// If all we have is the filename, then make sure that the destination is empty and go for it.
$volume = $sourceAsset->getVolume();
$volume->deleteFile(rtrim($sourceAsset->folderPath, '/') . '/' . $targetFilename);
$sourceAsset->newFilename = $targetFilename;
// Don't validate required custom fields
Craft::$app->getElements()->saveElement($sourceAsset);
$assetId = $sourceAsset->id;
}
}
$resultingAsset = $assetToReplace ?: $sourceAsset;
return $this->asSuccess(data: [
'assetId' => $assetId,
'filename' => $resultingAsset->getFilename(),
'formattedSize' => $resultingAsset->getFormattedSize(0),
'formattedSizeInBytes' => $resultingAsset->getFormattedSizeInBytes(false),
'formattedDateUpdated' => Craft::$app->getFormatter()->asDatetime($resultingAsset->dateUpdated, Formatter::FORMAT_WIDTH_SHORT),
'dimensions' => $resultingAsset->getDimensions(),
]);
}
/**
* Creates a folder.
*
* @return Response
* @throws BadRequestHttpException if the parent folder cannot be found
* @throws InvalidConfigException
*/
public function actionCreateFolder(): Response
{
$this->requireAcceptsJson();
$parentId = $this->request->getRequiredBodyParam('parentId');
$folderName = $this->request->getRequiredBodyParam('folderName');
$folderName = Assets::prepareAssetName($folderName, false);
$assets = Craft::$app->getAssets();
$parentFolder = $assets->findFolder(['id' => $parentId]);
if (!$parentFolder) {
throw new BadRequestHttpException('The parent folder cannot be found');
}
try {
// Check if it's possible to create subfolders in the target volume.
$this->requireVolumePermissionByFolder('createFolders', $parentFolder);
$folderModel = new VolumeFolder();
$folderModel->name = $folderName;
$folderModel->parentId = $parentId;
$folderModel->volumeId = $parentFolder->volumeId;
$folderModel->path = $parentFolder->path . $folderName . '/';
$assets->createFolder($folderModel);
return $this->asSuccess(data: [
'folderName' => $folderModel->name,
'folderUid' => $folderModel->uid,
'folderId' => $folderModel->id,
]);
} catch (UserException $exception) {
return $this->asFailure($exception->getMessage());
}
}
/**
* Delete a folder.
*
* @return Response
* @throws BadRequestHttpException if the folder cannot be found
* @throws ForbiddenHttpException
* @throws InvalidConfigException
* @throws FsException
* @throws Throwable
*/
public function actionDeleteFolder(): Response
{
$this->requireAcceptsJson();
$folderId = $this->request->getRequiredBodyParam('folderId');
$assets = Craft::$app->getAssets();
$folder = $assets->getFolderById($folderId);
if (!$folder) {
throw new BadRequestHttpException('The folder cannot be found');
}
// Check if it's possible to delete objects in the target volume.
$this->requireVolumePermissionByFolder('deleteAssets', $folder);
$assets->deleteFoldersByIds($folderId);
return $this->asSuccess();
}
/**
* Deletes an asset.
*
* @return Response|null
* @throws BadRequestHttpException if the folder cannot be found
* @throws ForbiddenHttpException
* @throws Throwable
*/
public function actionDeleteAsset(): ?Response
{
$this->requirePostRequest();
$assetId = $this->request->getBodyParam('sourceId') ?? $this->request->getRequiredBodyParam('assetId');
$asset = Craft::$app->getAssets()->getAssetById($assetId);
if (!$asset) {
throw new BadRequestHttpException("Invalid asset ID: $assetId");
}
// Check if it's possible to delete objects in the target volume.
$this->requireVolumePermissionByAsset('deleteAssets', $asset);
$this->requirePeerVolumePermissionByAsset('deletePeerAssets', $asset);
$success = Craft::$app->getElements()->deleteElement($asset);
if (!$success) {
return $this->asModelFailure(
$asset,
Craft::t('app', 'Couldn’t delete {type}.', [
'type' => Asset::lowerDisplayName(),
]),
'asset'
);
}
return $this->asModelSuccess(
$asset,
Craft::t('app', '{type} deleted.', [
'type' => Asset::displayName(),
]),
'asset',
);
}
/**
* Renames a folder.
*
* @return Response
* @throws BadRequestHttpException if the folder cannot be found
* @throws ForbiddenHttpException
* @throws InvalidConfigException|VolumeException
*/
public function actionRenameFolder(): Response
{
$this->requireAcceptsJson();
$assets = Craft::$app->getAssets();
$folderId = $this->request->getRequiredBodyParam('folderId');
$newName = $this->request->getRequiredBodyParam('newName');
$folder = $assets->getFolderById($folderId);
if (!$folder) {
throw new BadRequestHttpException('The folder cannot be found');
}
// Check if it's possible to delete objects and create folders in the target volume.
$this->requireVolumePermissionByFolder('deleteAssets', $folder);
$this->requireVolumePermissionByFolder('createFolders', $folder);
$newName = Craft::$app->getAssets()->renameFolderById($folderId, $newName);
return $this->asSuccess(data: ['newName' => $newName]);
}
/**
* Move one or more assets.
*
* @return Response
* @throws BadRequestHttpException if the asset or the target folder cannot be found
* @throws Exception
* @throws ForbiddenHttpException
* @throws InvalidConfigException
* @throws VolumeException
* @throws Throwable
* @throws ElementNotFoundException
*/
public function actionMoveAsset(): Response
{
$this->requireAcceptsJson();
$assetsService = Craft::$app->getAssets();
// Get the asset
$assetId = $this->request->getRequiredBodyParam('assetId');
$asset = $assetsService->getAssetById($assetId);
if ($asset === null) {
throw new BadRequestHttpException('The Asset cannot be found');
}
// Get the target folder
$folderId = $this->request->getBodyParam('folderId', $asset->folderId);
$folder = $assetsService->getFolderById($folderId);
if ($folder === null) {
throw new BadRequestHttpException('The folder cannot be found');
}
// Get the target filename
$filename = $this->request->getBodyParam('filename') ?? $asset->getFilename();
// Check if it's possible to delete objects in the source volume and save assets in the target volume.
$this->requireVolumePermissionByFolder('saveAssets', $folder);
$this->requireVolumePermissionByAsset('deleteAssets', $asset);
$this->requirePeerVolumePermissionByAsset('savePeerAssets', $asset);
$this->requirePeerVolumePermissionByAsset('deletePeerAssets', $asset);
if ($this->request->getBodyParam('force')) {
// Check for a conflicting asset
/** @var Asset|null $conflictingAsset */
$conflictingAsset = Asset::find()
->select(['elements.id'])
->folderId($folderId)
->filename(Db::escapeParam($asset->getFilename()))
->one();
// If there's a conflicting asset, then merge and replace the file.
if ($conflictingAsset) {
Craft::$app->getElements()->mergeElementsByIds($conflictingAsset->id, $asset->id);
} else {
$volume = $folder->getVolume();
$volume->deleteFile(rtrim($folder->path, '/') . '/' . $asset->getFilename());
}
}
$result = $assetsService->moveAsset($asset, $folder, $filename);
if (!$result) {
// Get the corrected filename
[, $filename] = Assets::parseFileLocation($asset->newLocation);
return $this->asJson([
'conflict' => $asset->getFirstError('newLocation'),
'suggestedFilename' => $asset->suggestedFilename,
'filename' => $filename,
'assetId' => $asset->id,
]);
}
return $this->asSuccess();
}
/**
* Moves a folder.
*
* @return Response
* @throws BadRequestHttpException if the folder to move, or the destination parent folder, cannot be found
* @throws ForbiddenHttpException
* @throws InvalidConfigException
* @throws VolumeException
* @throws Throwable
*/
public function actionMoveFolder(): Response
{
$this->requirePostRequest();
$this->requireAcceptsJson();
$folderBeingMovedId = $this->request->getRequiredBodyParam('folderId');
$newParentFolderId = $this->request->getRequiredBodyParam('parentId');
$force = $this->request->getBodyParam('force', false);
$merge = !$force ? $this->request->getBodyParam('merge', false) : false;
$assets = Craft::$app->getAssets();
$folderToMove = $assets->getFolderById($folderBeingMovedId);
$destinationFolder = $assets->getFolderById($newParentFolderId);
if ($folderToMove === null) {
throw new BadRequestHttpException('The folder you are trying to move does not exist');
}
if ($destinationFolder === null) {
throw new BadRequestHttpException('The destination folder does not exist');
}
// Check if it's possible to delete objects in the source volume, create folders
// in the target volume, and save assets in the target volume.
$this->requireVolumePermissionByFolder('deleteAssets', $folderToMove);
$this->requireVolumePermissionByFolder('createFolders', $destinationFolder);
$this->requireVolumePermissionByFolder('saveAssets', $destinationFolder);
$targetVolume = $destinationFolder->getVolume();
$existingFolder = $assets->findFolder([
'parentId' => $newParentFolderId,
'name' => $folderToMove->name,
]);
if (!$existingFolder) {
$existingFolder = $targetVolume->directoryExists(rtrim($destinationFolder->path, '/') . '/' . $folderToMove->name);
}
// If this a conflict and no force or merge flags were passed in then STOP RIGHT THERE!
if ($existingFolder && !$force && !$merge) {
// Throw a prompt
return $this->asJson([
'conflict' => Craft::t('app', 'Folder “{folder}” already exists at target location', ['folder' => $folderToMove->name]),
'folderId' => $folderBeingMovedId,
'parentId' => $newParentFolderId,
]);
}
$sourceTree = $assets->getAllDescendantFolders($folderToMove);
if (!$existingFolder) {
// No conflicts, mirror the existing structure
$folderIdChanges = Assets::mirrorFolderStructure($folderToMove, $destinationFolder);
// Get the file transfer list.
$allSourceFolderIds = array_keys($sourceTree);
$allSourceFolderIds[] = $folderBeingMovedId;
/** @var Asset[] $foundAssets */
$foundAssets = Asset::find()
->folderId($allSourceFolderIds)
->all();
$fileTransferList = Assets::fileTransferList($foundAssets, $folderIdChanges);
} else {
$targetTreeMap = [];
// If an indexed folder is conflicting
if ($existingFolder instanceof VolumeFolder) {
// Delete if using force
if ($force) {
try {
$assets->deleteFoldersByIds($existingFolder->id);
} catch (VolumeException $exception) {
Craft::$app->getErrorHandler()->logException($exception);
return $this->asFailure(Craft::t('app', 'Directories cannot be deleted while moving assets.'));
}
} else {
// Or build a map of existing folders for file move
$targetTree = $assets->getAllDescendantFolders($existingFolder);
$targetPrefixLength = strlen($destinationFolder->path);
foreach ($targetTree as $existingFolder) {
$targetTreeMap[substr($existingFolder->path,
$targetPrefixLength)] = $existingFolder->id;
}
}
} elseif ($force) {
// An un-indexed folder is conflicting. If we're forcing things, just remove it.
$targetVolume->deleteDirectory(rtrim($destinationFolder->path, '/') . '/' . $folderToMove->name);
}
// Mirror the structure, passing along the exsting folder map
$folderIdChanges = Assets::mirrorFolderStructure($folderToMove, $destinationFolder, $targetTreeMap);
// Get file transfer list for the progress bar
$allSourceFolderIds = array_keys($sourceTree);
$allSourceFolderIds[] = $folderBeingMovedId;
/** @var Asset[] $foundAssets */
$foundAssets = Asset::find()
->folderId($allSourceFolderIds)
->all();
$fileTransferList = Assets::fileTransferList($foundAssets, $folderIdChanges);
}
$newFolderId = $folderIdChanges[$folderBeingMovedId] ?? null;
$newFolder = $assets->getFolderById($newFolderId);
return $this->asSuccess(data: [
'transferList' => $fileTransferList,
'newFolderUid' => $newFolder->uid,
'newFolderId' => $newFolderId,
]);
}
/**
* Returns the Image Editor template.
*
* @return Response
* @throws BadRequestHttpException if the asset is missing.
* @throws Exception
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function actionImageEditor(): Response
{
$assetId = $this->request->getRequiredBodyParam('assetId');
$asset = Craft::$app->getAssets()->getAssetById($assetId);
if (!$asset) {
throw new BadRequestHttpException(Craft::t('app', 'The asset you’re trying to edit does not exist.'));
}
$focal = $asset->getHasFocalPoint() ? $asset->getFocalPoint() : null;
$html = $this->getView()->renderTemplate('_special/image_editor.twig');
return $this->asJson(['html' => $html, 'focalPoint' => $focal]);
}
/**
* Returns the image being edited.
*
* @return Response
* @throws BadRequestHttpException
* @throws Exception
*/
public function actionEditImage(): Response
{
$assetId = (int)$this->request->getRequiredQueryParam('assetId');
$size = (int)$this->request->getRequiredQueryParam('size');
$asset = Asset::findOne($assetId);
if (!$asset) {
throw new BadRequestHttpException('The Asset cannot be found');
}
try {
$url = Craft::$app->getAssets()->getImagePreviewUrl($asset, $size, $size);
return $this->response->redirect($url);
} catch (NotSupportedException) {
// just output the file contents
$path = ImageTransforms::getLocalImageSource($asset);
return $this->response->sendFile($path, $asset->getFilename());
}
}
/**
* Saves an image according to the posted parameters.
*
* @return Response
* @throws BadRequestHttpException if some parameters are missing.
* @throws Throwable if something went wrong saving the asset.
*/
public function actionSaveImage(): Response
{
$this->requireAcceptsJson();
$assets = Craft::$app->getAssets();
$assetId = $this->request->getRequiredBodyParam('assetId');
$viewportRotation = (int)$this->request->getRequiredBodyParam('viewportRotation');
$imageRotation = (float)$this->request->getRequiredBodyParam('imageRotation');
$replace = $this->request->getRequiredBodyParam('replace');
$cropData = $this->request->getRequiredBodyParam('cropData');
$focalPoint = $this->request->getBodyParam('focalPoint');
$imageDimensions = $this->request->getBodyParam('imageDimensions');
$flipData = $this->request->getBodyParam('flipData');
$zoom = (float)$this->request->getBodyParam('zoom', 1);
$asset = $assets->getAssetById($assetId);
if ($asset === null) {
throw new BadRequestHttpException('The Asset cannot be found');
}
$folder = $asset->getFolder();
// Do what you want with your own photo.
if ($asset->id != static::currentUser()->photoId) {
$this->requireVolumePermissionByAsset('editImages', $asset);
$this->requirePeerVolumePermissionByAsset('editPeerImages', $asset);
}
// Verify parameter adequacy
if (!in_array($viewportRotation, [0, 90, 180, 270], false)) {
throw new BadRequestHttpException('Viewport rotation must be 0, 90, 180 or 270 degrees');
}
if (
is_array($cropData) &&
array_diff(['offsetX', 'offsetY', 'height', 'width'], array_keys($cropData))
) {
throw new BadRequestHttpException('Invalid cropping parameters passed');
}
// TODO Fire an event for any other image editing takers.
$transformer = new ImageTransformer();
$originalImageWidth = $asset->width;
$originalImageHeight = $asset->height;
$transformer->startImageEditing($asset);
$imageCropped = ($cropData['width'] !== $imageDimensions['width'] || $cropData['height'] !== $imageDimensions['height']);
$imageRotated = $viewportRotation !== 0 || $imageRotation !== 0.0;
$imageFlipped = !empty($flipData['x']) || !empty($flipData['y']);
$imageChanged = $imageCropped || $imageRotated || $imageFlipped;
if ($imageFlipped) {
$transformer->flipImage(!empty($flipData['x']), !empty($flipData['y']));
}
$generalConfig = Craft::$app->getConfig()->getGeneral();
$upscale = $generalConfig->upscaleImages;
$generalConfig->upscaleImages = true;
if ($zoom !== 1.0) {
$transformer->scaleImage((int)($originalImageWidth * $zoom), (int)($originalImageHeight * $zoom));
}
$generalConfig->upscaleImages = $upscale;
if ($imageRotated) {
$transformer->rotateImage($imageRotation + $viewportRotation);
}
$imageCenterX = $transformer->getEditedImageWidth() / 2;
$imageCenterY = $transformer->getEditedImageHeight() / 2;
$adjustmentRatio = min($originalImageWidth / $imageDimensions['width'], $originalImageHeight / $imageDimensions['height']);
$width = $cropData['width'] * $zoom * $adjustmentRatio;
$height = $cropData['height'] * $zoom * $adjustmentRatio;
$x = $imageCenterX + ($cropData['offsetX'] * $zoom * $adjustmentRatio) - $width / 2;
$y = $imageCenterY + ($cropData['offsetY'] * $zoom * $adjustmentRatio) - $height / 2;
$focal = null;
if ($focalPoint) {
$adjustmentRatio = min($originalImageWidth / $focalPoint['imageDimensions']['width'], $originalImageHeight / $focalPoint['imageDimensions']['height']);
$fx = $imageCenterX + ($focalPoint['offsetX'] * $zoom * $adjustmentRatio) - $x;
$fy = $imageCenterY + ($focalPoint['offsetY'] * $zoom * $adjustmentRatio) - $y;
$focal = [
'x' => $fx / $width,
'y' => $fy / $height,
];
}
if ($imageCropped) {
$transformer->crop((int)$x, (int)$y, (int)$width, (int)$height);
}
if ($imageChanged) {
$finalImage = $transformer->finishImageEditing();
} else {
$finalImage = $transformer->cancelImageEditing();
}
$output = [];
if ($replace) {
$oldFocal = $asset->getHasFocalPoint() ? $asset->getFocalPoint() : null;
$focalChanged = $focal !== $oldFocal;
$asset->setFocalPoint($focal);
if ($focalChanged) {
$transforms = Craft::$app->getImageTransforms();
$transforms->deleteCreatedTransformsForAsset($asset);
}
// Only replace file if it changed, otherwise just save changed focal points
if ($imageChanged) {
$assets->replaceAssetFile($asset, $finalImage, $asset->getFilename());
} elseif ($focalChanged) {
Craft::$app->getElements()->saveElement($asset);
}
} else {
$newAsset = new Asset();
$newAsset->avoidFilenameConflicts = true;
$newAsset->setScenario(Asset::SCENARIO_CREATE);
$newAsset->tempFilePath = $finalImage;
$newAsset->setFilename($asset->getFilename());
$newAsset->newFolderId = $folder->id;
$newAsset->setVolumeId($folder->volumeId);