RecoverUploadLocationsHelper::getQuery()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 58
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 43
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 58
rs 9.232

How to fix   Long Method   

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 SilverStripe\UserForms\Task;
4
5
use Psr\Log\LoggerInterface;
6
use Psr\Log\NullLogger;
7
use RuntimeException;
8
use SilverStripe\Assets\File;
9
use SilverStripe\Assets\Folder;
10
use SilverStripe\Core\Config\Configurable;
11
use SilverStripe\Core\Convert;
12
use SilverStripe\Core\Environment;
13
use SilverStripe\Core\Injector\Injector;
14
use SilverStripe\Core\Injector\Injectable;
15
use SilverStripe\ORM\DataObject;
16
use SilverStripe\ORM\Queries\SQLSelect;
17
use SilverStripe\Security\InheritedPermissions;
18
use SilverStripe\UserForms\Model\EditableFormField;
19
use SilverStripe\UserForms\Model\EditableFormField\EditableFileField;
20
use SilverStripe\UserForms\Model\Submission\SubmittedForm;
21
use SilverStripe\UserForms\Model\Submission\SubmittedFormField;
22
use SilverStripe\UserForms\Model\Submission\SubmittedFileField;
23
use SilverStripe\UserForms\Model\UserDefinedForm;
24
use SilverStripe\Versioned\Versioned;
25
26
/**
27
 * A helper to recover the UserForm uploads targeting folders incorrectly migrated from Silverstripe CMS 3
28
 *
29
 * In short, the migrated folders do not have Live version records in the database, as such
30
 * all the files uploaded through UserForms EditableFileField end up in a default fallback folder (/Uploads by default)
31
 *
32
 * If your project has not been migrated from Silverstripe CMS 3, you do not need this helper.
33
 * For more details see CVE-2020-9280
34
 *
35
 * @internal This class is not a part of Silverstripe CMS public API
36
 */
