/
File.php
1520 lines (1363 loc) · 44.3 KB
/
File.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
namespace SilverStripe\Assets;
use InvalidArgumentException;
use SilverStripe\Assets\Shortcodes\FileLink;
use SilverStripe\Assets\Shortcodes\FileLinkTracking;
use SilverStripe\Assets\Shortcodes\FileShortcodeProvider;
use SilverStripe\Assets\Shortcodes\ImageShortcodeProvider;
use SilverStripe\Assets\Storage\AssetContainer;
use SilverStripe\Assets\Storage\AssetNameGenerator;
use SilverStripe\Assets\Storage\DBFile;
use SilverStripe\Control\Director;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Resettable;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HTMLReadonlyField;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\CMSPreviewable;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\HasManyList;
use SilverStripe\ORM\Hierarchy\Hierarchy;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\InheritedPermissions;
use SilverStripe\Security\InheritedPermissionsExtension;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\PermissionChecker;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Security;
use SilverStripe\Versioned\RecursivePublishable;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\HTML;
/**
* This class handles the representation of a file on the filesystem within the framework.
* Most of the methods also handle the {@link Folder} subclass.
*
* Note: The files are stored in the assets/ directory, but SilverStripe
* looks at the db object to gather information about a file such as URL
* It then uses this for all processing functions (like image manipulation).
*
* <b>Security</b>
*
* Caution: It is recommended to disable any script execution in the "assets/"
* directory in the webserver configuration, to reduce the risk of exploits.
* See http://doc.silverstripe.org/secure-development#filesystem
*
* <b>Asset storage</b>
*
* As asset storage is configured separately to any File DataObject records, this class
* does not make any assumptions about how these records are saved. They could be on
* a local filesystem, remote filesystem, or a virtual record container (such as in local memory).
*
* The File dataobject simply represents an externally facing view of shared resources
* within this asset store.
*
* Internally individual files are referenced by a"Filename" parameter, which represents a File, extension,
* and is optionally prefixed by a list of custom directories. This path is root-agnostic, so it does not
* automatically have a direct url mapping (even to the site's base directory).
*
* Additionally, individual files may have several versions distinguished by sha1 hash,
* of which a File DataObject can point to a single one. Files can also be distinguished by
* variants, which may be resized images or format-shifted documents.
*
* <b>Properties</b>
*
* - "Title": Optional title of the file (for display purposes only).
* Defaults to "Name". Note that the Title field of Folder (subclass of File)
* is linked to Name, so Name and Title will always be the same.
* -"File": Physical asset backing this DB record. This is a composite DB field with
* its own list of properties. {@see DBFile} for more information
* - "Content": Typically unused, but handy for a textual representation of
* files, e.g. for fulltext indexing of PDF documents.
* - "ParentID": Points to a {@link Folder} record. Should be in sync with
* "Filename". A ParentID=0 value points to the "assets/" folder, not the webroot.
* -"ShowInSearch": True if this file is searchable
*
* @property string $Name Basename of the file
* @property string $Title Title of the file
* @property string $Filename Full filename of this file
* @property DBFile $File asset stored behind this File record
* @property string $Content
* @property string $ShowInSearch Boolean that indicates if file is shown in search. Doesn't apply to Folders
* @property int $ParentID ID of parent File/Folder
* @property int $OwnerID ID of Member who owns the file
*
* @method File Parent() Returns parent File
* @method Member Owner() Returns Member object of file owner.
* @method HasManyList|FileLink[] BackLinks() List of SiteTreeLink objects attached to this page
*
* @mixin Hierarchy
* @mixin Versioned
* @mixin RecursivePublishable
* @mixin InheritedPermissionsExtension
*/
class File extends DataObject implements AssetContainer, Thumbnail, CMSPreviewable, PermissionProvider, Resettable
{
use ImageManipulation;
/**
* Permission for edit all files
*/
const EDIT_ALL = 'FILE_EDIT_ALL';
private static $default_sort = "\"Name\"";
/**
* @config
* @var string
*/
private static $singular_name = "File";
private static $plural_name = "Files";
/**
* Control whether images in the admin will be resampled
*
* Can be turned off e.g. when using an external resampling service
* or a backend that may not support resampling.
*
* @config
* @var bool
*/
private static $resample_images = true;
/**
* Anyone with CMS access can view draft files
*
* @config
* @var array
*/
private static $non_live_permissions = ['CMS_ACCESS', 'VIEW_DRAFT_CONTENT'];
private static $db = [
"Name" => "Varchar(255)",
"Title" => "Varchar(255)",
"File" => "DBFile",
// Only applies to files, doesn't inherit for folder
'ShowInSearch' => 'Boolean(1)',
];
private static $has_one = [
"Parent" => File::class,
"Owner" => Member::class,
];
private static $has_many = [
'BackLinks' => FileLink::class . '.Linked',
];
private static $owned_by = [
'BackLinks',
];
private static $indexes = [
'FileHash' => true
];
private static $defaults = [
"ShowInSearch" => 1,
];
private static $extensions = [
Hierarchy::class,
InheritedPermissionsExtension::class,
];
private static $casting = [
'TreeTitle' => 'HTMLFragment',
'getTreeTitle' => 'HTMLFragment',
'Tag' => 'HTMLFragment',
'getTag' => 'HTMLFragment',
'AttributesHTML' => 'HTMLFragment',
'getAttributesHTML' => 'HTMLFragment',
];
private static $table_name = 'File';
/**
* @config
* @var array List of allowed file extensions, enforced through {@link validate()}.
*
* You can remove extensions from this list with YAML configuration, for example:
*
* ```
* SilverStripe\Assets\File:
* allowed_extensions:
* ppt: false
* ```
*
* Note: if you modify this, you should also change a configuration file in the assets directory.
* Otherwise, the files will be able to be uploaded but they won't be able to be served by the
* webserver.
*
* - If you are running Apache you will need to change assets/.htaccess
* - If you are running IIS you will need to change assets/web.config
*
* Instructions for the change you need to make are included in a comment in the config file.
*/
private static $allowed_extensions = [
'', 'ace', 'arc', 'arj', 'asf', 'au', 'avi', 'bmp', 'bz2', 'cab', 'cda', 'csv', 'dmg', 'doc',
'docx', 'dotx', 'flv', 'gif', 'gz', 'hqx', 'ico', 'jpeg', 'jpg', 'kml',
'm4a', 'm4v', 'mid', 'midi', 'mkv', 'mov', 'mp3', 'mp4', 'mpa', 'mpeg', 'mpg', 'ogg', 'ogv', 'pages',
'pcx', 'pdf', 'png', 'pps', 'ppt', 'pptx', 'potx', 'ra', 'ram', 'rm', 'rtf', 'sit', 'sitx',
'tar', 'tgz', 'tif', 'tiff', 'txt', 'wav', 'webm', 'webp', 'wma', 'wmv', 'xls', 'xlsx', 'xltx', 'zip',
'zipx',
];
/**
* @config
* @var array Category identifiers mapped to commonly used extensions.
*/
private static $app_categories = [
'archive' => [
'ace', 'arc', 'arj', 'bz', 'bz2', 'cab', 'dmg', 'gz', 'hqx', 'jar', 'rar', 'sit', 'sitx', 'tar', 'tgz',
'zip', 'zipx',
],
'audio' => [
'aif', 'aifc', 'aiff', 'apl', 'au', 'avr', 'cda', 'm4a', 'mid', 'midi', 'mp3', 'ogg', 'ra',
'ram', 'rm', 'snd', 'wav', 'wma',
],
'document' => [
'css', 'csv', 'doc', 'docx', 'dotm', 'dotx', 'htm', 'html', 'js', 'kml', 'pages', 'pdf',
'potm', 'potx', 'pps', 'ppt', 'pptx', 'rtf', 'txt', 'xhtml', 'xls', 'xlsx', 'xltm', 'xltx', 'xml',
],
'image' => [
'alpha', 'als', 'bmp', 'cel', 'gif', 'ico', 'icon', 'jpeg', 'jpg', 'pcx', 'png', 'ps', 'psd', 'tif', 'tiff', 'webp'
],
'image/supported' => [
'gif', 'jpeg', 'jpg', 'png', 'bmp', 'ico', 'webp'
],
'flash' => [
'fla', 'swf'
],
'video' => [
'asf', 'avi', 'flv', 'ifo', 'm1v', 'm2v', 'm4v', 'mkv', 'mov', 'mp2', 'mp4', 'mpa', 'mpe', 'mpeg',
'mpg', 'ogv', 'qt', 'vob', 'webm', 'wmv',
],
];
/**
* Map of file extensions to class type
*
* @config
* @var
*/
private static $class_for_file_extension = [
'*' => File::class,
'jpg' => Image::class,
'jpeg' => Image::class,
'png' => Image::class,
'gif' => Image::class,
'bmp' => Image::class,
'ico' => Image::class,
'webp' => Image::class,
];
/**
* @config
* @var bool If this is true, then restrictions set in {@link $allowed_max_file_size} and
* {@link $allowed_extensions} will be applied to users with admin privileges as
* well.
*/
private static $apply_restrictions_to_admin = true;
/**
* @config
* @var boolean
*/
private static $update_filesystem = true;
/**
* A list of file extensions and a description of what type of file they represent
*
* @config
* @var string[]
*/
private static $file_types = [];
/**
* @internal
* @see hasRestrictedPermissions
*/
private static $has_restricted_permissions_cache = [];
public static function get_shortcodes()
{
return 'file_link';
}
/**
* A file only exists if the file_exists() and is in the DB as a record
*
* Use $file->isInDB() to only check for a DB record
* Use $file->File->exists() to only check if the asset exists
*
* @return bool
*/
public function exists()
{
return parent::exists() && $this->File->exists();
}
/**
* Find a File object by the given filename.
*
* @param string $filename Filename to search for, including any custom parent directories.
* @return File|null
*/
public static function find($filename)
{
// Split to folders and the actual filename, and traverse the structure.
$parts = array_filter(preg_split("#[/\\\\]+#", $filename ?? '') ?? []);
$parentID = 0;
/** @var File $item */
$item = null;
foreach ($parts as $part) {
$item = File::get()->filter([
'Name' => $part,
'ParentID' => $parentID
])->first();
if (!$item) {
break;
}
$parentID = $item->ID;
}
return $item;
}
/**
* Just an alias function to keep a consistent API with SiteTree
*
* @return string The link to the file
*/
public function Link()
{
return $this->getURL();
}
/**
* @deprecated 1.0.0 Use getURL() instead
*/
public function RelativeLink()
{
Deprecation::notice('1.0.0', 'Use getURL() instead');
return Director::makeRelative($this->getURL());
}
/**
* Just an alias function to keep a consistent API with SiteTree
*
* @return string The absolute link to the file
*/
public function AbsoluteLink()
{
return $this->getAbsoluteURL();
}
/**
* @return string
*/
public function getTreeTitle()
{
return Convert::raw2xml($this->Title);
}
/**
* @param Member $member
* @return bool
*/
public function canView($member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
$result = $this->extendedCan('canView', $member);
if ($result !== null) {
return $result;
}
if (Permission::checkMember($member, 'ADMIN')) {
return true;
}
// Check inherited permissions from the parent folder
if ($this->CanViewType === InheritedPermissions::INHERIT && $this->ParentID) {
return $this->getPermissionChecker()->canView($this->ParentID, $member);
}
// Any logged in user can view this file
if ($this->CanViewType === InheritedPermissions::LOGGED_IN_USERS && !$member) {
return false;
}
// Specific user groups can view this file
if ($this->CanViewType === InheritedPermissions::ONLY_THESE_USERS) {
if (!$member) {
return false;
}
return $member->inGroups($this->ViewerGroups());
}
// Check default root level permissions
return $this->getPermissionChecker()->canView($this->ID, $member);
}
/**
* Check if this file can be modified
*
* @param Member $member
* @return boolean
*/
public function canEdit($member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
$result = $this->extendedCan('canEdit', $member);
if ($result !== null) {
return $result;
}
if (Permission::checkMember($member, self::EDIT_ALL)) {
return true;
}
// Delegate to parent if inheriting permissions
if ($this->CanEditType === 'Inherit' && $this->ParentID) {
return $this->getPermissionChecker()->canEdit($this->ParentID, $member);
}
// Check inherited permissions
return $this->getPermissionChecker()->canEdit($this->ID, $member);
}
/**
* Check if a file can be created
*
* @param Member $member
* @param array $context
* @return boolean
*/
public function canCreate($member = null, $context = [])
{
if (!$member) {
$member = Security::getCurrentUser();
}
$result = $this->extendedCan('canCreate', $member, $context);
if ($result !== null) {
return $result;
}
if (Permission::checkMember($member, self::EDIT_ALL)) {
return true;
}
// If Parent is provided, file can be created if parent can be edited
/** @var Folder $parent */
$parent = isset($context['Parent']) ? $context['Parent'] : null;
if ($parent) {
return $parent->canEdit($member);
}
return false;
}
/**
* Check if this file can be deleted
*
* @param Member $member
* @return boolean
*/
public function canDelete($member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
$result = $this->extendedCan('canDelete', $member);
if ($result !== null) {
return $result;
}
if (!$member) {
return false;
}
// Default permission check
if (Permission::checkMember($member, self::EDIT_ALL)) {
return true;
}
// Check inherited permissions
return static::getPermissionChecker()
->canDelete($this->ID, $member);
}
/**
* Check if the File has a CanViewType set or inherited at "LoggedInUsers or above"
*
* This is a bit different from a canView() check in that it doesn't check anything against a member.
* Instead it is a member-less permission check
*
* @return bool
*/
public function hasRestrictedAccess(): bool
{
return $this->hasRestrictedPermissions($this);
}
/**
* Recursively determine whether a File has, or inherits, restricted permissions.
*
* @param File $file
* @return bool
*/
private function hasRestrictedPermissions(File $file): bool
{
$id = $file->ID;
$parentID = $file->ParentID;
$canViewType = $file->CanViewType;
if (in_array($canViewType, [InheritedPermissions::LOGGED_IN_USERS, InheritedPermissions::ONLY_THESE_USERS])) {
self::$has_restricted_permissions_cache[$id] = true;
return true;
}
if ($canViewType == InheritedPermissions::INHERIT && $parentID != 0) {
if (isset(self::$has_restricted_permissions_cache[$parentID])) {
return self::$has_restricted_permissions_cache[$parentID];
}
$parent = $file->Parent();
if ($parent->exists()) {
$value = $this->hasRestrictedPermissions($parent);
self::$has_restricted_permissions_cache[$parentID] = $value;
return $value;
}
}
self::$has_restricted_permissions_cache[$id] = false;
return false;
}
/**
* If the file was uploaded via a form and tracked in the database
*
* @return bool
*/
public function isTrackedFormUpload(): bool
{
$value = false;
$this->extend('updateTrackedFormUpload', $value);
return (bool) $value;
}
/**
* List of basic content editable file fields.
*
* Note: These fields no longer affect the edit form in asset-admin. To add fields to the file
* edit form in asset-admin, you will need to add an extension to FileFormFactory and use the
* updateFormFields() hook.
*
* @return FieldList
*/
public function getCMSFields()
{
$image = HTML::createTag('img', [
'src' => $this->PreviewLink(),
'alt' => $this->getTitle(),
'class' => 'd-block mx-auto',
]);
$fields = FieldList::create(
HTMLReadonlyField::create('IconFull', _t(__CLASS__.'.PREVIEW', 'Preview'), $image),
TextField::create("Title", $this->fieldLabel('Title')),
TextField::create("Name", $this->fieldLabel('Filename')),
TextField::create("Filename", _t(__CLASS__.'.PATH', 'Path'))
->setReadonly(true)
);
$this->extend('updateCMSFields', $fields);
return $fields;
}
/**
* Get title for current file status
*
* @return string
*/
public function getStatusTitle()
{
$statusTitle = '';
if ($this->isOnDraftOnly()) {
$statusTitle = _t(__CLASS__.'.DRAFT', 'Draft');
} elseif ($this->isModifiedOnDraft()) {
$statusTitle = _t(__CLASS__.'.MODIFIED', 'Modified');
}
return $statusTitle;
}
/**
* Returns a category based on the file extension.
* This can be useful when grouping files by type,
* showing icons on filelinks, etc.
* Possible group values are: "audio", "mov", "zip", "image".
*
* @param string $ext Extension to check
* @return string
*/
public static function get_app_category($ext)
{
$ext = strtolower($ext ?? '');
foreach (static::config()->get('app_categories') as $category => $exts) {
if (in_array($ext, $exts ?? [])) {
return $category;
}
}
return false;
}
/**
* For a category or list of categories, get the list of file extensions
*
* @param array|string $categories List of categories, or single category
* @return array
*/
public static function get_category_extensions($categories)
{
if (empty($categories)) {
return [];
}
// Fix arguments into a single array
if (!is_array($categories)) {
$categories = [$categories];
} elseif (count($categories ?? []) === 1 && is_array(reset($categories))) {
$categories = reset($categories);
}
// Check configured categories
$appCategories = static::config()->get('app_categories');
// Merge all categories into list of extensions
$extensions = [];
foreach (array_filter($categories ?? []) as $category) {
if (isset($appCategories[$category])) {
$extensions = array_merge($extensions, $appCategories[$category]);
} else {
throw new InvalidArgumentException("Unknown file category: $category");
}
}
$extensions = array_unique($extensions ?? []);
sort($extensions);
return $extensions;
}
/**
* Returns a category based on the file extension.
*
* @return string
*/
public function appCategory()
{
return self::get_app_category($this->getExtension());
}
/**
* Should be called after the file was uploaded
*/
public function onAfterUpload()
{
$this->extend('onAfterUpload');
}
/**
* Make sure the file has a name
*/
protected function onBeforeWrite()
{
// Set default owner
if (!$this->isInDB() && !$this->OwnerID && Security::getCurrentUser()) {
$this->OwnerID = Security::getCurrentUser()->ID;
}
$currentname = $name = $this->getField('Name');
$title = $this->getField('Title');
$changed = $this->isChanged('Name') || $this->isChanged('ParentID');
// Name can't be blank, default to Title or singular name
if (!$name) {
$name = $title ?: $this->i18n_singular_name();
}
$name = $this->filterFilename($name);
if ($name !== $currentname) {
$changed = true;
}
// Check for duplicates when the name has changed (or is set for the first time)
if ($changed) {
$nameGenerator = $this->getNameGenerator($name);
// Defaults to returning the original filename on first iteration
foreach ($nameGenerator as $newName) {
// This logic is also used in the Folder subclass, but we're querying
// for duplicates on the File base class here (including the Folder subclass).
// TODO Add read lock to avoid other processes creating files with the same name
// before this process has a chance to persist in the database.
$existingFile = File::get()->filter([
'Name' => $newName,
'ParentID' => (int) $this->ParentID
])->exclude([
'ID' => $this->ID
])->first();
if (!$existingFile) {
$name = $newName;
break;
}
}
}
// Update actual field value
$this->setField('Name', $name);
// Update title
if (!$title) {
// Generate a readable title, dashes and underscores replaced by whitespace,
// and any file extensions removed.
$this->setField(
'Title',
str_replace(['-','_'], ' ', preg_replace('/\.[^.]+$/', '', $name ?? '') ?? '')
);
}
// Propagate changes to the AssetStore and update the DBFile field
$this->updateFilesystem();
parent::onBeforeWrite();
}
/**
* Update link tracking on delete
*/
protected function onAfterDelete()
{
parent::onAfterDelete();
$this->updateDependantObjects();
}
public function onAfterRevertToLive()
{
// Force query of draft object and update (as source record is bound to live stage)
/** @var File $draftRecord */
if (class_exists(Versioned::class) &&
$draftRecord = Versioned::get_by_stage(self::class, Versioned::DRAFT)->byID($this->ID)
) {
$draftRecord->updateDependantObjects();
}
}
/**
* Update objects linking to this file
*/
protected function updateDependantObjects()
{
// Skip live stage
if (class_exists(Versioned::class) && Versioned::get_stage() === Versioned::LIVE) {
return;
}
// Need to flush cache to avoid outdated versionnumber references
$this->flushCache();
// Trigger update of all parent owners on change
/** @var DataObject|FileLinkTracking $object */
foreach ($this->BackLinkTracking() as $object) {
// Update sync link tracking
$object->syncLinkTracking();
if ($object->isChanged()) {
$object->write();
}
}
}
/**
* This will check if the parent record and/or name do not match the name on the underlying
* DBFile record, and if so, copy this file to the new location, and update the record to
* point to this new file.
*
* This method will update the File {@see DBFile} field value on success, so it must be called
* before writing to the database
*
* @return bool True if changed
*/
public function updateFilesystem()
{
if (!$this->config()->get('update_filesystem')) {
return false;
}
// Check the file exists
if (!$this->File->exists()) {
return false;
}
// Avoid moving files on live; Rely on this being done on stage prior to publish.
if (class_exists(Versioned::class) && Versioned::get_stage() !== Versioned::DRAFT) {
return false;
}
// Check path updated record will point to
// If no changes necessary, skip
$pathBefore = $this->File->getFilename();
$pathAfter = $this->generateFilename();
if ($pathAfter === $pathBefore) {
return false;
}
// Copy record to new location and point DB fields to updated Filename,
// respecting back end conflict resolution
$expectedPath = $pathAfter;
$pathAfter = $this->File->copyFile($pathAfter);
if (!$pathAfter) {
return false;
}
if ($expectedPath !== $pathAfter) {
$this->setFilename($pathAfter);
}
$this->File->Filename = $pathAfter;
return true;
}
/**
* Collate selected descendants of this page.
* $condition will be evaluated on each descendant, and if it is succeeds, that item will be added
* to the $collator array.
*
* @param string $condition The PHP condition to be evaluated. The page will be called $item
* @param array $collator An array, passed by reference, to collect all of the matching descendants.
* @return true|null
*/
public function collateDescendants($condition, &$collator)
{
if ($children = $this->Children()) {
foreach ($children as $item) {
/** @var File $item */
if (!$condition || eval("return $condition;")) {
$collator[] = $item;
}
$item->collateDescendants($condition, $collator);
}
return true;
}
return null;
}
/**
* Get an asset renamer for the given filename.
*
* @param string $filename Path name
* @return AssetNameGenerator
*/
protected function getNameGenerator($filename)
{
return Injector::inst()->createWithArgs(AssetNameGenerator::class, [$filename]);
}
/**
* Gets the URL of this file
*
* @return string
*/
public function getAbsoluteURL()
{
$url = $this->getURL();
if ($url) {
return Director::absoluteURL($url);
}
return null;
}
/**
* Gets the URL of this file
*
* @uses Director::baseURL()
* @param bool $grant Ensures that the url for any protected assets is granted for the current user.
* @return string
*/
public function getURL($grant = true)
{
if ($this->File->exists()) {
return $this->File->getURL($grant);
}
return null;
}
/**
* Get URL, but without resampling.
*
* @param bool $grant Ensures that the url for any protected assets is granted for the current user.
* @return string
*/
public function getSourceURL($grant = true)
{
if ($this->File->exists()) {
return $this->File->getSourceURL($grant);
}
return null;
}
/**
* Get expected value of Filename tuple value. Will be used to trigger
* a file move on draft stage.
*
* @return string
*/
public function generateFilename()
{
// Check if this file is nested within a folder
$parent = $this->Parent();
if ($parent && $parent->exists()) {
return $this->join_paths($parent->getFilename(), $this->Name);
}
return $this->Name;
}
/**
* Rename this file.
* Note: This method will immediately save to the database to maintain
* filesystem consistency with the database.
*
* @param string $newName
* @return string
*/
public function renameFile($newName)
{
$this->setFilename($newName);
$this->write();
return $this->getFilename();
}
public function copyFile($newName)
{
$newName = $this->filterFilename($newName);
// Copy doesn't modify this record, so can be performed immediately
return $this->File->copyFile($newName);
}
/**
* Update the ParentID and Name for the given filename.
*
* On save, the underlying DBFile record will move the underlying file to this location.
* Thus it will not update the underlying Filename value until this is done.
*
* @param string $filename
* @return $this
*/
public function setFilename($filename)
{
$filename = $this->filterFilename($filename);
// Check existing folder path
$folder = '';
$parent = $this->Parent();
if ($parent && $parent->exists()) {
$folder = $parent->getFilename();
}
// Detect change in foldername
$newFolder = ltrim(dirname(trim($filename ?? '', '/')), '.');
if ($folder !== $newFolder) {
if (!$newFolder) {
$this->ParentID = 0;
} else {
$parent = Folder::find_or_make($newFolder);
$this->ParentID = $parent->ID;
}
}
// Update base name
$this->Name = basename($filename ?? '');
return $this;
}
/**
* Returns the file extension
*
* @return string
*/
public function getExtension()
{
return self::get_file_extension($this->Name);
}
/**