Passed
Push — master ( e6a9a9...b9d1ee )
by Thomas
02:25
created

FilePondField::getExistingUploadsData()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 52
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
cc 12
eloc 30
c 6
b 1
f 0
nc 12
nop 0
dl 0
loc 52
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
            $this->posterWidth = $width;
343
        } else {
344
            // Adjust width to keep aspect ratio with our default height
345
            $ratio = $height / self::getDefaultPosterHeight();
346
            $this->posterWidth = $width / $ratio;
347
        }
348
349
        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...
350
    }
351
352
    /**
353
     * Return the config applied for this field
354
     *
355
     * Typically converted to json and set in a data attribute
356
     *
357
     * @return array
358
     */
359
    public function getFilePondConfig()
360
    {
361
        $name = $this->getName();
362
        $multiple = $this->getIsMultiUpload();
363
364
        // Multi uploads need []
365
        if ($multiple && strpos($name, '[]') === false) {
366
            $name .= '[]';
367
            $this->setName($name);
368
        }
369
370
        $i18nConfig = [
371
            'labelIdle' => _t('FilePondField.labelIdle', 'Drag & Drop your files or <span class="filepond--label-action"> Browse </span>'),
372
            'labelFileProcessing' => _t('FilePondField.labelFileProcessing', 'Uploading'),
373
            'labelFileProcessingComplete' => _t('FilePondField.labelFileProcessingComplete', 'Upload complete'),
374
            'labelFileProcessingAborted' => _t('FilePondField.labelFileProcessingAborted', 'Upload cancelled'),
375
            'labelTapToCancel' => _t('FilePondField.labelTapToCancel', 'tap to cancel'),
376
            'labelTapToRetry' => _t('FilePondField.labelTapToCancel', 'tap to retry'),
377
            'labelTapToUndo' => _t('FilePondField.labelTapToCancel', 'tap to undo'),
378
        ];
379
380
        // Base config
381
        $config = [
382
            'name' => $name, // This will also apply to the hidden fields
383
            'allowMultiple' => $multiple,
384
            'maxFiles' => $this->getAllowedMaxFileNumber(),
385
            'maxFileSize' => $this->getMaxFileSize(),
386
            'server' => $this->getServerOptions(),
387
            'files' => $this->getExistingUploadsData(),
388
        ];
389
390
        $acceptedFileTypes = $this->getAcceptedFileTypes();
391
        if (!empty($acceptedFileTypes)) {
392
            $config['acceptedFileTypes'] = array_values($acceptedFileTypes);
393
        }
394
395
        // image poster
396
        // @link https://pqina.nl/filepond/docs/api/plugins/file-poster/#usage
397
        if (self::config()->enable_poster) {
398
            $config['filePosterHeight'] = self::config()->poster_height ?? 264;
399
        }
400
401
        // image validation/crop based on record
402
        $record = $this->getForm()->getRecord();
403
        if ($record) {
0 ignored issues
show
introduced by
$record is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
404
            $sizes = $record->config()->image_sizes;
405
            $name = $this->getSafeName();
406
            if ($sizes && isset($sizes[$name])) {
407
                $newConfig = $this->getImageSizeConfigFromArray($sizes[$name]);
408
                $config = array_merge($config, $newConfig);
409
            }
410
        }
411
412
413
        // Any custom setting will override the base ones
414
        $config = array_merge($config, $i18nConfig, $this->filePondConfig);
415
416
        return $config;
417
    }
418
419
    /**
420
     * Compute best size for chunks based on server settings
421
     *
422
     * @return int
423
     */
424
    protected function computeMaxChunkSize()
425
    {
426
        $maxUpload = Convert::memstring2bytes(ini_get('upload_max_filesize'));
427
        $maxPost = Convert::memstring2bytes(ini_get('post_max_size'));
428
429
        // ~90%, allow some overhead
430
        return round(min($maxUpload, $maxPost) * 0.9);
431
    }
432
433
    /**
434
     * @inheritDoc
435
     */
436
    public function setValue($value, $record = null)
