Passed
Push — master ( a489aa...e6a9a9 )
by Thomas
02:21
created

FilePondField::getCustomConfigValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
namespace LeKoala\FilePond;
4
5
use Exception;
6
use LogicException;
7
use RuntimeException;
8
use SilverStripe\Assets\File;
9
use SilverStripe\ORM\SS_List;
10
use SilverStripe\Assets\Image;
11
use SilverStripe\Core\Convert;
12
use SilverStripe\ORM\ArrayList;
13
use SilverStripe\ORM\DataObject;
14
use SilverStripe\Control\Director;
15
use SilverStripe\Security\Security;
16
use SilverStripe\View\Requirements;
17
use SilverStripe\Control\HTTPRequest;
18
use SilverStripe\Versioned\Versioned;
19
use SilverStripe\Control\HTTPResponse;
20
use SilverStripe\ORM\DataObjectInterface;
21
use SilverStripe\ORM\ValidationException;
22
use SilverStripe\Core\Manifest\ModuleResourceLoader;
23
24
/**
25
 * A FilePond field
26
 */
27
class FilePondField extends AbstractUploadField
28
{
29
    const BASE_CDN = "https://cdn.jsdelivr.net/gh/pqina";
30
    const IMAGE_MODE_MIN = "min";
31
    const IMAGE_MODE_MAX = "max";
32
    const IMAGE_MODE_CROP = "crop";
33
    const IMAGE_MODE_RESIZE = "resize";
34
    const IMAGE_MODE_CROP_RESIZE = "crop_resize";
35
36
    /**
37
     * @config
38
     * @var array
39
     */
40
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
41
        'upload',
42
        'chunk',
43
        'revert',
44
    ];
45
46
    /**
47
     * @config
48
     * @var boolean
49
     */
50
    private static $enable_requirements = true;
51
52
    /**
53
     * @config
54
     * @var boolean
55
     */
56
    private static $enable_validation = true;
57
58
    /**
59
     * @config
60
     * @var boolean
61
     */
62
    private static $enable_poster = false;
63
64
    /**
65
     * @config
66
     * @var boolean
67
     */
68
    private static $enable_image = false;
69
70
    /**
71
     * @config
72
     * @var boolean
73
     */
74
    private static $enable_polyfill = true;
75
76
    /**
77
     * @config
78
     * @var boolean
79
     */
80
    private static $enable_ajax_init = true;
81
82
    /**
83
     * @config
84
     * @var boolean
85
     */
86
    private static $chunk_by_default = false;
87
88
    /**
89
     * @config
90
     * @var boolean
91
     */
92
    private static $enable_default_description = true;
0 ignored issues
show
introduced by
The private property $enable_default_description is not used, and could be removed.
Loading history...
93
94
    /**
95
     * @config
96
     * @var boolean
97
     */
98
    private static $auto_clear_temp_folder = true;
99
100
    /**
101
     * @config
102
     * @var int
103
     */
104
    private static $auto_clear_threshold = true;
105
106
    /**
107
     * @config
108
     * @var boolean
109
     */
110
    private static $use_cdn = true;
111
112
    /**
113
     * @config
114
     * @var boolean
115
     */
116
    private static $use_bundle = false;
117
118
    /**
119
     * @config
120
     * @var boolean
121
     */
122
    private static $enable_auto_thumbnails = false;
0 ignored issues
show
introduced by
The private property $enable_auto_thumbnails is not used, and could be removed.
Loading history...
123
124
    /**
125
     * @config
126
     * @var int
127
     */
128
    private static $poster_width = 352;
129
130
    /**
131
     * @config
132
     * @var int
133
     */
134
    private static $poster_height = 264;
135
136
    /**
137
     * @var array
138
     */
139
    protected $filePondConfig = [];
140
141
    /**
142
     * @var array
143
     */
144
    protected $customServerConfig = null;
145
146
    /**
147
     * @var int
148
     */
149
    protected $posterHeight = null;
150
151
    /**
152
     * @var int
153
     */
154
    protected $posterWidth = null;
155
156
    /**
157
     * Create a new file field.
158
     *
159
     * @param string $name The internal field name, passed to forms.
160
     * @param string $title The field label.
161
     * @param SS_List $items Items assigned to this field
162
     */
163
    public function __construct($name, $title = null, SS_List $items = null)
164
    {
165
        parent::__construct($name, $title, $items);
166
167
        if (self::config()->chunk_by_default) {
168
            $this->setChunkUploads(true);
169
        }
170
    }
171
172
    /**
173
     * Set a custom config value for this field
174
     *
175
     * @link https://pqina.nl/filepond/docs/patterns/api/filepond-instance/#properties
176
     * @param string $k
177
     * @param string|bool|array $v
178
     * @return $this
179
     */
180
    public function addFilePondConfig($k, $v)
181
    {
182
        $this->filePondConfig[$k] = $v;
183
        return $this;
184
    }
