. * */ namespace SP\Core; use SP\Config\Config; use SP\Core\Exceptions\SPException; use SP\Log\Email; use SP\Storage\DB; use SP\Log\Log; use SP\Storage\DBUtil; use SP\Storage\QueryData; use SP\Util\Checks; use SP\Util\Util; defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); /** * Esta clase es la encargada de realizar la copia y restauración de sysPass. */ class Backup { /** * Realizar backup de la BBDD y aplicación. * * @return bool */ public static function doBackup() { $Log = new Log(_('Realizar Backup')); $siteName = Util::getAppInfo('appname'); $backupDir = Init::$SERVERROOT; // Generar hash unico para evitar descargas no permitidas $backupUniqueHash = uniqid(); Config::getConfig()->setBackupHash($backupUniqueHash); Config::saveConfig(); $backupDstDir = $backupDir . DIRECTORY_SEPARATOR . 'backup'; $bakFileApp = $backupDstDir . DIRECTORY_SEPARATOR . $siteName . '-' . $backupUniqueHash . '.tar'; $bakFileDB = $backupDstDir . DIRECTORY_SEPARATOR . $siteName . 'db-' . $backupUniqueHash . '.sql'; try { self::checkBackupDir($backupDstDir); self::deleteOldBackups($backupDstDir); self::backupTables('*', $bakFileDB); self::backupApp($bakFileApp); } catch (\Exception $e) { $Log->setLogLevel(Log::ERROR); $Log->addDescription(_('Error al realizar el backup')); $Log->addDetails($e->getCode(), $e->getMessage()); $Log->writeLog(); Email::sendEmail($Log); return false; } $Log->addDescription(_('Copia de la aplicación y base de datos realizada correctamente')); $Log->writeLog(); Email::sendEmail($Log); return true; } /** * Backup de las tablas de la BBDD. * Utilizar '*' para toda la BBDD o 'table1 table2 table3...' * * @param string $tables * @param string $backupFile * @throws SPException * @return bool */ private static function backupTables($tables = '*', $backupFile) { $dbname = Config::getConfig()->getDbName(); try { $handle = fopen($backupFile, 'w'); $Data = new QueryData(); if ($tables == '*') { $Data->setQuery('SHOW TABLES'); $resTables = DB::getResults($Data); } else { $resTables = is_array($tables) ? $tables : explode(',', $tables); } $sqlOut = '--' . PHP_EOL; $sqlOut .= '-- sysPass DB dump generated on ' . time() . ' (START)' . PHP_EOL; $sqlOut .= '--' . PHP_EOL; $sqlOut .= '-- Please, do not alter this file, it could break your DB' . PHP_EOL; $sqlOut .= '--' . PHP_EOL . PHP_EOL; $sqlOut .= 'CREATE DATABASE IF NOT EXISTS `' . $dbname . '`;' . PHP_EOL . PHP_EOL; $sqlOut .= 'USE `' . $dbname . '`;' . PHP_EOL . PHP_EOL; fwrite($handle, $sqlOut); // Recorrer las tablas y almacenar los datos foreach ($resTables as $table) { $tableName = $table->{'Tables_in_' . $dbname}; $Data->setQuery('SHOW CREATE TABLE ' . $tableName); $sqlOut = '-- ' . PHP_EOL; $sqlOut .= '-- Table ' . strtoupper($tableName) . PHP_EOL; $sqlOut .= '-- ' . PHP_EOL; // Consulta para crear la tabla $sqlOut .= 'DROP TABLE IF EXISTS `' . $tableName . '`;' . PHP_EOL . PHP_EOL; $txtCreate = DB::getResults($Data); $sqlOut .= $txtCreate->{'Create Table'} . ';' . PHP_EOL . PHP_EOL; fwrite($handle, $sqlOut); $Data->setQuery('SELECT * FROM ' . $tableName); // Consulta para obtener los registros de la tabla $queryRes = DB::getResultsRaw($Data); $numColumns = $queryRes->columnCount(); while ($row = $queryRes->fetch(\PDO::FETCH_NUM)) { fwrite($handle, 'INSERT INTO `' . $tableName . '` VALUES('); $field = 1; foreach ($row as $value) { if (is_numeric($value)) { fwrite($handle, $value); } else { fwrite($handle, DBUtil::escape($value)); } if ($field < $numColumns) { fwrite($handle, ','); } $field++; } fwrite($handle, ');' . PHP_EOL); } fwrite($handle, PHP_EOL . PHP_EOL); } $sqlOut = '--' . PHP_EOL; $sqlOut .= '-- sysPass DB dump generated on ' . time() . ' (END)' . PHP_EOL; $sqlOut .= '--' . PHP_EOL; $sqlOut .= '-- Please, do not alter this file, it could break your DB' . PHP_EOL; $sqlOut .= '--' . PHP_EOL . PHP_EOL; fwrite($handle, $sqlOut); fclose($handle); } catch (\Exception $e) { throw new SPException(SPException::SP_CRITICAL, $e->getMessage()); } return true; } /** * Realizar un backup de la aplicación y comprimirlo. * * @param string $backupFile nombre del archivo de backup * @throws SPException * @return bool */ private static function backupApp($backupFile) { if (!class_exists('PharData')) { if (Checks::checkIsWindows()) { throw new SPException(SPException::SP_CRITICAL, _('Esta operación sólo es posible en entornos Linux')); } elseif (!self::backupAppLegacyLinux($backupFile)) { throw new SPException(SPException::SP_CRITICAL, _('Error al realizar backup en modo compatibilidad')); } return true; } $compressedFile = $backupFile . '.gz'; try { if (file_exists($compressedFile)) { unlink($compressedFile); } $archive = new \PharData($backupFile); $archive->buildFromDirectory(Init::$SERVERROOT); $archive->compress(\Phar::GZ); unlink($backupFile); } catch (\Exception $e) { throw new SPException(SPException::SP_CRITICAL, $e->getMessage()); } return file_exists($backupFile); } /** * Realizar un backup de la aplicación y comprimirlo usando aplicaciones del SO Linux. * * @param string $backupFile nombre del archivo de backup * @return int Con el código de salida del comando ejecutado */ private static function backupAppLegacyLinux($backupFile) { $compressedFile = $backupFile . '.gz'; $backupDir = Init::$SERVERROOT; $bakDstDir = $backupDir . '/backup'; $command = 'tar czf ' . $compressedFile . ' ' . $backupDir . ' --exclude "' . $bakDstDir . '" 2>&1'; exec($command, $resOut, $resBakApp); return $resBakApp; } /** * Comprobar y crear el directorio de backups. * * @param string $backupDir ruta del directorio de backup * @throws SPException * @return bool */ private static function checkBackupDir($backupDir) { if (!is_dir($backupDir)) { if (!@mkdir($backupDir, 0550)) { throw new SPException(SPException::SP_CRITICAL, _('No es posible crear el directorio de backups') . ' (' . $backupDir . ')'); } } if (!is_writable($backupDir)) { throw new SPException(SPException::SP_CRITICAL, _('Compruebe los permisos del directorio de backups')); } return true; } /** * Eliminar las copias de seguridad anteriores * * @param string $backupDir El directorio de backups */ private static function deleteOldBackups($backupDir) { array_map('unlink', glob($backupDir . DIRECTORY_SEPARATOR . '*.tar.gz')); array_map('unlink', glob($backupDir . DIRECTORY_SEPARATOR . '*.sql')); } }