437
    {
438
        // Normalize values to something similar to UploadField usage
439
        if (is_numeric($value)) {
440
            $value = ['Files' => [$value]];
441
        } elseif (is_array($value) && empty($value['Files'])) {
442
            $value = ['Files' => $value];
443
        }
444
        // Track existing record data
445
        if ($record) {
446
            $name = $this->name;
447
            if ($record instanceof DataObject && $record->hasMethod($name)) {
448
                $data = $record->$name();
449
                // Wrap
450
                if ($data instanceof DataObject) {
451
                    $data = new ArrayList([$data]);
452
                }
453
                foreach ($data as $uploadedItem) {
454
                    $this->trackFileID($uploadedItem->ID);
455
                }
456
            }
457
        }
458
        return parent::setValue($value, $record);
459
    }
460
461
    /**
462
     * Configure our endpoint
463
     *
464
     * @link https://pqina.nl/filepond/docs/patterns/api/server/
465
     * @return array
466
     */
467
    public function getServerOptions()
468
    {
469
        if (!empty($this->customServerConfig)) {
470
            return $this->customServerConfig;
471
        }
472
        if (!$this->getForm()) {
473
            throw new LogicException(
474
                'Field must be associated with a form to call getServerOptions(). Please use $field->setForm($form);'
475
            );
476
        }
477
        $endpoint = $this->getChunkUploads() ? 'chunk' : 'upload';
478
        $server = [
479
            'process' => $this->getUploadEnabled() ? $this->getLinkParameters($endpoint) : null,
480
            'fetch' => null,
481
            'revert' => $this->getUploadEnabled() ? $this->getLinkParameters('revert') : null,
482
        ];
483
        if ($this->getUploadEnabled() && $this->getChunkUploads()) {
484
            $server['fetch'] =  $this->getLinkParameters($endpoint . "?fetch=");
485
            $server['patch'] =  $this->getLinkParameters($endpoint . "?patch=");
486
        }
487
        return $server;
488
    }
489
490
    /**
491
     * Configure the following parameters:
492
     *
493
     * url : Path to the end point
494
     * method : Request method to use
495
     * withCredentials : Toggles the XMLHttpRequest withCredentials on or off
496
     * headers : An object containing additional headers to send
497
     * timeout : Timeout for this action
498
     * onload : Called when server response is received, useful for getting the unique file id from the server response
499
     * onerror : Called when server error is received, receis the response body, useful to select the relevant error data
500
     *
501
     * @param string $action
502
     * @return array
503
     */
504
    protected function getLinkParameters($action)
505
    {
506
        $form = $this->getForm();
507
        $token = $form->getSecurityToken()->getValue();
508
        $record = $form->getRecord();
509
510
        $headers = [
511
            'X-SecurityID' => $token
512
        ];
513
        // Allow us to track the record instance
514
        if ($record) {
0 ignored issues
show
introduced by
$record is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
515
            $headers['X-RecordClassName'] = get_class($record);
516
            $headers['X-RecordID'] = $record->ID;
517
        }
518
        return [
519
            'url' => $this->Link($action),
520
            'headers' => $headers,
521
        ];
522
    }
523
524
    /**
525
     * The maximum size of a file, for instance 5MB or 750KB
526
     * Suitable for JS usage
527
     *
528
     * @return string
529
     */
530
    public function getMaxFileSize()
531
    {
532
        return str_replace(' ', '', File::format_size($this->getValidator()->getAllowedMaxFileSize()));
533
    }
534
535
    /**
536
     * Set initial values to FilePondField
537
     * See: https://pqina.nl/filepond/docs/patterns/api/filepond-object/#setting-initial-files
538
     *
539
     * @return array
540
     */
541
    public function getExistingUploadsData()
