Total Complexity | 46 |
Total Lines | 532 |
Duplicated Lines | 0 % |
Changes | 4 | ||
Bugs | 1 | Features | 0 |
Complex classes like RecoverUploadLocationsHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use RecoverUploadLocationsHelper, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
37 | class RecoverUploadLocationsHelper |
||
38 | { |
||
39 | use Injectable; |
||
40 | use Configurable; |
||
41 | |||
42 | private static $dependencies = [ |
||
|
|||
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) { |
||
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) { |
||
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) { |
||
253 | $draft = Versioned::get_version(File::class, $fileId, $draftVersion); |
||
254 | } else { |
||
255 | $draft = null; |
||
256 | } |
||
257 | |||
258 | if ($liveVersion) { |
||
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()) { |
||
338 | // Find if another file record refer to the same physical location |
||
339 | $another = Versioned::get_by_stage(File::class, Versioned::LIVE, [ |
||
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 |
||
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; |
||
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() |
||
557 | ; |
||
558 | } |
||
559 | |||
560 | /** |
||
561 | * Returns DataList object containing every |
||
562 | * uploaded file record |
||
563 | * |
||
564 | * @return DataList |
||
565 | */ |
||
566 | private function getCountQuery() |
||
569 | } |
||
570 | } |
||
571 |