-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
Dbafs.php
842 lines (703 loc) · 20.2 KB
/
Dbafs.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
<?php
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao;
use Contao\Filter\SyncExclude;
use Contao\Model\Collection;
/**
* Handles the database assisted file system (DBAFS)
*
* The class provides static methods to add, move, copy and delete resources as
* well as a method to synchronize the file system and the database.
*
* Usage:
*
* $file = Dbafs::addResource('files/james-wilson.jpg');
*
* @author Leo Feyer <https://github.com/leofeyer>
*/
class Dbafs
{
/**
* Synchronize the database
* @var array
*/
protected static $arrShouldBeSynchronized = array();
/**
* Adds a file or folder with its parent folders
*
* @param string $strResource The path to the file or folder
* @param boolean $blnUpdateFolders If true, the parent folders will be updated
*
* @return FilesModel The files model
*
* @throws \Exception If a parent ID entry is missing
* @throws \InvalidArgumentException If the resource is outside the upload folder
*/
public static function addResource($strResource, $blnUpdateFolders=true)
{
$strUploadPath = Config::get('uploadPath') . '/';
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
// Remove trailing slashes (see #5707)
if (substr($strResource, -1) == '/')
{
$strResource = substr($strResource, 0, -1);
}
// Normalize the path (see #6034)
$strResource = str_replace(array('\\', '//'), '/', $strResource);
// The resource does not exist or lies outside the upload directory
if ($strResource == '' || !file_exists($rootDir . '/' . $strResource) || strncmp($strResource, $strUploadPath, \strlen($strUploadPath)) !== 0)
{
throw new \InvalidArgumentException("Invalid resource $strResource");
}
$objModel = FilesModel::findByPath($strResource);
// Return the model if it exists already
if ($objModel !== null)
{
$objFile = ($objModel->type == 'folder') ? new Folder($objModel->path) : new File($objModel->path);
// Update the timestamp and file hash (see #4818, #7828)
if ($objModel->hash != $objFile->hash)
{
$objModel->tstamp = time();
$objModel->hash = $objFile->hash;
$objModel->save();
}
return $objModel;
}
$arrPaths = array();
$arrChunks = explode('/', $strResource);
$strPath = array_shift($arrChunks);
$arrPids = array($strPath => null);
$arrUpdate = array($strResource);
$objDatabase = Database::getInstance();
// Build the paths
while (\count($arrChunks))
{
$strPath .= '/' . array_shift($arrChunks);
$arrPaths[] = $strPath;
}
unset($arrChunks);
$objModels = FilesModel::findMultipleByPaths($arrPaths);
// Unset the entries in $arrPaths if the DB entry exists
if ($objModels !== null)
{
while ($objModels->next())
{
if (($i = array_search($objModels->path, $arrPaths)) !== false)
{
unset($arrPaths[$i]);
$arrPids[$objModels->path] = $objModels->uuid;
}
}
}
$arrPaths = array_values($arrPaths);
// If the resource is a folder, also add its contents
if (is_dir($rootDir . '/' . $strResource))
{
/** @var \SplFileInfo[] $objFiles */
$objFiles = new \RecursiveIteratorIterator(
new SyncExclude(
new \RecursiveDirectoryIterator(
$rootDir . '/' . $strResource,
\FilesystemIterator::UNIX_PATHS|\FilesystemIterator::FOLLOW_SYMLINKS|\FilesystemIterator::SKIP_DOTS
)
),
\RecursiveIteratorIterator::SELF_FIRST
);
// Add the relative path
foreach ($objFiles as $objFile)
{
$strRelpath = StringUtil::stripRootDir($objFile->getPathname());
if ($objFile->isDir())
{
$arrUpdate[] = $strRelpath;
}
$arrPaths[] = $strRelpath;
}
}
$objReturn = null;
// Create the new resources
foreach ($arrPaths as $strPath)
{
if (\in_array(basename($strPath), array('.public', '.nosync')))
{
continue;
}
$strParent = \dirname($strPath);
// The parent ID should be in $arrPids
// Do not use isset() here, because the PID can be null
if (\array_key_exists($strParent, $arrPids))
{
$strPid = $arrPids[$strParent];
}
else
{
throw new \Exception("No parent entry for $strParent");
}
// Create the file or folder
if (is_file($rootDir . '/' . $strPath))
{
$objFile = new File($strPath);
$objModel = new FilesModel();
$objModel->pid = $strPid;
$objModel->tstamp = time();
$objModel->name = $objFile->name;
$objModel->type = 'file';
$objModel->path = $objFile->path;
$objModel->extension = $objFile->extension;
$objModel->hash = $objFile->hash;
$objModel->uuid = $objDatabase->getUuid();
$objModel->save();
$arrPids[$objFile->path] = $objModel->uuid;
}
else
{
$objFolder = new Folder($strPath);
$objModel = new FilesModel();
$objModel->pid = $strPid;
$objModel->tstamp = time();
$objModel->name = $objFolder->name;
$objModel->type = 'folder';
$objModel->path = $objFolder->path;
$objModel->extension = '';
$objModel->uuid = $objDatabase->getUuid();
$objModel->save();
$arrPids[$objFolder->path] = $objModel->uuid;
}
// Store the model to be returned (see #5979)
if ($objModel->path == $strResource)
{
$objReturn = $objModel;
}
}
// Update the folder hashes from bottom up after all file hashes are set
foreach (array_reverse($arrPaths) as $strPath)
{
if (is_dir($rootDir . '/' . $strPath))
{
$objModel = FilesModel::findByPath($strPath);
$objModel->hash = static::getFolderHash($strPath);
$objModel->save();
}
}
// Update the folder hashes
if ($blnUpdateFolders)
{
static::updateFolderHashes($arrUpdate);
}
return $objReturn;
}
/**
* Moves a file or folder to a new location
*
* @param string $strSource The source path
* @param string $strDestination The target path
*
* @return FilesModel The files model
*/
public static function moveResource($strSource, $strDestination)
{
$objFile = FilesModel::findByPath($strSource);
// If there is no entry, directly add the destination
if ($objFile === null)
{
$objFile = static::addResource($strDestination);
}
$strFolder = \dirname($strDestination);
// Set the new parent ID
if ($strFolder == Config::get('uploadPath'))
{
$objFile->pid = null;
}
else
{
$objFolder = FilesModel::findByPath($strFolder);
if ($objFolder === null)
{
$objFolder = static::addResource($strFolder);
}
$objFile->pid = $objFolder->uuid;
}
// Save the resource
$objFile->path = $strDestination;
$objFile->name = basename($strDestination);
$objFile->save();
// Update all child records
if ($objFile->type == 'folder')
{
$objFiles = FilesModel::findMultipleByBasepath($strSource . '/');
if ($objFiles !== null)
{
while ($objFiles->next())
{
$objFiles->path = preg_replace('@^' . preg_quote($strSource, '@') . '/@', $strDestination . '/', $objFiles->path);
$objFiles->save();
}
}
}
// Update the MD5 hash of the parent folders
if (($strPath = \dirname($strSource)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
if (($strPath = \dirname($strDestination)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
return $objFile;
}
/**
* Copies a file or folder to a new location
*
* @param string $strSource The source path
* @param string $strDestination The target path
*
* @return FilesModel The files model
*/
public static function copyResource($strSource, $strDestination)
{
$objDatabase = Database::getInstance();
$objFile = FilesModel::findByPath($strSource);
// Add the source entry
if ($objFile === null)
{
$objFile = static::addResource($strSource);
}
$strFolder = \dirname($strDestination);
/** @var FilesModel $objNewFile */
$objNewFile = clone $objFile->current();
// Set the new parent ID
if ($strFolder == Config::get('uploadPath'))
{
$objNewFile->pid = null;
}
else
{
$objFolder = FilesModel::findByPath($strFolder);
if ($objFolder === null)
{
$objFolder = static::addResource($strFolder);
}
$objNewFile->pid = $objFolder->uuid;
}
// Save the resource
$objNewFile->tstamp = time();
$objNewFile->uuid = $objDatabase->getUuid();
$objNewFile->path = $strDestination;
$objNewFile->name = basename($strDestination);
$objNewFile->save();
// Update all child records
if ($objFile->type == 'folder')
{
$objFiles = FilesModel::findMultipleByBasepath($strSource . '/');
if ($objFiles !== null)
{
while ($objFiles->next())
{
/** @var FilesModel $objNew */
$objNew = clone $objFiles->current();
$objNew->pid = $objNewFile->uuid;
$objNew->tstamp = time();
$objNew->uuid = $objDatabase->getUuid();
$objNew->path = str_replace($strSource . '/', $strDestination . '/', $objFiles->path);
$objNew->save();
}
}
}
// Update the MD5 hash of the parent folders
if (($strPath = \dirname($strSource)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
if (($strPath = \dirname($strDestination)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
return $objNewFile;
}
/**
* Removes a file or folder
*
* @param string $strResource The path to the file or folder
*/
public static function deleteResource($strResource)
{
$objModel = FilesModel::findByPath($strResource);
// Remove the resource
if ($objModel !== null)
{
$objModel->delete();
}
// Look for subfolders and files
$objFiles = FilesModel::findMultipleByBasepath($strResource . '/');
// Remove subfolders and files as well
if ($objFiles !== null)
{
while ($objFiles->next())
{
$objFiles->delete();
}
}
static::updateFolderHashes(\dirname($strResource));
return null;
}
/**
* Update the hashes of all parent folders of a resource
*
* @param mixed $varResource A path or an array of paths to update
*/
public static function updateFolderHashes($varResource)
{
$arrPaths = array();
if (!\is_array($varResource))
{
$varResource = array($varResource);
}
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
foreach ($varResource as $strResource)
{
$arrChunks = explode('/', $strResource);
$strPath = array_shift($arrChunks);
// Do not check files
if (is_file($rootDir . '/' . $strResource))
{
array_pop($arrChunks);
}
// Build the paths
while (\count($arrChunks))
{
$strPath .= '/' . array_shift($arrChunks);
$arrPaths[] = $strPath;
}
unset($arrChunks);
}
$arrPaths = array_values(array_unique($arrPaths));
// Store the hash of each folder
foreach (array_reverse($arrPaths) as $strPath)
{
$objModel = FilesModel::findByPath($strPath);
// The DB entry does not yet exist
if ($objModel === null)
{
$objModel = static::addResource($strPath, false);
}
$objModel->hash = static::getFolderHash($strPath);
$objModel->save();
}
}
/**
* Synchronize the file system with the database
*
* @return string The path to the synchronization log file
*
* @throws \Exception If a parent ID entry is missing
*/
public static function syncFiles()
{
@ini_set('max_execution_time', 0);
// Consider the suhosin.memory_limit (see #7035)
if (\extension_loaded('suhosin'))
{
if (($limit = ini_get('suhosin.memory_limit')) !== '')
{
@ini_set('memory_limit', $limit);
}
}
else
{
@ini_set('memory_limit', -1);
}
$objDatabase = Database::getInstance();
// Begin atomic database access
$objDatabase->lockTables(array('tl_files'=>'WRITE'));
$objDatabase->beginTransaction();
// Reset the "found" flag
$objDatabase->query("UPDATE tl_files SET found=''");
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
/** @var \SplFileInfo[] $objFiles */
$objFiles = new \RecursiveIteratorIterator(
new SyncExclude(
new \RecursiveDirectoryIterator(
$rootDir . '/' . Config::get('uploadPath'),
\FilesystemIterator::UNIX_PATHS|\FilesystemIterator::FOLLOW_SYMLINKS|\FilesystemIterator::SKIP_DOTS
)
),
\RecursiveIteratorIterator::SELF_FIRST
);
$strLog = 'system/tmp/' . md5(uniqid(mt_rand(), true));
// Open the log file
$objLog = new File($strLog);
$objLog->truncate();
$arrModels = array();
$arrFoldersToHash = array();
$arrFoldersToCompare = array();
// Create or update the database entries
foreach ($objFiles as $objFile)
{
$strRelpath = StringUtil::stripRootDir($objFile->getPathname());
// Get all subfiles in a single query
if ($objFile->isDir())
{
$objSubfiles = FilesModel::findMultipleFilesByFolder($strRelpath);
if ($objSubfiles !== null)
{
while ($objSubfiles->next())
{
$arrModels[$objSubfiles->path] = $objSubfiles->current();
}
}
}
/** @var Model $objModel */
$objModel = $arrModels[$strRelpath] ?? FilesModel::findByPath($strRelpath);
if ($objModel === null)
{
// Add a log entry
$objLog->append("[Added] $strRelpath");
// Get the parent folder
$strParent = \dirname($strRelpath);
// Get the parent ID
if ($strParent == Config::get('uploadPath'))
{
$strPid = null;
}
else
{
$objParent = FilesModel::findByPath($strParent);
if ($objParent === null)
{
throw new \Exception("No parent entry for $strParent");
}
$strPid = $objParent->uuid;
}
// Create the file or folder
if (is_file($rootDir . '/' . $strRelpath))
{
$objFile = new File($strRelpath);
$objModel = new FilesModel();
$objModel->pid = $strPid;
$objModel->tstamp = time();
$objModel->name = $objFile->name;
$objModel->type = 'file';
$objModel->path = $objFile->path;
$objModel->extension = $objFile->extension;
$objModel->found = 2;
$objModel->hash = $objFile->hash;
$objModel->uuid = $objDatabase->getUuid();
$objModel->save();
}
else
{
$objFolder = new Folder($strRelpath);
$objModel = new FilesModel();
$objModel->pid = $strPid;
$objModel->tstamp = time();
$objModel->name = $objFolder->name;
$objModel->type = 'folder';
$objModel->path = $objFolder->path;
$objModel->extension = '';
$objModel->found = 2;
$objModel->uuid = $objDatabase->getUuid();
$objModel->save();
$arrFoldersToHash[] = $strRelpath;
}
}
elseif ($objFile->isDir())
{
$arrFoldersToCompare[] = $objModel;
}
else
{
// Check whether the MD5 hash has changed
$strHash = (new File($strRelpath))->hash;
$strType = ($objModel->hash != $strHash) ? 'Changed' : 'Unchanged';
// Add a log entry
$objLog->append("[$strType] $strRelpath");
// Update the record
$objModel->found = 1;
$objModel->hash = $strHash;
$objModel->save();
}
}
// Update the folder hashes from bottom up after all file hashes are set
foreach (array_reverse($arrFoldersToHash) as $strPath)
{
$objModel = FilesModel::findByPath($strPath);
$objModel->hash = static::getFolderHash($strPath);
$objModel->save();
}
// Compare the folders after all hashes are set
foreach (array_reverse($arrFoldersToCompare) as $objModel)
{
// Check whether the MD5 hash has changed
$strHash = static::getFolderHash($objModel->path);
$strType = ($objModel->hash != $strHash) ? 'Changed' : 'Unchanged';
// Add a log entry
$objLog->append("[$strType] {$objModel->path}");
// Update the record
$objModel->found = 1;
$objModel->hash = $strHash;
$objModel->save();
}
// Check for left-over entries in the DB
$objFiles = FilesModel::findByFound('');
if ($objFiles !== null)
{
$arrMapped = array();
$arrPidUpdate = array();
/** @var Collection|FilesModel $objFiles */
while ($objFiles->next())
{
$objFound = FilesModel::findBy(array('hash=?', 'found=2'), $objFiles->hash);
if ($objFound !== null)
{
// Check for matching file names if the result is ambiguous (see #5644)
if ($objFound->count() > 1)
{
while ($objFound->next())
{
if ($objFound->name == $objFiles->name)
{
$objFound = $objFound->current();
break;
}
}
}
// If another file has been mapped already, delete the entry (see #6008)
if (\in_array($objFound->path, $arrMapped))
{
$objLog->append("[Deleted] {$objFiles->path}");
$objFiles->delete();
continue;
}
$arrMapped[] = $objFound->path;
// Store the PID change
if ($objFiles->type == 'folder')
{
$arrPidUpdate[$objFound->uuid] = $objFiles->uuid;
}
// Add a log entry BEFORE changing the object
$objLog->append("[Moved] {$objFiles->path} to {$objFound->path}");
// Update the original entry
$objFiles->pid = $objFound->pid;
$objFiles->tstamp = $objFound->tstamp;
$objFiles->name = $objFound->name;
$objFiles->type = $objFound->type;
$objFiles->path = $objFound->path;
$objFiles->found = 1;
// Delete the newer (duplicate) entry
$objFound->delete();
// Then save the modified original entry (prevents duplicate key errors)
$objFiles->save();
}
else
{
// Add a log entry BEFORE changing the object
$objLog->append("[Deleted] {$objFiles->path}");
// Delete the entry if the resource has gone
$objFiles->delete();
}
}
// Update the PID of the child records
if (!empty($arrPidUpdate))
{
foreach ($arrPidUpdate as $from=>$to)
{
$objChildren = FilesModel::findByPid($from);
if ($objChildren !== null)
{
while ($objChildren->next())
{
$objChildren->pid = $to;
$objChildren->save();
}
}
}
}
}
// Close the log file
$objLog->close();
// Reset the found flag
$objDatabase->query("UPDATE tl_files SET found=1 WHERE found=2");
// Finalize database access
$objDatabase->commitTransaction();
$objDatabase->unlockTables();
// Return the path to the log file
return $strLog;
}
/**
* Get the folder hash from the databse by combining the hashes of all children
*
* @param string $strPath The relative path
*
* @return string MD5 hash
*/
public static function getFolderHash($strPath)
{
$strPath = str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $strPath);
$arrHash = array();
$objChildren = Database::getInstance()
->prepare("SELECT hash, name FROM tl_files WHERE path LIKE ? AND path NOT LIKE ? ORDER BY name")
->execute($strPath . '/%', $strPath . '/%/%')
;
if ($objChildren !== null)
{
while ($objChildren->next())
{
$arrHash[] = $objChildren->hash . $objChildren->name;
}
}
return md5(implode("\0", $arrHash));
}
/**
* Check if the current resource should be synchronized with the database
*
* @param string $strPath The relative path
*
* @return bool True if the current resource needs to be synchronized with the database
*/
public static function shouldBeSynchronized($strPath)
{
if (!isset(static::$arrShouldBeSynchronized[$strPath]) || !\is_bool(static::$arrShouldBeSynchronized[$strPath]))
{
static::$arrShouldBeSynchronized[$strPath] = !static::isFileSyncExclude($strPath);
}
return static::$arrShouldBeSynchronized[$strPath];
}
/**
* Check if a file or folder is excluded from synchronization
*
* @param string $strPath The relative path
*
* @return bool True if the file or folder is excluded from synchronization
*/
protected static function isFileSyncExclude($strPath)
{
if (Config::get('uploadPath') == 'templates')
{
return true;
}
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
// Look for an existing parent folder (see #410)
while ($strPath != '.' && !is_dir($rootDir . '/' . $strPath))
{
$strPath = \dirname($strPath);
}
if ($strPath == '.')
{
return true;
}
$uploadPath = System::getContainer()->getParameter('contao.upload_path');
// Outside the files directory
if (strncmp($strPath . '/', $uploadPath . '/', \strlen($uploadPath) + 1) !== 0)
{
return true;
}
return (new Folder($strPath))->isUnsynchronized();
}
}
class_alias(Dbafs::class, 'Dbafs');