542
    {
543
        // Both Value() & dataValue() seem to return an array eg: ['Files' => [258, 259, 257]]
544
        $fileIDarray = $this->Value() ?: ['Files' => []];
545
        if (!isset($fileIDarray['Files']) || !count($fileIDarray['Files'])) {
546
            return [];
547
        }
548
549
        $existingUploads = [];
550
        foreach ($fileIDarray['Files'] as $fileID) {
551
            /* @var $file File */
552
            $file = File::get()->byID($fileID);
553
            if (!$file) {
554
                continue;
555
            }
556
            $existingUpload = [
557
                // the server file reference
558
                'source' => (int) $fileID,
559
                // set type to local to indicate an already uploaded file
560
                'options' => [
561
                    'type' => 'local',
562
                    // file information
563
                    'file' => [
564
                        'name' => $file->Name,
565
                        'size' => (int) $file->getAbsoluteSize(),
566
                        'type' => $file->getMimeType(),
567
                    ],
568
                ],
569
                'metadata' => []
570
            ];
571
572
            // Show poster
573
            // @link https://pqina.nl/filepond/docs/api/plugins/file-poster/#usage
574
            if (self::config()->enable_poster && $file instanceof Image && $file->ID) {
575
                // Size matches the one from asset admin or from or set size
576
                $w = self::getDefaultPosterWidth();
577
                if ($this->posterWidth) {
578
                    $w = $this->posterWidth;
579
                }
580
                $h = self::getDefaultPosterHeight();
581
                if ($this->posterHeight) {
582
                    $h = $this->posterHeight;
583
                }
584
                $resizedImage = $file->Fill($w, $h);
585
                if ($resizedImage) {
586
                    $poster = $resizedImage->getAbsoluteURL();
587
                    $existingUpload['options']['metadata']['poster'] = $poster;
588
                }
589
            }
590
            $existingUploads[] = $existingUpload;
591
        }
592
        return $existingUploads;
593
    }
594
595
    /**
596
     * @return int
597
     */
598
    public static function getDefaultPosterWidth()
599
    {
600
        return self::config()->poster_width ?? 352;
601
    }
602
603
    /**
604
     * @return int
605
     */
606
    public static function getDefaultPosterHeight()
607
    {
608
        return self::config()->poster_height ?? 264;
609
    }
610
611
    /**
612
     * Requirements are NOT versioned since filepond is regularly updated
613
     *
614
     * @return void
615
     */
616
    public static function Requirements()
617
    {
618
        $baseDir = self::BASE_CDN;
619
        if (!self::config()->use_cdn || self::config()->use_bundle) {
620
            // We need some kind of base url to serve as a starting point
621
            $asset = ModuleResourceLoader::resourceURL('lekoala/silverstripe-filepond:javascript/FilePondField.js');
622
            $baseDir = dirname($asset) . "/cdn";
623
        }
624
        $baseDir = rtrim($baseDir, '/');
625
626
        // It will load everything regardless of enabled plugins
627
        if (self::config()->use_bundle) {
628
            Requirements::css('lekoala/silverstripe-filepond:javascript/bundle.css');
629
            Requirements::javascript('lekoala/silverstripe-filepond:javascript/bundle.js');
630
        } else {
631
            // Polyfill to ensure max compatibility
632
            if (self::config()->enable_polyfill) {
633
                Requirements::javascript("$baseDir/filepond-polyfill/dist/filepond-polyfill.min.js");
634
            }
635
636
            // File/image validation plugins
637
            if (self::config()->enable_validation) {
638
                Requirements::javascript("$baseDir/filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.min.js");
639
                Requirements::javascript("$baseDir/filepond-plugin-file-validate-size/dist/filepond-plugin-file-validate-size.min.js");
640
                Requirements::javascript("$baseDir/filepond-plugin-image-validate-size/dist/filepond-plugin-image-validate-size.min.js");
641
            }
642
643
            // Poster plugins
644
            if (self::config()->enable_poster) {
645
                Requirements::javascript("$baseDir/filepond-plugin-file-metadata/dist/filepond-plugin-file-metadata.min.js");
646
                Requirements::css("$baseDir/filepond-plugin-file-poster/dist/filepond-plugin-file-poster.min.css");
647
                Requirements::javascript("$baseDir/filepond-plugin-file-poster/dist/filepond-plugin-file-poster.min.js");
648
            }
649
650
            // Image plugins
651
            if (self::config()->enable_image) {
652
                Requirements::javascript("$baseDir/filepond-plugin-image-exif-orientation/dist/filepond-plugin-image-exif-orientation.min.js");
653
                Requirements::css("$baseDir/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css");
654
                Requirements::javascript("$baseDir/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js");
655
                Requirements::javascript("$baseDir/filepond-plugin-image-transform/dist/filepond-plugin-image-transform.min.js");
656
                Requirements::javascript("$baseDir/filepond-plugin-image-resize/dist/filepond-plugin-image-resize.min.js");
657
                Requirements::javascript("$baseDir/filepond-plugin-image-crop/dist/filepond-plugin-image-crop.min.js");
658
            }
659
660
            // Base elements
661
            Requirements::css("$baseDir/filepond/dist/filepond.min.css");
662
            Requirements::javascript("$baseDir/filepond/dist/filepond.min.js");
663
        }
664
665
        // Our custom init
666
        Requirements::javascript('lekoala/silverstripe-filepond:javascript/FilePondField.js');
667
668
        // In the cms, init will not be triggered
669
        // Or you could use simpler instead
670
        if (self::config()->enable_ajax_init && Director::is_ajax()) {
671
            Requirements::javascript('lekoala/silverstripe-filepond:javascript/FilePondField-init.js?t=' . time());
672
        }
673
    }