185
186
    /**
187
     * @param string $k
188
     * @param mixed $default
189
     * @return mixed
190
     */
191
    public function getCustomConfigValue($k, $default = null)
192
    {
193
        if (isset($this->filePondConfig[$k])) {
194
            return $this->filePondConfig[$k];
195
        }
196
        return $default;
197
    }
198
199
    /**
200
     * Custom configuration applied to this field
201
     *
202
     * @return array
203
     */
204
    public function getCustomFilePondConfig()
205
    {
206
        return $this->filePondConfig;
207
    }
208
209
    /**
210
     * Get the value of chunkUploads
211
     * @return bool
212
     */
213
    public function getChunkUploads()
214
    {
215
        if (!isset($this->filePondConfig['chunkUploads'])) {
216
            return false;
217
        }
218
        return $this->filePondConfig['chunkUploads'];
219
    }
220
221
    /**
222
     * Get the value of customServerConfig
223
     * @return array
224
     */
225
    public function getCustomServerConfig()
226
    {
227
        return $this->customServerConfig;
228
    }
229
230
    /**
231
     * Set the value of customServerConfig
232
     *
233
     * @param array $customServerConfig
234
     * @return $this
235
     */
236
    public function setCustomServerConfig(array $customServerConfig)
237
    {
238
        $this->customServerConfig = $customServerConfig;
239
        return $this;
240
    }
241
242
    /**
243
     * Set the value of chunkUploads
244
     *
245
     * Note: please set max file upload first if you want
246
     * to see the size limit in the description
247
     *
248
     * @param bool $chunkUploads
249
     * @return $this
250
     */
251
    public function setChunkUploads($chunkUploads)
252
    {
253
        $this->addFilePondConfig('chunkUploads', true);
254
        $this->addFilePondConfig('chunkForce', true);
255
        $this->addFilePondConfig('chunkSize', $this->computeMaxChunkSize());
256
        if ($this->isDefaultMaxFileSize()) {
257
            $this->showDescriptionSize = false;
258
        }
259
        return $this;
260
    }
261
262
    /**
263
     * @param array $sizes
264
     * @return array
265
     */
266
    public function getImageSizeConfigFromArray($sizes)
267
    {
268
        $mode = null;
269
        if (isset($sizes[2])) {
270
            $mode = $sizes[2];
271
        }
272
        return $this->getImageSizeConfig($sizes[0], $sizes[1], $mode);
273
    }
274
275
    /**
276
     * @param int $width
277
     * @param int $height
278
     * @param string $mode min|max|crop
279
     * @return array
280
     */
281
    public function getImageSizeConfig($width, $height, $mode = null)
282
    {
283
        if ($mode === null) {
284
            $mode = self::IMAGE_MODE_MIN;
285
        }
286
        $config = [];
287
        switch ($mode) {
288
            case self::IMAGE_MODE_MIN:
289
                $config['imageValidateSizeMinWidth'] = $width;
290
                $config['imageValidateSizeMinHeight'] = $height;
291
                break;
292
            case self::IMAGE_MODE_MAX:
293
                $config['imageValidateSizeMaxWidth'] = $width;
294
                $config['imageValidateSizeMaxHeight'] = $height;
295
                break;
296
            case self::IMAGE_MODE_CROP:
297
                // It crops only to given ratio and tries to keep the largest image
298
                $config['allowImageCrop'] = true;
299
                $config['imageCropAspectRatio'] = "{$width}:{$height}";
300
                break;
301
            case self::IMAGE_MODE_RESIZE:
302
                //  Cover will respect the aspect ratio and will scale to fill the target dimensions
303
                $config['allowImageResize'] = true;
304
                $config['imageResizeTargetWidth'] = $width;
305
                $config['imageResizeTargetHeight'] = $height;
306
307
                // Don't use these settings and keep api simple
308
                // $config['imageResizeMode'] = 'cover';
309
                // $config['imageResizeUpscale'] = true;
310
                break;
311
            case self::IMAGE_MODE_CROP_RESIZE:
312
                $config['allowImageResize'] = true;
313
                $config['imageResizeTargetWidth'] = $width;
314
                $config['imageResizeTargetHeight'] = $height;
315
                $config['allowImageCrop'] = true;
316
                $config['imageCropAspectRatio'] = "{$width}:{$height}";
317
                break;
318
            default:
319
                throw new Exception("Unsupported '$mode' mode");
320
        }
321
        return $config;
322
    }
323
324
    /**
325
     * @param int $width
326
     * @param int $height
327
     * @param string $mode min|max|crop|resize|crop_resize
328
     * @return $this
329
     */
330
    public function setImageSize($width, $height, $mode = null)
