-
Notifications
You must be signed in to change notification settings - Fork 641
/
Assets.php
1131 lines (974 loc) · 38 KB
/
Assets.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\fields;
use Craft;
use craft\base\ElementInterface;
use craft\elements\Asset;
use craft\elements\conditions\ElementCondition;
use craft\elements\db\AssetQuery;
use craft\elements\db\ElementQueryInterface;
use craft\elements\ElementCollection;
use craft\errors\FsObjectNotFoundException;
use craft\errors\InvalidFsException;
use craft\errors\InvalidSubpathException;
use craft\events\LocateUploadedFilesEvent;
use craft\fs\Temp;
use craft\gql\arguments\elements\Asset as AssetArguments;
use craft\gql\interfaces\elements\Asset as AssetInterface;
use craft\gql\resolvers\elements\Asset as AssetResolver;
use craft\helpers\ArrayHelper;
use craft\helpers\Assets as AssetsHelper;
use craft\helpers\Cp;
use craft\helpers\ElementHelper;
use craft\helpers\FileHelper;
use craft\helpers\Gql;
use craft\helpers\Gql as GqlHelper;
use craft\helpers\Html;
use craft\models\GqlSchema;
use craft\models\Volume;
use craft\models\VolumeFolder;
use craft\services\ElementSources;
use craft\services\Gql as GqlService;
use craft\web\UploadedFile;
use GraphQL\Type\Definition\Type;
use Twig\Error\RuntimeError;
use yii\base\InvalidConfigException;
/**
* Assets represents an Assets field.
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class Assets extends BaseRelationField
{
/**
* @since 3.5.11
*/
public const PREVIEW_MODE_FULL = 'full';
/**
* @since 3.5.11
*/
public const PREVIEW_MODE_THUMBS = 'thumbs';
/**
* @event LocateUploadedFilesEvent The event that is triggered when identifying any uploaded files that
* should be stored as assets and related by the field.
* @since 4.0.2
*/
public const EVENT_LOCATE_UPLOADED_FILES = 'locateUploadedFiles';
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('app', 'Assets');
}
/**
* @inheritdoc
*/
public static function icon(): string
{
return 'image';
}
/**
* @inheritdoc
*/
public static function elementType(): string
{
return Asset::class;
}
/**
* @inheritdoc
*/
public static function defaultSelectionLabel(): string
{
return Craft::t('app', 'Add an asset');
}
/**
* @inheritdoc
*/
public static function phpType(): string
{
return sprintf('\\%s|\\%s<\\%s>', AssetQuery::class, ElementCollection::class, Asset::class);
}
/**
* @var bool Whether assets should be restricted to a single location.
* @since 4.0.0
*/
public bool $restrictLocation = false;
/**
* @var string|null The source key where assets can be selected from, if assets are restricted.
* @since 4.0.0
*/
public ?string $restrictedLocationSource = null;
/**
* @var string|null The subpath where assets can be selected from, if assets are restricted.
* @since 4.0.0
*/
public ?string $restrictedLocationSubpath = null;
/**
* @var bool Whether assets can be selected from subfolders, if assets are restricted.
* @since 4.0.0
*/
public bool $allowSubfolders = false;
/**
* @var string|null The subpath where assets should be uploaded to by default, if assets are restricted and subfolders are allowed.
* @since 4.0.0
*/
public ?string $restrictedDefaultUploadSubpath = null;
/**
* @var string|null The source where assets should be uploaded by default, if assets aren’t restricted.
*/
public ?string $defaultUploadLocationSource = null;
/**
* @var string|null The subpath where assets should be uploaded by default, if assets aren’t restricted.
*/
public ?string $defaultUploadLocationSubpath = null;
/**
* @var bool Whether it should be possible to upload files directly to the field.
* @since 3.5.13
*/
public bool $allowUploads = true;
/**
* @var bool Whether the available assets should be restricted to
* [[allowedKinds]]
*/
public bool $restrictFiles = false;
/**
* @var array|null The file kinds that the field should be restricted to
* (only used if [[restrictFiles]] is true)
*/
public ?array $allowedKinds = null;
/**
* @var bool Whether to show input sources for volumes the user doesn’t have permission to view.
* @since 3.4.0
*/
public bool $showUnpermittedVolumes = false;
/**
* @var bool Whether to show files the user doesn’t have permission to view, per the
* “View files uploaded by other users” permission.
* @since 3.4.0
*/
public bool $showUnpermittedFiles = false;
/**
* @var string How related assets should be presented within element index views.
* @phpstan-var self::PREVIEW_MODE_FULL|self::PREVIEW_MODE_THUMBS
* @since 3.5.11
*/
public string $previewMode = self::PREVIEW_MODE_FULL;
/**
* @inheritdoc
*/
protected bool $allowLargeThumbsView = true;
/**
* @inheritdoc
*/
protected string $settingsTemplate = '_components/fieldtypes/Assets/settings.twig';
/**
* @inheritdoc
*/
protected string $inputTemplate = '_components/fieldtypes/Assets/input.twig';
/**
* @inheritdoc
*/
protected ?string $inputJsClass = 'Craft.AssetSelectInput';
/**
* @var array|null References for files uploaded as data strings for this field.
*/
private ?array $_uploadedDataFiles = null;
/**
* @inheritdoc
*/
public function __construct(array $config = [])
{
// Rename old settings
$oldSettings = [
'useSingleFolder' => 'restrictLocation',
'singleUploadLocationSource' => 'restrictedLocationSource',
'singleUploadLocationSubpath' => 'restrictedLocationSubpath',
];
foreach ($oldSettings as $old => $new) {
if (array_key_exists($old, $config)) {
$config[$new] = ArrayHelper::remove($config, $old);
}
}
// Default showUnpermittedVolumes to true for existing Assets fields
if (isset($config['id']) && !isset($config['showUnpermittedVolumes'])) {
$config['showUnpermittedVolumes'] = true;
}
parent::__construct($config);
}
/**
* @inheritdoc
*/
protected function defineRules(): array
{
$rules = parent::defineRules();
$rules[] = [
['allowedKinds'], 'required', 'when' => function(self $field): bool {
return (bool)$field->restrictFiles;
},
];
$rules[] = [['previewMode'], 'in', 'range' => [self::PREVIEW_MODE_FULL, self::PREVIEW_MODE_THUMBS], 'skipOnEmpty' => false];
return $rules;
}
/**
* @inheritdoc
*/
public function getSourceOptions(): array
{
$sourceOptions = [];
foreach (Asset::sources('settings') as $volume) {
if (!isset($volume['heading'])) {
$sourceOptions[] = [
'label' => $volume['label'],
'value' => $volume['key'],
];
}
}
return $sourceOptions;
}
/**
* Returns the available file kind options for the settings
*
* @return array
*/
public function getFileKindOptions(): array
{
$fileKindOptions = [];
foreach (AssetsHelper::getAllowedFileKinds() as $value => $kind) {
$fileKindOptions[] = ['value' => $value, 'label' => $kind['label']];
}
return $fileKindOptions;
}
/**
* @inheritdoc
*/
protected function inputHtml(mixed $value, ?ElementInterface $element, bool $inline): string
{
try {
return parent::inputHtml($value, $element, $inline);
} catch (InvalidSubpathException) {
return Html::tag('p', Craft::t('app', 'This field’s target subfolder path is invalid: {path}', [
'path' => '<code>' . $this->restrictedLocationSubpath . '</code>',
]), [
'class' => ['warning', 'with-icon'],
]);
} catch (InvalidFsException $e) {
return Html::tag('p', $e->getMessage(), [
'class' => ['warning', 'with-icon'],
]);
}
}
/**
* @inheritdoc
*/
public function getElementValidationRules(): array
{
$rules = parent::getElementValidationRules();
$rules[] = 'validateFileType';
$rules[] = 'validateFileSize';
return $rules;
}
/**
* Validates the files to make sure they are one of the allowed file kinds.
*
* @param ElementInterface $element
*/
public function validateFileType(ElementInterface $element): void
{
// Make sure the field restricts file types
if (!$this->restrictFiles) {
return;
}
$filenames = [];
// Get all the value's assets' filenames
/** @var AssetQuery $value */
$value = $element->getFieldValue($this->handle);
foreach ($value->all() as $asset) {
/** @var Asset $asset */
$filenames[] = $asset->getFilename();
}
// Get any uploaded filenames
$uploadedFiles = $this->_getUploadedFiles($element);
foreach ($uploadedFiles as $file) {
$filenames[] = $file['filename'];
}
// Now make sure that they all check out
$allowedExtensions = $this->_getAllowedExtensions();
foreach ($filenames as $filename) {
if (!in_array(mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION)), $allowedExtensions, true)) {
$element->addError($this->handle, Craft::t('app', '“{filename}” is not allowed in this field.', [
'filename' => $filename,
]));
}
}
}
/**
* Validates the files to make sure they are under the allowed max file size.
*
* @param ElementInterface $element
*/
public function validateFileSize(ElementInterface $element): void
{
$maxSize = Craft::$app->getConfig()->getGeneral()->maxUploadFileSize;
$filenames = [];
// Get any uploaded filenames
$uploadedFiles = $this->_getUploadedFiles($element);
foreach ($uploadedFiles as $file) {
switch ($file['type']) {
case 'data':
if (strlen($file['data']) > $maxSize) {
$filenames[] = $file['filename'];
}
break;
case 'file':
case 'upload':
if (file_exists($file['path']) && (filesize($file['path']) > $maxSize)) {
$filenames[] = $file['filename'];
}
break;
}
}
foreach ($filenames as $filename) {
$element->addError($this->handle, Craft::t('app', '“{filename}” is too large.', [
'filename' => $filename,
]));
}
}
/**
* @inheritdoc
*/
public function normalizeValue(mixed $value, ?ElementInterface $element): mixed
{
// If data strings are passed along, make sure the array keys are retained.
if (is_array($value) && isset($value['data']) && !empty($value['data'])) {
$this->_uploadedDataFiles = ['data' => $value['data'], 'filename' => $value['filename']];
unset($value['data'], $value['filename']);
/** @var Asset $class */
$class = static::elementType();
$query = $class::find();
$targetSite = $this->targetSiteId($element);
if ($this->targetSiteId) {
$query->siteId($targetSite);
} else {
$query
->site('*')
->unique()
->preferSites([$targetSite]);
}
// $value might be an array of element IDs
if (is_array($value)) {
$query
->id(array_values(array_filter($value)))
->fixedOrder();
if ($this->allowLimit && $this->maxRelations) {
$query->limit($this->maxRelations);
}
return $query;
}
}
return parent::normalizeValue($value, $element);
}
/**
* @inheritdoc
*/
public function isValueEmpty(mixed $value, ElementInterface $element): bool
{
return parent::isValueEmpty($value, $element) && empty($this->_getUploadedFiles($element));
}
/**
* Resolve source path for uploading for this field.
*
* @param ElementInterface|null $element
* @return int
*/
public function resolveDynamicPathToFolderId(?ElementInterface $element = null): int
{
return $this->_uploadFolder($element)->id;
}
/**
* @inheritdoc
*/
public function includeInGqlSchema(GqlSchema $schema): bool
{
return Gql::canQueryAssets($schema);
}
/**
* @inheritdoc
* @since 3.3.0
*/
public function getContentGqlType(): Type|array
{
return [
'name' => $this->handle,
'type' => Type::nonNull(Type::listOf(AssetInterface::getType())),
'args' => AssetArguments::getArguments(),
'resolve' => AssetResolver::class . '::resolve',
'complexity' => GqlHelper::relatedArgumentComplexity(GqlService::GRAPHQL_COMPLEXITY_EAGER_LOAD),
];
}
/**
* @inheritdoc
*/
protected function previewHtml(ElementCollection $elements): string
{
return Cp::elementPreviewHtml(
$elements->all(),
showLabel: $this->previewMode === self::PREVIEW_MODE_FULL,
);
}
/**
* @inheritdoc
*/
public function previewPlaceholderHtml(mixed $value, ?ElementInterface $element): string
{
$asset = new Asset();
$asset->title = Craft::t('app', 'Related {type} Title', ['type' => $asset->displayName()]);
if ($this->restrictFiles) {
$extensions = $this->_getAllowedExtensions();
$filename = 'test.' . $extensions[0];
} else {
$filename = 'test.txt';
}
$asset->filename = $filename;
$collection = new ElementCollection([$asset]);
return $this->previewHtml($collection);
}
// Events
// -------------------------------------------------------------------------
/**
* @inheritdoc
*/
public function beforeElementSave(ElementInterface $element, bool $isNew): bool
{
// Only handle file uploads for the initial site
if (!$element->propagating) {
// No special treatment for revisions
$rootElement = $element->getRootOwner();
if (!$rootElement->getIsRevision()) {
// Figure out what we're working with and set up some initial variables.
$isCanonical = $rootElement->getIsCanonical();
$query = $element->getFieldValue($this->handle);
$assetsService = Craft::$app->getAssets();
$getUploadFolderId = function() use ($element, $isCanonical, &$_targetFolderId): int {
return $_targetFolderId ?? ($_targetFolderId = $this->_uploadFolder($element, $isCanonical)->id);
};
// Were there any uploaded files?
$uploadedFiles = $this->_getUploadedFiles($element);
if (!empty($uploadedFiles)) {
$uploadFolderId = $getUploadFolderId();
// Convert them to assets
$assetIds = [];
foreach ($uploadedFiles as $file) {
$tempPath = AssetsHelper::tempFilePath($file['filename']);
switch ($file['type']) {
case 'data':
FileHelper::writeToFile($tempPath, $file['data']);
break;
case 'file':
rename($file['path'], $tempPath);
break;
case 'upload':
move_uploaded_file($file['path'], $tempPath);
break;
}
$uploadFolder = $assetsService->getFolderById($uploadFolderId);
$asset = new Asset();
$asset->tempFilePath = $tempPath;
$asset->setFilename($file['filename']);
$asset->newFolderId = $uploadFolderId;
$asset->setVolumeId($uploadFolder->volumeId);
$asset->uploaderId = Craft::$app->getUser()->getId();
$asset->avoidFilenameConflicts = true;
$asset->setScenario(Asset::SCENARIO_CREATE);
if (Craft::$app->getElements()->saveElement($asset)) {
$assetIds[] = $asset->id;
} else {
Craft::warning('Couldn’t save uploaded asset due to validation errors: ' . implode(', ', $asset->getFirstErrors()), __METHOD__);
}
}
if (!empty($assetIds)) {
// Add the newly uploaded IDs to the mix.
if (is_array($query->id)) {
$query = $this->normalizeValue(array_merge($query->id, $assetIds), $element);
} elseif (isset($query->where['elements.id']) && ArrayHelper::isNumeric($query->where['elements.id'])) {
$query = $this->normalizeValue(array_merge($query->where['elements.id'], $assetIds), $element);
} else {
$query = $this->normalizeValue($assetIds, $element);
}
$element->setFieldValue($this->handle, $query);
// Make sure that all traces of processed files are removed.
$this->_uploadedDataFiles = null;
}
}
}
}
return parent::beforeElementSave($element, $isNew);
}
/**
* @inheritdoc
*/
public function afterElementSave(ElementInterface $element, bool $isNew): void
{
// No special treatment for revisions
$rootElement = ElementHelper::rootElement($element);
if (!$rootElement->getIsRevision()) {
// Figure out what we're working with and set up some initial variables.
$isCanonical = $rootElement->getIsCanonical();
$query = $element->getFieldValue($this->handle);
$assetsService = Craft::$app->getAssets();
$getUploadFolderId = function() use ($element, $isCanonical, &$_targetFolderId): int {
return $_targetFolderId ?? ($_targetFolderId = $this->_uploadFolder($element, $isCanonical)->id);
};
// Are there any related assets?
/** @var AssetQuery $query */
/** @var Asset[] $assets */
$assets = $query->all();
if (!empty($assets)) {
// Only enforce the restricted asset location for canonical elements
if ($this->restrictLocation && $isCanonical) {
if (!$this->allowSubfolders) {
$rootRestrictedFolderId = $getUploadFolderId();
} else {
$rootRestrictedFolderId = $this->_uploadFolder($element, true, false)->id;
}
$assetsToMove = array_filter($assets, function(Asset $asset) use ($rootRestrictedFolderId, $assetsService) {
if ($asset->folderId === $rootRestrictedFolderId) {
return false;
}
if (!$this->allowSubfolders) {
return true;
}
$rootRestrictedFolder = $assetsService->getFolderById($rootRestrictedFolderId);
return (
$asset->volumeId !== $rootRestrictedFolder->volumeId ||
!str_starts_with($asset->folderPath, $rootRestrictedFolder->path)
);
});
} else {
// Find the files with temp sources and just move those.
/** @var Asset[] $assetsToMove */
$assetsToMove = $assetsService->createTempAssetQuery()
->id(array_map(fn(Asset $asset) => $asset->id, $assets))
->all();
}
if (!empty($assetsToMove)) {
$uploadFolder = $assetsService->getFolderById($getUploadFolderId());
// Resolve all conflicts by keeping both
foreach ($assetsToMove as $asset) {
$asset->avoidFilenameConflicts = true;
try {
$assetsService->moveAsset($asset, $uploadFolder);
} catch (FsObjectNotFoundException $e) {
// Don't freak out about that.
Craft::warning('Couldn’t move asset because the file doesn’t exist: ' . $e->getMessage());
Craft::$app->getErrorHandler()->logException($e);
}
}
}
}
}
parent::afterElementSave($element, $isNew);
}
/**
* @inheritdoc
* @since 3.3.0
*/
public function getEagerLoadingGqlConditions(): ?array
{
$allowedEntities = Gql::extractAllowedEntitiesFromSchema();
$volumeUids = $allowedEntities['volumes'] ?? [];
if (empty($volumeUids)) {
return null;
}
$volumesService = Craft::$app->getVolumes();
$volumeIds = array_filter(array_map(function(string $uid) use ($volumesService) {
$volume = $volumesService->getVolumeByUid($uid);
return $volume->id ?? null;
}, $volumeUids));
return [
'volumeId' => $volumeIds,
];
}
/**
* @inheritdoc
*/
public function getInputSources(?ElementInterface $element = null): array|string|null
{
$folder = $this->_uploadFolder($element, false, false);
Craft::$app->getSession()->authorize('saveAssets:' . $folder->getVolume()->uid);
if ($this->restrictLocation) {
if (!$this->showUnpermittedVolumes) {
// Make sure they have permission to view the volume
// (Use restrictedLocationSource here because the actual folder could belong to a temp volume)
$volume = $this->_volumeBySourceKey($this->restrictedLocationSource);
if (!$volume || !Craft::$app->getUser()->checkPermission("viewAssets:$volume->uid")) {
return [];
}
}
$sources = [$this->_sourceKeyByFolder($folder)];
if ($this->allowSubfolders) {
$userFolder = Craft::$app->getAssets()->getUserTemporaryUploadFolder();
if ($userFolder->id !== $folder->id) {
$sources[] = $this->_sourceKeyByFolder($userFolder);
}
}
return $sources;
}
if (is_array($this->sources)) {
$sources = array_merge($this->sources);
} else {
$sources = [];
foreach (Craft::$app->getElementSources()->getSources(Asset::class) as $source) {
if ($source['type'] !== ElementSources::TYPE_HEADING) {
$sources[] = $source['key'];
}
}
}
// Now enforce the showUnpermittedVolumes setting
if (!$this->showUnpermittedVolumes && !empty($sources)) {
$userService = Craft::$app->getUser();
$volumesService = Craft::$app->getVolumes();
return ArrayHelper::where($sources, function(string $source) use ($volumesService, $userService) {
// If it’s not a volume folder, let it through
if (!str_starts_with($source, 'volume:')) {
return true;
}
// Only show it if they have permission to view it, or if it's the temp volume
$volumeUid = explode(':', $source)[1];
if ($userService->checkPermission("viewAssets:$volumeUid")) {
return true;
}
$volume = $volumesService->getVolumeByUid($volumeUid);
return $volume?->getFs() instanceof Temp;
}, true, true, false);
}
return $sources;
}
/**
* @inheritdoc
*/
protected function inputTemplateVariables(array|ElementQueryInterface $value = null, ?ElementInterface $element = null): array
{
$variables = parent::inputTemplateVariables($value, $element);
$uploadVolume = $this->_uploadVolume();
$uploadFs = $uploadVolume?->getFs();
$variables['fsType'] = $uploadFs::class;
$variables['showFolders'] = !$this->restrictLocation || $this->allowSubfolders;
$variables['canUpload'] = (
$this->allowUploads &&
$uploadVolume &&
$uploadFs &&
Craft::$app->getUser()->checkPermission("saveAssets:$uploadVolume->uid")
);
$variables['defaultFieldLayoutId'] = $uploadVolume->fieldLayoutId ?? null;
if ($this->restrictLocation && !$this->allowSubfolders) {
$variables['showSourcePath'] = false;
}
if (!$this->restrictLocation || $this->allowSubfolders) {
$uploadFolder = $this->_uploadFolder($element, false);
if ($uploadFolder->volumeId) {
// If the location is restricted, don't go passed the base source folder
$baseUploadFolder = $this->restrictLocation ? $this->_uploadFolder($element, false, false) : null;
$folders = $this->_folderWithAncestors($uploadFolder, $baseUploadFolder);
$variables['defaultSource'] = $this->_sourceKeyByFolder($folders[0]);
$variables['defaultSourcePath'] = array_map(function(VolumeFolder $folder) {
return $folder->getSourcePathInfo();
}, $folders);
}
}
return $variables;
}
/**
* @inheritdoc
*/
public function getInputSelectionCriteria(): array
{
$criteria = parent::getInputSelectionCriteria();
$criteria['kind'] = ($this->restrictFiles && !empty($this->allowedKinds)) ? $this->allowedKinds : [];
if ($this->showUnpermittedFiles) {
$criteria['uploaderId'] = null;
}
return $criteria;
}
/**
* @inheritdoc
*/
protected function createSelectionCondition(): ?ElementCondition
{
$condition = Asset::createCondition();
$condition->queryParams = ['volume', 'volumeId', 'kind'];
return $condition;
}
/**
* Returns any files that were uploaded to the field.
*
* @param ElementInterface $element
* @return array
*/
private function _getUploadedFiles(ElementInterface $element): array
{
$files = [];
if (ElementHelper::isRevision($element)) {
return $files;
}
// Grab data strings
if (isset($this->_uploadedDataFiles['data']) && is_array($this->_uploadedDataFiles['data'])) {
foreach ($this->_uploadedDataFiles['data'] as $index => $dataString) {
if (preg_match('/^data:(?<type>[a-z0-9]+\/[a-z0-9\+\-\.]+);base64,(?<data>.+)/i', $dataString, $matches)) {
$type = $matches['type'];
$data = base64_decode($matches['data']);
if (!$data) {
continue;
}
if (!empty($this->_uploadedDataFiles['filename'][$index])) {
$filename = $this->_uploadedDataFiles['filename'][$index];
} else {
$extensions = FileHelper::getExtensionsByMimeType($type);
if (empty($extensions)) {
continue;
}
$filename = 'Uploaded_file.' . reset($extensions);
}
$files[] = [
'filename' => $filename,
'data' => $data,
'type' => 'data',
];
}
}
}
// See if we have uploaded file(s).
$paramName = $this->requestParamName($element);
if ($paramName !== null) {
$uploadedFiles = UploadedFile::getInstancesByName($paramName);
foreach ($uploadedFiles as $uploadedFile) {
$files[] = [
'filename' => $uploadedFile->name,
'path' => $uploadedFile->tempName,
'type' => 'upload',
];
}
}
// Fire a 'locateUploadedFiles' event
if ($this->hasEventHandlers(self::EVENT_LOCATE_UPLOADED_FILES)) {
$event = new LocateUploadedFilesEvent([
'element' => $element,
'files' => $files,
]);
$this->trigger(self::EVENT_LOCATE_UPLOADED_FILES, $event);
return $event->files;
}
return $files;
}
/**
* Finds a volume folder by a source key and (dynamic?) subpath.
*
* @param string $sourceKey
* @param string|null $subpath
* @param ElementInterface|null $element
* @param bool $createDynamicFolders whether missing folders should be created in the process
* @return VolumeFolder
* @throws InvalidSubpathException if the subpath cannot be parsed in full
* @throws InvalidFsException if the volume root folder doesn’t exist
*/
private function _findFolder(string $sourceKey, ?string $subpath, ?ElementInterface $element, bool $createDynamicFolders): VolumeFolder
{
// Make sure the volume and root folder actually exist
$volume = $this->_volumeBySourceKey($sourceKey);
if (!$volume) {
throw new InvalidFsException("Invalid source key: $sourceKey");
}
$assetsService = Craft::$app->getAssets();
$rootFolder = $assetsService->getRootFolderByVolumeId($volume->id);
// Are we looking for the root folder?
$subpath = trim($subpath ?? '', '/');
if ($subpath === '') {
return $rootFolder;
}
$isDynamic = preg_match('/\{|\}/', $subpath);
if ($isDynamic) {
// Prepare the path by parsing tokens and normalizing slashes.
try {
if ($element?->duplicateOf) {
$element = $element->duplicateOf;
}
$renderedSubpath = Craft::$app->getView()->renderObjectTemplate($subpath, $element);
} catch (InvalidConfigException|RuntimeError $e) {
throw new InvalidSubpathException($subpath, null, 0, $e);
}
// Did any of the tokens return null?
if (
$renderedSubpath === '' ||
trim($renderedSubpath, '/') != $renderedSubpath ||
str_contains($renderedSubpath, '//')
) {
throw new InvalidSubpathException($subpath);
}
// Sanitize the subpath
$segments = array_filter(explode('/', $renderedSubpath), function(string $segment): bool {
return $segment !== ':ignore:';
});
$generalConfig = Craft::$app->getConfig()->getGeneral();
$segments = array_map(function(string $segment) use ($generalConfig): string {
return FileHelper::sanitizeFilename($segment, [
'asciiOnly' => $generalConfig->convertFilenamesToAscii,
]);
}, $segments);
$subpath = implode('/', $segments);
}
$folder = $assetsService->findFolder([
'volumeId' => $volume->id,
'path' => $subpath . '/',
]);
// Ensure that the folder exists
if (!$folder) {
if (!$createDynamicFolders) {
throw new InvalidSubpathException($subpath);
}
$folder = $assetsService->ensureFolderByFullPathAndVolume($subpath, $volume);
}
return $folder;
}
/**
* Get a list of allowed extensions for a list of file kinds.
*
* @return array
*/
private function _getAllowedExtensions(): array
{
if (!is_array($this->allowedKinds)) {
return [];
}
$extensions = [];
$allKinds = AssetsHelper::getFileKinds();
foreach ($this->allowedKinds as $allowedKind) {
foreach ($allKinds[$allowedKind]['extensions'] as $ext) {
$extensions[] = $ext;
}
}
return $extensions;
}
/**
* Returns the upload folder that should be used for an element.
*
* @param ElementInterface|null $element
* @param bool $createDynamicFolders whether missing folders should be created in the process