/
Asset.php
2087 lines (1774 loc) · 57 KB
/
Asset.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
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Commercial License (PCL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PCL
*/
namespace Pimcore\Model;
use Doctrine\DBAL\Exception\DeadlockException;
use League\Flysystem\FilesystemOperator;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToMoveFile;
use Pimcore\Event\AssetEvents;
use Pimcore\Event\FrontendEvents;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\File;
use Pimcore\Helper\TemporaryFileHelperTrait;
use Pimcore\Loader\ImplementationLoader\Exception\UnsupportedException;
use Pimcore\Localization\LocaleServiceInterface;
use Pimcore\Logger;
use Pimcore\Messenger\AssetUpdateTasksMessage;
use Pimcore\Messenger\VersionDeleteMessage;
use Pimcore\Model\Asset\Listing;
use Pimcore\Model\Asset\MetaData\ClassDefinition\Data\Data;
use Pimcore\Model\Asset\MetaData\ClassDefinition\Data\DataDefinitionInterface;
use Pimcore\Model\Element\ElementInterface;
use Pimcore\Model\Element\Service;
use Pimcore\Model\Element\Traits\ScheduledTasksTrait;
use Pimcore\Model\Element\ValidationException;
use Pimcore\Model\Exception\NotFoundException;
use Pimcore\Tool;
use Pimcore\Tool\Storage;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Mime\MimeTypes;
/**
* @method \Pimcore\Model\Asset\Dao getDao()
* @method bool __isBasedOnLatestData()
* @method int getChildAmount($user = null)
* @method string|null getCurrentFullPath()
*/
class Asset extends Element\AbstractElement
{
use ScheduledTasksTrait;
use TemporaryFileHelperTrait;
/**
* all possible types of assets
*
* @internal
*
* @var array
*/
public static $types = ['folder', 'image', 'text', 'audio', 'video', 'document', 'archive', 'unknown'];
/**
* @internal
*
* @var int
*/
protected $id;
/**
* @internal
*
* @var int
*/
protected $parentId;
/**
* @internal
*
* @var self|null
*/
protected $parent;
/**
* @internal
*
* @var string
*/
protected $type;
/**
* @internal
*
* @var string
*/
protected $filename;
/**
* @internal
*
* @var string
*/
protected $path;
/**
* @internal
*
* @var string
*/
protected $mimetype;
/**
* @internal
*
* @var int
*/
protected $creationDate;
/**
* @internal
*
* @var int
*/
protected $modificationDate;
/**
* @internal
*
* @var resource|null
*/
protected $stream;
/**
* @internal
*
* @var int|null
*/
protected ?int $userOwner = null;
/**
* @internal
*
* @var int|null
*/
protected ?int $userModification = null;
/**
* @internal
*
* @var array
*/
protected $properties = null;
/**
* @internal
*
* @var array|null
*/
protected $versions = null;
/**
* @internal
*
* @var array
*/
protected $metadata = [];
/**
* @internal
*
* enum('self','propagate') nullable
*
* @var string|null
*/
protected $locked;
/**
* List of some custom settings [key] => value
* Here there can be stored some data, eg. the video thumbnail files, ... of the asset, ...
*
* @internal
*
* @var array
*/
protected $customSettings = [];
/**
* @internal
*
* @var bool
*/
protected $hasMetaData = false;
/**
* @internal
*
* @var array|null
*/
protected $siblings;
/**
* @internal
*
* @var bool|null
*/
protected $hasSiblings;
/**
* @internal
*
* @var bool
*/
protected $_dataChanged = false;
/**
* @internal
*
* @var int
*/
protected $versionCount;
/**
*
* @return array
*/
public static function getTypes()
{
return self::$types;
}
/**
* Static helper to get an asset by the passed path
*
* @param string $path
* @param bool $force
*
* @return static|null
*/
public static function getByPath($path, $force = false)
{
if (!$path) {
return null;
}
$path = Element\Service::correctPath($path);
try {
$asset = new Asset();
$asset->getDao()->getByPath($path);
return static::getById($asset->getId(), $force);
} catch (NotFoundException $e) {
return null;
}
}
/**
* @internal
*
* @param Asset $asset
*
* @return bool
*/
protected static function typeMatch(Asset $asset)
{
$staticType = get_called_class();
if ($staticType != Asset::class) {
if (!$asset instanceof $staticType) {
return false;
}
}
return true;
}
/**
* @param int $id
* @param bool $force
*
* @return static|null
*/
public static function getById($id, $force = false)
{
if (!is_numeric($id) || $id < 1) {
return null;
}
$id = (int)$id;
$cacheKey = self::getCacheKey($id);
if (!$force && \Pimcore\Cache\Runtime::isRegistered($cacheKey)) {
$asset = \Pimcore\Cache\Runtime::get($cacheKey);
if ($asset && static::typeMatch($asset)) {
return $asset;
}
}
if ($force || !($asset = \Pimcore\Cache::load($cacheKey))) {
$asset = new Asset();
try {
$asset->getDao()->getById($id);
$className = 'Pimcore\\Model\\Asset\\' . ucfirst($asset->getType());
/** @var Asset $asset */
$asset = self::getModelFactory()->build($className);
\Pimcore\Cache\Runtime::set($cacheKey, $asset);
$asset->getDao()->getById($id);
$asset->__setDataVersionTimestamp($asset->getModificationDate());
$asset->resetDirtyMap();
\Pimcore\Cache::save($asset, $cacheKey);
} catch (NotFoundException $e) {
return null;
}
} else {
\Pimcore\Cache\Runtime::set($cacheKey, $asset);
}
if (!$asset || !static::typeMatch($asset)) {
return null;
}
return $asset;
}
/**
* @param int $parentId
* @param array $data
* @param bool $save
*
* @return Asset
*/
public static function create($parentId, $data = [], $save = true)
{
// create already the real class for the asset type, this is especially for images, because a system-thumbnail
// (tree) is generated immediately after creating an image
$class = Asset::class;
if (array_key_exists('filename', $data) && (array_key_exists('data', $data) || array_key_exists('sourcePath', $data) || array_key_exists('stream', $data))) {
if (array_key_exists('data', $data) || array_key_exists('stream', $data)) {
$tmpFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/asset-create-tmp-file-' . uniqid() . '.' . File::getFileExtension($data['filename']);
if (array_key_exists('data', $data)) {
File::put($tmpFile, $data['data']);
self::checkMaxPixels($tmpFile);
$mimeType = MimeTypes::getDefault()->guessMimeType($tmpFile);
unlink($tmpFile);
} else {
$streamMeta = stream_get_meta_data($data['stream']);
if (file_exists($streamMeta['uri'])) {
// stream is a local file, so we don't have to write a tmp file
self::checkMaxPixels($streamMeta['uri']);
$mimeType = MimeTypes::getDefault()->guessMimeType($streamMeta['uri']);
} else {
// write a tmp file because the stream isn't a pointer to the local filesystem
$isRewindable = @rewind($data['stream']);
$dest = fopen($tmpFile, 'w+', false, File::getContext());
stream_copy_to_stream($data['stream'], $dest);
self::checkMaxPixels($tmpFile);
$mimeType = MimeTypes::getDefault()->guessMimeType($tmpFile);
if (!$isRewindable) {
$data['stream'] = $dest;
} else {
fclose($dest);
unlink($tmpFile);
}
}
}
} else {
if (is_dir($data['sourcePath'])) {
$mimeType = 'directory';
} else {
self::checkMaxPixels($data['sourcePath']);
$mimeType = MimeTypes::getDefault()->guessMimeType($data['sourcePath']);
if (is_file($data['sourcePath'])) {
$data['stream'] = fopen($data['sourcePath'], 'rb', false, File::getContext());
}
}
unset($data['sourcePath']);
}
$type = self::getTypeFromMimeMapping($mimeType, $data['filename']);
$class = '\\Pimcore\\Model\\Asset\\' . ucfirst($type);
if (array_key_exists('type', $data)) {
unset($data['type']);
}
}
/** @var Asset $asset */
$asset = self::getModelFactory()->build($class);
$asset->setParentId($parentId);
self::checkCreateData($data);
$asset->setValues($data);
if ($save) {
$asset->save();
}
return $asset;
}
private static function checkMaxPixels(string $localPath): void
{
$maxPixels = \Pimcore::getContainer()->getParameter('pimcore.config')['assets']['image']['max_pixels'];
if($size = getimagesize($localPath)) {
if($size[0] * $size[1] > $maxPixels) {
throw new ValidationException(
'Image exceeds max pixel size of ' . $maxPixels . ', you can change the value in config pimcore.assets.image.max_pixels');
}
}
}
/**
* @param array $config
*
* @return mixed
*
* @throws \Exception
*/
public static function getList($config = [])
{
if (!\is_array($config)) {
throw new \Exception('Unable to initiate list class - please provide valid configuration array');
}
$listClass = Listing::class;
$list = self::getModelFactory()->build($listClass);
$list->setValues($config);
return $list;
}
/**
* @deprecated will be removed in Pimcore 11
*
* @param array $config
*
* @return int total count
*/
public static function getTotalCount($config = [])
{
$list = static::getList($config);
$count = $list->getTotalCount();
return $count;
}
/**
* @internal
*
* @param string $mimeType
* @param string $filename
*
* @return string
*/
public static function getTypeFromMimeMapping($mimeType, $filename)
{
if ($mimeType == 'directory') {
return 'folder';
}
$type = null;
$mappings = [
'unknown' => ["/\.stp$/"],
'image' => ['/image/', "/\.eps$/", "/\.ai$/", "/\.svgz$/", "/\.pcx$/", "/\.iff$/", "/\.pct$/", "/\.wmf$/"],
'text' => ['/text/', '/xml$/', '/\.json$/'],
'audio' => ['/audio/'],
'video' => ['/video/'],
'document' => ['/msword/', '/pdf/', '/powerpoint/', '/office/', '/excel/', '/opendocument/'],
'archive' => ['/zip/', '/tar/'],
];
foreach ($mappings as $assetType => $patterns) {
foreach ($patterns as $pattern) {
if (preg_match($pattern, $mimeType . ' .' . File::getFileExtension($filename))) {
$type = $assetType;
break;
}
}
// break at first match
if ($type) {
break;
}
}
if (!$type) {
$type = 'unknown';
}
return $type;
}
/**
* {@inheritdoc}
*/
public function save()
{
// additional parameters (e.g. "versionNote" for the version note)
$params = [];
if (func_num_args() && is_array(func_get_arg(0))) {
$params = func_get_arg(0);
}
$isUpdate = false;
$differentOldPath = null;
try {
$preEvent = new AssetEvent($this, $params);
if ($this->getId()) {
$isUpdate = true;
\Pimcore::getEventDispatcher()->dispatch($preEvent, AssetEvents::PRE_UPDATE);
} else {
\Pimcore::getEventDispatcher()->dispatch($preEvent, AssetEvents::PRE_ADD);
}
$params = $preEvent->getArguments();
$this->correctPath();
// we wrap the save actions in a loop here, so that we can restart the database transactions in the case it fails
// if a transaction fails it gets restarted $maxRetries times, then the exception is thrown out
// this is especially useful to avoid problems with deadlocks in multi-threaded environments (forked workers, ...)
$maxRetries = 5;
for ($retries = 0; $retries < $maxRetries; $retries++) {
$this->beginTransaction();
try {
if (!$isUpdate) {
$this->getDao()->create();
}
// get the old path from the database before the update is done
$oldPath = null;
if ($isUpdate) {
$oldPath = $this->getDao()->getCurrentFullPath();
}
$this->update($params);
$storage = Storage::get('asset');
// if the old path is different from the new path, update all children
$updatedChildren = [];
if ($oldPath && $oldPath != $this->getRealFullPath()) {
$differentOldPath = $oldPath;
try {
$storage->move($oldPath, $this->getRealFullPath());
} catch (UnableToMoveFile $e) {
//update children, if unable to move parent
$this->updateChildPaths($storage, $oldPath);
}
$this->getDao()->updateWorkspaces();
$updatedChildren = $this->getDao()->updateChildPaths($oldPath);
$this->relocateThumbnails($oldPath);
}
// lastly create a new version if necessary
// this has to be after the registry update and the DB update, otherwise this would cause problem in the
// $this->__wakeUp() method which is called by $version->save(); (path correction for version restore)
if ($this->getType() != 'folder') {
$this->saveVersion(false, false, isset($params['versionNote']) ? $params['versionNote'] : null);
}
$this->commit();
break; // transaction was successfully completed, so we cancel the loop here -> no restart required
} catch (\Exception $e) {
try {
$this->rollBack();
} catch (\Exception $er) {
// PDO adapter throws exceptions if rollback fails
Logger::error($er);
}
// we try to start the transaction $maxRetries times again (deadlocks, ...)
if ($e instanceof DeadlockException && $retries < ($maxRetries - 1)) {
$run = $retries + 1;
$waitTime = rand(1, 5) * 100000; // microseconds
Logger::warn('Unable to finish transaction (' . $run . ". run) because of the following reason '" . $e->getMessage() . "'. --> Retrying in " . $waitTime . ' microseconds ... (' . ($run + 1) . ' of ' . $maxRetries . ')');
usleep($waitTime); // wait specified time until we restart the transaction
} else {
// if the transaction still fail after $maxRetries retries, we throw out the exception
throw $e;
}
}
}
$additionalTags = [];
if (isset($updatedChildren) && is_array($updatedChildren)) {
foreach ($updatedChildren as $assetId) {
$tag = 'asset_' . $assetId;
$additionalTags[] = $tag;
// remove the child also from registry (internal cache) to avoid path inconsistencies during long running scripts, such as CLI
\Pimcore\Cache\Runtime::set($tag, null);
}
}
$this->clearDependentCache($additionalTags);
if ($this->getDataChanged()) {
if (in_array($this->getType(), ['image', 'video', 'document'])) {
$this->addToUpdateTaskQueue();
}
}
$this->setDataChanged(false);
$postEvent = new AssetEvent($this, $params);
if ($isUpdate) {
if ($differentOldPath) {
$postEvent->setArgument('oldPath', $differentOldPath);
}
\Pimcore::getEventDispatcher()->dispatch($postEvent, AssetEvents::POST_UPDATE);
} else {
\Pimcore::getEventDispatcher()->dispatch($postEvent, AssetEvents::POST_ADD);
}
return $this;
} catch (\Exception $e) {
$failureEvent = new AssetEvent($this, $params);
$failureEvent->setArgument('exception', $e);
if ($isUpdate) {
\Pimcore::getEventDispatcher()->dispatch($failureEvent, AssetEvents::POST_UPDATE_FAILURE);
} else {
\Pimcore::getEventDispatcher()->dispatch($failureEvent, AssetEvents::POST_ADD_FAILURE);
}
throw $e;
}
}
/**
* @internal
*
* @throws \Exception
*/
public function correctPath()
{
// set path
if ($this->getId() != 1) { // not for the root node
if (!Element\Service::isValidKey($this->getKey(), 'asset')) {
throw new \Exception("invalid filename '" . $this->getKey() . "' for asset with id [ " . $this->getId() . ' ]');
}
if ($this->getParentId() == $this->getId()) {
throw new \Exception("ParentID and ID is identical, an element can't be the parent of itself.");
}
if ($this->getFilename() === '..' || $this->getFilename() === '.') {
throw new \Exception('Cannot create asset called ".." or "."');
}
$parent = Asset::getById($this->getParentId());
if ($parent) {
// use the parent's path from the database here (getCurrentFullPath), to ensure the path really exists and does not rely on the path
// that is currently in the parent asset (in memory), because this might have changed but wasn't not saved
$this->setPath(str_replace('//', '/', $parent->getCurrentFullPath() . '/'));
} else {
// parent document doesn't exist anymore, set the parent to to root
$this->setParentId(1);
$this->setPath('/');
}
} elseif ($this->getId() == 1) {
// some data in root node should always be the same
$this->setParentId(0);
$this->setPath('/');
$this->setFilename('');
$this->setType('folder');
}
// do not allow PHP and .htaccess files
if (preg_match("@\.ph(p[\d+]?|t|tml|ps|ar)$@i", $this->getFilename()) || $this->getFilename() == '.htaccess') {
$this->setFilename($this->getFilename() . '.txt');
}
if (mb_strlen($this->getFilename()) > 255) {
throw new \Exception('Filenames longer than 255 characters are not allowed');
}
if (Asset\Service::pathExists($this->getRealFullPath())) {
$duplicate = Asset::getByPath($this->getRealFullPath());
if ($duplicate instanceof Asset && $duplicate->getId() != $this->getId()) {
throw new \Exception('Duplicate full path [ ' . $this->getRealFullPath() . ' ] - cannot save asset');
}
}
$this->validatePathLength();
}
/**
* @internal
*
* @param array $params additional parameters (e.g. "versionNote" for the version note)
*
* @throws \Exception
*/
protected function update($params = [])
{
$storage = Storage::get('asset');
$this->updateModificationInfos();
$path = $this->getRealFullPath();
$typeChanged = false;
if ($this->getType() != 'folder') {
if ($this->getDataChanged()) {
$src = $this->getStream();
// Write original data to temp path for writing stream
// as original file will be deleted before overwrite
$pathInfo = pathinfo($this->getFilename());
$tempFilePath = $this->getRealPath() . uniqid('temp_') . '.' . $pathInfo['extension'];
$storage->writeStream($tempFilePath, $src);
$dbPath = $this->getDao()->getCurrentFullPath();
if ($dbPath !== $path && $storage->fileExists($dbPath)) {
$storage->delete($dbPath);
}
if ($storage->fileExists($path)) {
// We don't open a stream on existing files, because they could be possibly used by versions
// using hardlinks, so it's safer to delete them first, so the inode and therefore also the
// versioning information persists. Using the stream on the existing file would overwrite the
// contents of the inode and therefore leads to wrong version data
$storage->delete($path);
}
$storage->move($tempFilePath, $path);
$this->stream = null; // set stream to null, so that the source stream isn't used anymore after saving
$mimeType = $storage->mimeType($path);
$this->setMimeType($mimeType);
// set type
$type = self::getTypeFromMimeMapping($mimeType, $this->getFilename());
if ($type != $this->getType()) {
$this->setType($type);
$typeChanged = true;
}
// not only check if the type is set but also if the implementation can be found
$className = 'Pimcore\\Model\\Asset\\' . ucfirst($this->getType());
if (!self::getModelFactory()->supports($className)) {
throw new \Exception('unable to resolve asset implementation with type: ' . $this->getType());
}
}
} else {
$storage->createDirectory($path);
}
if (!$this->getType()) {
$this->setType('unknown');
}
$this->postPersistData();
// save properties
$this->getProperties();
$this->getDao()->deleteAllProperties();
if (is_array($this->getProperties()) && count($this->getProperties()) > 0) {
foreach ($this->getProperties() as $property) {
if (!$property->getInherited()) {
$property->setDao(null);
$property->setCid($this->getId());
$property->setCtype('asset');
$property->setCpath($this->getRealFullPath());
$property->save();
}
}
}
// save dependencies
$d = new Dependency();
$d->setSourceType('asset');
$d->setSourceId($this->getId());
foreach ($this->resolveDependencies() as $requirement) {
if ($requirement['id'] == $this->getId() && $requirement['type'] == 'asset') {
// dont't add a reference to yourself
continue;
} else {
$d->addRequirement($requirement['id'], $requirement['type']);
}
}
$d->save();
$this->getDao()->update();
//set asset to registry
$cacheKey = self::getCacheKey($this->getId());
\Pimcore\Cache\Runtime::set($cacheKey, $this);
if (get_class($this) == 'Asset' || $typeChanged) {
// get concrete type of asset
// this is important because at the time of creating an asset it's not clear which type (resp. class) it will have
// the type (image, document, ...) depends on the mime-type
\Pimcore\Cache\Runtime::set($cacheKey, null);
Asset::getById($this->getId()); // call it to load it to the runtime cache again
}
$this->closeStream();
}
/**
* @internal
*/
protected function postPersistData()
{
// hook for the save process, can be overwritten in implementations, such as Image
}
/**
* @param bool $setModificationDate
* @param bool $saveOnlyVersion
* @param string $versionNote version note
*
* @return null|Version
*
* @throws \Exception
*/
public function saveVersion($setModificationDate = true, $saveOnlyVersion = true, $versionNote = null)
{
try {
// hook should be also called if "save only new version" is selected
if ($saveOnlyVersion) {
$event = new AssetEvent($this, [
'saveVersionOnly' => true,
]);
\Pimcore::getEventDispatcher()->dispatch($event, AssetEvents::PRE_UPDATE);
}
// set date
if ($setModificationDate) {
$this->setModificationDate(time());
}
// scheduled tasks are saved always, they are not versioned!
$this->saveScheduledTasks();
// create version
$version = null;
// only create a new version if there is at least 1 allowed
// or if saveVersion() was called directly (it's a newer version of the asset)
$assetsConfig = \Pimcore\Config::getSystemConfiguration('assets');
if ((is_null($assetsConfig['versions']['days'] ?? null) && is_null($assetsConfig['versions']['steps'] ?? null))
|| (!empty($assetsConfig['versions']['steps']))
|| !empty($assetsConfig['versions']['days'])
|| $setModificationDate) {
$saveStackTrace = !($assetsConfig['versions']['disable_stack_trace'] ?? false);
$version = $this->doSaveVersion($versionNote, $saveOnlyVersion, $saveStackTrace);
}
// hook should be also called if "save only new version" is selected
if ($saveOnlyVersion) {
$event = new AssetEvent($this, [
'saveVersionOnly' => true,
]);
\Pimcore::getEventDispatcher()->dispatch($event, AssetEvents::POST_UPDATE);
}
return $version;
} catch (\Exception $e) {
$event = new AssetEvent($this, [
'saveVersionOnly' => true,
'exception' => $e,
]);
\Pimcore::getEventDispatcher()->dispatch($event, AssetEvents::POST_UPDATE_FAILURE);
throw $e;
}
}
/**
* {@inheritdoc}
*/
public function getFullPath()
{
$path = $this->getPath() . $this->getFilename();
if (Tool::isFrontend()) {
return $this->getFrontendFullPath();
}
return $path;
}
/**
* Returns the full path of the asset (listener aware)
*
* @return string
*
* @internal
*/
public function getFrontendFullPath()
{
$path = $this->getPath() . $this->getFilename();
$path = urlencode_ignore_slash($path);
$prefix = \Pimcore::getContainer()->getParameter('pimcore.config')['assets']['frontend_prefixes']['source'];
$path = $prefix . $path;
$event = new GenericEvent($this, [
'frontendPath' => $path,
]);
\Pimcore::getEventDispatcher()->dispatch($event, FrontendEvents::ASSET_PATH);
return $event->getArgument('frontendPath');
}
/**
* {@inheritdoc}
*/
public function getRealPath()
{
return $this->path;
}
/**
* {@inheritdoc}
*/
public function getRealFullPath()
{
$path = $this->getRealPath() . $this->getFilename();
return $path;
}
/**
* @return array
*/
public function getSiblings()
{
if ($this->siblings === null) {
$list = new Asset\Listing();
// string conversion because parentId could be 0
$list->addConditionParam('parentId = ?', (string)$this->getParentId());
$list->addConditionParam('id != ?', $this->getId());
$list->setOrderKey('filename');
$list->setOrder('asc');
$this->siblings = $list->getAssets();
}
return $this->siblings;
}
/**
* @return bool
*/
public function hasSiblings()
{
if (is_bool($this->hasSiblings)) {
if (($this->hasSiblings && empty($this->siblings)) || (!$this->hasSiblings && !empty($this->siblings))) {
return $this->getDao()->hasSiblings();
} else {
return $this->hasSiblings;
}
}
return $this->getDao()->hasSiblings();
}
/**
* @return bool
*/
public function hasChildren()
{
return false;
}
/**
* @return Asset[]
*/
public function getChildren()
{
return [];
}
/**
* {@inheritdoc}
*/
public function getLocked()
{
return $this->locked;