331
    {
332
        $config = $this->getImageSizeConfig($width, $height, $mode);
333
        foreach ($config as $k => $v) {
334
            $this->addFilePondConfig($k, $v);
335
        }
336
337
        // We need a custom poster size
338
339
        // If the height is smaller than our default, make smaller
340
        if ($height < self::getDefaultPosterHeight()) {
341
            $this->posterHeight = $height;
342
        }
343
        // Adjust width accordingly
344
        $ratio = $height / self::getDefaultPosterHeight();
345
        $this->posterWidth = $width / $ratio;
346
347
        return $config;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $config returns the type array which is incompatible with the documented return type LeKoala\FilePond\FilePondField.
Loading history...
348
    }
349
350
    /**
351
     * Return the config applied for this field
352
     *
353
     * Typically converted to json and set in a data attribute
354
     *
355
     * @return array
356
     */
357
    public function getFilePondConfig()
358
    {
359
        $name = $this->getName();
360
        $multiple = $this->getIsMultiUpload();
361
362
        // Multi uploads need []
363
        if ($multiple && strpos($name, '[]') === false) {
364
            $name .= '[]';
365
            $this->setName($name);
366
        }
367
368
        $i18nConfig = [
369
            'labelIdle' => _t('FilePondField.labelIdle', 'Drag & Drop your files or <span class="filepond--label-action"> Browse </span>'),
370
            'labelFileProcessing' => _t('FilePondField.labelFileProcessing', 'Uploading'),
371
            'labelFileProcessingComplete' => _t('FilePondField.labelFileProcessingComplete', 'Upload complete'),
372
            'labelFileProcessingAborted' => _t('FilePondField.labelFileProcessingAborted', 'Upload cancelled'),
373
            'labelTapToCancel' => _t('FilePondField.labelTapToCancel', 'tap to cancel'),
374
            'labelTapToRetry' => _t('FilePondField.labelTapToCancel', 'tap to retry'),
375
            'labelTapToUndo' => _t('FilePondField.labelTapToCancel', 'tap to undo'),
376
        ];
377
378
        // Base config
379
        $config = [
380
            'name' => $name, // This will also apply to the hidden fields
381
            'allowMultiple' => $multiple,
382
            'maxFiles' => $this->getAllowedMaxFileNumber(),
383
            'maxFileSize' => $this->getMaxFileSize(),
384
            'server' => $this->getServerOptions(),
385
            'files' => $this->getExistingUploadsData(),
386
        ];
387
388
        $acceptedFileTypes = $this->getAcceptedFileTypes();
389
        if (!empty($acceptedFileTypes)) {
390
            $config['acceptedFileTypes'] = array_values($acceptedFileTypes);
391
        }
392
393
        // image poster
394
        // @link https://pqina.nl/filepond/docs/api/plugins/file-poster/#usage
395
        if (self::config()->enable_poster) {
396
            $config['filePosterHeight'] = self::config()->poster_height ?? 264;
397
        }
398
399
        // image validation/crop based on record
400
        $record = $this->getForm()->getRecord();
401
        if ($record) {
0 ignored issues
show
introduced by
$record is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
402
            $sizes = $record->config()->image_sizes;
403
            $name = $this->getSafeName();
404
            if ($sizes && isset($sizes[$name])) {
405
                $newConfig = $this->getImageSizeConfigFromArray($sizes[$name]);
406
                $config = array_merge($config, $newConfig);
407
            }
408
        }
409
410
411
        // Any custom setting will override the base ones
412
        $config = array_merge($config, $i18nConfig, $this->filePondConfig);
413
414
        return $config;
415
    }
416
417
    /**
418
     * Compute best size for chunks based on server settings
419
     *
420
     * @return int
421
     */
422
    protected function computeMaxChunkSize()
423
    {
424
        $maxUpload = Convert::memstring2bytes(ini_get('upload_max_filesize'));
425
        $maxPost = Convert::memstring2bytes(ini_get('post_max_size'));
426
427
        // ~90%, allow some overhead
428
        return round(min($maxUpload, $maxPost) * 0.9);
429
    }
430
431
    /**
432
     * @inheritDoc
433
     */
434
    public function setValue($value, $record = null)
435
    {
436
        // Normalize values to something similar to UploadField usage
437
        if (is_numeric($value)) {
438
            $value = ['Files' => [$value]];
439
        } elseif (is_array($value) && empty($value['Files'])) {
440
            $value = ['Files' => $value];
441
        }
442
        // Track existing record data
443
        if ($record) {
444
            $name = $this->name;
445
            if ($record instanceof DataObject && $record->hasMethod($name)) {
446
                $data = $record->$name();
447
                // Wrap
448
                if ($data instanceof DataObject) {
449
                    $data = new ArrayList([$data]);
450
                }
451
                foreach ($data as $uploadedItem) {
452
                    $this->trackFileID($uploadedItem->ID);
453
                }
454
            }
455
        }
456
        return parent::setValue($value, $record);
457
    }
458
459
    /**
460
     * Configure our endpoint
461
     *
462
     * @link https://pqina.nl/filepond/docs/patterns/api/server/
463
     * @return array
464
     */
