* Restores files from Trash based on an array of trash file identifiers. * * @param array $trashFiles An array of trash file names (i.e. the 'trashName' fields). * @return array An associative array with keys "restored" (an array of successfully restored items) * and optionally an "error" message if any issues occurred. */
(array $trashFiles)
| 3186 | * and optionally an "error" message if any issues occurred. |
| 3187 | */ |
| 3188 | public static function restoreFiles(array $trashFiles) |
| 3189 | { |
| 3190 | $errors = []; |
| 3191 | $restoredItems = []; |
| 3192 | $storage = self::storage(); |
| 3193 | |
| 3194 | // Setup Trash directory and trash metadata file. |
| 3195 | $trashDir = rtrim(self::trashRoot(), '/\\') . DIRECTORY_SEPARATOR; |
| 3196 | if ($storage->stat($trashDir) === null) { |
| 3197 | $storage->mkdir($trashDir, 0755, true); |
| 3198 | } |
| 3199 | $trashMetadataFile = $trashDir . "trash.json"; |
| 3200 | $trashData = []; |
| 3201 | $trashJson = $storage->read($trashMetadataFile); |
| 3202 | if ($trashJson !== false) { |
| 3203 | $trashData = json_decode($trashJson, true); |
| 3204 | } |
| 3205 | if (!is_array($trashData)) { |
| 3206 | $trashData = []; |
| 3207 | } |
| 3208 | |
| 3209 | // Helper to get metadata file path for a folder. |
| 3210 | $getMetadataFilePath = static fn($folder): string => self::getMetadataFilePath((string)$folder); |
| 3211 | |
| 3212 | // Process each provided trash file name. |
| 3213 | foreach ($trashFiles as $trashFileName) { |
| 3214 | $trashFileName = trim($trashFileName); |
| 3215 | // Validate file name with REGEX_FILE_NAME. |
| 3216 | if (!preg_match(REGEX_FILE_NAME, $trashFileName)) { |
| 3217 | $errors[] = "$trashFileName has an invalid format."; |
| 3218 | continue; |
| 3219 | } |
| 3220 | |
| 3221 | // Locate the matching trash record. |
| 3222 | $recordKey = null; |
| 3223 | foreach ($trashData as $key => $record) { |
| 3224 | if (isset($record['trashName']) && $record['trashName'] === $trashFileName) { |
| 3225 | $recordKey = $key; |
| 3226 | break; |
| 3227 | } |
| 3228 | } |
| 3229 | if ($recordKey === null) { |
| 3230 | $errors[] = "No trash record found for $trashFileName."; |
| 3231 | continue; |
| 3232 | } |
| 3233 | |
| 3234 | $record = $trashData[$recordKey]; |
| 3235 | if (!isset($record['originalFolder']) || !isset($record['originalName'])) { |
| 3236 | $errors[] = "Incomplete trash record for $trashFileName."; |
| 3237 | continue; |
| 3238 | } |
| 3239 | $originalFolder = $record['originalFolder']; |
| 3240 | $originalName = $record['originalName']; |
| 3241 | |
| 3242 | // Convert absolute original folder to relative folder. |
| 3243 | $relativeFolder = 'root'; |
| 3244 | $root = rtrim(self::uploadRoot(), '/\\') . DIRECTORY_SEPARATOR; |
| 3245 | if (strpos($originalFolder, $root) === 0) { |
no test coverage detected