diff --git a/src/install/sql/content.sql b/src/install/sql/content.sql index b2bbdec34..3ea6900de 100644 --- a/src/install/sql/content.sql +++ b/src/install/sql/content.sql @@ -303,7 +303,7 @@ LOCK TABLES `setting` WRITE; INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`) VALUES - (1,'last_patch','64',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), + (1,'last_patch','65',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), (2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (3,'company_email','support@yourcompany.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), diff --git a/src/install/sql/structure.sql b/src/install/sql/structure.sql index e4052bae5..c8ac68681 100644 --- a/src/install/sql/structure.sql +++ b/src/install/sql/structure.sql @@ -938,6 +938,7 @@ CREATE TABLE `service_downloadable` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `client_id` bigint(20) DEFAULT NULL, `filename` varchar(100) DEFAULT NULL, + `stored_filename` varchar(100) DEFAULT NULL, `downloads` int(11) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php index f0253c7e1..c3c9053d3 100644 --- a/src/library/FOSSBilling/UpdatePatcher.php +++ b/src/library/FOSSBilling/UpdatePatcher.php @@ -21,6 +21,7 @@ class UpdatePatcher implements InjectionAwareInterface { private ?\Pimple\Container $di = null; private readonly Filesystem $filesystem; + private array $downloadableStorageMigrationMap = []; public function __construct() { @@ -441,6 +442,7 @@ class UpdatePatcher implements InjectionAwareInterface 62 => 'patch62', 63 => 'patch63', 64 => 'patch64', + 65 => 'patch65', ]; ksort($patches, SORT_NATURAL); @@ -1388,6 +1390,133 @@ class UpdatePatcher implements InjectionAwareInterface ]); } + private function patch65(): void + { + if (!$this->tableHasColumn('service_downloadable', 'stored_filename')) { + $this->executeSql('ALTER TABLE `service_downloadable` ADD COLUMN `stored_filename` VARCHAR(100) DEFAULT NULL AFTER `filename`;'); + } + + $this->downloadableStorageMigrationMap = []; + $this->migrateDownloadableProductStorageKeys(); + $this->migrateDownloadableServiceStorageKeys(); + $this->migrateDownloadableOrderStorageKeys(); + } + + private function generateDownloadableStoredFilename(): string + { + do { + $storedFilename = bin2hex(random_bytes(32)); + $filePath = Path::join(PATH_UPLOADS, $storedFilename); + } while ($this->filesystem->exists($filePath)); + + return $storedFilename; + } + + private function copyLegacyDownloadableFile(string $filename): ?string + { + if (isset($this->downloadableStorageMigrationMap[$filename])) { + return $this->downloadableStorageMigrationMap[$filename]; + } + + $legacyPath = Path::join(PATH_UPLOADS, md5($filename)); + if (!$this->filesystem->exists($legacyPath)) { + return null; + } + + $storedFilename = $this->generateDownloadableStoredFilename(); + $this->filesystem->copy($legacyPath, Path::join(PATH_UPLOADS, $storedFilename)); + $this->downloadableStorageMigrationMap[$filename] = $storedFilename; + + return $storedFilename; + } + + private function migrateDownloadableProductStorageKeys(): void + { + $products = $this->fetchAll("SELECT id, config FROM product WHERE type = 'downloadable'"); + + foreach ($products as $product) { + $config = json_decode((string) $product['config'], true) ?: []; + if (!isset($config['filename']) || isset($config['stored_filename'])) { + continue; + } + + $storedFilename = $this->copyLegacyDownloadableFile((string) $config['filename']); + if ($storedFilename === null) { + continue; + } + + $config['stored_filename'] = $storedFilename; + $this->executeSql('UPDATE product SET config = :config, updated_at = :updated_at WHERE id = :id', [ + 'config' => json_encode($config), + 'updated_at' => date('Y-m-d H:i:s'), + 'id' => $product['id'], + ]); + } + } + + private function migrateDownloadableServiceStorageKeys(): void + { + $services = $this->fetchAll('SELECT sd.id, sd.filename, sd.stored_filename, co.id AS order_id, co.config AS order_config FROM service_downloadable sd LEFT JOIN client_order co ON sd.id = co.service_id WHERE sd.filename IS NOT NULL AND sd.filename != ""'); + + foreach ($services as $service) { + if (!empty($service['stored_filename'])) { + $storedFilename = (string) $service['stored_filename']; + } else { + $storedFilename = $this->copyLegacyDownloadableFile((string) $service['filename']); + if ($storedFilename === null) { + continue; + } + + $this->executeSql('UPDATE service_downloadable SET stored_filename = :stored_filename, updated_at = :updated_at WHERE id = :id', [ + 'stored_filename' => $storedFilename, + 'updated_at' => date('Y-m-d H:i:s'), + 'id' => $service['id'], + ]); + } + + if (empty($service['order_id'])) { + continue; + } + + $orderConfig = json_decode($service['order_config'] ?? '', true) ?: []; + if (isset($orderConfig['stored_filename'])) { + continue; + } + + $orderConfig['filename'] = $orderConfig['filename'] ?? $service['filename']; + $orderConfig['stored_filename'] = $storedFilename; + $this->executeSql('UPDATE client_order SET config = :config, updated_at = :updated_at WHERE id = :id', [ + 'config' => json_encode($orderConfig), + 'updated_at' => date('Y-m-d H:i:s'), + 'id' => $service['order_id'], + ]); + } + } + + private function migrateDownloadableOrderStorageKeys(): void + { + $orders = $this->fetchAll("SELECT id, config FROM client_order WHERE service_type = 'downloadable' AND config LIKE '%filename%'"); + + foreach ($orders as $order) { + $config = json_decode($order['config'] ?? '', true) ?: []; + if (!isset($config['filename']) || isset($config['stored_filename'])) { + continue; + } + + $storedFilename = $this->copyLegacyDownloadableFile((string) $config['filename']); + if ($storedFilename === null) { + continue; + } + + $config['stored_filename'] = $storedFilename; + $this->executeSql('UPDATE client_order SET config = :config, updated_at = :updated_at WHERE id = :id', [ + 'config' => json_encode($config), + 'updated_at' => date('Y-m-d H:i:s'), + 'id' => $order['id'], + ]); + } + } + private function migrateDefaultBrandingAssetsToPublicDirectory(): void { $settings = [ diff --git a/src/modules/Servicedownloadable/Service.php b/src/modules/Servicedownloadable/Service.php index 693edbd50..5aaf466a5 100644 --- a/src/modules/Servicedownloadable/Service.php +++ b/src/modules/Servicedownloadable/Service.php @@ -21,6 +21,8 @@ use Symfony\Component\HttpFoundation\Response; class Service implements InjectionAwareInterface { + private const string STORED_FILENAME_CONFIG_KEY = 'stored_filename'; + private const array DEFAULT_ALLOWED_EXTENSIONS = [ 'zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', 'rar', '7z', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', @@ -145,10 +147,12 @@ class Service implements InjectionAwareInterface $config = json_decode($product->config ?? '', true) ?? []; $required = [ 'filename' => 'Product is not configured completely.', + self::STORED_FILENAME_CONFIG_KEY => 'Product is not configured completely.', ]; $this->di['validator']->checkRequiredParamsForArray($required, $config); $data['filename'] = $config['filename']; + $data[self::STORED_FILENAME_CONFIG_KEY] = $config[self::STORED_FILENAME_CONFIG_KEY]; return array_merge($config, $data); } @@ -157,6 +161,7 @@ class Service implements InjectionAwareInterface { $required = [ 'filename' => 'Filename is missing in product config', + self::STORED_FILENAME_CONFIG_KEY => 'Stored filename is missing in product config', ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); } @@ -175,6 +180,7 @@ class Service implements InjectionAwareInterface $model = $this->di['db']->dispense('ServiceDownloadable'); $model->client_id = $order->client_id; $model->filename = $c['filename']; + $model->stored_filename = $c[self::STORED_FILENAME_CONFIG_KEY]; $model->downloads = 0; $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); @@ -247,13 +253,67 @@ class Service implements InjectionAwareInterface ]; if ($identity instanceof \Model_Admin) { - $result['path'] = Path::join(PATH_UPLOADS, md5($model->filename)); + $result['path'] = Path::join(PATH_UPLOADS, $model->stored_filename); $result['downloads'] = $model->downloads; } return $result; } + private function generateStoredFilename(): string + { + do { + $storedFilename = bin2hex(random_bytes(32)); + $filePath = Path::join(PATH_UPLOADS, $storedFilename); + } while ($this->filesystem->exists($filePath)); + + return $storedFilename; + } + + private function storeUploadedFile(\Symfony\Component\HttpFoundation\File\UploadedFile $file): string + { + $storedFilename = $this->generateStoredFilename(); + $file->move(PATH_UPLOADS, $storedFilename); + + return $storedFilename; + } + + private function isStoredFilenameReferenced(string $storedFilename): bool + { + $count = (int) $this->di['db']->getCell( + 'SELECT COUNT(*) FROM service_downloadable WHERE stored_filename = :stored_filename', + [':stored_filename' => $storedFilename] + ); + if ($count > 0) { + return true; + } + + $count = (int) $this->di['db']->getCell( + 'SELECT COUNT(*) FROM product WHERE config LIKE :pattern', + [':pattern' => '%' . $storedFilename . '%'] + ); + if ($count > 0) { + return true; + } + + $count = (int) $this->di['db']->getCell( + 'SELECT COUNT(*) FROM client_order WHERE config LIKE :pattern', + [':pattern' => '%' . $storedFilename . '%'] + ); + + return $count > 0; + } + + private function removeStoredFileIfOrphaned(string $storedFilename): void + { + if (!$this->isStoredFilenameReferenced($storedFilename)) { + $filePath = Path::join(PATH_UPLOADS, $storedFilename); + if ($this->filesystem->exists($filePath)) { + $this->filesystem->remove($filePath); + } + } + } + public function uploadProductFile(\Model_Product $productModel): bool { $productService = $this->di['mod_service']('product'); @@ -272,19 +332,10 @@ class Service implements InjectionAwareInterface $this->validateFileUpload($file); - $fileNameHash = md5((string) $fileName); - $fileSavePath = PATH_UPLOADS; - $file->move($fileSavePath, $fileNameHash); + $storedFilename = $this->storeUploadedFile($file); $config = json_decode($productModel->config ?? '', true) ?? []; - - // Remove old file. - if (isset($config['filename'])) { - $oldFilePath = Path::join(PATH_UPLOADS, md5((string) $config['filename'])); - if ($this->filesystem->exists($oldFilePath)) { - $this->filesystem->remove($oldFilePath); - } - } + $oldStoredFilename = $config[self::STORED_FILENAME_CONFIG_KEY] ?? null; // Check if update_orders is true and update all orders if (isset($config['update_orders']) && $config['update_orders']) { @@ -297,39 +348,44 @@ class Service implements InjectionAwareInterface $serviceDownloadable = $orderService->getOrderService($ordermodel); // Update the filename - $oldconfig = json_decode($order['config'] ?? '', true); + $oldconfig = json_decode($order['config'] ?? '', true) ?: []; $oldconfig['filename'] = $fileName; - - // Save the change to the DB + $oldconfig[self::STORED_FILENAME_CONFIG_KEY] = $storedFilename; $ordermodel->config = json_encode($oldconfig); - $ordermodel->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($ordermodel); // Pass the filename since the file was already uploaded and moved - $this->updateProductFile($serviceDownloadable, $ordermodel, $fileName); + $this->updateProductFile($serviceDownloadable, $ordermodel, $fileName, $storedFilename); } } $config['filename'] = $fileName; + $config[self::STORED_FILENAME_CONFIG_KEY] = $storedFilename; $productModel->config = json_encode($config); $productModel->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($productModel); $this->di['logger']->info('Uploaded new file for product %s', $productModel->id); + if ($oldStoredFilename !== null && $oldStoredFilename !== $storedFilename) { + $this->removeStoredFileIfOrphaned($oldStoredFilename); + } + return true; } /** * @throws \FOSSBilling\Exception */ - public function updateProductFile(\Model_ServiceDownloadable $serviceDownloadable, \Model_ClientOrder $order, ?string $filename = null): bool + public function updateProductFile(\Model_ServiceDownloadable $serviceDownloadable, \Model_ClientOrder $order, ?string $filename = null, ?string $storedFilename = null): bool { $request = $this->di['request']; // If filename is provided, use it directly (file was already uploaded in uploadProductFile) if ($filename !== null) { $fileName = $filename; + if ($storedFilename === null) { + throw new \FOSSBilling\Exception('No stored filename available for order file update'); + } } elseif ($request->files->count() > 0) { $file = $request->files->get('file_data'); $fileName = $file->getClientOriginalName(); @@ -341,14 +397,14 @@ class Service implements InjectionAwareInterface $this->validateFileUpload($file); - $fileNameHash = md5((string) $fileName); - $fileSavePath = PATH_UPLOADS; - $file->move($fileSavePath, $fileNameHash); + $oldStoredFilename = $serviceDownloadable->stored_filename ?? null; + $storedFilename = $this->storeUploadedFile($file); } else { $fileName = null; if (isset($order->config)) { $config = json_decode($order->config, true); $fileName = $config['filename'] ?? null; + $storedFilename = $config[self::STORED_FILENAME_CONFIG_KEY] ?? null; } if (!$fileName && isset($serviceDownloadable->filename)) { $fileName = $serviceDownloadable->filename; @@ -356,14 +412,32 @@ class Service implements InjectionAwareInterface if (!$fileName) { throw new \FOSSBilling\Exception('No filename available for order file update'); } + if (!$storedFilename && isset($serviceDownloadable->stored_filename)) { + $storedFilename = $serviceDownloadable->stored_filename; + } + if (!$storedFilename) { + throw new \FOSSBilling\Exception('No stored filename available for order file update'); + } } $serviceDownloadable->filename = $fileName; + $serviceDownloadable->stored_filename = $storedFilename; $serviceDownloadable->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($serviceDownloadable); + $config = json_decode($order->config ?? '', true) ?: []; + $config['filename'] = $fileName; + $config[self::STORED_FILENAME_CONFIG_KEY] = $storedFilename; + $order->config = json_encode($config); + $order->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($order); + $this->di['logger']->info('Uploaded new file for order %s', $order->id); + if (isset($oldStoredFilename) && $oldStoredFilename !== $storedFilename) { + $this->removeStoredFileIfOrphaned($oldStoredFilename); + } + return true; } @@ -384,7 +458,12 @@ class Service implements InjectionAwareInterface public function sendFile(\Model_ServiceDownloadable $serviceDownloadable): Response { $fileName = $serviceDownloadable->filename; - $filePath = Path::join(PATH_UPLOADS, md5($fileName)); + $storedFilename = $serviceDownloadable->stored_filename; + if (!$storedFilename) { + throw new \FOSSBilling\Exception('File cannot be downloaded at the moment. Please contact support.', null, 404); + } + + $filePath = Path::join(PATH_UPLOADS, $storedFilename); if (!$this->filesystem->exists($filePath)) { throw new \FOSSBilling\Exception('File cannot be downloaded at the moment. Please contact support.', null, 404); } @@ -430,12 +509,12 @@ class Service implements InjectionAwareInterface $config = $product->config; $config = json_decode($config ?? '', true) ?: []; - if (!isset($config['filename'])) { + if (!isset($config['filename'], $config[self::STORED_FILENAME_CONFIG_KEY])) { throw new \FOSSBilling\Exception('No file associated with this product.', null, 404); } $fileName = $config['filename']; - $filePath = Path::join(PATH_UPLOADS, md5((string) $fileName)); + $filePath = Path::join(PATH_UPLOADS, $config[self::STORED_FILENAME_CONFIG_KEY]); if (!$this->filesystem->exists($filePath)) { throw new \FOSSBilling\Exception('File cannot be downloaded at the moment. Please contact support.', null, 404); diff --git a/tests-legacy/modules/Servicedownloadable/ServiceTest.php b/tests-legacy/modules/Servicedownloadable/ServiceTest.php index 206fbf84d..fb0060b10 100644 --- a/tests-legacy/modules/Servicedownloadable/ServiceTest.php +++ b/tests-legacy/modules/Servicedownloadable/ServiceTest.php @@ -20,7 +20,7 @@ final class ServiceTest extends \BBTestCase { $productModel = new \Model_Product(); $productModel->loadBean(new \DummyBean()); - $productModel->config = '{"filename" : "temp/asdcxTest.txt"}'; + $productModel->config = '{"filename" : "temp/asdcxTest.txt", "stored_filename": "stored-temp-file"}'; $data = []; @@ -40,7 +40,7 @@ final class ServiceTest extends \BBTestCase { $clientOrderModel = new \Model_ClientOrder(); $clientOrderModel->loadBean(new \DummyBean()); - $clientOrderModel->config = '{"filename" : "temp/asdcxTest.txt"}'; + $clientOrderModel->config = '{"filename" : "temp/asdcxTest.txt", "stored_filename": "stored-temp-file"}'; $model = new \Model_ServiceDownloadable(); $model->loadBean(new \DummyBean()); @@ -62,6 +62,7 @@ final class ServiceTest extends \BBTestCase $this->service->setDi($di); $result = $this->service->action_create($clientOrderModel); $this->assertInstanceOf('\Model_ServiceDownloadable', $result); + $this->assertSame('stored-temp-file', $result->stored_filename); } public function testActionDelete(): void @@ -212,9 +213,103 @@ final class ServiceTest extends \BBTestCase $this->invokeValidateFileUpload($file); } + public function testUploadsWithSameOriginalFilenameUseSeparateStoredFiles(): void + { + $di = $this->createUploadDi(); + $this->service->setDi($di); + + $productA = $this->createProductModel(null); + $productB = $this->createProductModel(null); + + $this->uploadFile($di, $productA, 'download.txt', 'PRODUCT_A_CONTENT'); + $this->uploadFile($di, $productB, 'download.txt', 'PRODUCT_B_CONTENT'); + + $configA = json_decode($productA->config, true); + $configB = json_decode($productB->config, true); + + $this->assertSame('download.txt', $configA['filename']); + $this->assertSame('download.txt', $configB['filename']); + $this->assertNotSame($configA['stored_filename'], $configB['stored_filename']); + + $pathA = \Symfony\Component\Filesystem\Path::join(PATH_UPLOADS, $configA['stored_filename']); + $pathB = \Symfony\Component\Filesystem\Path::join(PATH_UPLOADS, $configB['stored_filename']); + + try { + $this->assertSame('PRODUCT_A_CONTENT', file_get_contents($pathA)); + $this->assertSame('PRODUCT_B_CONTENT', file_get_contents($pathB)); + $this->assertSame('PRODUCT_A_CONTENT', $this->service->sendProductFile($productA)->getContent()); + $this->assertSame('PRODUCT_B_CONTENT', $this->service->sendProductFile($productB)->getContent()); + } finally { + @unlink($pathA); + @unlink($pathB); + } + } + + public function testSendProductFileRequiresStoredFilename(): void + { + $di = $this->createUploadDi(); + $this->service->setDi($di); + + $product = $this->createProductModel('{"filename": "legacy.txt"}'); + + $this->expectException(\FOSSBilling\Exception::class); + $this->expectExceptionMessage('No file associated with this product.'); + + $this->service->sendProductFile($product); + } + private function invokeValidateFileUpload(\Symfony\Component\HttpFoundation\File\UploadedFile $file): void { $reflection = new \ReflectionMethod(Service::class, 'validateFileUpload'); $reflection->invoke($this->service, $file); } + + private function createUploadDi(): \Pimple\Container + { + $di = new \Pimple\Container(); + $di['db'] = new class { + public function store($model): int + { + return 1; + } + }; + $di['logger'] = new class { + public function info(...$args): void + { + } + + public function warn(...$args): void + { + } + }; + $di['mod_service'] = $di->protect(fn (): object => new class { + public function getOrdersForProduct(\Model_Product $product): array + { + return []; + } + }); + + return $di; + } + + private function createProductModel(?string $config): \Model_Product + { + $product = new \Model_Product(); + $product->loadBean(new \DummyBean()); + $product->id = random_int(1000, 9999); + $product->config = $config; + + return $product; + } + + private function uploadFile(\Pimple\Container $di, \Model_Product $product, string $filename, string $contents): void + { + $temporaryFile = tempnam(sys_get_temp_dir(), 'fb-downloadable-'); + file_put_contents($temporaryFile, $contents); + + $file = new \Symfony\Component\HttpFoundation\File\UploadedFile($temporaryFile, $filename, 'text/plain', UPLOAD_ERR_OK, true); + $di['request'] = new \Symfony\Component\HttpFoundation\Request([], [], [], [], ['file_data' => $file]); + + $this->service->uploadProductFile($product); + } }