37
class RecoverUploadLocationsHelper
38
{
39
    use Injectable;
40
    use Configurable;
41
42
    private static $dependencies = [
0 ignored issues
show
introduced by
The private property $dependencies is not used, and could be removed.
Loading history...
43
        'logger' => '%$' . LoggerInterface::class . '.quiet',
44
    ];
45
46
    /**
47
     * @var LoggerInterface
48
     */
49
    private $logger;
50
51
    /**
52
     * @var Versioned
53
     */
54
    private $versionedExtension;
55
56
    /**
57
     * Whether File class has Versioned extension installed
58
     *
59
     * @var bool
60
     */
61
    private $filesVersioned;
62
63
    /**
64
     * Cache of the EditableFileField versions
65
     *
66
     * @var EditableFileField
67
     */
68
    private $fieldFolderCache = array();
69
70
    public function __construct()
71
    {
72
        $this->logger = new NullLogger();
73
74
        // Set up things before going into the loop
75
        $this->versionedExtension = Injector::inst()->get(Versioned::class);
76
        $this->filesVersioned = $this->versionedExtension->canBeVersioned(File::class);
77
    }
78
79
    /**
80
     * @param LoggerInterface $logger
81
     * @return $this
82
     */
83
    public function setLogger(LoggerInterface $logger)
84
    {
85
        $this->logger = $logger;
86
        return $this;
87
    }
88
89
    /**
90
     * Process the UserForm uplodas
91
     *
92
     * @return int Number of files processed
93
     */
94
    public function run()
95
    {
96
        // Set max time and memory limit
97
        Environment::increaseTimeLimitTo();
98
        Environment::setMemoryLimitMax(-1);
99
        Environment::increaseMemoryLimitTo(-1);
100
101
        $this->logger->notice('Begin UserForm uploaded files destination folders recovery');
102
103
        if (!class_exists(Versioned::class)) {
104
            $this->logger->warning('Versioned extension is not installed. Skipping recovery.');
105
            return 0;
106
        }
107
108
        if (!$this->versionedExtension->canBeVersioned(UserDefinedForm::class)) {
109
            $this->logger->warning('Versioned extension is not set up for UserForms. Skipping recovery.');
110
            return 0;
111
        }
112
113
        return $this->process();
114
    }
115
116
    /**
117
     * Process all the files and return the number
118
     *
119
     * @return int Number of files processed
120
     */
121
    protected function process()
122
    {
123
        // Check if we have folders to migrate
124
        $totalCount = $this->getCountQuery()->count();
125
        if (!$totalCount) {
126
            $this->logger->warning('No UserForm uploads found');
127
            return 0;
128
        }
129
130
        $this->logger->notice(sprintf('Processing %d file records', $totalCount));
131
132
        $processedCount = 0;
133
        $recoveryCount = 0;
134
        $errorsCount = 0;
135
136
        // Loop over the files to process
137
        foreach ($this->chunk() as $uploadRecord) {
138
            ++$processedCount;
139
140
            $fileId = $uploadRecord['UploadedFileID'];
141
            $fieldId = $uploadRecord['FieldID'];
142
            $fieldVersion = $uploadRecord['FieldVersion'];
143
144
            try {
145
                $expectedFolderId = $this->getExpectedUploadFolderId($fieldId, $fieldVersion);
146
                if ($expectedFolderId == 0) {
147
                    $this->logger->warning(sprintf(
148
                        'The upload folder was not set for the file %d, SKIPPING',
149
                        $fileId
150
                    ));
151
                    continue;
152
                }
153
                $recoveryCount += $this->recover($fileId, $expectedFolderId);
154
            } catch (\Exception $e) {
155
                $this->logger->error(sprintf('Could not process the file: %d', $fileId), ['exception' => $e]);
156
                ++$errorsCount;
157
            }
158
        }
159
160
        // Show summary of results
161
        if ($processedCount > 0) {
162
            $this->logger->notice(sprintf('%d file records have been processed.', $processedCount));
163
            $this->logger->notice(sprintf('%d files recovered', $recoveryCount));
164
            $this->logger->notice(sprintf('%d errors', $errorsCount));
165
        } else {
166
            $this->logger->notice('No files found');
167
        }
168
169
        return $processedCount;
170
    }
171
172
    /**
173
     * Fetches the EditableFileField version from cache and returns its FolderID
174
     *
175
     * @param int $fieldId EditableFileField.ID
176
     * @param int EditableFileField Version
177
     *
178
     * @return int
179
     */
180
    protected function getExpectedUploadFolderId($fieldId, $fieldVersion)
181
    {
182
        // return if cache is warm
183
        if (isset($this->fieldFolderCache[$fieldId][$fieldVersion])) {
184
            return $this->fieldFolderCache[$fieldId][$fieldVersion]->FolderID;
185
        }
186
187
        // fetch the version
188
        $editableFileField = Versioned::get_version(EditableFileField::class, $fieldId, $fieldVersion);
189
190
        // populate the cache
191
        $this->fieldFolderCache[$fieldId][$fieldVersion] = $editableFileField;
192
193
        return $editableFileField->FolderID;
194
    }
195
196
    /**
197
     * Fetches a Folder by its ID, gracefully handling
198
     * deleted folders
199
     *
200
     * @param int $id Folder.ID
201
     *
202
     * @return Folder
203
     *
204
     * @throws RuntimeException when folder could not be found
205
     */
206
    protected function getFolder($id)
207
    {
208
        $folder = Folder::get()->byID($id);
209
210
        if (!$folder && $this->filesVersioned) {
0 ignored issues
show
introduced by
$folder is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
211
            // The folder might have been deleted, let's look up its latest version
212
            $folder = Versioned::get_latest_version(Folder::class, $id);
213
214
            if ($folder) {
215
                $this->logger->warning(sprintf('Restoring (as protected) a deleted folder: "%s"', $folder->Filename));
216
                if ($folder->CanViewType === InheritedPermissions::INHERIT) {
217
                    // enforce restored top level folders to be protected
218
                    $folder->CanViewType = InheritedPermissions::ONLY_THESE_USERS;
219
                }
220
221
                $folder->publishSingle();
222
            }
223
        }
224
225
        if (!$folder) {
0 ignored issues
show
introduced by
$folder is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
226
            throw new RuntimeException(sprintf('Could not fetch the folder with id "%d"', $id));
227
        }
228
229
        return $folder;
230
    }
231
232
    /**
233
     * Recover an uploaded file location
234
     *
235
     * @param int $fileId File.ID
236
     * @param int $expectedFolderId ID of the folder where the file should have end up
237
     *
238
     * @return int Number of files recovered
239
     */
240
    protected function recover($fileId, $expectedFolderId)
241
    {
242
        /* @var File */
243
        $draft = null;
244
245
        /* @var File */
246
        $live = null;
247
248
        if ($this->filesVersioned) {
249
            $draftVersion = Versioned::get_versionnumber_by_stage(File::class, Versioned::DRAFT, $fileId);
250
            $liveVersion = Versioned::get_versionnumber_by_stage(File::class, Versioned::LIVE, $fileId);
251
252
            if ($draftVersion && $draftVersion != $liveVersion) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $draftVersion of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
253
                $draft = Versioned::get_version(File::class, $fileId, $draftVersion);
254
            } else {
255
                $draft = null;
256
            }
257
258
            if ($liveVersion) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $liveVersion of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
259
                $live = Versioned::get_version(File::class, $fileId, $liveVersion);
260
            }
261
        } else {
262
            $live = File::get()->byID($fileId);
263
        }