465
    public function getServerOptions()
466
    {
467
        if (!empty($this->customServerConfig)) {
468
            return $this->customServerConfig;
469
        }
470
        if (!$this->getForm()) {
471
            throw new LogicException(
472
                'Field must be associated with a form to call getServerOptions(). Please use $field->setForm($form);'
473
            );
474
        }
475
        $endpoint = $this->getChunkUploads() ? 'chunk' : 'upload';
476
        $server = [
477
            'process' => $this->getUploadEnabled() ? $this->getLinkParameters($endpoint) : null,
478
            'fetch' => null,
479
            'revert' => $this->getUploadEnabled() ? $this->getLinkParameters('revert') : null,
480
        ];
481
        if ($this->getUploadEnabled() && $this->getChunkUploads()) {
482
            $server['fetch'] =  $this->getLinkParameters($endpoint . "?fetch=");
483
            $server['patch'] =  $this->getLinkParameters($endpoint . "?patch=");
484
        }
485
        return $server;
486
    }
487
488
    /**
489
     * Configure the following parameters:
490
     *
491
     * url : Path to the end point
492
     * method : Request method to use
493
     * withCredentials : Toggles the XMLHttpRequest withCredentials on or off
494
     * headers : An object containing additional headers to send
495
     * timeout : Timeout for this action
496
     * onload : Called when server response is received, useful for getting the unique file id from the server response
497
     * onerror : Called when server error is received, receis the response body, useful to select the relevant error data
498
     *
499
     * @param string $action
500
     * @return array
501
     */
502
    protected function getLinkParameters($action)
503
    {
504
        $form = $this->getForm();
505
        $token = $form->getSecurityToken()->getValue();
506
        $record = $form->getRecord();
507
508
        $headers = [
509
            'X-SecurityID' => $token
510
        ];
511
        // Allow us to track the record instance
512
        if ($record) {
0 ignored issues
show
introduced by
$record is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
513
            $headers['X-RecordClassName'] = get_class($record);
514
            $headers['X-RecordID'] = $record->ID;
515
        }
516
        return [
517
            'url' => $this->Link($action),
518
            'headers' => $headers,
519
        ];
520
    }
521
522
    /**
523
     * The maximum size of a file, for instance 5MB or 750KB
524
     * Suitable for JS usage
525
     *
526
     * @return string
527
     */
528
    public function getMaxFileSize()
529
    {
530
        return str_replace(' ', '', File::format_size($this->getValidator()->getAllowedMaxFileSize()));
531
    }
532
533
    /**
534
     * Set initial values to FilePondField
535
     * See: https://pqina.nl/filepond/docs/patterns/api/filepond-object/#setting-initial-files
536
     *
537
     * @return array
538
     */
539
    public function getExistingUploadsData()
540
    {
541
        // Both Value() & dataValue() seem to return an array eg: ['Files' => [258, 259, 257]]
542
        $fileIDarray = $this->Value() ?: ['Files' => []];
543
        if (!isset($fileIDarray['Files']) || !count($fileIDarray['Files'])) {
544
            return [];
545
        }
546
547
        $existingUploads = [];
548
        foreach ($fileIDarray['Files'] as $fileID) {
549
            /* @var $file File */
550
            $file = File::get()->byID($fileID);
551
            if (!$file) {
552
                continue;
553
            }
554
            $existingUpload = [
555
                // the server file reference
556
                'source' => (int) $fileID,
557
                // set type to local to indicate an already uploaded file
558
                'options' => [
559
                    'type' => 'local',
560
                    // file information
561
                    'file' => [
562
                        'name' => $file->Name,
563
                        'size' => (int) $file->getAbsoluteSize(),
564
                        'type' => $file->getMimeType(),
565
                    ],
566
                ],
567
                'metadata' => []
568
            ];
569
570
            // Show poster
571
            // @link https://pqina.nl/filepond/docs/api/plugins/file-poster/#usage
572
            if (self::config()->enable_poster && $file instanceof Image && $file->ID) {
573
                // Size matches the one from asset admin or from or set size
574
                $w = self::getDefaultPosterWidth();
575
                if ($this->posterWidth) {
576
                    $w = $this->posterWidth;
577
                }
578
                $h = self::getDefaultPosterHeight();
579
                $resizedImage = $file->Fill($w, $h);
580
                if ($resizedImage) {
581
                    $poster = $resizedImage->getAbsoluteURL();
582
                    $existingUpload['options']['metadata']['poster'] = $poster;
583
                }
584
            }
585
            $existingUploads[] = $existingUpload;
586
        }
587
        return $existingUploads;
588
    }
589
590
    /**
591
     * @return int
592
     */
593
    public static function getDefaultPosterWidth()
594
    {
595
        return self::config()->poster_width ?? 352;
596
    }
597
598
    /**
599
     * @return int
600
     */
