Skip to content
backup.inc.php 107 KiB
Newer Older
<?php

/*
Copyright (c) 2007, Till Brehm, projektfarm Gmbh
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of ISPConfig nor the names of its contributors
      may be used to endorse or promote products derived from this software without
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * Class backup
 * All code that makes actual backup and restore of web files and database is here.
 * @author Ramil Valitov <ramilvalitov@gmail.com>
 * @author Jorge Muñoz <elgeorge2k@gmail.com> (Repository addition)
 * @see backup::run_backup() to run a single backup
 * @see backup::run_all_backups() to run all backups
 * @see backup::restoreBackupDatabase() to restore a database
 * @see backup::restoreBackupWebFiles() to restore web files
 */
class backup
{
    /**
     * Returns file extension for specified backup format
     * @param string $format backup format
     * @return string|null
     * @author Ramil Valitov <ramilvalitov@gmail.com>
     */
    protected static function getBackupDbExtension($format)
    {
        $prefix = '.sql';
        switch ($format) {
            case 'gzip':
                return $prefix . '.gz';
            case 'bzip2':
                return $prefix . '.bz2';
            case 'xz':
                return $prefix . '.xz';
            case 'zip':
            case 'zip_bzip2':
                return '.zip';
            case 'rar':
                return '.rar';
        }
        if (strpos($format, "7z_") === 0) {
            return $prefix . '.7z';
        }
        return null;
    }

    /**
     * Returns file extension for specified backup format
     * @param string $format backup format
     * @return string|null
     * @author Ramil Valitov <ramilvalitov@gmail.com>
     */
    protected static function getBackupWebExtension($format)
    {
        switch ($format) {
            case 'tar_gzip':
                return '.tar.gz';
            case 'tar_bzip2':
                return '.tar.bz2';
            case 'tar_xz':
                return '.tar.xz';
            case 'zip':
            case 'zip_bzip2':
                return '.zip';
            case 'rar':
                return '.rar';
        }
        if (strpos($format, "tar_7z_") === 0) {
            return '.tar.7z';
        }
        return null;
    }
    /**
     * Checks whatever a backup mode is for a repository
     * @param $mode Backup mode
     * @return bool
     * @author Jorge Muñoz <elgeorge2k@gmail.com>
     */
    protected static function backupModeIsRepos($mode)
    {
        return 'borg' === $mode;
    }

    /**
     * Sets file ownership to $web_user for all files and folders except log, ssl and web/stats
     * @param string $web_document_root
     * @param string $web_user
     * @author Ramil Valitov <ramilvalitov@gmail.com>
     */
    protected static function restoreFileOwnership($web_document_root, $web_user, $web_group)
        $blacklist = array('bin', 'dev', 'etc', 'home', 'lib', 'lib32', 'lib64', 'log', 'opt', 'proc', 'net', 'run', 'sbin', 'ssl', 'srv', 'sys', 'usr', 'var');

	$find_excludes = '-not -path "." -and -not -path "./web/stats/*"';

	foreach ( $blacklist as $dir ) {
		$find_excludes .= ' -and -not -path "./'.$dir.'" -and -not -path "./'.$dir.'/*"';
	}