264
265
        if (!$live) {
266
            $this->logger->notice(sprintf('Could not find file with id %d (perhaps it has been deleted)', $fileId));
267
            return 0;
268
        }
269
270
        // Check whether the file has been modified (moved) after the upload
271
        if ($live->Version > 1) {
272
            if ($live->ParentID != $expectedFolderId) {
273
                // The file was updated after upload (perhaps was moved)
274
                // We should assume that was intentional and do not process
275
                // it, but rather make a warning here
276
                $this->logger->notice(sprintf(
277
                    'The file was updated after initial upload, skipping! "%s"',
278
                    $live->getField('FileFilename')
279
                ));
280
            }
281
282
            // check for residual files in the original folder
283
            return $this->checkResidual($fileId, $live, $draft);
284
        }
285
286
        if ($live->ParentID == $expectedFolderId) {
287
            $this->logger->info(sprintf('OK: "%s"', $live->getField('FileFilename')));
288
            return 0;
289
        }
290
291
        $this->logger->warning(sprintf('Found a misplaced file: "%s"', $live->getField('FileFilename')));
292
293
        $expectedFolder = $this->getFolder($expectedFolderId);
294
295
        if ($draft) {
296
            return $this->recoverWithDraft($live, $draft, $expectedFolder);
297
        } else {
298
            return $this->recoverLiveOnly($live, $expectedFolder);
299
        }
300
    }
301
302
    /**
303
     * Handles gracefully a bug in UserForms that prevents
304
     * some uploaded files from being removed on the filesystem level
305
     * when manually moving them to another folder through CMS
306
     *
307
     * @see https://github.com/silverstripe/silverstripe-userforms/issues/944
308
     *
309
     * @param int $fileId File.ID
310
     * @param File $file The live version of the file
311
     * @param File|null $draft The draft version of the file
312
     *
313
     * @return int Number of files recovered
314
     */
315
    protected function checkResidual($fileId, File $file, File $draft = null)