601
    public static function getDefaultPosterHeight()
602
    {
603
        return self::config()->poster_height ?? 264;
604
    }
605
606
    /**
607
     * Requirements are NOT versioned since filepond is regularly updated
608
     *
609
     * @return void
610
     */
611
    public static function Requirements()
612
    {
613
        $baseDir = self::BASE_CDN;
614
        if (!self::config()->use_cdn || self::config()->use_bundle) {
615
            // We need some kind of base url to serve as a starting point
616
            $asset = ModuleResourceLoader::resourceURL('lekoala/silverstripe-filepond:javascript/FilePondField.js');
617
            $baseDir = dirname($asset) . "/cdn";
618
        }
619
        $baseDir = rtrim($baseDir, '/');
620
621
        // It will load everything regardless of enabled plugins
622
        if (self::config()->use_bundle) {
623
            Requirements::css('lekoala/silverstripe-filepond:javascript/bundle.css');
624
            Requirements::javascript('lekoala/silverstripe-filepond:javascript/bundle.js');
625
        } else {
626
            // Polyfill to ensure max compatibility
627
            if (self::config()->enable_polyfill) {
628
                Requirements::javascript("$baseDir/filepond-polyfill/dist/filepond-polyfill.min.js");
629
            }
630
631
            // File/image validation plugins
632
            if (self::config()->enable_validation) {
633
                Requirements::javascript("$baseDir/filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.min.js");
634
                Requirements::javascript("$baseDir/filepond-plugin-file-validate-size/dist/filepond-plugin-file-validate-size.min.js");
635
                Requirements::javascript("$baseDir/filepond-plugin-image-validate-size/dist/filepond-plugin-image-validate-size.min.js");
636
            }
637
638
            // Poster plugins
639
            if (self::config()->enable_poster) {
640
                Requirements::javascript("$baseDir/filepond-plugin-file-metadata/dist/filepond-plugin-file-metadata.min.js");
641
                Requirements::css("$baseDir/filepond-plugin-file-poster/dist/filepond-plugin-file-poster.min.css");
642
                Requirements::javascript("$baseDir/filepond-plugin-file-poster/dist/filepond-plugin-file-poster.min.js");
643
            }
644
645
            // Image plugins
646
            if (self::config()->enable_image) {
647
                Requirements::javascript("$baseDir/filepond-plugin-image-exif-orientation/dist/filepond-plugin-image-exif-orientation.min.js");
648
                Requirements::css("$baseDir/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css");
649
                Requirements::javascript("$baseDir/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js");
650
                Requirements::javascript("$baseDir/filepond-plugin-image-transform/dist/filepond-plugin-image-transform.min.js");
651
                Requirements::javascript("$baseDir/filepond-plugin-image-resize/dist/filepond-plugin-image-resize.min.js");
652
                Requirements::javascript("$baseDir/filepond-plugin-image-crop/dist/filepond-plugin-image-crop.min.js");
653
            }
654
655
            // Base elements
656
            Requirements::css("$baseDir/filepond/dist/filepond.min.css");
657
            Requirements::javascript("$baseDir/filepond/dist/filepond.min.js");
658
        }
659
660
        // Our custom init
661
        Requirements::javascript('lekoala/silverstripe-filepond:javascript/FilePondField.js');
662
663
        // In the cms, init will not be triggered
664
        // Or you could use simpler instead
665
        if (self::config()->enable_ajax_init && Director::is_ajax()) {
666
            Requirements::javascript('lekoala/silverstripe-filepond:javascript/FilePondField-init.js?t=' . time());
667
        }
668
    }
669
670
    public function FieldHolder($properties = array())
671
    {
672
        $config = $this->getFilePondConfig();
673
674
        $this->setAttribute('data-config', json_encode($config));
675
676
        if (self::config()->enable_requirements) {
677
            self::Requirements();
678
        }
679
680
        return parent::FieldHolder($properties);
681
    }
682
683
    /**
684
     * Check the incoming request
685
     *
686
     * @param HTTPRequest $request
687
     * @return array
688
     */
689
    public function prepareUpload(HTTPRequest $request)
690
    {
691
        $name = $this->getName();
692
        $tmpFile = $request->postVar($name);
693
        if (!$tmpFile) {
694
            throw new RuntimeException("No file");
695
        }
696
        $tmpFile = $this->normalizeTempFile($tmpFile);
697
698
        // Update $tmpFile with a better name
699
        if ($this->renamePattern) {
700
            $tmpFile['name'] = $this->changeFilenameWithPattern(
701
                $tmpFile['name'],
702
                $this->renamePattern
703
            );
704
        }
705
706
        return $tmpFile;
707
    }
708
709
    /**
710
     * @param HTTPRequest $request
711
     * @return void
712
     */
713
    protected function securityChecks(HTTPRequest $request)