        $app->log('Restoring permissions for ' . $web_document_root, LOGLEVEL_DEBUG);
        $app->system->exec_safe('cd ? && find . '.$find_excludes.' -exec chown ?:? {} \;', $web_document_root, $web_user, $web_group);

    }

    /**
     * Returns default backup format used in previous versions of ISPConfig
     * @param string $backup_mode can be 'userzip' or 'rootgz'
     * @param string $backup_type can be 'web' or 'mysql'
     * @return string
     * @author Ramil Valitov <ramilvalitov@gmail.com>
     */
    protected static function getDefaultBackupFormat($backup_mode, $backup_type)
    {
        //We have a backup from old version of ISPConfig
        switch ($backup_type) {
            case 'mysql':
                return 'gzip';
            case 'web':
                return ($backup_mode == 'userzip') ? 'zip' : 'tar_gzip';
        }
        return "";
    }

    /**
     * Restores a database backup.
     * The backup directory must be mounted before calling this method.
     * @param string $backup_format
     * @param string $password password for encrypted backup or empty string if archive is not encrypted
     * @param string $backup_dir
     * @param string $filename
     * @param string $backup_mode
     * @param string $backup_type
     * @return bool true if succeeded
     * @see backup_plugin::mount_backup_dir()
     * @author Ramil Valitov <ramilvalitov@gmail.com>
     * @author Jorge Muñoz <elgeorge2k@gmail.com>
     */
    public static function restoreBackupDatabase($backup_format, $password, $backup_dir, $filename, $backup_mode, $backup_type)
    {
        global $app;

        //* Load sql dump into db
        include 'lib/mysql_clientdb.conf';
        if (self::backupModeIsRepos($backup_mode)) {
            $backup_archive = $filename;

            preg_match('@^(manual-)?db_(?P<db>.+)_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$@', $backup_archive, $matches);
            if (isset($matches['db']) && ! empty($matches['db'])) {
                $db_name = $matches['db'];
                $backup_repos_folder = self::getReposFolder($backup_mode, 'mysql', '_' . $db_name);
                $backup_repos_path = $backup_dir . '/' . $backup_repos_folder;
                $full_archive_path = $backup_repos_path . '::' . $backup_archive;

                $app->log('Restoring MySQL backup from archive ' . $backup_archive . ', backup mode "' . $backup_mode . '"', LOGLEVEL_DEBUG);

                $archives = self::getReposArchives($backup_mode, $backup_repos_path, $password);
            } else {
                $app->log('Failed to detect database name during restore of ' . $backup_archive, LOGLEVEL_ERROR);
                $db_name = null;
                $archives = null;
            }
            if (is_array($archives)) {
                if (in_array($backup_archive, $archives)) {
                    switch ($backup_mode) {
                        case "borg":
                            $command = self::getBorgCommand('borg extract --nobsdflags', $password);
                            $command .= " --stdout ? stdin | mysql -h ? -u ? -p? ?";
                            break;
                    }
                } else {
                    $app->log('Failed to process MySQL backup ' . $full_archive_path . ' because it does not exist', LOGLEVEL_ERROR);
                    $command = null;
                }
            }
            if (!empty($command)) {
                /** @var string $clientdb_host */
                /** @var string $clientdb_user */
                /** @var string $clientdb_password */
                $app->system->exec_safe($command, $full_archive_path, $clientdb_host, $clientdb_user, $clientdb_password, $db_name);
                $retval = $app->system->last_exec_retcode();
                if ($retval == 0) {
                    $app->log('Restored database backup ' . $full_archive_path, LOGLEVEL_DEBUG);
                    $success = true;
                } else {
                    $app->log('Failed to restore database backup ' . $full_archive_path . ', exit code ' . $retval, LOGLEVEL_ERROR);
                }
            }
        } else {
            if (empty($backup_format)) {
                $backup_format = self::getDefaultBackupFormat($backup_mode, $backup_type);
            }
            $extension = self::getBackupDbExtension($backup_format);
            if (!empty($extension)) {
                //Replace dots for preg_match search
                $extension = str_replace('.', '\.', $extension);
            }
            $success = false;
            $full_filename = $backup_dir . '/' . $filename;
            $app->log('Restoring MySQL backup ' . $full_filename . ', backup format "' . $backup_format . '", backup mode "' . $backup_mode . '"', LOGLEVEL_DEBUG);

            preg_match('@^(manual-)?db_(?P<db>.+)_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}' . $extension . '$@', $filename, $matches);
            if (!isset($matches['db']) || empty($matches['db'])) {
                $app->log('Failed to detect database name during restore of ' . $full_filename, LOGLEVEL_ERROR);
                $db_name = null;
            } else {
                $db_name = $matches['db'];

            if ( ! empty($db_name)) {
                $file_check = file_exists($full_filename) && !empty($extension);
                if ( ! $file_check) {
                    $app->log('Archive test failed for ' . $full_filename, LOGLEVEL_WARN);
                }
            } else {
                $file_check = false;
            }
            if ($file_check) {
                switch ($backup_format) {
                    case "gzip":
                        $command = "gunzip --stdout ? | mysql -h ? -u ? -p? ?";
                        break;
                    case "zip":
                    case "zip_bzip2":
                        $command = "unzip -qq -p -P " . escapeshellarg($password) . " ? | mysql -h ? -u ? -p? ?";
                        break;
                    case "bzip2":
                        $command = "bunzip2 -q -c ? | mysql -h ? -u ? -p? ?";
                        break;
                    case "xz":
                        $command = "unxz -q -q -c ? | mysql -h ? -u ? -p? ?";
                        break;
                    case "rar":
                        //First, test that the archive is correct and we have a correct password
                        $options = self::getUnrarOptions($password);
                        $app->system->exec_safe("rar t " . $options . " ?", $full_filename);
                        if ($app->system->last_exec_retcode() == 0) {
                            $app->log('Archive test passed for ' . $full_filename, LOGLEVEL_DEBUG);
                            $command = "rar x " . $options. " ? | mysql -h ? -u ? -p? ?";
                        }
                        break;
                }
                if (strpos($backup_format, "7z_") === 0) {
                    $options = self::get7zDecompressOptions($password);
                    //First, test that the archive is correct and we have a correct password
                    $app->system->exec_safe("7z t " . $options . " ?", $full_filename);
                    if ($app->system->last_exec_retcode() == 0) {
                        $app->log('Archive test passed for ' . $full_filename, LOGLEVEL_DEBUG);
                        $command = "7z x " . $options . " -so ? | mysql -h ? -u ? -p? ?";
                    } else
                        $command = null;
                }
            }
            if (!empty($command)) {
                /** @var string $clientdb_host */
                /** @var string $clientdb_user */
                /** @var string $clientdb_password */
                $app->system->exec_safe($command, $full_filename, $clientdb_host, $clientdb_user, $clientdb_password, $db_name);
                $retval = $app->system->last_exec_retcode();
                if ($retval == 0) {
                    $app->log('Restored MySQL backup ' . $full_filename, LOGLEVEL_DEBUG);
                    $success = true;
                } else {
                    $app->log('Failed to restore MySQL backup ' . $full_filename . ', exit code ' . $retval, LOGLEVEL_ERROR);
                }
            }
        }
        unset($clientdb_host);
        unset($clientdb_user);
        unset($clientdb_password);

        return $success;
    }

    /**
     * Restores web files backup.
     * The backup directory must be mounted before calling this method.
     * @param string $backup_format
     * @param string $password password for encrypted backup or empty string if archive is not encrypted
     * @param string $backup_dir
     * @param string $filename
     * @param string $backup_mode
     * @param string $backup_type
     * @param string $web_root
     * @param string $web_user
     * @param string $web_group
     * @return bool true if succeed
     * @see backup_plugin::mount_backup_dir()
     * @author Ramil Valitov <ramilvalitov@gmail.com>
     * @author Jorge Muñoz <elgeorge2k@gmail.com>
     */
    public static function restoreBackupWebFiles($backup_format, $password, $backup_dir, $filename, $backup_mode, $backup_type, $web_root, $web_user, $web_group)
    {
        global $app;

        $result = false;

        $app->system->web_folder_protection($web_root, false);
        if (self::backupModeIsRepos($backup_mode)) {
            $backup_archive = $filename;
            $backup_repos_folder = self::getReposFolder($backup_mode, 'web');
            $backup_repos_path = $backup_dir . '/' . $backup_repos_folder;
            $full_archive_path = $backup_repos_path . '::' . $backup_archive;

            $app->log('Restoring web backup archive ' . $full_archive_path . ', backup mode "' . $backup_mode . '"', LOGLEVEL_DEBUG);

            $archives = self::getReposArchives($backup_mode, $backup_repos_path, $password);
            if (is_array($archives) && in_array($backup_archive, $archives)) {
                $retval = 0;
                switch ($backup_mode) {
                    case "borg":
                        $command = 'cd ? && borg extract --nobsdflags ?';
                        $app->system->exec_safe($command, $web_root, $full_archive_path);
                        $retval = $app->system->last_exec_retcode();
                        $success = ($retval == 0 || $retval == 1);
                        break;
                }
                if ($success) {
                    $app->log('Restored web backup ' . $full_archive_path, LOGLEVEL_DEBUG);
                    $result = true;
                } else {
                    $app->log('Failed to restore web backup ' . $full_archive_path . ', exit code ' . $retval, LOGLEVEL_ERROR);
                }
            } else {
                $app->log('Web backup archive does not exist ' . $full_archive_path, LOGLEVEL_ERROR);
            }
        } elseif ($backup_mode == 'userzip' || $backup_mode == 'rootgz') {
            if (empty($backup_format) || $backup_format == 'default') {
                $backup_format = self::getDefaultBackupFormat($backup_mode, $backup_type);
            }
            $full_filename = $backup_dir . '/' . $filename;

            $app->log('Restoring web backup ' . $full_filename . ', backup format "' . $backup_format . '", backup mode "' . $backup_mode . '"', LOGLEVEL_DEBUG);

            $user_mode = $backup_mode == 'userzip';
            $filename = $user_mode ? ($web_root . '/backup/' . $filename) : $full_filename;

            if (file_exists($full_filename) && $web_root != '' && $web_root != '/' && !stristr($full_filename, '..') && !stristr($full_filename, 'etc')) {
                if ($user_mode) {
                    if (file_exists($filename)) rename($filename, $filename . '.bak');
                    copy($full_filename, $filename);
                    chgrp($filename, $web_group);
                }
                $user_prefix_cmd = $user_mode ? 'sudo -u ' . escapeshellarg($web_user) : '';
                $success = false;
                $retval = 0;
                switch ($backup_format) {
                    case "tar_gzip":
                    case "tar_bzip2":
                    case "tar_xz":
                        $command = $user_prefix_cmd . ' tar xf ? --directory ?';
                        $app->system->exec_safe($command, $filename, $web_root);
                        $retval = $app->system->last_exec_retcode();
                        $success = ($retval == 0 || $retval == 2);
                        break;
                    case "zip":
                    case "zip_bzip2":
                        $command = $user_prefix_cmd . ' unzip -qq -P ' . escapeshellarg($password) . ' -o ? -d ? 2> /dev/null';
                        $app->system->exec_safe($command, $filename, $web_root);
                        $retval = $app->system->last_exec_retcode();
                        /*
                         * Exit code 50 can happen when zip fails to overwrite files that do not
                         * belong to selected user, so we can consider this situation as success
                         * with warnings.
                         */
                        $success = ($retval == 0 || $retval == 50);
                        if ($success) {
                            self::restoreFileOwnership($web_root, $web_user, $web_group);
                        }
                        break;
                    case 'rar':
                        $options = self::getUnRarOptions($password);
                        //First, test that the archive is correct and we have a correct password
                        $command = $user_prefix_cmd . " rar t " . $options . " ? ?";
                        //Rar requires trailing slash
                        $app->system->exec_safe($command, $filename, $web_root . '/');
                        $success = ($app->system->last_exec_retcode() == 0);
                        if ($success) {
                            //All good, now we can extract
                            $app->log('Archive test passed for ' . $full_filename, LOGLEVEL_DEBUG);
                            $command = $user_prefix_cmd . " rar x " . $options . " ? ?";
                            //Rar requires trailing slash
                            $app->system->exec_safe($command, $filename, $web_root . '/');
                            $retval = $app->system->last_exec_retcode();
                            //Exit code 9 can happen when we have file permission errors, in this case some
                            //files will be skipped during extraction.
                            $success = ($retval == 0 || $retval == 1 || $retval == 9);
                        } else {
                            $app->log('Archive test failed for ' . $full_filename, LOGLEVEL_DEBUG);
                        }
                        break;
                }
                if (strpos($backup_format, "tar_7z_") === 0) {
                    $options = self::get7zDecompressOptions($password);
                    //First, test that the archive is correct and we have a correct password
                    $command = $user_prefix_cmd . " 7z t " . $options . " ?";
                    $app->system->exec_safe($command, $filename);
                    $success = ($app->system->last_exec_retcode() == 0);
                        //All good, now we can extract
                        $app->log('Archive test passed for ' . $full_filename, LOGLEVEL_DEBUG);
                        $command = $user_prefix_cmd . " 7z x " . $options . " -so ? | tar xf - --directory ?";
                        $app->system->exec_safe($command, $filename, $web_root);
                        $retval = $app->system->last_exec_retcode();
                        $success = ($retval == 0 || $retval == 2);
                        $app->log('Archive test failed for ' . $full_filename, LOGLEVEL_DEBUG);
                if ($user_mode) {
                    unlink($filename);
                    if (file_exists($filename . '.bak')) rename($filename . '.bak', $filename);
                }
                if ($success) {
                    $app->log('Restored web backup ' . $full_filename, LOGLEVEL_DEBUG);
                    $result = true;
                } else {
                    $app->log('Failed to restore web backup ' . $full_filename . ', exit code ' . $retval, LOGLEVEL_ERROR);
                }
            $app->log('Failed to restore web backup ' . $filename . ', backup mode "' . $backup_mode . '" not recognized.', LOGLEVEL_DEBUG);
        $app->system->web_folder_protection($web_root, true);
    /**
     * Deletes backup copy
     * @param string $backup_format
     * @param string $backup_password
     * @param string $backup_dir
     * @param string $filename
     * @param string $backup_mode
     * @param string $backup_type
     * @param int $domain_id
     * @param bool true on success
     * @author Jorge Muñoz <elgeorge2k@gmail.com>
     */
    public static function deleteBackup($backup_format, $backup_password, $backup_dir, $filename, $backup_mode, $backup_type, $domain_id) {
        global $app, $conf;
        $server_id = $conf['server_id'];
        $success = false;

        if (empty($backup_format) || $backup_format == 'default') {
            $backup_format = self::getDefaultBackupFormat($backup_mode, $backup_type);
        }
        if(self::backupModeIsRepos($backup_mode)) {
            $repos_password = '';
            $backup_archive = $filename;
            $backup_repos_folder = self::getBackupReposFolder($backup_mode, $backup_type);
            if ($backup_type != 'web') {
                preg_match('@^(manual-)?db_(?P<db>.+)_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$@', $backup_archive, $matches);
                if (!isset($matches['db']) || empty($matches['db'])) {
                    $app->log('Failed to detect database name during delete of ' . $backup_archive, LOGLEVEL_ERROR);
                    return false;
                }
                $db_name = $matches['db'];
                $backup_repos_folder .= '_' . $db_name;
            }
            $backup_repos_path = $backup_dir . '/' . $backup_repos_folder;
            $archives = self::getReposArchives($backup_mode, $backup_repos_path, $repos_password);
            if (is_array($archives) && in_array($backup_archive, $archives)) {
                $success = self::deleteArchive($backup_mode, $backup_repos_path, $backup_archive, $repos_password);
            } else {
                $success = true;
            }
        } else {
            if(file_exists($backup_dir.'/'.$filename) && !stristr($backup_dir.'/'.$filename, '..') && !stristr($backup_dir.'/'.$filename, 'etc')) {
                $success = unlink($backup_dir.'/'.$filename);
            } else {
                $success = true;
            }
        }
        if ($success) {
            $sql = "DELETE FROM web_backup WHERE server_id = ? AND parent_domain_id = ? AND filename = ?";
            $app->db->query($sql, $server_id, $domain_id, $filename);
            if($app->running_on_slaveserver())
                $app->dbmaster->query($sql, $server_id, $domain_id, $filename);
            $app->log($sql . ' - ' . json_encode([$server_id, $domain_id, $filename]), LOGLEVEL_DEBUG);
        }
        return $success;
    }
    /**
     * Downloads the backup copy
     * @param string $backup_format
     * @param string $password
     * @param string $backup_dir
     * @param string $filename
     * @param string $backup_mode
     * @param string $backup_type
     * @param array $domain web_domain record
     * @param bool true on success
     * @author Jorge Muñoz <elgeorge2k@gmail.com>
     */
    public static function downloadBackup($backup_format, $password, $backup_dir, $filename, $backup_mode, $backup_type, $domain)
    {
        global $app;

        $success = false;

        if (self::backupModeIsRepos($backup_mode)) {
            $backup_archive = $filename;
            //When stored in repos, we first get target backup format to generate final download file
            $repos_password = '';
            $server_id = $domain['server_id'];
            $password = $domain['backup_encrypt'] == 'y' ? trim($domain['backup_password']) : '';
            $server_config = $app->getconf->get_server_config($server_id, 'server');
            $backup_tmp = trim($server_config['backup_tmp']);

            if ($backup_type == 'web') {
                $backup_format = $domain['backup_format_web'];
                if (empty($backup_format) || $backup_format == 'default') {
                    $backup_format = self::getDefaultBackupFormat($server_backup_mode, 'web');
                }
                $backup_repos_folder = self::getBackupReposFolder($backup_mode, 'web');
                $extension = self::getBackupWebExtension($backup_format);
            } else {
                if (preg_match('@^(manual-)?db_(?P<db>.+)_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$@', $backup_archive, $matches)) {
                    $db_name = $matches['db'];
                    $backup_format = $domain['backup_format_db'];
                    if (empty($backup_format)) {
                        $backup_format = self::getDefaultBackupFormat($server_backup_mode, $backup_type);
                    }
                    $backup_repos_folder = self::getBackupReposFolder($backup_mode, $backup_type) . '_' . $db_name;
                    $extension = self::getBackupDbExtension($backup_format);
                } else {
                    $app->log('Failed to detect database name during download of ' . $backup_archive, LOGLEVEL_ERROR);
                    $db_name = null;
                }
            }
            if ( ! empty($extension)) {
                $filename .= $extension;
                $backup_repos_path = $backup_dir . '/' . $backup_repos_folder;
                $full_archive_path = $backup_repos_path . '::' . $backup_archive;
                $archives = self::getReposArchives($backup_mode, $backup_repos_path, $repos_password);
            } else {
                $archives = null;
            }
            if (is_array($archives)) {
                if (in_array($backup_archive, $archives)) {
                    $app->log('Extracting ' . $backup_type . ' backup from repository archive '.$full_archive_path. ' to ' . $domain['document_root'].'/backup/' . $filename, LOGLEVEL_DEBUG);
                    switch ($backup_mode) {
                        case 'borg':
                            if ($backup_type == 'mysql') {
                                if (strpos($extension, '.sql.gz') === 0 || strpos($extension, '.sql.bz2') === 0) {
                                    //* .sql.gz and .sql.bz2 don't need a source file, so we can just pipe through the compression command
                                    $ccmd = strpos($extension, '.sql.gz') === 0 ? 'gzip' : 'bzip2';
                                    $command = self::getBorgCommand('borg extract', $repos_password) . ' --stdout ? stdin | ' . $ccmd . ' -c > ?';
                                    $success = $app->system->exec_safe($command, $full_archive_path, $domain['document_root'].'/backup/'.$filename) == 0;
                                } else {
                                    $tmp_extract = $backup_tmp . '/' . $backup_archive . '.sql';
                                    if (file_exists($tmp_extract)) {
                                        unlink($tmp_extract);
                                    }
                                    $command = self::getBorgCommand('borg extract', $repos_password) . ' --stdout ? stdin > ?';
                                    $app->system->exec_safe($command, $full_archive_path, $tmp_extract);
                                }
                            } else {
                                if (strpos($extension, '.tar') === 0 && ($password == '' || strpos($extension, '.tar.7z') !== 0)) {
                                    //* .tar.gz, .tar.bz2, etc are supported via borg export-tar, if they don't need encryption
                                    $command = self::getBorgCommand('borg export-tar', $repos_password) . ' ? ?';
                                    $app->system->exec_safe($command, $full_archive_path, $domain['document_root'].'/backup/'.$filename);
                                    $success = $app->system->last_exec_retcode() == 0;
                                } else {
                                    $tmp_extract = tempnam($backup_tmp, $backup_archive);
                                    unlink($tmp_extract);
                                    mkdir($tmp_extract);
                                    $command = 'cd ' . $tmp_extract . ' && ' . self::getBorgCommand('borg extract --nobsdflags', $repos_password) . ' ?';
                                    $app->system->exec_safe($command, $full_archive_path);
                                    if ($app->system->last_exec_retcode() != 0) {
                                        $app->log('Extraction of ' . $full_archive_path . ' into ' . $tmp_extract . ' failed.', LOGLEVEL_ERROR);
                                        $tmp_extract = null;
                                    }
                                }
                            }
                            break;
                    }
                    if ( ! empty($tmp_extract)) {
                        if (is_dir($tmp_extract)) {
                            $web_config = $app->getconf->get_server_config($server_id, 'web');
                            $http_server_user = $web_config['user'];
                            $success = self::runWebCompression($backup_format, [], 'rootgz', $tmp_extract, $domain['document_root'].'/backup/', $filename, $domain['system_user'], $domain['system_group'], $http_server_user, $backup_tmp, $password);
                        } else {
                            self::runDatabaseCompression($backup_format, dirname($tmp_extract), basename($tmp_extract), $filename, $backup_tmp, $password)
                                AND $success = rename(dirname($tmp_extract) . '/' . $filename, $domain['document_root'].'/backup/'. $filename);
                        }
                        if ($success) {
                            $app->system->exec_safe('rm -Rf ?', $tmp_extract);
                        } else {
                             $app->log('Failed to run compression of ' . $tmp_extract . ' into ' . $domain['document_root'].'/backup/' . $filename . ' failed.', LOGLEVEL_ERROR);
                        }
                    }
                } else {
                    $app->log('Failed to find archive ' . $full_archive_path . ' for download', LOGLEVEL_ERROR);
                }
            }
            if ($success) {
                $app->log('Download of archive ' . $full_archive_path . ' into ' . $domain['document_root'].'/backup/'.$filename . ' succeeded.', LOGLEVEL_DEBUG);
            }
        }
        //* Copy the backup file to the backup folder of the website
        elseif(file_exists($backup_dir.'/'.$filename) && file_exists($domain['document_root'].'/backup/') && !stristr($backup_dir.'/'.$filename, '..') && !stristr($backup_dir.'/'.$filename, 'etc')) {
            $success = copy($backup_dir.'/'.$filename, $domain['document_root'].'/backup/'.$filename);
        }
        if (file_exists($domain['document_root'].'/backup') && fileowner($domain['document_root'].'/backup') === 0) {
            // Fix old web backup dir permissions from before #6628
            chown($domain['document_root'].'/backup', $domain['system_user']);
            chgrp($domain['document_root'].'/backup', $domain['system_group']);
            $app->log('Fixed old directory permissions from root:root to '.$domain['system_user'].':'.$domain['system_group'].' for backup dir '.$domain['document_root'].'/backup/', LOGLEVEL_DEBUG);
        }
        if (file_exists($domain['document_root'].'/backup/'.$filename)) {
            // Change backup file permissions
            chgrp($domain['document_root'].'/backup/'.$filename, $domain['system_group']);
            chown($domain['document_root'].'/backup/'.$filename, $domain['system_user']);
            chmod($domain['document_root'].'/backup/'.$filename,0600);
            $app->log('Ready '.$domain['document_root'].'/backup/'.$filename, LOGLEVEL_DEBUG);
            return true;
        } else {
            $app->log('Failed download of '.$domain['document_root'].'/backup/'.$filename , LOGLEVEL_ERROR);
            return false;
        }
    }


    /**
     * Returns a compression method, for example returns bzip2 for tar_7z_bzip2
     * @param string $format
     * @return false|string
     * @author Ramil Valitov <ramilvalitov@gmail.com>
     */
    protected static function getCompressionMethod($format)
    {
        $pos = strrpos($format, "_");
        return substr($format, $pos + 1);
    }

    /**
     * Returns default options for compressing rar
     * @param string $backup_tmp temporary directory that rar can use
     * @param string|null $password backup password if any
     * @return string options for rar
     */
    protected static function getRarOptions($backup_tmp, $password)
    {
        /**
         * All rar options are listed here:
         * https://documentation.help/WinRAR/HELPCommands.htm
         * https://documentation.help/WinRAR/HELPSwitches.htm
         * Some compression profiles and different versions of rar may use different default values, so it's better
         * to specify everything explicitly.
         * The difference between compression methods is not big in terms of file size, but is huge in terms of
         * CPU and RAM consumption. Therefore it makes sense only to use fastest the compression method.
         */
        $options = array(
            /**
             * Start with fastest compression method (least compressive)
             */
            '-m1',

            /**
             * Disable solid archiving.
             * Never use solid archive: it's very slow and requires to read and sort all files first
             */
            '-S-',

            /**
             * Ignore default profile and environment variables
             * https://documentation.help/WinRAR/HELPSwCFGm.htm
             */
            '-CFG-',

            /**
             *  Disable error messages output
             * https://documentation.help/WinRAR/HELPSwINUL.htm
             */
            '-inul',

            /**
             * Lock archive: this switch prevents any further archive modifications by rar
             * https://documentation.help/WinRAR/HELPSwK.htm
             */
            '-k',

            /**
             * Create archive in RAR 5.0 format
             * https://documentation.help/WinRAR/HELPSwMA.htm
             */
            '-ma',

            /**
             * Set dictionary size to 16Mb.
             * When archiving, rar needs about 6x memory of specified dictionary size.
             * https://documentation.help/WinRAR/HELPSwMD.htm
             */
            '-md16m',

            /**
             * Use only one CPU thread
             * https://documentation.help/WinRAR/HELPSwMT.htm
             */
            '-mt1',

            /**
             * Use this switch when archiving to save file security information and when extracting to restore it.
             * It stores file owner, group, file permissions and audit information.
             * https://documentation.help/WinRAR/HELPSwOW.htm
             */
            '-ow',

            /**
             * Overwrite all
             * https://documentation.help/WinRAR/HELPSwO.htm
             */
            '-o+',

            /**
             * Exclude base folder from names.
             * Required for correct directory structure inside archive
             * https://documentation.help/WinRAR/HELPSwEP1.htm
             */
            '-ep1',

            /**
             * Never add quick open information.
             * This information is useful only if you want to read the contents of archive (list of files).
             * Besides it can increase the archive size. As we need the archive only for future complete extraction,
             * there's no need to use this information at all.
             * https://documentation.help/WinRAR/HELPSwQO.htm
             */
            '-qo-',

            /**
             * Set lowest task priority (1) and 10ms sleep time between read/write operations.
             * https://documentation.help/WinRAR/HELPSwRI.htm
             */
            '-ri1:10',

            /**
             * Temporary folder
             * https://documentation.help/WinRAR/HELPSwW.htm
             */
            '-w' . escapeshellarg($backup_tmp),

            /**
             * Assume Yes on all queries
             * https://documentation.help/WinRAR/HELPSwY.htm
             */
            '-y',
        );

        $options = implode(" ", $options);

        if (!empty($password)) {
            /**
             * Encrypt both file data and headers
             * https://documentation.help/WinRAR/HELPSwHP.htm
             */
            $options .= ' -HP' . escapeshellarg($password);
        }
        return $options;
    }

    /**
     * Returns default options for decompressing rar
     * @param string|null $password backup password if any
     * @return string options for rar
     */
    protected static function getUnRarOptions($password)
    {
        /**
         * All rar options are listed here:
         * https://documentation.help/WinRAR/HELPCommands.htm
         * https://documentation.help/WinRAR/HELPSwitches.htm
         * Some compression profiles and different versions of rar may use different default values, so it's better
         * to specify everything explicitly.
         * The difference between compression methods is not big in terms of file size, but is huge in terms of
         * CPU and RAM consumption. Therefore it makes sense only to use fastest the compression method.
         */
        $options = array(
            /**
             * Ignore default profile and environment variables
             * https://documentation.help/WinRAR/HELPSwCFGm.htm
             */
            '-CFG-',

            /**
             *  Disable error messages output
             * https://documentation.help/WinRAR/HELPSwINUL.htm
             */
            '-inul',

            /**
             * Use only one CPU thread
             * https://documentation.help/WinRAR/HELPSwMT.htm
             */
            '-mt1',

            /**
             * Use this switch when archiving to save file security information and when extracting to restore it.
             * It stores file owner, group, file permissions and audit information.
             * https://documentation.help/WinRAR/HELPSwOW.htm
             */
            '-ow',

            /**
             * Overwrite all
             * https://documentation.help/WinRAR/HELPSwO.htm
             */
            '-o+',

            /**
             * Set lowest task priority (1) and 10ms sleep time between read/write operations.
             * https://documentation.help/WinRAR/HELPSwRI.htm
             */
            '-ri1:10',

            /**
             * Assume Yes on all queries
             * https://documentation.help/WinRAR/HELPSwY.htm
             */
            '-y',
        );

        $options = implode(" ", $options);

        if (!empty($password)) {
            $options .= ' -P' . escapeshellarg($password);
        }
        return $options;
    }

    /**
     * Returns compression options for 7z
     * @param string $format compression format used in 7z
     * @param string $password password if any
     * @return string
     */
    protected static function get7zCompressOptions($format, $password)
    {
        $method = self::getCompressionMethod($format);
        /**
         * List of 7z options is here:
         * https://linux.die.net/man/1/7z
         * https://sevenzip.osdn.jp/chm/cmdline/syntax.htm
         * https://sevenzip.osdn.jp/chm/cmdline/switches/
         */
        $options = array(
            /**
             * Use 7z format (container)
             */
            '-t7z',

            /**
             * Compression method (LZMA, LZMA2, etc.)
             * https://sevenzip.osdn.jp/chm/cmdline/switches/method.htm
             */
            '-m0=' . $method,

            /**
             * Fastest compression method
             */
            '-mx=1',

            /**
             * Disable solid mode
             */
            '-ms=off',

            /**
             * Disable multithread mode, use less CPU
             */
            '-mmt=off',

            /**
             * Disable multithread mode for filters, use less CPU
             */
            '-mmtf=off',

            /**
             * Disable progress indicator
             */
            '-bd',

            /**
             * Assume yes on all queries
             * https://sevenzip.osdn.jp/chm/cmdline/switches/yes.htm
             */
            '-y',
        );
        $options = implode(" ", $options);
        switch (strtoupper($method)) {
            case 'LZMA':
            case 'LZMA2':
                /**
                 * Dictionary size is 5Mb.
                 * 7z can use 12 times more RAM
                 */
                $options .= ' -md=5m';
                break;
            case 'PPMD':
                /**
                 * Dictionary size is 64Mb.
                 * It's the maximum RAM that 7z is allowed to use.
                 */
                $options .= ' -mmem=64m';
                break;
        }
        if (!empty($password)) {
            $options .= ' -mhe=on -p' . escapeshellarg($password);
        }
        return $options;
    }

    /**
     * Returns decompression options for 7z
     * @param string $password password if any
     * @return string
     */
    protected static function get7zDecompressOptions($password)
    {
        /**
         * List of 7z options is here:
         * https://linux.die.net/man/1/7z
         * https://sevenzip.osdn.jp/chm/cmdline/syntax.htm
         * https://sevenzip.osdn.jp/chm/cmdline/switches/
         */
        $options = array(
            /**
             * Disable multithread mode, use less CPU
             */
            '-mmt=off',

            /**
             * Disable progress indicator
             */
            '-bd',

            /**
             * Assume yes on all queries
             * https://sevenzip.osdn.jp/chm/cmdline/switches/yes.htm
             */
            '-y',
        );
        $options = implode(" ", $options);
        if (!empty($password)) {
            $options .= ' -p' . escapeshellarg($password);
        }
        return $options;
    }

    /**
     * Get borg command with password appended to the base command
     * @param $command Base command to add password to
     * @param $password Password to add
     * @param $is_new Specify if command is for a new borg repository initialization
     */
    protected static function getBorgCommand($command, $password, $is_new = false)
    {
        if ($password) {
            if ($is_new) {
                return "BORG_NEW_PASSPHRASE='" . escapeshellarg($password) . "' " . $command;
            }
            return "BORG_PASSPHRASE='" . escapeshellarg($password) . "' " . $command;
        }
        return $command;
    }
    /**
     * Obtains command line options for "borg create" command.
     * @param string $compression Compression options are validated and fixed if necessary.
     *      See: https://borgbackup.readthedocs.io/en/stable/internals/data-structures.html#compression