|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace OCA\Google\Service\Utils; |
| 4 | + |
| 5 | +use OCP\Files\EmptyFileNameException; |
| 6 | +use OCP\Files\FileNameTooLongException; |
| 7 | +use OCP\Files\InvalidCharacterInPathException; |
| 8 | +use OCP\Files\InvalidDirectoryException; |
| 9 | +use OCP\Files\ReservedWordException; |
| 10 | +use Psr\Container\ContainerExceptionInterface; |
| 11 | +use Psr\Container\NotFoundExceptionInterface; |
| 12 | +use Psr\Log\LoggerInterface; |
| 13 | + |
| 14 | +final class FileUtils { |
| 15 | + |
| 16 | + public function __construct( |
| 17 | + private \OCP\Files\IFilenameValidator $validator, |
| 18 | + private \OCP\IConfig $config, |
| 19 | + private LoggerInterface $logger, |
| 20 | + ) { |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Sanitize the filename to ensure it is valid, does not exceed length limits. |
| 25 | + * |
| 26 | + * @param string $filename The original filename to sanitize. |
| 27 | + * @param string $id A unique ID to append if necessary to ensure uniqueness. |
| 28 | + * @param int $recursionDepth The current recursion depth (used to prevent infinite loops). |
| 29 | + * @param string|null $originalFilename The original filename for logging. |
| 30 | + * @return string The sanitized and validated filename. |
| 31 | + */ |
| 32 | + public function sanitizeFilename( |
| 33 | + string $filename, |
| 34 | + string $id, |
| 35 | + int $recursionDepth = 0, |
| 36 | + ?string $originalFilename = null, |
| 37 | + ): string { |
| 38 | + if ($recursionDepth > 15) { |
| 39 | + $filename = 'Untitled_' . $id; |
| 40 | + $this->logger->warning('Maximum recursion depth reached while sanitizing filename: ' . ($originalFilename ?? $filename) . ' renaming to ' . $filename); |
| 41 | + return $filename; |
| 42 | + } |
| 43 | + |
| 44 | + if ($originalFilename === null) { |
| 45 | + $originalFilename = $filename; |
| 46 | + } |
| 47 | + |
| 48 | + // Use Nextcloud 32+ validator if available |
| 49 | + if (version_compare($this->config->getSystemValueString('version', '0.0.0'), '32.0.0', '>=')) { |
| 50 | + $this->logger->debug('Using Nextcloud 32+ filename validator for sanitization.'); |
| 51 | + try { |
| 52 | + return $this->validator->sanitizeFilename($filename); |
| 53 | + } catch (\InvalidArgumentException|NotFoundExceptionInterface|ContainerExceptionInterface $exception) { |
| 54 | + $this->logger->error('Unable to sanitize filename: ' . $filename, ['exception' => $exception]); |
| 55 | + return 'Untitled_' . $id; |
| 56 | + } |
| 57 | + } else { |
| 58 | + $this->logger->debug('Using legacy filename sanitization method.'); |
| 59 | + } |
| 60 | + |
| 61 | + // Trim whitespace and trailing dots |
| 62 | + $filename = rtrim(trim($filename), '.'); |
| 63 | + |
| 64 | + // Append ID if needed |
| 65 | + if ($originalFilename !== $filename && strpos($filename, $id) === false) { |
| 66 | + $filename = self::appendIdBeforeExtension($filename, $id); |
| 67 | + } |
| 68 | + |
| 69 | + // Enforce max length |
| 70 | + $maxLength = 254; |
| 71 | + if (mb_strlen($filename) > $maxLength) { |
| 72 | + $filename = self::truncateAndAppendId($filename, $id, $maxLength); |
| 73 | + } |
| 74 | + |
| 75 | + try { |
| 76 | + $this->validator->validateFilename($filename); |
| 77 | + if ($recursionDepth > 0) { |
| 78 | + $this->logger->info('Filename sanitized successfully: "' . $filename . '" (original: "' . $originalFilename . '")'); |
| 79 | + } |
| 80 | + return $filename; |
| 81 | + } catch (\Throwable $exception) { |
| 82 | + $this->logger->warning('Exception during filename validation: ' . $filename, ['exception' => $exception]); |
| 83 | + $filename = self::handleFilenameException($filename, $id, $exception, $this->logger); |
| 84 | + if (strpos($filename, $id) === false) { |
| 85 | + $filename = self::appendIdBeforeExtension($filename, $id); |
| 86 | + } |
| 87 | + return $this->sanitizeFilename($filename, $id, $recursionDepth + 1, $originalFilename); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + private static function appendIdBeforeExtension(string $filename, string $id): string { |
| 92 | + $pathInfo = pathinfo($filename); |
| 93 | + if (isset($pathInfo['extension'])) { |
| 94 | + return $pathInfo['filename'] . '_' . $id . '.' . $pathInfo['extension']; |
| 95 | + } |
| 96 | + return $filename . '_' . $id; |
| 97 | + } |
| 98 | + |
| 99 | + private static function truncateAndAppendId(string $filename, string $id, int $maxLength): string { |
| 100 | + $pathInfo = pathinfo($filename); |
| 101 | + $baseLength = $maxLength - mb_strlen($id) - 2; |
| 102 | + if (isset($pathInfo['extension'])) { |
| 103 | + $baseLength -= mb_strlen($pathInfo['extension']); |
| 104 | + return mb_substr($pathInfo['filename'], 0, $baseLength) . '_' . $id . '.' . $pathInfo['extension']; |
| 105 | + } |
| 106 | + return mb_substr($filename, 0, $baseLength) . '_' . $id; |
| 107 | + } |
| 108 | + |
| 109 | + private static function handleFilenameException(string $filename, string $id, \Throwable $exception, LoggerInterface $logger): string { |
| 110 | + if ($exception instanceof FileNameTooLongException) { |
| 111 | + return mb_substr($filename, 0, 254 - mb_strlen($id) - 2); |
| 112 | + } |
| 113 | + if ($exception instanceof EmptyFileNameException) { |
| 114 | + return 'Untitled'; |
| 115 | + } |
| 116 | + if ($exception instanceof InvalidCharacterInPathException) { |
| 117 | + if (preg_match('/"(.*?)"/', $exception->getMessage(), $matches)) { |
| 118 | + $invalidChars = array_merge(str_split($matches[1]), ['"']); |
| 119 | + return str_replace($invalidChars, '-', $filename); |
| 120 | + } |
| 121 | + } |
| 122 | + if ($exception instanceof InvalidDirectoryException) { |
| 123 | + $logger->error('Invalid directory detected in filename: ' . $exception->getMessage()); |
| 124 | + return 'Untitled'; |
| 125 | + } |
| 126 | + if ($exception instanceof ReservedWordException) { |
| 127 | + if (preg_match('/"(.*?)"/', $exception->getMessage(), $matches)) { |
| 128 | + $reservedWord = $matches[1]; |
| 129 | + return str_ireplace($reservedWord, '-' . $reservedWord . '-', $filename); |
| 130 | + } |
| 131 | + } |
| 132 | + $logger->error('Unknown exception encountered during filename sanitization: ' . $filename); |
| 133 | + return 'Untitled'; |
| 134 | + } |
| 135 | +} |
0 commit comments