714
    {
715
        if ($this->isDisabled() || $this->isReadonly()) {
716
            throw new RuntimeException("Field is disabled or readonly");
717
        }
718
719
        // CSRF check
720
        $token = $this->getForm()->getSecurityToken();
721
        if (!$token->checkRequest($request)) {
722
            throw new RuntimeException("Invalid token");
723
        }
724
    }
725
726
    /**
727
     * @param File $file
728
     * @param HTTPRequest $request
729
     * @return void
730
     */
731
    protected function setFileDetails(File $file, HTTPRequest $request)
732
    {
733
        // Mark as temporary until properly associated with a record
734
        // Files will be unmarked later on by saveInto method
735
        $file->IsTemporary = true;
736
737
        // We can also track the record
738
        $RecordID = $request->getHeader('X-RecordID');
739
        $RecordClassName = $request->getHeader('X-RecordClassName');
740
        if (!$file->ObjectID) {
741
            $file->ObjectID = $RecordID;
742
        }
743
        if (!$file->ObjectClass) {
744
            $file->ObjectClass = $RecordClassName;
745
        }
746
747
        if ($file->isChanged()) {
748
            // If possible, prevent creating a version for no reason
749
            // @link https://docs.silverstripe.org/en/4/developer_guides/model/versioning/#writing-changes-to-a-versioned-dataobject
750
            if ($file->hasExtension(Versioned::class)) {
751
                $file->writeWithoutVersion();
752
            } else {
753
                $file->write();
754
            }
755
        }
756
    }
757
758
    /**
759
     * Creates a single file based on a form-urlencoded upload.
760
     *
761
     * 1 client uploads file my-file.jpg as multipart/form-data using a POST request
762
     * 2 server saves file to unique location tmp/12345/my-file.jpg
763
     * 3 server returns unique location id 12345 in text/plain response
764
     * 4 client stores unique id 12345 in a hidden input field
765
     * 5 client submits the FilePond parent form containing the hidden input field with the unique id
766
     * 6 server uses the unique id to move tmp/12345/my-file.jpg to its final location and remove the tmp/12345 folder
767
     *
768
     * Along with the file object, FilePond also sends the file metadata to the server, both these objects are given the same name.
769
     *
770
     * @param HTTPRequest $request
771
     * @return HTTPResponse
772
     */
773
    public function upload(HTTPRequest $request)
774
    {
775
        try {
776
            $this->securityChecks($request);
777
            $tmpFile = $this->prepareUpload($request);
778
        } catch (Exception $ex) {
779
            return $this->httpError(400, $ex->getMessage());
780
        }
781
782
        $file = $this->saveTemporaryFile($tmpFile, $error);
783
784
        // Handle upload errors
785
        if ($error) {
786
            $this->getUpload()->clearErrors();
787
            return $this->httpError(400, json_encode($error));
788
        }
789
790
        // File can be an AssetContainer and not a DataObject
791
        if ($file instanceof DataObject) {
792
            $this->setFileDetails($file, $request);
793
        }
794
795
        $this->getUpload()->clearErrors();
796
        $fileId = $file->ID;
0 ignored issues
show
Bug introduced by
Accessing ID on the interface SilverStripe\Assets\Storage\AssetContainer suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
797
        $this->trackFileID($fileId);
798
799
        if (self::config()->auto_clear_temp_folder) {
800
            // Set a limit of 100 because otherwise it would be really slow
801
            self::clearTemporaryUploads(true, 100);
802
        }
803
804
        // server returns unique location id 12345 in text/plain response
805
        $response = new HTTPResponse($fileId);
806
        $response->addHeader('Content-Type', 'text/plain');
807
        return $response;
808
    }
809
810
    /**
811
     * @link https://pqina.nl/filepond/docs/api/server/#process-chunks
812
     * @param HTTPRequest $request
813
     * @return HTTPResponse
814
     */
815
    public function chunk(HTTPRequest $request)
