diff --git a/Lib/BackupFile.php b/Lib/BackupFile.php index e0a1883..48ad4a3 100644 --- a/Lib/BackupFile.php +++ b/Lib/BackupFile.php @@ -20,9 +20,12 @@ namespace FacturaScripts\Plugins\Backup\Lib; use FacturaScripts\Core\Tools; +use FilesystemIterator; use Generator; +use RecursiveCallbackFilterIterator; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; +use SplFileInfo; use Throwable; use ZipArchive; use ZipStream\Option\Archive; @@ -31,6 +34,8 @@ /** * Genera la copia de seguridad de los archivos en un zip dentro de MyFiles/Backups. * Usa ZipStream y, en PHP de 32 bits o si ZipStream falla, ZipArchive. + * Salta las carpetas excluidas sin entrar en ellas y las carpetas o archivos que no se pueden leer + * (open_basedir, permisos), para que la copia no falle por ellos. * * @author Daniel Fernández Giménez */ @@ -58,7 +63,7 @@ public static function generate(string $channel = ''): bool // creamos un archivo $file_path = Tools::folder('MyFiles', 'Backups', date('Y-m-d_H-i-s') . '.zip'); - if (false === static::zipFolder($file_path)) { + if (false === static::zipFolder($file_path, $channel)) { Tools::log($channel)->error('record-save-error'); return false; } @@ -85,40 +90,97 @@ protected static function canUseZipStream(): bool * del zip (clave) y su ruta absoluta (valor). Es un generador para no cargar en memoria la * lista completa de archivos de la instalación. * + * - SKIP_DOTS evita visitar '.' y '..': con open_basedir, comprobar '..' lanzaba un error. + * - Las carpetas excluidas se podan sin entrar en ellas. + * - Se saltan las carpetas y archivos sin permiso de lectura y lo que no sea un archivo + * normal (sockets, enlaces rotos...). + * - CATCH_GET_CHILD salta las subcarpetas que, aun así, lancen una excepción al abrirlas. + * + * @param string|null $sourceFolder Carpeta a comprimir. Por defecto, FS_FOLDER. + * * @return Generator */ - protected static function getFilesToZip(): Generator + protected static function getFilesToZip(?string $sourceFolder = null): Generator { + $root = str_replace(DIRECTORY_SEPARATOR, '/', rtrim($sourceFolder ?? FS_FOLDER, '/\\')); + + $filtered = new RecursiveCallbackFilterIterator( + new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), + function (SplFileInfo $current) use ($root): bool { + if (false === is_readable($current->getPathname())) { + return false; + } + + if ($current->isDir()) { + $relative = static::getRelativePath($root, $current->getPathname()); + return false === in_array($relative . '/', static::EXCLUDED_FOLDERS, true); + } + + return $current->isFile(); + } + ); + $files = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator(FS_FOLDER), - RecursiveIteratorIterator::LEAVES_ONLY + $filtered, + RecursiveIteratorIterator::LEAVES_ONLY, + RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ($files as $file) { + // los enlaces a carpetas no se recorren y llegan aquí como hojas if ($file->isDir()) { continue; } - $filePath = $file->getRealPath(); - $relativePath = str_replace(DIRECTORY_SEPARATOR, '/', substr($filePath, strlen(FS_FOLDER) + 1)); + $filePath = $file->getPathname(); + yield static::getRelativePath($root, $filePath) => $filePath; + } + } - foreach (static::EXCLUDED_FOLDERS as $folder) { - if (strpos($relativePath, $folder) === 0) { - continue 2; - } - } + /** + * Devuelve la ruta de un archivo relativa a la raíz de la copia, con '/' como separador. + * + * @param string $root Raíz de la copia, con '/' como separador y sin '/' final. + * @param string $path Ruta absoluta del archivo o carpeta. + */ + protected static function getRelativePath(string $root, string $path): string + { + return substr(str_replace(DIRECTORY_SEPARATOR, '/', $path), strlen($root) + 1); + } + + /** + * Comprime los archivos de FacturaScripts en el zip indicado: ZipStream si es posible + * y ZipArchive en PHP de 32 bits o si ZipStream falla. + * + * @param string $fileName Ruta completa del zip a crear. + * @param string $channel Canal de log donde registrar los errores. + * @param string|null $sourceFolder Carpeta a comprimir. Por defecto, FS_FOLDER. + */ + protected static function zipFolder(string $fileName, string $channel = '', ?string $sourceFolder = null): bool + { + // en PHP de 32 bits no se puede usar ZipStream 3.x + if (false === static::canUseZipStream()) { + return static::zipFolderWithZipArchive($fileName, $channel, $sourceFolder); + } - yield $relativePath => $filePath; + if (static::zipFolderWithZipStream($fileName, $channel, $sourceFolder)) { + return true; } + + // si falla ZipStream, lo intentamos con ZipArchive + return static::zipFolderWithZipArchive($fileName, $channel, $sourceFolder); } /** * Genera el zip con la extensión ZipArchive (requisito del plugin). * Es la alternativa a ZipStream para PHP de 32 bits o cuando ZipStream falla. + * Si falla, registra el motivo como error. * * @param string $fileName Ruta completa del zip a crear. + * @param string $channel Canal de log donde registrar los errores. + * @param string|null $sourceFolder Carpeta a comprimir. Por defecto, FS_FOLDER. */ - protected static function zipFolderWithZipArchive(string $fileName): bool + protected static function zipFolderWithZipArchive(string $fileName, string $channel = '', ?string $sourceFolder = null): bool { // ZipArchive no puede abrir un archivo vacío ya creado, así que lo borramos antes if (file_exists($fileName)) { @@ -126,53 +188,44 @@ protected static function zipFolderWithZipArchive(string $fileName): bool } $zip = new ZipArchive(); - if ($zip->open($fileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { + $result = $zip->open($fileName, ZipArchive::CREATE | ZipArchive::OVERWRITE); + if ($result !== true) { + Tools::log($channel)->error('backup-files-error', ['%error%' => 'ZipArchive::open() ' . $result]); return false; } try { - foreach (static::getFilesToZip() as $relativePath => $filePath) { + foreach (static::getFilesToZip($sourceFolder) as $relativePath => $filePath) { if (false === $zip->addFile($filePath, $relativePath)) { + Tools::log($channel)->error('backup-files-error', ['%error%' => $zip->getStatusString() . ': ' . $filePath]); $zip->close(); return false; } } } catch (Throwable $e) { + Tools::log($channel)->error('backup-files-error', ['%error%' => $e->getMessage()]); $zip->close(); return false; } // close() escribe el archivo; si falla, la copia no es válida - return $zip->close(); - } - - /** - * Comprime los archivos de FacturaScripts en el zip indicado: ZipStream si es posible - * y ZipArchive en PHP de 32 bits o si ZipStream falla. - * - * @param string $fileName Ruta completa del zip a crear. - */ - protected static function zipFolder(string $fileName): bool - { - // en PHP de 32 bits no se puede usar ZipStream 3.x - if (false === static::canUseZipStream()) { - return static::zipFolderWithZipArchive($fileName); - } - - if (static::zipFolderWithZipStream($fileName)) { - return true; + if (false === $zip->close()) { + Tools::log($channel)->error('backup-files-error', ['%error%' => $zip->getStatusString()]); + return false; } - // si falla ZipStream, lo intentamos con ZipArchive - return static::zipFolderWithZipArchive($fileName); + return true; } /** * Genera el zip con ZipStream (2.x o 3.x) escribiendo directamente al archivo, sin cargarlo en memoria. + * Si falla, registra el motivo como aviso, porque a continuación se reintenta con ZipArchive. * * @param string $fileName Ruta completa del zip a crear. + * @param string $channel Canal de log donde registrar los errores. + * @param string|null $sourceFolder Carpeta a comprimir. Por defecto, FS_FOLDER. */ - protected static function zipFolderWithZipStream(string $fileName): bool + protected static function zipFolderWithZipStream(string $fileName, string $channel = '', ?string $sourceFolder = null): bool { // abrimos un stream de escritura hacia el archivo destino $outputStream = fopen($fileName, 'wb'); @@ -197,12 +250,13 @@ protected static function zipFolderWithZipStream(string $fileName): bool ); } - foreach (static::getFilesToZip() as $relativePath => $filePath) { + foreach (static::getFilesToZip($sourceFolder) as $relativePath => $filePath) { $zip->addFileFromPath($relativePath, $filePath); } $zip->finish(); } catch (Throwable $e) { + Tools::log($channel)->warning('backup-files-error', ['%error%' => $e->getMessage()]); fclose($outputStream); return false; } diff --git a/README.md b/README.md index 7cfb190..b3711f0 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Permite crear y restaurar copias de seguridad de la base de datos (MySQL y Postg ## Requisitos - Extensión PHP `zip`. - La copia de archivos se genera con ZipStream. **En PHP de 32 bits** (donde ZipStream 3.x no funciona) o si ZipStream falla, se genera automáticamente con ZipArchive, así que el plugin funciona igualmente. El `composer.json` desactiva `platform-check` para que la comprobación de plataforma de Composer no rompa la instalación en esos entornos. +- La copia de archivos no incluye `MyFiles/Backups`, `MyFiles/Cache`, `MyFiles/Tmp` ni `Dinamic`, y salta sin fallar las carpetas o archivos que PHP no puede leer (restricción `open_basedir`, carpetas sin permisos como `mysql/` o `@eaDir` de Synology, enlaces rotos). Si aun así la copia falla, se muestra el motivo en el registro. ## Carpeta La carpeta debe llamarse igual que el plugin: **Backup**. diff --git a/Test/main/BackupFileUnreadableFoldersTest.php b/Test/main/BackupFileUnreadableFoldersTest.php new file mode 100644 index 0000000..7a5ad7f --- /dev/null +++ b/Test/main/BackupFileUnreadableFoldersTest.php @@ -0,0 +1,205 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +namespace FacturaScripts\Test\Plugins; + +use FacturaScripts\Plugins\Backup\Lib\BackupFile; +use PHPUnit\Framework\TestCase; +use ReflectionMethod; +use ZipArchive; + +/** + * Comprueba que la copia de archivos poda las carpetas excluidas y salta las que no se pueden leer. + * + * @author Esteban Sánchez Martínez + */ +final class BackupFileUnreadableFoldersTest extends TestCase +{ + /** @var string Carpeta temporal que hace de raíz de FacturaScripts. */ + private string $root = ''; + + /** @var string Ruta del zip generado. */ + private string $zipPath = ''; + + public static function setUpBeforeClass(): void + { + // sin el autoloader del vendor del plugin no se encuentra ZipStream + if (false === class_exists(\ZipStream\ZipStream::class)) { + require_once FS_FOLDER . '/Plugins/Backup/vendor/autoload.php'; + } + } + + protected function setUp(): void + { + $base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'backup_test_' . uniqid(); + $this->root = $base . DIRECTORY_SEPARATOR . 'root'; + $this->zipPath = $base . DIRECTORY_SEPARATOR . 'out.zip'; + + // estructura: archivos normales, carpetas excluidas y una carpeta sin permisos + $files = [ + 'visible.txt', + 'sub/visible2.txt', + 'MyFiles/user.txt', + 'MyFiles/Backups/old.zip', + 'MyFiles/Cache/cache.txt', + 'MyFiles/Tmp/tmp.txt', + 'MyFilesExtra/keep.txt', + 'Dinamic/dinamic.php', + 'locked/secret.txt', + ]; + foreach ($files as $file) { + $path = $this->root . '/' . $file; + mkdir(dirname($path), 0777, true); + file_put_contents($path, 'contenido ' . $file); + } + } + + protected function tearDown(): void + { + // restauramos los permisos para poder borrar la carpeta bloqueada + @chmod($this->root . '/locked', 0777); + + $base = dirname($this->root); + if (is_dir($base)) { + $items = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST + ); + foreach ($items as $item) { + $item->isDir() ? @rmdir($item->getPathname()) : @unlink($item->getPathname()); + } + @rmdir($base); + } + } + + /** + * Motores de compresión con los que se prueba el recorrido de carpetas. + * + * @return array}> + */ + public static function engineProvider(): array + { + return [ + 'ZipStream' => [BackupFile::class], + 'ZipArchive' => [BackupFileUnreadableZipArchive::class], + ]; + } + + /** + * @dataProvider engineProvider + * + * @param class-string $className Clase que genera el zip. + */ + public function testBrokenSymlinkIsSkipped(string $className): void + { + // un enlace roto no es un archivo normal: antes rompía toda la copia + if (false === @symlink($this->root . '/no-existe.txt', $this->root . '/roto.txt')) { + $this->markTestSkipped('No se pueden crear enlaces simbólicos en este entorno.'); + } + + $this->assertTrue($this->zipFolder($className), 'zipFolder() debería devolver true con un enlace roto'); + + $names = $this->zipNames(); + $this->assertContains('visible.txt', $names); + $this->assertNotContains('roto.txt', $names); + } + + /** + * @dataProvider engineProvider + * + * @param class-string $className Clase que genera el zip. + */ + public function testExcludedFoldersAreNotZipped(string $className): void + { + $this->assertTrue($this->zipFolder($className), 'zipFolder() debería devolver true'); + + $names = $this->zipNames(); + $this->assertContains('visible.txt', $names); + $this->assertContains('sub/visible2.txt', $names); + $this->assertContains('MyFiles/user.txt', $names); + $this->assertContains('MyFilesExtra/keep.txt', $names, 'No debe excluirse una carpeta con el mismo prefijo'); + + foreach ($names as $name) { + $this->assertStringStartsNotWith('MyFiles/Backups/', $name); + $this->assertStringStartsNotWith('MyFiles/Cache/', $name); + $this->assertStringStartsNotWith('MyFiles/Tmp/', $name); + $this->assertStringStartsNotWith('Dinamic/', $name); + } + } + + /** + * @dataProvider engineProvider + * + * @param class-string $className Clase que genera el zip. + */ + public function testUnreadableFolderIsSkipped(string $className): void + { + chmod($this->root . '/locked', 0000); + + // en Windows o ejecutando como root chmod no impide leer: no se puede simular + if (is_readable($this->root . '/locked')) { + $this->markTestSkipped('No se pueden quitar los permisos de lectura en este entorno.'); + } + + $this->assertTrue($this->zipFolder($className), 'zipFolder() debería devolver true con una carpeta sin permisos'); + + $names = $this->zipNames(); + $this->assertContains('visible.txt', $names); + $this->assertNotContains('locked/secret.txt', $names); + } + + /** + * Ejecuta zipFolder() de la clase indicada sobre la carpeta temporal. + * + * @param class-string $className Clase que genera el zip. + */ + private function zipFolder(string $className): bool + { + $method = new ReflectionMethod($className, 'zipFolder'); + return $method->invoke(null, $this->zipPath, 'test', $this->root); + } + + /** + * Devuelve los nombres de las entradas del zip generado. + * + * @return string[] + */ + private function zipNames(): array + { + $zip = new ZipArchive(); + $this->assertTrue($zip->open($this->zipPath), 'No se pudo abrir el zip'); + $names = []; + for ($i = 0; $i < $zip->numFiles; $i++) { + $names[] = $zip->getNameIndex($i); + } + $zip->close(); + return $names; + } +} + +/** + * BackupFile que simula un PHP de 32 bits: nunca usa ZipStream, solo ZipArchive. + */ +class BackupFileUnreadableZipArchive extends BackupFile +{ + protected static function canUseZipStream(): bool + { + return false; + } +} diff --git a/Test/main/BackupFileZipArchiveTest.php b/Test/main/BackupFileZipArchiveTest.php index 06ba0fb..c9ee82c 100644 --- a/Test/main/BackupFileZipArchiveTest.php +++ b/Test/main/BackupFileZipArchiveTest.php @@ -41,25 +41,6 @@ final class BackupFileZipArchiveTest extends TestCase /** @var string Ruta del zip generado durante el test. */ private string $zipFile = ''; - protected function setUp(): void - { - // carpeta marcador que debe aparecer en la copia - $this->markerDir = 'BackupZipArchiveTest_' . substr(md5(uniqid('', true)), 0, 8); - $markerPath = Tools::folder('MyFiles', $this->markerDir); - Tools::folderCheckOrCreate($markerPath); - file_put_contents($markerPath . DIRECTORY_SEPARATOR . 'marker.txt', 'zip-archive-marker'); - } - - protected function tearDown(): void - { - if ($this->zipFile && file_exists($this->zipFile)) { - unlink($this->zipFile); - } - - Tools::folderDelete(Tools::folder('MyFiles', $this->markerDir)); - $this->logErrors(); - } - public function testComposerDoesNotRequire64Bits(): void { // el plugin no debe tumbar la instalación en PHP de 32 bits @@ -76,18 +57,18 @@ public function testComposerDoesNotRequire64Bits(): void ); } - public function testGenerateWithZipArchive(): void - { - // forzamos el camino de ZipArchive, como en PHP de 32 bits - $this->assertValidBackup(BackupFileForceZipArchive::class); - } - public function testGenerateFallsBackToZipArchiveWhenZipStreamFails(): void { // si ZipStream falla y deja un archivo a medias, se debe rehacer con ZipArchive $this->assertValidBackup(BackupFileZipStreamFails::class); } + public function testGenerateWithZipArchive(): void + { + // forzamos el camino de ZipArchive, como en PHP de 32 bits + $this->assertValidBackup(BackupFileForceZipArchive::class); + } + /** * Genera la copia con la clase indicada y comprueba que el zip es válido, que incluye * el archivo marcador y que respeta las carpetas excluidas. @@ -126,6 +107,25 @@ private function assertValidBackup(string $className): void $zip->close(); } + + protected function setUp(): void + { + // carpeta marcador que debe aparecer en la copia + $this->markerDir = 'BackupZipArchiveTest_' . substr(md5(uniqid('', true)), 0, 8); + $markerPath = Tools::folder('MyFiles', $this->markerDir); + Tools::folderCheckOrCreate($markerPath); + file_put_contents($markerPath . DIRECTORY_SEPARATOR . 'marker.txt', 'zip-archive-marker'); + } + + protected function tearDown(): void + { + if ($this->zipFile && file_exists($this->zipFile)) { + unlink($this->zipFile); + } + + Tools::folderDelete(Tools::folder('MyFiles', $this->markerDir)); + $this->logErrors(); + } } /** @@ -149,7 +149,7 @@ protected static function canUseZipStream(): bool return true; } - protected static function zipFolderWithZipStream(string $fileName): bool + protected static function zipFolderWithZipStream(string $fileName, string $channel = '', ?string $sourceFolder = null): bool { file_put_contents($fileName, 'zip-incompleto'); return false; diff --git a/Translation/es_ES.json b/Translation/es_ES.json index 36a248c..6f9b734 100644 --- a/Translation/es_ES.json +++ b/Translation/es_ES.json @@ -5,6 +5,7 @@ "backup-charset-error": "La codificación de la copia de seguridad es %db-charset%, mientras que en el config.php es %config-charset%. Pulsa el botón cambiar codificación antes de restaurar.", "backup-charset-mixed-warning": "Advertencia: La copia de seguridad contiene tablas con múltiples codificaciones (%charsets%). Tu configuración actual es %config-charset%.", "backup-file-too-big": "El archivo de copia de seguridad es demasiado grande para subirlo al servidor. El tamaño máximo es %size% MB", + "backup-files-error": "Error al comprimir los archivos de la copia de seguridad: %error%", "backup-memory-warning": "Advertencia: la copia de seguridad ocupa %size% MB, pero solamente tienes %memory% MB de memoria RAM disponible. Insuficiente para realizar la copia de seguridad. Como alternativa puedes comprimir la carpeta de FacturaScripts, que es equivalente a una copia de los archivos.", "backup-port-warning": "El puerto de MySQL debe ser el 3306, pero estás usando el %port%", "backup-use-fixer-plugin": "Se recomienda usar el plugin Fixer para corregir las codificaciones de las tablas antes de realizar copias de seguridad.",