BackupPathResolver.php
55 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Backup\Utils; |
| 4 | |
| 5 | use WPStaging\Backup\Service\BackupsFinder; |
| 6 | use WPStaging\Backup\WithBackupIdentifier; |
| 7 | |
| 8 | /** |
| 9 | * Utility for resolving backup file paths securely within the backups directory. |
| 10 | */ |
| 11 | class BackupPathResolver |
| 12 | { |
| 13 | use WithBackupIdentifier; |
| 14 | |
| 15 | /** |
| 16 | * @var BackupsFinder |
| 17 | */ |
| 18 | private $backupsFinder; |
| 19 | |
| 20 | /** |
| 21 | * @param BackupsFinder $backupsFinder |
| 22 | */ |
| 23 | public function __construct(BackupsFinder $backupsFinder) |
| 24 | { |
| 25 | $this->backupsFinder = $backupsFinder; |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Resolve a backup file path securely within the backups directory. |
| 30 | * |
| 31 | * @param string $filePath |
| 32 | * @return string Empty string if invalid, or the resolved path |
| 33 | */ |
| 34 | public function resolveBackupPath(string $filePath): string |
| 35 | { |
| 36 | $backupDir = wp_normalize_path($this->backupsFinder->getBackupsDirectory()); |
| 37 | $filePath = wp_normalize_path(untrailingslashit($filePath)); |
| 38 | |
| 39 | $resolvedPath = $backupDir . str_replace($backupDir, '', $filePath); |
| 40 | $resolvedPath = wp_normalize_path($resolvedPath); |
| 41 | |
| 42 | if (strpos($resolvedPath, $backupDir) !== 0) { |
| 43 | return ''; |
| 44 | } |
| 45 | |
| 46 | $basename = wp_basename($resolvedPath); |
| 47 | $extension = strtolower(pathinfo($basename, PATHINFO_EXTENSION)); |
| 48 | if (!in_array($extension, ['wpstg', 'sql'], true) && !$this->isBackupPart($basename)) { |
| 49 | return ''; |
| 50 | } |
| 51 | |
| 52 | return $resolvedPath; |
| 53 | } |
| 54 | } |
| 55 |