816
    {
817
        try {
818
            $this->securityChecks($request);
819
        } catch (Exception $ex) {
820
            return $this->httpError(400, $ex->getMessage());
821
        }
822
823
        $method = $request->httpMethod();
824
825
        // The random token is returned as a query string
826
        $id = $request->getVar('patch');
827
828
        // FilePond will send a POST request (without file) to start a chunked transfer,
829
        // expecting to receive a unique transfer id in the response body, it'll add the Upload-Length header to this request.
830
        if ($method == "POST") {
831
            // Initial post payload doesn't contain name
832
            // It would be better to return some kind of random token instead
833
            // But FilePond stores the id upon the first request :-(
834
            $file = new File();
835
            $this->setFileDetails($file, $request);
836
            $fileId = $file->ID;
837
            $this->trackFileID($fileId);
838
            $response = new HTTPResponse($fileId, 200);
839
            $response->addHeader('Content-Type', 'text/plain');
840
            return $response;
841
        }
842
843
        // location of patch files
844
        $filePath = TEMP_PATH . "/filepond-" . $id;
845
846
        // FilePond will send a HEAD request to determine which chunks have already been uploaded,
847
        // expecting the file offset of the next expected chunk in the Upload-Offset response header.
848
        if ($method == "HEAD") {
849
            $nextOffset = 0;
850
            while (is_file($filePath . '.patch.' . $nextOffset)) {
851
                $nextOffset++;
852
            }
853
854
            $response = new HTTPResponse($nextOffset, 200);
855
            $response->addHeader('Content-Type', 'text/plain');
856
            $response->addHeader('Upload-Offset', $nextOffset);
857
            return $response;
858
        }
859
860
        // FilePond will send a PATCH request to push a chunk to the server.
861
        // Each of these requests is accompanied by a Content-Type, Upload-Offset, Upload-Name, and Upload-Length header.
862
        if ($method != "PATCH") {
863
            return $this->httpError(400, "Invalid method");
864
        }
865
866
        // The name of the file being transferred
867
        $uploadName = $request->getHeader('Upload-Name');
868
        // The offset of the chunk being transferred (starts with 0)
869
        $offset = $request->getHeader('Upload-Offset');
870
        // The total size of the file being transferred (in bytes)
871
        $length = (int) $request->getHeader('Upload-Length');
872
873
        // should be numeric values, else exit
874
        if (!is_numeric($offset) || !is_numeric($length)) {
875
            return $this->httpError(400, "Invalid offset or length");
876
        }
877
878
        // write patch file for this request
879
        file_put_contents($filePath . '.patch.' . $offset, $request->getBody());
880
881
        // calculate total size of patches
882
        $size = 0;
883
        $patch = glob($filePath . '.patch.*');
884
        foreach ($patch as $filename) {
885
            $size += filesize($filename);
886
        }
887
        // if total size equals length of file we have gathered all patch files
888
        if ($size >= $length) {
889
            // create output file
890
            $outputFile = fopen($filePath, 'wb');
891
            // write patches to file
892
            foreach ($patch as $filename) {
893
                // get offset from filename
894
                list($dir, $offset) = explode('.patch.', $filename, 2);
895
                // read patch and close
896
                $patchFile = fopen($filename, 'rb');
897
                $patchContent = fread($patchFile, filesize($filename));
898
                fclose($patchFile);
899
900
                // apply patch
901
                fseek($outputFile, (int) $offset);
902
                fwrite($outputFile, $patchContent);
903
            }
904
            // remove patches
905
            foreach ($patch as $filename) {
906
                unlink($filename);
907
            }
908
            // done with file
909
            fclose($outputFile);
910
911
            // Finalize real filename
912
913
            // We need to class this as it mutates the state and set the record if any
914
            $relationClass = $this->getRelationAutosetClass(null);
0 ignored issues
show
Unused Code introduced by
The assignment to $relationClass is dead and can be removed.
Loading history...
915
            $realFilename = $this->getFolderName() . "/" . $uploadName;
916
            if ($this->renamePattern) {
917
                $realFilename = $this->changeFilenameWithPattern(
918
                    $realFilename,
919
                    $this->renamePattern
920
                );
921
            }
922
923
            // write output file to asset store
924
            $file = $this->getFileByID($id);
925
            if (!$file) {
926
                return $this->httpError(400, "File $id not found");
927
            }
928
            $file->setFromLocalFile($filePath);
929
            $file->setFilename($realFilename);
930
            $file->Title = $uploadName;
931
            // Set proper class
932
            $relationClass = File::get_class_for_file_extension(
933
                File::get_file_extension($realFilename)
934
            );
935
            $file->setClassName($relationClass);
936
            $file->write();
937
            // Reload file instance to get the right class
938
            // it is not cached so we should get a fresh record
939
            $file = $this->getFileByID($id);
940
            // since we don't go through our upload object, call extension manually
941
            $file->extend('onAfterUpload');
942
        }
943
        $response = new HTTPResponse('', 204);
944
        return $response;
945
    }
946
947
    /**
948
     * @link https://pqina.nl/filepond/docs/api/server/#revert
949
     * @param HTTPRequest $request
950
     * @return HTTPResponse
951
     */
952
    public function revert(HTTPRequest $request)
953
    {
954
        try {
955
            $this->securityChecks($request);
956
        } catch (Exception $ex) {
957
            return $this->httpError(400, $ex->getMessage());
958
        }
959
960
        $method = $request->httpMethod();
961
962
        if ($method != "DELETE") {
963
            return $this->httpError(400, "Invalid method");
964
        }
965
966
        $fileID = (int) $request->getBody();
967
        if (!in_array($fileID, $this->getTrackedIDs())) {
968
            return $this->httpError(400, "Invalid ID");
969
        }
970
        $file = File::get()->byID($fileID);
971
        if (!$file->IsTemporary) {
972
            return $this->httpError(400, "Invalid file");
973
        }
974
        if (!$file->canDelete()) {
975
            return $this->httpError(400, "Cannot delete file");
976
        }
977
        $file->delete();
978
        $response = new HTTPResponse('', 200);
979
        return $response;
980
    }