674
675
    public function FieldHolder($properties = array())
676
    {
677
        $config = $this->getFilePondConfig();
678
679
        $this->setAttribute('data-config', json_encode($config));
680
681
        if (self::config()->enable_requirements) {
682
            self::Requirements();
683
        }
684
685
        return parent::FieldHolder($properties);
686
    }
687
688
    /**
689
     * Check the incoming request
690
     *
691
     * @param HTTPRequest $request
692
     * @return array
693
     */
694
    public function prepareUpload(HTTPRequest $request)
695
    {
696
        $name = $this->getName();
697
        $tmpFile = $request->postVar($name);
698
        if (!$tmpFile) {
699
            throw new RuntimeException("No file");
700
        }
701
        $tmpFile = $this->normalizeTempFile($tmpFile);
702
703
        // Update $tmpFile with a better name
704
        if ($this->renamePattern) {
705
            $tmpFile['name'] = $this->changeFilenameWithPattern(
706
                $tmpFile['name'],
707
                $this->renamePattern
708
            );
709
        }
710
711
        return $tmpFile;
712
    }
713
714
    /**
715
     * @param HTTPRequest $request
716
     * @return void
717
     */
718
    protected function securityChecks(HTTPRequest $request)
719
    {
720
        if ($this->isDisabled() || $this->isReadonly()) {
721
            throw new RuntimeException("Field is disabled or readonly");
722
        }
723
724
        // CSRF check
725
        $token = $this->getForm()->getSecurityToken();
726
        if (!$token->checkRequest($request)) {
727
            throw new RuntimeException("Invalid token");
728
        }
729
    }
730
731
    /**
732
     * @param File $file
733
     * @param HTTPRequest $request
734
     * @return void
735
     */
736
    protected function setFileDetails(File $file, HTTPRequest $request)
737
    {
738
        // Mark as temporary until properly associated with a record
739
        // Files will be unmarked later on by saveInto method
740
        $file->IsTemporary = true;
741
742
        // We can also track the record
743
        $RecordID = $request->getHeader('X-RecordID');
744
        $RecordClassName = $request->getHeader('X-RecordClassName');
745
        if (!$file->ObjectID) {
746
            $file->ObjectID = $RecordID;
747
        }
748
        if (!$file->ObjectClass) {
749
            $file->ObjectClass = $RecordClassName;
750
        }
751
752
        if ($file->isChanged()) {
753
            // If possible, prevent creating a version for no reason
754
            // @link https://docs.silverstripe.org/en/4/developer_guides/model/versioning/#writing-changes-to-a-versioned-dataobject
755
            if ($file->hasExtension(Versioned::class)) {
756
                $file->writeWithoutVersion();
757
            } else {
758
                $file->write();
759
            }
760
        }
761
    }
762
763
    /**
764
     * Creates a single file based on a form-urlencoded upload.
765
     *
766
     * 1 client uploads file my-file.jpg as multipart/form-data using a POST request
767
     * 2 server saves file to unique location tmp/12345/my-file.jpg
768
     * 3 server returns unique location id 12345 in text/plain response
769
     * 4 client stores unique id 12345 in a hidden input field
770
     * 5 client submits the FilePond parent form containing the hidden input field with the unique id
771
     * 6 server uses the unique id to move tmp/12345/my-file.jpg to its final location and remove the tmp/12345 folder
772
     *
773
     * Along with the file object, FilePond also sends the file metadata to the server, both these objects are given the same name.
774
     *
775
     * @param HTTPRequest $request
776
     * @return HTTPResponse
777
     */