316
    {
317
        if (!$this->filesVersioned) {
318
            return 0;
319
        }
320
321
        $upload = Versioned::get_version(File::class, $fileId, 1);
322
323
        if ($upload->ParentID == $file->ParentID) {
324
            // The file is published in the original folder, so we're good
325
            return 0;
326
        }
327
328
        if ($draft && $upload->ParentID == $draft->ParentID) {
329
            // The file draft is residing in the same folder where it
330
            // has been uploaded originally. It's under the draft's control now
331
            return 0;
332
        }
333
334
        $deleted = 0;
335
        $dbFile = $upload->File;
336
337
        if ($dbFile->exists()) {
0 ignored issues
show
Bug introduced by
The method exists() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

337
        if ($dbFile->/** @scrutinizer ignore-call */ exists()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
338
            // Find if another file record refer to the same physical location
339
            $another = Versioned::get_by_stage(File::class, Versioned::LIVE, [
0 ignored issues
show
Bug introduced by
array('"ID" != ?' => $fi..."' => $dbFile->Variant) of type array<string,integer|mixed> is incompatible with the type string expected by parameter $filter of SilverStripe\Versioned\Versioned::get_by_stage(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

339
            $another = Versioned::get_by_stage(File::class, Versioned::LIVE, /** @scrutinizer ignore-type */ [
Loading history...
340
                '"ID" != ?' => $fileId,
341
                '"FileFilename"' => $dbFile->Filename,
342
                '"FileHash"' => $dbFile->Hash,
343
                '"FileVariant"' => $dbFile->Variant
344
            ])->exists();
345
346
            // A lazy check for draft (no check if we already found live)
347
            $another = $another || Versioned::get_by_stage(File::class, Versioned::DRAFT, [
348
                '"ID" != ?' => $fileId,
349
                '"FileFilename"' => $dbFile->Filename,
350
                '"FileHash"' => $dbFile->Hash,
351
                '"FileVariant"' => $dbFile->Variant
352
            ])->exists();
353
354
            if (!$another) {
355
                $this->logger->warning(sprintf('Found a residual file on the filesystem, going to delete it: "%s"', $dbFile->Filename));
356
                if ($dbFile->deleteFile()) {
357
                    $this->logger->warning(sprintf('DELETE: "%s"', $dbFile->Filename));
358
                    ++$deleted;
359
                } else {
360
                    $this->logger->warning(sprintf('FAILED TO DELETE: "%s"', $dbFile->Filename));
361
                }
362
            }
363
        }
364
365
        return $deleted;
366
    }
367
368
    /**
369
     * Recover a file with only Live version (with no draft)
370
     *
371
     * @param File $file the file instance
372
     * @param int $expectedFolder The expected folder
373
     *
374
     * @return int How many files have been recovered
375
     */
376
    protected function recoverLiveOnly(File $file, Folder $expectedFolder)
377
    {
378
        $this->logger->warning(sprintf('MOVE: "%s" to %s', $file->Filename, $expectedFolder->Filename));
379
        return $this->moveFileToFolder($file, $expectedFolder);
380
    }
381
382
    /**
383
     * Recover a live version of the file preserving the draft
384
     *
385
     * @param File $live Live version of the file
386
     * @param File $draft Draft version of the file
387
     * @param Folder $expectedFolder The expected folder
388
     *
389
     * @return int How many files have been recovered
390
     */
391
    protected function recoverWithDraft(File $live, File $draft, Folder $expectedFolder)
392
    {
393
        $this->logger->warning(sprintf(
394
            'MOVE: "%s" to "%s", preserving draft "%s"',
395
            $live->Filename,
396
            $expectedFolder->Filename,
397
            $draft->Filename
398
        ));
399
400
        $result = $this->moveFileToFolder($live, $expectedFolder);
401
402
        // Restore the DB record of the draft deleted after publishing
403
        $draft->writeToStage(Versioned::DRAFT);
404
405
        // This hack makes it copy the file on the filesystem level.
406
        // The file under the Filename link of the draft has been removed
407
        // when we published the updated live version of the file.
408
        $draft->File->Filename = $live->File->Filename;
409
410
        // If the draft parent folder has been deleted (e.g. the draft file was alone there)
411
        // we explicitly restore it here, otherwise it
412
        // will be lost and saved in the root directory
413
        $draft->Parent = $this->getFolder($draft->ParentID);
414
415
        // Save the draft and copy over the file from the Live version
416
        // on the filesystem level
417
        $draft->write();
418
419
        return $result;
420
    }
421
422
    protected function moveFileToFolder(File $file, Folder $folder)
423
    {
424
        $file->Parent = $folder;
425
        $file->write();
426
        $file->publishSingle();
427
428
        return 1;
429
    }
430
431
    /**
432
     * Split queries into smaller chunks to avoid using too much memory
433
     * @param int $chunkSize
434
     * @return Generator
0 ignored issues
show
Bug introduced by
The type SilverStripe\UserForms\Task\Generator was not found. Did you mean Generator? If so, make sure to prefix the type with \.
Loading history...
435
     */
436
    private function chunk($chunkSize = 100)
437
    {
438
        $greaterThanID = 0;
439
440
        do {
441
            $count = 0;
442
443
            $chunk = $this->getQuery()
444
                ->setLimit($chunkSize)
445
                ->addWhere([
446
                    '"SubmittedFileFieldTable"."UploadedFileID" > ?' => $greaterThanID
447
                ])->execute();
448
449
            // TODO: Versioned::prepopulate_versionnumber_cache
450
451
            foreach ($chunk as $item) {
452
                yield $item;
0 ignored issues
show
Bug Best Practice introduced by
The expression yield $item returns the type Generator which is incompatible with the documented return type SilverStripe\UserForms\Task\Generator.
Loading history...
453
                $greaterThanID = $item['UploadedFileID'];
454
                ++$count;
455
            }
456
        } while ($count > 0);
457
    }
458
459
    /**
460
     * Returns SQLQuery instance
461
     *
462
select
463
    SubmittedFileField.UploadedFileID,
464
    EditableFileField_Versions.RecordID as FieldID,
465
    MAX(EditableFileField_Versions.Version) as FieldVersion
466
from
467
    SubmittedFileField
468
left join
469
    SubmittedFormField
470
on
471
    SubmittedFormField.ID = SubmittedFileField.ID
472
left join
473
    SubmittedForm
474
on
475
    SubmittedForm.ID = SubmittedFormField.ParentID
476
left join
477
    EditableFormField_Versions
478
on
479
    EditableFormField_Versions.ParentID = SubmittedForm.ParentID
480
and
481
    EditableFormField_Versions.Name = SubmittedFormField.Name
482
and
483
    EditableFormField_Versions.LastEdited < SubmittedForm.Created
484
inner join
485
    EditableFileField_Versions
486
on
487
    EditableFileField_Versions.RecordID = EditableFormField_Versions.RecordID
488
and
489
    EditableFileField_Versions.Version = EditableFormField_Versions.Version
490
where
491
    SubmittedFileField.UploadedFileID != 0
492
group by
493
    SubmittedFileField.UploadedFileID,
494
    EditableFileField_Versions.RecordID
495
order by
496
    SubmittedFileField.UploadedFileID
497
limit 100
498
     */
499
    private function getQuery()
500
    {
501
        $schema = DataObject::getSchema();
502
        $submittedFileFieldTable = $schema->tableName(SubmittedFileField::class);
503
        $submittedFormFieldTable = $schema->tableName(SubmittedFormField::class);
504
505
        $submittedFormTable = $schema->tableName(SubmittedForm::class);
506
507
        $editableFileFieldTable = $schema->tableName(EditableFileField::class);
508
        $editableFileFieldVersionsTable = sprintf('%s_Versions', $editableFileFieldTable);
509
510
        $editableFormFieldTable = $schema->tableName(EditableFormField::class);
511
        $editableFormFieldVersionsTable = sprintf('%s_Versions', $editableFormFieldTable);
512
513
        return SQLSelect::create()
514
            ->setSelect([
515
                '"SubmittedFileFieldTable"."UploadedFileID"',
516
                '"EditableFileFieldVersions"."RecordID" as "FieldID"',
517
                'MAX("EditableFileFieldVersions"."Version") as "FieldVersion"'
518
            ])
519
            ->setFrom(sprintf('%s as "SubmittedFileFieldTable"', Convert::symbol2sql($submittedFileFieldTable)))
520
            ->setWhere([
521
                '"SubmittedFileFieldTable"."UploadedFileID" != 0'
522
            ])
523
            ->setGroupBy([
524
                '"SubmittedFileFieldTable"."UploadedFileID"',
525
                '"EditableFileFieldVersions"."RecordID"'
526
            ])
527
            ->addLeftJoin(
528
                $submittedFormFieldTable,
529
                '"SubmittedFormFieldTable"."ID" = "SubmittedFileFieldTable"."ID"',
530
                'SubmittedFormFieldTable'
531
            )
532
            ->addLeftJoin(
533
                $submittedFormTable,
534
                '"SubmittedFormTable"."ID" = "SubmittedFormFieldTable"."ParentID"',
535
                'SubmittedFormTable'
536
            )
537
            ->addLeftJoin(
538
                $editableFormFieldVersionsTable,
539
                sprintf(
540
                    '%s AND %s AND %s',
541
                    '"EditableFormFieldVersions"."ParentID" = "SubmittedFormTable"."ParentID"',
542
                    '"EditableFormFieldVersions"."Name" = "SubmittedFormFieldTable"."Name"',
543
                    '"EditableFormFieldVersions"."LastEdited" < "SubmittedFormTable"."Created"'
544
                ),
545
                'EditableFormFieldVersions'
546
            )
547
            ->addInnerJoin(
548
                $editableFileFieldVersionsTable,
549
                sprintf(
550
                    '%s AND %s',
551
                    '"EditableFileFieldVersions"."RecordID" = "EditableFormFieldVersions"."RecordID"',
552
                    '"EditableFileFieldVersions"."Version" = "EditableFormFieldVersions"."Version"'
553
                ),
554
                'EditableFileFieldVersions'
555
            )
556
            ->addOrderBy('"SubmittedFileFieldTable"."UploadedFileID"', 'ASC')
557
        ;
558
    }
559
560
    /**
561
     * Returns DataList object containing every
562
     * uploaded file record
563
     *
564
     * @return DataList
0 ignored issues
show
Bug introduced by
The type SilverStripe\UserForms\Task\DataList was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
565
     */
566
    private function getCountQuery()
567
    {
568
        return SubmittedFileField::get()->filter(['UploadedFileID:NOT' => 0]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return SilverStripe\User...oadedFileID:NOT' => 0)) returns the type SilverStripe\ORM\DataList which is incompatible with the documented return type SilverStripe\UserForms\Task\DataList.
Loading history...
569
    }
570
}
571