981
982
    /**
983
     * Clear temp folder that should not contain any file other than temporary
984
     *
985
     * @param boolean $doDelete Set to true to actually delete the files, otherwise it's just a dry-run
986
     * @param int $limit
987
     * @return File[] List of files removed
988
     */
989
    public static function clearTemporaryUploads($doDelete = false, $limit = 0)
990
    {
991
        $tempFiles = File::get()->filter('IsTemporary', true);
992
        if ($limit) {
993
            $tempFiles = $tempFiles->limit($limit);
994
        }
995
996
        $threshold = self::config()->auto_clear_threshold;
997
998
        // Set a default threshold if none set
999
        if (!$threshold) {
1000
            if (Director::isDev()) {
1001
                $threshold = '-10 minutes';
1002
            } else {
1003
                $threshold = '-1 day';
1004
            }
1005
        }
1006
        if (is_int($threshold)) {
1007
            $thresholdTime = time() - $threshold;
1008
        } else {
1009
            $thresholdTime = strtotime($threshold);
1010
        }
1011
1012
        // Update query to avoid fetching unecessary records
1013
        $tempFiles = $tempFiles->filter("Created:LessThan", date('Y-m-d H:i:s', $thresholdTime));
1014
1015
        $filesDeleted = [];
1016
        foreach ($tempFiles as $tempFile) {
1017
            $createdTime = strtotime($tempFile->Created);
1018
            if ($createdTime < $thresholdTime) {
1019
                $filesDeleted[] = $tempFile;
1020
                if ($doDelete) {
1021
                    if ($tempFile->hasExtension(Versioned::class)) {
1022
                        $tempFile->deleteFromStage(Versioned::LIVE);
1023
                        $tempFile->deleteFromStage(Versioned::DRAFT);
1024
                    } else {
1025
                        $tempFile->delete();
1026
                    }
1027
                }
1028
            }
1029
        }
1030
        return $filesDeleted;
1031
    }
1032
1033
    /**
1034
     * Allows tracking uploaded ids to prevent unauthorized attachements
1035
     *
1036
     * @param int $fileId
1037
     * @return void
1038
     */
1039
    public function trackFileID($fileId)
1040
    {
1041
        $session = $this->getRequest()->getSession();
1042
        $uploadedIDs = $this->getTrackedIDs();
1043
        if (!in_array($fileId, $uploadedIDs)) {
1044
            $uploadedIDs[] = $fileId;
1045
        }
1046
        $session->set('FilePond', $uploadedIDs);
1047
    }
1048
1049
    /**
1050
     * Get all authorized tracked ids
1051
     * @return array
1052
     */
1053
    public function getTrackedIDs()
1054
    {
1055
        $session = $this->getRequest()->getSession();
1056
        $uploadedIDs = $session->get('FilePond');
1057
        if ($uploadedIDs) {
1058
            return $uploadedIDs;
1059
        }
1060
        return [];
1061
    }
1062
1063
    public function saveInto(DataObjectInterface $record)
1064
    {
1065
        // Note that the list of IDs is based on the value sent by the user
1066
        // It can be spoofed because checks are minimal (by default, canView = true and only check if isInDB)
1067
        $IDs = $this->getItemIDs();
1068
1069
        $Member = Security::getCurrentUser();
1070
1071
        // Ensure the files saved into the DataObject have been tracked (either because already on the DataObject or uploaded by the user)
1072
        $trackedIDs = $this->getTrackedIDs();
1073
        foreach ($IDs as $ID) {
1074
            if (!in_array($ID, $trackedIDs)) {
1075
                throw new ValidationException("Invalid file ID : $ID");
1076
            }
1077
        }
1078
1079
        // Move files out of temporary folder
1080
        foreach ($IDs as $ID) {
1081
            $file = $this->getFileByID($ID);
1082
            if ($file && $file->IsTemporary) {
1083
                // The record does not have an ID which is a bad idea to attach the file to it
1084
                if (!$record->ID) {
1085
                    $record->write();
1086
                }
1087
                // Check if the member is owner
1088
                if ($Member && $Member->ID != $file->OwnerID) {
1089
                    throw new ValidationException("Failed to authenticate owner");
1090
                }
1091
                $file->IsTemporary = false;
1092
                $file->ObjectID = $record->ID;
1093
                $file->ObjectClass = get_class($record);
1094
                $file->write();
1095
            } else {
1096
                // File was uploaded earlier, no need to do anything
1097
            }
1098
        }
1099
1100
        // Proceed
1101
        return parent::saveInto($record);
1102
    }
1103
1104
    public function Type()
1105
    {
1106
        return 'filepond';
1107
    }
1108
}
1109