778
    public function upload(HTTPRequest $request)
779
    {
780
        try {
781
            $this->securityChecks($request);
782
            $tmpFile = $this->prepareUpload($request);
783
        } catch (Exception $ex) {
784
            return $this->httpError(400, $ex->getMessage());
785
        }
786
787
        $file = $this->saveTemporaryFile($tmpFile, $error);
788
789
        // Handle upload errors
790
        if ($error) {
791
            $this->getUpload()->clearErrors();
792
            return $this->httpError(400, json_encode($error));
793
        }
794
795
        // File can be an AssetContainer and not a DataObject
796
        if ($file instanceof DataObject) {
797
            $this->setFileDetails($file, $request);
798
        }
799
800
        $this->getUpload()->clearErrors();
801
        $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...
802
        $this->trackFileID($fileId);
803
804
        if (self::config()->auto_clear_temp_folder) {
805
            // Set a limit of 100 because otherwise it would be really slow
806
            self::clearTemporaryUploads(true, 100);
807
        }
808
809
        // server returns unique location id 12345 in text/plain response
810
        $response = new HTTPResponse($fileId);
811
        $response->addHeader('Content-Type', 'text/plain');
812
        return $response;
813
    }
814
815
    /**
816
     * @link https://pqina.nl/filepond/docs/api/server/#process-chunks
817
     * @param HTTPRequest $request
818
     * @return HTTPResponse
819
     */
820
    public function chunk(HTTPRequest $request)
