Skip to content
backup.inc.php 98.2 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>
 * @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;
    }

    /**
     * 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>
     */
    public static function restoreBackupDatabase($backup_format, $password, $backup_dir, $filename, $backup_mode, $backup_type)
    {
        global $app;

Jorge Muñoz's avatar
Jorge Muñoz committed
        //* Added for compatibility with repository type backups
        if (self::formatIsRepos($backup_format, 'mysql')) {
            return self::restoreBackupDatabaseRepos($backup_format, $password, $backup_dir, $filename, $backup_mode, $backup_type);
        }
        //* END

        //* Load sql dump into db
        include 'lib/mysql_clientdb.conf';

        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);

        if (file_exists($full_filename) && !empty($extension)) {
            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);
                return false;
            }
            $db_name = $matches['db'];
            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
Loading full blame...