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;
                }
Loading full blame...