821
    {
822
        try {
823
            $this->securityChecks($request);
824
        } catch (Exception $ex) {
825
            return $this->httpError(400, $ex->getMessage());
826
        }
827
828
        $method = $request->httpMethod();
829
830
        // The random token is returned as a query string
831
        $id = $request->getVar('patch');
832
833
        // FilePond will send a POST request (without file) to start a chunked transfer,
834
        // expecting to receive a unique transfer id in the response body, it'll add the Upload-Length header to this request.
835
        if ($method == "POST") {
836
            // Initial post payload doesn't contain name
837
            // It would be better to return some kind of random token instead
838
            // But FilePond stores the id upon the first request :-(
839
            $file = new File();
840
            $this->setFileDetails($file, $request);
841
            $fileId = $file->ID;
842
            $this->trackFileID($fileId);
843
            $response = new HTTPResponse($fileId, 200);
844
            $response->addHeader('Content-Type', 'text/plain');
845
            return $response;
846
        }
847
848
        // location of patch files
849
        $filePath = TEMP_PATH . "/filepond-" . $id;
850
851
        // FilePond will send a HEAD request to determine which chunks have already been uploaded,
852
        // expecting the file offset of the next expected chunk in the Upload-Offset response header.
853
        if ($method == "HEAD") {
854
            $nextOffset = 0;
855
            while (is_file($filePath . '.patch.' . $nextOffset)) {
856
                $nextOffset++;
857
            }
858
859
            $response = new HTTPResponse($nextOffset, 200);
860
            $response->addHeader('Content-Type', 'text/plain');
861
            $response->addHeader('Upload-Offset', $nextOffset);
862
            return $response;
863
        }
864
865
        // FilePond will send a PATCH request to push a chunk to the server.
866
        // Each of these requests is accompanied by a Content-Type, Upload-Offset, Upload-Name, and Upload-Length header.
867
        if ($method != "PATCH") {
868
            return $this->httpError(400, "Invalid method");
869
        }
870
871
        // The name of the file being transferred
872
        $uploadName = $request->getHeader('Upload-Name');
873
        // The offset of the chunk being transferred (starts with 0)
874
        $offset = $request->getHeader('Upload-Offset');
875
        // The total size of the file being transferred (in bytes)
876
        $length = (int) $request->getHeader('Upload-Length');
877
878
        // should be numeric values, else exit
879
        if (!is_numeric($offset) || !is_numeric($length)) {
880
            return $this->httpError(400, "Invalid offset or length");
881
        }
882
883
        // write patch file for this request
884
        file_put_contents($filePath . '.patch.' . $offset, $request->getBody());
885
886
        // calculate total size of patches
887
        $size = 0;
888
        $patch = glob($filePath . '.patch.*');
889
        foreach ($patch as $filename) {
890
            $size += filesize($filename);
891
        }
892
        // if total size equals length of file we have gathered all patch files
893
        if ($size >= $length) {
894
            // create output file
895
            $outputFile = fopen($filePath, 'wb');
896
            // write patches to file
897
            foreach ($patch as $filename) {
898
                // get offset from filename
899
                list($dir, $offset) = explode('.patch.', $filename, 2);
900
                // read patch and close
901
                $patchFile = fopen($filename, 'rb');
902
                $patchContent = fread($patchFile, filesize($filename));
903
                fclose($patchFile);
904
905
                // apply patch
906
                fseek($outputFile, (int) $offset);
907
                fwrite($outputFile, $patchContent);
908
            }
909
            // remove patches
910
            foreach ($patch as $filename) {
911
                unlink($filename);
912
            }
913
            // done with file
914
            fclose($outputFile);
915
916
            // Finalize real filename
917
918
            // We need to class this as it mutates the state and set the record if any
919
            $relationClass = $this->getRelationAutosetClass(null);
0 ignored issues
show
Unused Code introduced by
The assignment to $relationClass is dead and can be removed.
Loading history...
920
            $realFilename = $this->getFolderName() . "/" . $uploadName;
921
            if ($this->renamePattern) {
922
                $realFilename = $this->changeFilenameWithPattern(
923
                    $realFilename,
924
                    $this->renamePattern
925
                );
926
            }
927
928
            // write output file to asset store
929
            $file = $this->getFileByID($id);
930
            if (!$file) {
931
                return $this->httpError(400, "File $id not found");
932
            }
933
            $file->setFromLocalFile($filePath);
934
            $file->setFilename($realFilename);
935
            $file->Title = $uploadName;
936
            // Set proper class
937
            $relationClass = File::get_class_for_file_extension(
938
                File::get_file_extension($realFilename)
939
            );
940
            $file->setClassName($relationClass);
941
            $file->write();
942
            // Reload file instance to get the right class
943
            // it is not cached so we should get a fresh record
944
            $file = $this->getFileByID($id);
945
            // since we don't go through our upload object, call extension manually
946
            $file->extend('onAfterUpload');
947
        }
948
        $response = new HTTPResponse('', 204);
949
        return $response;
950
    }
951
952
    /**
953
     * @link https://pqina.nl/filepond/docs/api/server/#revert
954
     * @param HTTPRequest $request
955
     * @return HTTPResponse
956
     */
957
    public function revert(HTTPRequest $request)
958
    {
959
        try {
960
            $this->securityChecks($request);
961
        } catch (Exception $ex) {
962
            return $this->httpError(400, $ex->getMessage());
963
        }
964
965
        $method = $request->httpMethod();
966
967
        if ($method != "DELETE") {
968
            return $this->httpError(400, "Invalid method");
969
        }
970
971
        $fileID = (int) $request->getBody();
972
        if (!in_array($fileID, $this->getTrackedIDs())) {
973
            return $this->httpError(400, "Invalid ID");
974
        }
975
        $file = File::get()->byID($fileID);
976
        if (!$file->IsTemporary) {
977
            return $this->httpError(400, "Invalid file");
978
        }
979
        if (!$file->canDelete()) {
980
            return $this->httpError(400, "Cannot delete file");
981
        }
982
        $file->delete();
983
        $response = new HTTPResponse('', 200);
984
        return $response;
985
    }
986
987
    /**
988
     * Clear temp folder that should not contain any file other than temporary
989
     *
990
     * @param boolean $doDelete Set to true to actually delete the files, otherwise it's just a dry-run
991
     * @param int $limit
992
     * @return File[] List of files removed
993
     */
994
    public static function clearTemporaryUploads($doDelete = false, $limit = 0)
