Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 91 additions & 37 deletions Lib/BackupFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 <contacto@danielfg.es>
*/
Expand Down Expand Up @@ -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;
}
Expand All @@ -85,94 +90,142 @@ 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<string, string>
*/
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)) {
unlink($fileName);
}

$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');
Expand All @@ -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;
}
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**.
Expand Down
Loading
Loading