-
Notifications
You must be signed in to change notification settings - Fork 68
/
DBFile.php
635 lines (572 loc) · 15.4 KB
/
DBFile.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
<?php
namespace SilverStripe\Assets\Storage;
use SilverStripe\Assets\File;
use SilverStripe\Assets\ImageManipulation;
use SilverStripe\Assets\Thumbnail;
use SilverStripe\Control\Director;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\FieldType\DBComposite;
use SilverStripe\ORM\ValidationException;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\Permission;
use SilverStripe\View\ViewableData;
/**
* Represents a file reference stored in a database
*
* @property string $Hash SHA of the file
* @property string $Filename Name of the file, including directory
* @property string $Variant Variant of the file
*/
class DBFile extends DBComposite implements AssetContainer, Thumbnail
{
use ImageManipulation;
/**
* List of allowed file categories.
*
* {@see File::$app_categories}
*
* @var array
*/
protected $allowedCategories = [];
/**
* List of image mime types supported by the image manipulations API
*
* {@see File::app_categories} for matching extensions.
*
* @config
* @var array
*/
private static $supported_images = [
'image/jpg',
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/x-png',
'image/tiff',
'image/tif',
'image/x-tiff',
'image/x-tif',
'image/bmp',
'image/ms-bmp',
'image/x-bitmap',
'image/x-bmp',
'image/x-ms-bmp',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/x-xbitmap',
'image/x-ico',
'image/x-icon',
'image/vnd.microsoft.icon',
'image/vnd.adobe.photoshop',
'image/webp',
];
/**
* Create a new image manipulation
*
* @param string $name
* @param array|string $allowed List of allowed file categories (not extensions), as per File::$app_categories
*/
public function __construct($name = null, $allowed = [])
{
parent::__construct($name);
$this->setAllowedCategories($allowed);
}
/**
* Determine if a valid non-empty image exists behind this asset, which is a format
* compatible with image manipulations
*
* @return boolean
*/
public function getIsImage()
{
// Check file type
$mime = $this->getMimeType();
return $mime && in_array($mime, $this->config()->supported_images ?? []);
}
/**
* @return AssetStore
*/
protected function getStore()
{
return Injector::inst()->get(AssetStore::class);
}
private static $composite_db = [
"Hash" => "Varchar(255)", // SHA of the base content
"Filename" => "Varchar(255)", // Path identifier of the base content
"Variant" => "Varchar(255)", // Identifier of the variant to the base, if given
];
private static $casting = [
'URL' => 'Varchar',
'AbsoluteURL' => 'Varchar',
'Basename' => 'Varchar',
'Title' => 'Varchar',
'MimeType' => 'Varchar',
'String' => 'Text',
'Tag' => 'HTMLFragment',
'getTag' => 'HTMLFragment',
'Size' => 'Varchar',
'AttributesHTML' => 'HTMLFragment',
'getAttributesHTML' => 'HTMLFragment',
];
public function scaffoldFormField($title = null, $params = null)
{
return null;
}
/**
* Return a html5 tag of the appropriate for this file (normally img or a)
*
* @return string
*/
public function XML()
{
return $this->getTag() ?: '';
}
/**
* Return a html5 tag of the appropriate for this file (normally img or a)
*
* @return string
*/
public function getTag()
{
$template = $this->getFrontendTemplate();
if (empty($template)) {
return '';
}
return (string)$this->renderWith($template);
}
/**
* Determine the template to render as on the frontend
*
* @return string Name of template
*/
public function getFrontendTemplate()
{
// Check that path is available
$url = $this->getURL();
if (empty($url)) {
return null;
}
// Image template for supported images
if ($this->getIsImage()) {
return 'DBFile_image';
}
// Default download
return 'DBFile_download';
}
/**
* Get trailing part of filename
*
* @return string
*/
public function getBasename()
{
if (!$this->exists()) {
return null;
}
return basename($this->getSourceURL() ?? '');
}
/**
* Get file extension
*
* @return string
*/
public function getExtension()
{
if (!$this->exists()) {
return null;
}
return pathinfo($this->Filename ?? '', PATHINFO_EXTENSION);
}
/**
* Alt title for this
*
* @return string
*/
public function getTitle()
{
// If customised, use the customised title
if ($this->failover && ($title = $this->failover->Title)) {
return $title;
}
// fallback to using base name
return $this->getBasename();
}
public function setFromLocalFile($path, $filename = null, $hash = null, $variant = null, $config = [])
{
$this->assertFilenameValid($filename ?: $path);
$result = $this
->getStore()
->setFromLocalFile($path, $filename, $hash, $variant, $config);
// Update from result
if ($result) {
$this->setValue($result);
}
return $result;
}
public function setFromStream($stream, $filename, $hash = null, $variant = null, $config = [])
{
$this->assertFilenameValid($filename);
$result = $this
->getStore()
->setFromStream($stream, $filename, $hash, $variant, $config);
// Update from result
if ($result) {
$this->setValue($result);
}
return $result;
}
public function setFromString($data, $filename, $hash = null, $variant = null, $config = [])
{
$this->assertFilenameValid($filename);
$result = $this
->getStore()
->setFromString($data, $filename, $hash, $variant, $config);
// Update from result
if ($result) {
$this->setValue($result);
}
return $result;
}
public function getStream()
{
if (!$this->exists()) {
return null;
}
return $this
->getStore()
->getAsStream($this->Filename, $this->Hash, $this->Variant);
}
public function getString()
{
if (!$this->exists()) {
return null;
}
return $this
->getStore()
->getAsString($this->Filename, $this->Hash, $this->Variant);
}
public function getURL($grant = true)
{
if (!$this->exists()) {
return null;
}
$url = $this->getSourceURL($grant);
$this->updateURL($url);
$this->extend('updateURL', $url);
return $url;
}
/**
* Return URL for this image. Alias for getURL()
*
* @return string
*/
public function Link()
{
return $this->getURL();
}
/**
* Return absolute URL for this image. Alias for getAbsoluteURL()
*
* @return string
*/
public function AbsoluteLink()
{
return $this->getAbsoluteURL();
}
/**
* Get URL, but without resampling.
* Note that this will return the url even if the file does not exist.
*
* @param bool $grant Ensures that the url for any protected assets is granted for the current user.
* @return string
*/
public function getSourceURL($grant = true)
{
return $this
->getStore()
->getAsURL($this->Filename, $this->Hash, $this->Variant, $grant);
}
/**
* Get the absolute URL to this resource
*
* @return string
*/
public function getAbsoluteURL()
{
if (!$this->exists()) {
return null;
}
return Director::absoluteURL((string) $this->getURL());
}
public function getMetaData()
{
if (!$this->exists()) {
return null;
}
return $this
->getStore()
->getMetadata($this->Filename, $this->Hash, $this->Variant);
}
public function getMimeType()
{
if (!$this->exists()) {
return null;
}
return $this
->getStore()
->getMimeType($this->Filename, $this->Hash, $this->Variant);
}
public function getValue()
{
if (!$this->exists()) {
return null;
}
return [
'Filename' => $this->Filename,
'Hash' => $this->Hash,
'Variant' => $this->Variant
];
}
public function getVisibility()
{
if (empty($this->Filename)) {
return null;
}
return $this
->getStore()
->getVisibility($this->Filename, $this->Hash);
}
public function exists()
{
if (empty($this->Filename)) {
return false;
}
return $this
->getStore()
->exists($this->Filename, $this->Hash, $this->Variant);
}
public function getFilename()
{
return $this->getField('Filename');
}
public function getHash()
{
return $this->getField('Hash');
}
public function getVariant()
{
return $this->getField('Variant');
}
/**
* Return file size in bytes.
*
* @return int
*/
public function getAbsoluteSize()
{
$metadata = $this->getMetaData();
if (isset($metadata['size'])) {
return $metadata['size'];
}
return 0;
}
/**
* Customise this object with an "original" record for getting other customised fields
*
* @param AssetContainer $original
* @return $this
*/
public function setOriginal($original)
{
if ($original instanceof ViewableData) {
$this->setFailover($original);
}
return $this;
}
/**
* Get list of allowed file categories
*
* @return array
*/
public function getAllowedCategories()
{
return $this->allowedCategories;
}
/**
* Assign allowed categories
*
* @param array|string $categories
* @return $this
*/
public function setAllowedCategories($categories)
{
if (is_string($categories)) {
$categories = preg_split('/\s*,\s*/', $categories ?? '');
}
$this->allowedCategories = (array)$categories;
return $this;
}
/**
* Gets the list of extensions (if limited) for this field. Empty list
* means there is no restriction on allowed types.
*
* @return array
*/
protected function getAllowedExtensions()
{
$categories = $this->getAllowedCategories();
return File::get_category_extensions($categories);
}
/**
* Validate that this DBFile accepts this filename as valid
*
* @param string $filename
* @throws ValidationException
* @return bool
*/
protected function isValidFilename($filename)
{
$extension = strtolower(File::get_file_extension($filename) ?? '');
// Validate true if within the list of allowed extensions
$allowed = $this->getAllowedExtensions();
if ($allowed) {
return in_array($extension, $allowed ?? []);
}
// If no extensions are configured, fallback to global list
$globalList = File::getAllowedExtensions();
if (in_array($extension, $globalList ?? [])) {
return true;
}
// Only admins can bypass global rules
return !File::config()->apply_restrictions_to_admin && Permission::check('ADMIN');
}
/**
* Check filename, and raise a ValidationException if invalid
*
* @param string $filename
* @throws ValidationException
*/
protected function assertFilenameValid($filename)
{
$result = new ValidationResult();
$this->validate($result, $filename);
if (!$result->isValid()) {
throw new ValidationException($result);
}
}
/**
* Hook to validate this record against a validation result
*
* @param ValidationResult $result
* @param string $filename Optional filename to validate. If omitted, the current value is validated.
* @return bool Valid flag
*/
public function validate(ValidationResult $result, $filename = null)
{
if (empty($filename)) {
$filename = $this->getFilename();
}
if (empty($filename) || $this->isValidFilename($filename)) {
return true;
}
$message = _t(
'SilverStripe\\Assets\\File.INVALIDEXTENSION_SHORT_EXT',
'Extension \'{extension}\' is not allowed',
[ 'extension' => strtolower(File::get_file_extension($filename) ?? '') ]
);
$result->addError($message);
return false;
}
public function setField($field, $value, $markChanged = true)
{
// Catch filename validation on direct assignment
if ($field === 'Filename' && $value) {
$this->assertFilenameValid($value);
}
return parent::setField($field, $value, $markChanged);
}
/**
* Returns the size of the file type in an appropriate format.
*
* @return string|false String value, or false if doesn't exist
*/
public function getSize()
{
$size = $this->getAbsoluteSize();
if ($size) {
return File::format_size($size);
}
return false;
}
public function deleteFile()
{
if (!$this->Filename) {
return false;
}
return $this
->getStore()
->delete($this->Filename, $this->Hash);
}
public function publishFile()
{
if ($this->Filename) {
$this
->getStore()
->publish($this->Filename, $this->Hash);
}
}
public function protectFile()
{
if ($this->Filename) {
$this
->getStore()
->protect($this->Filename, $this->Hash);
}
}
public function grantFile()
{
if ($this->Filename) {
$this
->getStore()
->grant($this->Filename, $this->Hash);
}
}
public function revokeFile()
{
if ($this->Filename) {
$this
->getStore()
->revoke($this->Filename, $this->Hash);
}
}
public function canViewFile()
{
return $this->Filename
&& $this
->getStore()
->canView($this->Filename, $this->Hash);
}
public function renameFile($newName)
{
if (!$this->Filename) {
return null;
}
$newName = $this
->getStore()
->rename($this->Filename, $this->Hash, $newName);
if ($newName) {
$this->Filename = $newName;
}
return $newName;
}
public function copyFile($newName)
{
if (!$this->Filename) {
return null;
}
return $this
->getStore()
->copy($this->Filename, $this->Hash, $newName);
}
}