995
    {
996
        $tempFiles = File::get()->filter('IsTemporary', true);
997
        if ($limit) {
998
            $tempFiles = $tempFiles->limit($limit);
999
        }
1000
1001
        $threshold = self::config()->auto_clear_threshold;
1002
1003
        // Set a default threshold if none set
1004
        if (!$threshold) {
1005
            if (Director::isDev()) {
1006
                $threshold = '-10 minutes';
1007
            } else {
1008
                $threshold = '-1 day';
1009
            }
1010
        }
1011
        if (is_int($threshold)) {
1012
            $thresholdTime = time() - $threshold;
1013
        } else {
1014
            $thresholdTime = strtotime($threshold);
1015
        }
1016
1017
        // Update query to avoid fetching unecessary records
1018
        $tempFiles = $tempFiles->filter("Created:LessThan", date('Y-m-d H:i:s', $thresholdTime));
1019
1020
        $filesDeleted = [];
1021
        foreach ($tempFiles as $tempFile) {
1022
            $createdTime = strtotime($tempFile->Created);
1023
            if ($createdTime < $thresholdTime) {
1024
                $filesDeleted[] = $tempFile;
1025
                if ($doDelete) {
1026
                    if ($tempFile->hasExtension(Versioned::class)) {
1027
                        $tempFile->deleteFromStage(Versioned::LIVE);
1028
                        $tempFile->deleteFromStage(Versioned::DRAFT);
1029
                    } else {
1030
                        $tempFile->delete();
1031
                    }
1032
                }
1033
            }
1034
        }
1035
        return $filesDeleted;
1036
    }
1037
1038
    /**
1039
     * Allows tracking uploaded ids to prevent unauthorized attachements
1040
     *
1041
     * @param int $fileId
1042
     * @return void
1043
     */
1044
    public function trackFileID($fileId)
1045
    {
1046
        $session = $this->getRequest()->getSession();
1047
        $uploadedIDs = $this->getTrackedIDs();
1048
        if (!in_array($fileId, $uploadedIDs)) {
1049
            $uploadedIDs[] = $fileId;
1050
        }
1051
        $session->set('FilePond', $uploadedIDs);
1052
    }
1053
1054
    /**
1055
     * Get all authorized tracked ids
1056
     * @return array
1057
     */
1058
    public function getTrackedIDs()
1059
    {
1060
        $session = $this->getRequest()->getSession();
1061
        $uploadedIDs = $session->get('FilePond');
1062
        if ($uploadedIDs) {
1063
            return $uploadedIDs;
1064
        }
1065
        return [];
1066
    }
1067
1068
    public function saveInto(DataObjectInterface $record)
1069
    {
1070
        // Note that the list of IDs is based on the value sent by the user
1071
        // It can be spoofed because checks are minimal (by default, canView = true and only check if isInDB)
1072
        $IDs = $this->getItemIDs();
1073
1074
        $Member = Security::getCurrentUser();
1075
1076
        // Ensure the files saved into the DataObject have been tracked (either because already on the DataObject or uploaded by the user)
1077
        $trackedIDs = $this->getTrackedIDs();
1078
        foreach ($IDs as $ID) {
1079
            if (!in_array($ID, $trackedIDs)) {
1080
                throw new ValidationException("Invalid file ID : $ID");
1081
            }
1082
        }
1083
1084
        // Move files out of temporary folder
1085
        foreach ($IDs as $ID) {
1086
            $file = $this->getFileByID($ID);
1087
            if ($file && $file->IsTemporary) {
1088
                // The record does not have an ID which is a bad idea to attach the file to it
1089
                if (!$record->ID) {
1090
                    $record->write();
1091
                }
1092
                // Check if the member is owner
1093
                if ($Member && $Member->ID != $file->OwnerID) {
1094
                    throw new ValidationException("Failed to authenticate owner");
1095
                }
1096
                $file->IsTemporary = false;
1097
                $file->ObjectID = $record->ID;
1098
                $file->ObjectClass = get_class($record);
1099
                $file->write();
1100
            } else {
1101
                // File was uploaded earlier, no need to do anything
1102
            }
1103
        }
1104
1105
        // Proceed
1106
        return parent::saveInto($record);
1107
    }
1108
1109
    public function Type()
1110
    {
1111
        return 'filepond';
1112
    }
1113
}
1114