Esempio n. 1
0
 public static function test($settings)
 {
     $email = $settings['address'];
     pb_backupbuddy::status('details', 'Testing email destination. Sending ImportBuddy.php.');
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     $importbuddy_temp = backupbuddy_core::getTempDirectory() . 'importbuddy_' . pb_backupbuddy::random_string(10) . '.php.tmp';
     // Full path & filename to temporary importbuddy
     backupbuddy_core::importbuddy($importbuddy_temp);
     // Create temporary importbuddy.
     $files = array($importbuddy_temp);
     if (pb_backupbuddy::$options['email_return'] != '') {
         $email_return = pb_backupbuddy::$options['email_return'];
     } else {
         $email_return = get_option('admin_email');
     }
     $headers = 'From: BackupBuddy <' . $email_return . '>' . "\r\n";
     $wp_mail_result = wp_mail($email, 'BackupBuddy Test', 'BackupBuddy destination test for ' . site_url(), $headers, $files);
     pb_backupbuddy::status('details', 'Sent test email.');
     @unlink($importbuddy_temp);
     if ($wp_mail_result === true) {
         // WP sent. Hopefully it makes it!
         return true;
     } else {
         // WP couldn't try to send.
         echo 'WordPress was unable to attempt to send email. Check your WordPress & server settings.';
         return false;
     }
 }
Esempio n. 2
0
 function __construct($file, $read_only = false, $ignore_lock = false, $create_file = false)
 {
     $this->_file = $file;
     $this->_read_only = $read_only;
     // If read-only then ignore locks is forced.
     if ($read_only === true) {
         $ignore_lock = true;
     }
     if (!file_exists(dirname($file))) {
         // Directory exist?
         pb_backupbuddy::anti_directory_browsing(dirname($file), $die_on_fail = false, $deny_all = true);
     }
     /*
     if ( ! file_exists( $file ) ) { // File exist?
     	//$this->save();
     }
     */
     $this->load($ignore_lock, $create_file);
 }
Esempio n. 3
0
 public function destination_send($destination_settings, $files, $send_id = '', $delete_after = false, $identifier = '', $isRetry = false)
 {
     pb_backupbuddy::status('details', 'Beginning cron destination_send. Unique ID: `' . $identifier . '`.');
     if ('' != $identifier) {
         $lockFile = backupbuddy_core::getLogDirectory() . 'cronSend-' . $identifier . '.lock';
         pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
         if (@file_exists($lockFile)) {
             // Lock exists already. Duplicate run?
             $attempts = @file_get_contents($lockFile);
             $attempts++;
             pb_backupbuddy::status('warning', 'Lock file exists and now shows ' . $attempts . ' attempts.');
             $attempts = @file_get_contents($lockFile, $attempts);
             return;
         } else {
             // No lock yet.
             if (false === @file_put_contents($lockFile, '1')) {
                 pb_backupbuddy::status('warning', 'Unable to create destination send lock file `' . $lockFile . '`.');
             } else {
                 pb_backupbuddy::status('details', 'Create destination send lock file `' . $lockFile . '`.');
             }
         }
     }
     pb_backupbuddy::status('details', 'Launching destination send via cron.');
     if (!class_exists('backupbuddy_core')) {
         require_once pb_backupbuddy::plugin_path() . '/classes/core.php';
     }
     if (true === backupbuddy_core::destination_send($destination_settings, $files, $send_id, $delete_after, $isRetry)) {
         // completely finished, go ahead and clean up lock file.
         /* DO not delete here as we need to keep this locked down a little longer...
         			if ( '' != $identifier ) {
         				if ( true === @unlink( $lockFile ) ) {
         					pb_backupbuddy::status( 'details', 'Removed destination lock file.' );
         				} else {
         					pb_backupbuddy::status( 'warning', 'Unable to remove destination lock file `' . $lockFile . '`.' );
         				}
         			}
         			*/
     }
 }
// Calculate temp directory & lock it down.
$temp_dir = get_temp_dir();
$destination = $temp_dir . 'backupbuddy-' . $serial;
if (!file_exists($destination) && false === mkdir($destination)) {
    $error = 'Error #458485945b: Unable to create temporary location.';
    pb_backupbuddy::status('error', $error);
    die($error);
}
// If temp directory is within webroot then lock it down.
$temp_dir = str_replace('\\', '/', $temp_dir);
// Normalize for Windows.
$temp_dir = rtrim($temp_dir, '/\\') . '/';
// Enforce single trailing slash.
if (FALSE !== stristr($temp_dir, ABSPATH)) {
    // Temp dir is within webroot.
    pb_backupbuddy::anti_directory_browsing($destination);
}
unset($temp_dir);
$message = 'Extracting "' . $file . '" from archive "' . $archive_file . '" into temporary file "' . $destination . '". ';
echo '<!-- ';
pb_backupbuddy::status('details', $message);
echo $message;
$extractions = array($file => $temp_file);
$extract_result = $zipbuddy->extract(backupbuddy_core::getBackupDirectory() . $archive_file, $destination, $extractions);
if (false === $extract_result) {
    // failed.
    echo ' -->';
    $error = 'Error #584984458. Unable to extract.';
    pb_backupbuddy::status('error', $error);
    die($error);
} else {
Esempio n. 5
0
 public static function restore($archive_file, $files, $finalPath, &$zipbuddy = null)
 {
     if (!current_user_can(pb_backupbuddy::$options['role_access'])) {
         die('Error #473623. Access Denied.');
     }
     $serial = backupbuddy_core::get_serial_from_file($archive_file);
     // serial of archive.
     $success = false;
     foreach ($files as $file) {
         $file = str_replace('*', '', $file);
         // Remove any wildcard.
         if (file_exists($finalPath . $file) && is_dir($finalPath . $file)) {
             if (($file_count = @scandir($finalPath . $file)) && count($file_count) > 2) {
                 pb_backupbuddy::status('error', __('Error #9036. The destination directory being restored already exists and is NOT empty. The directory will not be restored to prevent inadvertently losing files within the existing directory. Delete existing directory first if you wish to proceed or restore individual files.', 'it-l10n-backupbuddy') . ' Existing directory: `' . $finalPath . $file . '`.');
                 return false;
             }
         }
     }
     if (null === $zipbuddy) {
         require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
         $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
     }
     // Calculate temp directory & lock it down.
     $temp_dir = get_temp_dir();
     $destination = $temp_dir . 'backupbuddy-' . $serial;
     if (!file_exists($destination) && false === mkdir($destination, 0777, true)) {
         $error = 'Error #458485945: Unable to create temporary location.';
         pb_backupbuddy::status('error', $error);
         return false;
     }
     // If temp directory is within webroot then lock it down.
     $temp_dir = str_replace('\\', '/', $temp_dir);
     // Normalize for Windows.
     $temp_dir = rtrim($temp_dir, '/\\') . '/';
     // Enforce single trailing slash.
     if (FALSE !== stristr($temp_dir, ABSPATH)) {
         // Temp dir is within webroot.
         pb_backupbuddy::anti_directory_browsing($destination);
     }
     unset($temp_dir);
     pb_backupbuddy::status('details', 'Extracting into temporary directory "' . $destination . '".');
     $prettyFilesList = array();
     foreach ($files as $fileSource => $fileDestination) {
         $prettyFilesList[] = $fileSource . ' => ' . $fileDestination;
     }
     pb_backupbuddy::status('details', 'Files to extract: `' . htmlentities(implode(', ', $prettyFilesList)) . '`.');
     unset($prettyFilesList);
     pb_backupbuddy::flush();
     // Do the actual extraction.
     $extract_success = true;
     if (false === $zipbuddy->extract($archive_file, $destination, $files)) {
         pb_backupbuddy::status('error', 'Error #584984458b. Unable to extract.');
         $extract_success = false;
     }
     if (true === $extract_success) {
         // Verify all files/directories to be extracted exist in temp destination directory. If any missing then delete everything and bail out.
         foreach ($files as &$file) {
             $file = str_replace('*', '', $file);
             // Remove any wildcard.
             if (!file_exists($destination . '/' . $file)) {
                 // Cleanup.
                 foreach ($files as $file) {
                     @trigger_error('');
                     // Clear out last error.
                     @unlink($destination . '/' . $file);
                     $last_error = error_get_last();
                     if (is_array($last_error)) {
                         pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                     }
                 }
                 pb_backupbuddy::status('error', 'Error #854783474. One or more expected files / directories missing.');
                 $extract_success = false;
                 break;
             }
         }
         unset($file);
         // Made it this far so files all exist. Move them all.
         foreach ($files as $file) {
             @trigger_error('');
             // Clear out last error.
             if (false === @rename($destination . '/' . $file, $finalPath . $file)) {
                 $last_error = error_get_last();
                 if (is_array($last_error)) {
                     //print_r( $last_error );
                     pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                 }
                 $error = 'Error #9035. Unable to move restored file `' . $destination . '/' . $file . '` to `' . $finalPath . $file . '`. Verify permissions on destination location & that the destination directory/file does not already exist.';
                 pb_backupbuddy::status('error', $error);
             } else {
                 $details = 'Moved `' . $destination . '/' . $file . '` to `' . $finalPath . $file . '`.<br>';
                 pb_backupbuddy::status('details', $details);
                 $success = true;
             }
         }
     }
     // end extract success.
     // Try to cleanup.
     if (file_exists($destination)) {
         if (false === pb_backupbuddy::$filesystem->unlink_recursive($destination)) {
             pb_backupbuddy::status('details', 'Unable to delete temporary holding directory `' . $destination . '`.');
         } else {
             pb_backupbuddy::status('details', 'Cleaned up temporary files.');
         }
     }
     if (true === $success) {
         pb_backupbuddy::status('message', 'File retrieval completed successfully.');
         return true;
     } else {
         return false;
     }
 }
Esempio n. 6
0
 public static function verify_directories($skipTempGeneration = false)
 {
     $success = true;
     // Update backup directory if unable to write to the defined one.
     if (!@is_writable(backupbuddy_core::getBackupDirectory())) {
         pb_backupbuddy::status('details', 'Backup directory invalid. Updating from `' . backupbuddy_core::getBackupDirectory() . '` to default.');
         pb_backupbuddy::$options['backup_directory'] = '';
         // Reset to default (blank).
         pb_backupbuddy::save();
     }
     $response = pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getBackupDirectory(), $die = false);
     if (false === $response) {
         $success = false;
     }
     // Update log directory if unable to write to the defined one.
     if (!@is_writable(backupbuddy_core::getLogDirectory())) {
         pb_backupbuddy::status('details', 'Log directory invalid. Updating from `' . backupbuddy_core::getLogDirectory() . '` to default.');
         pb_backupbuddy::$options['log_directory'] = '';
         // Reset to default (blank).
         pb_backupbuddy::save();
     }
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getLogDirectory(), $die = false);
     if (false === $response) {
         $success = false;
     }
     // Update temp directory if unable to write to the defined one.
     if (true !== $skipTempGeneration) {
         if (!@is_writable(backupbuddy_core::getTempDirectory())) {
             pb_backupbuddy::status('details', 'Temporary directory invalid. Updating from `' . backupbuddy_core::getTempDirectory() . '` to default.');
             pb_backupbuddy::$options['temp_directory'] = '';
             pb_backupbuddy::save();
         }
         pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
         if (false === $response) {
             $success = false;
         }
     }
     global $pb_backupbuddy_directory_verification;
     $pb_backupbuddy_directory_verification = $success;
     return $success;
 }
Esempio n. 7
0
/* BEGIN VERIFYING BACKUP DIRECTORY */
if (pb_backupbuddy::_POST('pb_backupbuddy_backup_directory') != '') {
    $backup_directory = pb_backupbuddy::_POST('pb_backupbuddy_backup_directory');
    $backup_directory = str_replace('\\', '/', $backup_directory);
    $backup_directory = rtrim($backup_directory, '/\\') . '/';
    // Enforce single trailing slash.
    if (!is_dir($backup_directory)) {
        if (false === @mkdir($backup_directory, 0755)) {
            pb_backupbuddy::alert('Error #4838594589: Selected backup directory does not exist and it could not be created. Verify the path is correct or manually create the directory and set proper permissions. Reset to default path.');
            $_POST['pb_backupbuddy_backup_directory'] = pb_backupbuddy::$options['backup_directory'];
            // Set back to previous value (aka unchanged).
        }
    }
    if (pb_backupbuddy::$options['backup_directory'] != $backup_directory) {
        // Directory differs. Needs updated in post var. Give messages here as this value is going to end up being saved.
        pb_backupbuddy::anti_directory_browsing($backup_directory);
        $old_backup_dir = pb_backupbuddy::$options['backup_directory'];
        $new_backup_dir = $backup_directory;
        // Move all files from old backup to new.
        $old_backups_moved = 0;
        $old_backups = glob($old_backup_dir . 'backup*.zip');
        if (!is_array($old_backups) || empty($old_backups)) {
            // On failure glob() returns false or an empty array depending on server settings so normalize here.
            $old_backups = array();
        }
        foreach ($old_backups as $old_backup) {
            if (false === rename($old_backup, $new_backup_dir . basename($old_backup))) {
                pb_backupbuddy::alert('ERROR: Unable to move backup "' . basename($old_backup) . '" to new storage directory. Manually move it or delete it for security and to prevent it from being backed up within backups.');
            } else {
                // rename success.
                $old_backups_moved++;
Esempio n. 8
0
    pb_backupbuddy::alert($errorMsg);
    return;
}
$restore->_state['defaultURL'] = $restore->getDefaultUrl();
$restore->_state['defaultDomain'] = $restore->getDefaultDomain();
if ('true' != pb_backupbuddy::_GET('deploy')) {
    // deployment mode pre-loads state data in a file instead of passing via post.
    $restore->_state = parse_options($restore->_state);
}
$restore->_state['skipUnzip'] = $skipUnzip;
// Set up state variables.
if ('db' == $restore->_state['dat']['backup_type'] || false == $restore->_state['restoreFiles']) {
    pb_backupbuddy::status('details', 'Database backup OR not restoring files.');
    $restore->_state['tempPath'] = ABSPATH . 'importbuddy/temp_' . pb_backupbuddy::random_string(12) . '/';
    $restore->_state['restoreFileRoot'] = $restore->_state['tempPath'];
    pb_backupbuddy::anti_directory_browsing($restore->_state['restoreFileRoot'], $die = false);
} else {
    pb_backupbuddy::status('details', 'Restoring files.');
    $restore->_state['restoreFileRoot'] = ABSPATH;
    // Restore files into current root.
}
// Parse submitted options for saving to state.
function parse_options($restoreData)
{
    if ('1' == pb_backupbuddy::_POST('restoreFiles')) {
        $restoreData['restoreFiles'] = true;
    } else {
        $restoreData['restoreFiles'] = false;
    }
    if ('1' == pb_backupbuddy::_POST('restoreDatabase')) {
        $restoreData['restoreDatabase'] = true;
Esempio n. 9
0
 function periodic_cleanup($backup_age_limit = 43200, $die_on_fail = true)
 {
     $max_importbuddy_age = 60 * 60 * 1;
     // 1hr - Max age, in seconds, importbuddy files can be there before cleaning up (delay useful if just imported and testing out site).
     pb_backupbuddy::status('message', 'Starting cleanup procedure for BackupBuddy v' . pb_backupbuddy::settings('version') . '.');
     if (!isset(pb_backupbuddy::$options)) {
         $this->load();
     }
     // TODO: Check for orphaned .gz files in root from PCLZip.
     // Cleanup backup itegrity portion of array.
     // (status logging info inside function)
     $this->trim_backups_integrity_stats();
     // Cleanup logs in pb_backupbuddy dirctory.
     pb_backupbuddy::status('details', 'Cleaning up old logs.');
     $log_directory = WP_CONTENT_DIR . '/uploads/pb_' . pb_backupbuddy::settings('slug') . '/';
     $files = glob($log_directory . '*.txt');
     if (is_array($files) && !empty($files)) {
         // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
         foreach ($files as $file) {
             $file_stats = stat($file);
             if (time() - $file_stats['mtime'] > $backup_age_limit) {
                 // If older than 12 hours, delete the log.
                 @unlink($file);
             }
         }
     }
     // Cleanup excess backup stats.
     pb_backupbuddy::status('details', 'Cleaning up backup stats.');
     if (count(pb_backupbuddy::$options['backups']) > 3) {
         // Keep a minimum number of backups in array for stats.
         $number_backups = count(pb_backupbuddy::$options['backups']);
         $kept_loop_count = 0;
         $needs_save = false;
         foreach (pb_backupbuddy::$options['backups'] as $backup_serial => $backup) {
             if ($number_backups - $kept_loop_count > 3) {
                 if (isset($backup['archive_file']) && !file_exists($backup['archive_file'])) {
                     unset(pb_backupbuddy::$options['backups'][$backup_serial]);
                     $needs_save = true;
                 } else {
                     $kept_loop_count++;
                 }
             }
         }
         if ($needs_save === true) {
             //echo 'saved';
             pb_backupbuddy::save();
         }
     }
     // Cleanup any temporary local destinations.
     pb_backupbuddy::status('details', 'Cleaning up any temporary local destinations.');
     foreach (pb_backupbuddy::$options['remote_destinations'] as $destination_id => $destination) {
         if ($destination['type'] == 'local' && (isset($destination['temporary']) && $destination['temporary'] === true)) {
             // If local and temporary.
             if (time() - $destination['created'] > $backup_age_limit) {
                 // Older than 12 hours; clear out!
                 pb_backupbuddy::status('details', 'Cleaned up stale local destination `' . $destination_id . '`.');
                 unset(pb_backupbuddy::$options['remote_destinations'][$destination_id]);
                 pb_backupbuddy::save();
             }
         }
     }
     // Cleanup excess remote sending stats.
     pb_backupbuddy::status('details', 'Cleaning up remote send stats.');
     $this->trim_remote_send_stats();
     // Check for orphaned backups in the data structure that havent been updates in 12+ hours & cleanup after them.
     pb_backupbuddy::status('details', 'Cleaning up data structure.');
     foreach ((array) pb_backupbuddy::$options['backups'] as $backup_serial => $backup) {
         if (isset($backup['updated_time'])) {
             if (time() - $backup['updated_time'] > $backup_age_limit) {
                 // If more than 12 hours has passed...
                 pb_backupbuddy::status('details', 'Cleaned up stale backup `' . $backup_serial . '`.');
                 $this->final_cleanup($backup_serial);
             }
         }
     }
     // Verify existance of anti-directory browsing files in backup directory.
     pb_backupbuddy::status('details', 'Verifying anti-directory browsing security on backup directory.');
     pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['backup_directory'], $die_on_fail);
     // Verify existance of anti-directory browsing files in status log directory.
     pb_backupbuddy::status('details', 'Verifying anti-directory browsing security on status log directory.');
     $status_directory = WP_CONTENT_DIR . '/uploads/pb_' . pb_backupbuddy::settings('slug') . '/';
     pb_backupbuddy::anti_directory_browsing($status_directory, $die_on_fail);
     // Handle high security mode archives directory .htaccess system. If high security backup directory mode: Make sure backup archives are NOT downloadable by default publicly. This is only lifted for ~8 seconds during a backup download for security. Overwrites any existing .htaccess in this location.
     if (pb_backupbuddy::$options['lock_archives_directory'] == '0') {
         // Normal security mode. Put normal .htaccess.
         pb_backupbuddy::status('details', 'Removing .htaccess high security mode for backups directory. Normal mode .htaccess to be added next.');
         // Remove high security .htaccess.
         if (file_exists(pb_backupbuddy::$options['backup_directory'] . '.htaccess')) {
             $unlink_status = @unlink(pb_backupbuddy::$options['backup_directory'] . '.htaccess');
             if ($unlink_status === false) {
                 pb_backupbuddy::alert('Error #844594. Unable to temporarily remove .htaccess security protection on archives directory to allow downloading. Please verify permissions of the BackupBuddy archives directory or manually download via FTP.');
             }
         }
         // Place normal .htaccess.
         pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['backup_directory'], $die_on_fail);
     } else {
         // High security mode. Make sure high security .htaccess in place.
         pb_backupbuddy::status('details', 'Adding .htaccess high security mode for backups directory.');
         $htaccess_creation_status = @file_put_contents(pb_backupbuddy::$options['backup_directory'] . '.htaccess', 'deny from all');
         if ($htaccess_creation_status === false) {
             pb_backupbuddy::alert('Error #344894545. Security Warning! Unable to create security file (.htaccess) in backups archive directory. This file prevents unauthorized downloading of backups should someone be able to guess the backup location and filenames. This is unlikely but for best security should be in place. Please verify permissions on the backups directory.');
         }
     }
     // Verify existance of anti-directory browsing files in temporary directory.
     pb_backupbuddy::status('details', 'Verifying anti-directory browsing security on temp directory.');
     pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['temp_directory'], $die_on_fail);
     // Remove any copy of importbuddy.php in root.
     pb_backupbuddy::status('details', 'Cleaning up importbuddy.php script in site root if it exists & is not very recent.');
     if (file_exists(ABSPATH . 'importbuddy.php')) {
         $modified = filemtime(ABSPATH . 'importbuddy.php');
         if (FALSE === $modified || time() > $modified + $max_importbuddy_age) {
             // If time modified unknown OR was modified long enough ago.
             pb_backupbuddy::status('details', 'Unlinked importbuddy.php in root of site.');
             unlink(ABSPATH . 'importbuddy.php');
         } else {
             pb_backupbuddy::status('details', 'SKIPPED unlinking importbuddy.php in root of site as it is fresh and may still be in use.');
         }
     }
     // Remove any copy of importbuddy directory in root.
     pb_backupbuddy::status('details', 'Cleaning up importbuddy directory in site root if it exists & is not very recent.');
     if (file_exists(ABSPATH . 'importbuddy/')) {
         $modified = filemtime(ABSPATH . 'importbuddy/');
         if (FALSE === $modified || time() > $modified + $max_importbuddy_age) {
             // If time modified unknown OR was modified long enough ago.
             pb_backupbuddy::status('details', 'Unlinked importbuddy directory recursively in root of site.');
             pb_backupbuddy::$filesystem->unlink_recursive(ABSPATH . 'importbuddy/');
         } else {
             pb_backupbuddy::status('details', 'SKIPPED unlinked importbuddy directory recursively in root of site as it is fresh and may still be in use.');
         }
     }
     // Remove any old temporary directories in wp-content/uploads/backupbuddy_temp/. Logs any directories it cannot delete.
     pb_backupbuddy::status('details', 'Cleaning up any old temporary zip directories in: wp-content/uploads/backupbuddy_temp/');
     $temp_directory = WP_CONTENT_DIR . '/uploads/backupbuddy_temp/';
     $files = glob($temp_directory . '*');
     if (is_array($files) && !empty($files)) {
         // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
         foreach ($files as $file) {
             if (strpos($file, 'index.') !== false || strpos($file, '.htaccess') !== false) {
                 // Index file or htaccess dont get deleted so go to next file.
                 continue;
             }
             $file_stats = stat($file);
             if (time() - $file_stats['mtime'] > $backup_age_limit) {
                 // If older than 12 hours, delete the log.
                 if (@pb_backupbuddy::$filesystem->unlink_recursive($file) === false) {
                     pb_backupbuddy::status('error', 'Unable to clean up (delete) temporary directory/file: `' . $file . '`. You should manually delete it or check permissions.');
                 }
             }
         }
     }
     // Remove any old temporary zip directories: wp-content/uploads/backupbuddy_backups/temp_zip_XXXX/. Logs any directories it cannot delete.
     pb_backupbuddy::status('details', 'Cleaning up any old temporary zip directories in backup directory temp location `' . pb_backupbuddy::$options['backup_directory'] . 'temp_zip_XXXX/`.');
     // $temp_directory = WP_CONTENT_DIR . '/uploads/backupbuddy_backups/temp_zip_*';
     $temp_directory = pb_backupbuddy::$options['backup_directory'] . 'temp_zip_*';
     $files = glob($temp_directory . '*');
     if (is_array($files) && !empty($files)) {
         // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
         foreach ($files as $file) {
             if (strpos($file, 'index.') !== false || strpos($file, '.htaccess') !== false) {
                 // Index file or htaccess dont get deleted so go to next file.
                 continue;
             }
             $file_stats = stat($file);
             if (time() - $file_stats['mtime'] > $backup_age_limit) {
                 // If older than 12 hours, delete the log.
                 if (@pb_backupbuddy::$filesystem->unlink_recursive($file) === false) {
                     pb_backupbuddy::status('error', 'Unable to clean up (delete) temporary directory/file: `' . $file . '`. You should manually delete it or check permissions.');
                 }
             }
         }
     }
     pb_backupbuddy::status('message', 'Finished cleanup procedure.');
 }
		return false;
	});
});
</script>
<?php 
// END TOUR.
// Check if performing an actual migration now. If so then load file and skip the rest of this page.
if (pb_backupbuddy::_GET('callback_data') != '' && pb_backupbuddy::_GET('callback_data') != 'importbuddy.php') {
    require_once '_migrate.php';
    return;
}
// Handle remote sending ImportBuddy.
if (pb_backupbuddy::_GET('callback_data') == 'importbuddy.php') {
    pb_backupbuddy::alert('<span id="pb_backupbuddy_ib_sent">Sending ImportBuddy file. This may take several seconds. Please wait ...</span>');
    pb_backupbuddy::flush();
    pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
    $importbuddy_file = backupbuddy_core::getTempDirectory() . 'importbuddy.php';
    // Render ImportBuddy to temp location.
    backupbuddy_core::importbuddy($importbuddy_file);
    if (file_exists($importbuddy_file)) {
        $response = backupbuddy_core::send_remote_destination($_GET['destination'], $importbuddy_file, $trigger = 'manual');
    } else {
        pb_backupbuddy::alert('Error #4589: Local importbuddy.php file not found for sending. Check directory permissions and / or manually migrating by downloading importbuddy.php.');
        $response = false;
    }
    if (file_exists($importbuddy_file)) {
        if (false === unlink($importbuddy_file)) {
            // Delete temporary ImportBuddy file.
            pb_backupbuddy::alert('Unable to delete file. For security please manually delete it: `' . $importbuddy_file . '`.');
        }
    }
Esempio n. 11
0
 public static function test($settings)
 {
     $settings = self::_normalizeSettings($settings);
     if (false === ($settings = self::_connect($settings))) {
         $error = 'Unable to connect with Google Drive. See log for details.';
         echo $error;
         pb_backupbuddy::status('error', $error);
         return false;
     }
     pb_backupbuddy::status('details', 'Testing Google Drive destination. Sending ImportBuddy.php.');
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     $importbuddy_temp = backupbuddy_core::getTempDirectory() . 'importbuddy_' . pb_backupbuddy::random_string(10) . '.php.tmp';
     // Full path & filename to temporary importbuddy
     backupbuddy_core::importbuddy($importbuddy_temp);
     // Create temporary importbuddy.
     $files = array($importbuddy_temp);
     $results = self::send($settings, $files, '', $delete_remote_after = true);
     @unlink($importbuddy_temp);
     if (true === $results) {
         echo 'Success sending test file to Google Drive. ';
         return true;
     } else {
         global $pb_backupbuddy_destination_errors;
         echo 'Failure sending test file to Google Drive. Details: `' . implode(', ', $pb_backupbuddy_destination_errors) . '`.';
         return false;
     }
 }
 function load_backup_dat()
 {
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     $dat_file = $this->import_options['extract_to'] . '/' . str_replace(ABSPATH, '', backupbuddy_core::getTempDirectory()) . $this->import_options['zip_id'] . '/backupbuddy_dat.php';
     $this->_backupdata = $this->get_backup_dat($dat_file);
 }
Esempio n. 13
0
 function pre_backup($serial, $type, $trigger, $pre_backup = array(), $post_backup = array(), $schedule_title = '', $export_plugins = array())
 {
     // Log some status information.
     pb_backupbuddy::status('details', __('Performing pre-backup procedures.', 'it-l10n-backupbuddy'));
     if ($type == 'full') {
         pb_backupbuddy::status('message', __('Full backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'db') {
         pb_backupbuddy::status('message', __('Database only backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'export') {
         pb_backupbuddy::status('message', __('Multisite Site Export mode.', 'it-l10n-backupbuddy'));
     } else {
         pb_backupbuddy::status('error', __('Unknown backup mode.', 'it-l10n-backupbuddy'));
     }
     //pb_backupbuddy::status( 'error', __( 'Error #9020: Testing.', 'it-l10n-backupbuddy' ) );
     // Delete all backup archives if this troubleshooting option is enabled.
     if (pb_backupbuddy::$options['delete_archives_pre_backup'] == '1') {
         pb_backupbuddy::status('message', 'Deleting all existing backups prior to backup as configured on the settings page.');
         $file_list = glob(pb_backupbuddy::$options['backup_directory'] . 'backup*.zip');
         if (is_array($file_list) && !empty($file_list)) {
             foreach ($file_list as $file) {
                 if (@unlink($file) === true) {
                     pb_backupbuddy::status('details', 'Deleted backup archive `' . basename($file) . '` based on settings to delete all backups.');
                 } else {
                     pb_backupbuddy::status('details', 'Unable to delete backup archive `' . basename($file) . '` based on settings to delete all backups. Verify permissions.');
                 }
             }
         }
     }
     // Generate unique serial ID.
     pb_backupbuddy::status('details', 'Backup serial generated: `' . $serial . '`.');
     $this->_backup =& pb_backupbuddy::$options['backups'][$serial];
     // Set reference.
     // Cleanup internal stats.
     pb_backupbuddy::status('details', 'Resetting statistics for last backup time and number of edits since last backup.');
     pb_backupbuddy::$options['last_backup'] = time();
     // Reset time since last backup.
     pb_backupbuddy::$options['edits_since_last'] = 0;
     // Reset edit stats for notifying user of how many posts/pages edited since last backup happened.
     pb_backupbuddy::$options['last_backup_serial'] = $serial;
     // Prepare some values for setting up the backup data.
     $siteurl_stripped = pb_backupbuddy::$classes['core']->backup_prefix();
     if (pb_backupbuddy::$options['force_compatibility'] == '1') {
         $force_compatibility = true;
     } else {
         $force_compatibility = false;
     }
     // Calculate customizable section of archive filename (date vs date+time).
     if (pb_backupbuddy::$options['archive_name_format'] == 'datetime') {
         // "datetime" = Date + time.
         $backupfile_datetime = date(self::ARCHIVE_NAME_FORMAT_DATETIME, pb_backupbuddy::$format->localize_time(time()));
     } else {
         // "date" = date only (the default).
         $backupfile_datetime = date(self::ARCHIVE_NAME_FORMAT_DATE, pb_backupbuddy::$format->localize_time(time()));
     }
     // Set up the backup data.
     $this->_backup = array('serial' => $serial, 'backup_mode' => pb_backupbuddy::$options['backup_mode'], 'type' => $type, 'start_time' => time(), 'finish_time' => 0, 'updated_time' => time(), 'status' => array(), 'archive_size' => 0, 'schedule_title' => $schedule_title, 'backup_directory' => pb_backupbuddy::$options['backup_directory'], 'archive_file' => pb_backupbuddy::$options['backup_directory'] . 'backup-' . $siteurl_stripped . '-' . $backupfile_datetime . '-' . $type . '-' . $serial . '.zip', 'trigger' => $trigger, 'force_compatibility' => $force_compatibility, 'steps' => array(), 'integrity' => array(), 'temp_directory' => '', 'backup_root' => '', 'export_plugins' => array(), 'additional_table_includes' => array(), 'additional_table_excludes' => array(), 'directory_exclusions' => pb_backupbuddy::$classes['core']->get_directory_exclusions());
     // Figure out paths.
     if ($this->_backup['type'] == 'full') {
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         $this->_backup['backup_root'] = ABSPATH;
         // ABSPATH contains trailing slash.
     } elseif ($this->_backup['type'] == 'db') {
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         $this->_backup['backup_root'] = $this->_backup['temp_directory'];
     } elseif ($this->_backup['type'] == 'export') {
         // WordPress unzips into wordpress subdirectory by default so must include that in path.
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         // We store temp data for export within the temporary WordPress installation within the temp directory. A bit confusing; sorry about that.
         $this->_backup['backup_root'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/';
     } else {
         pb_backupbuddy::status('error', __('Backup FAILED. Unknown backup type.', 'it-l10n-backupbuddy'));
         pb_backupbuddy::status('action', 'halt_script');
         // Halt JS on page.
     }
     // Plugins to export (only for MS exports).
     if (count($export_plugins) > 0) {
         $this->_backup['export_plugins'] = $export_plugins;
     }
     // Calculate additional database table inclusion/exclusion.
     $additional_includes = explode("\n", pb_backupbuddy::$options['mysqldump_additional_includes']);
     array_walk($additional_includes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_includes'] = array_unique($additional_includes);
     // removes duplicates.
     $additional_excludes = explode("\n", pb_backupbuddy::$options['mysqldump_additional_excludes']);
     array_walk($additional_excludes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_excludes'] = array_unique($additional_excludes);
     // removes duplicates.
     unset($additional_includes);
     unset($additional_excludes);
     /********* Begin setting up steps array. *********/
     if ($type == 'export') {
         pb_backupbuddy::status('details', 'Setting up export-specific steps.');
         $this->_backup['steps'][] = array('function' => 'ms_download_extract_wordpress', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_create_wp_config', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_plugins', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_themes', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_media', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_users_table', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     if (pb_backupbuddy::$options['skip_database_dump'] != '1') {
         // Backup database if not skipping.
         global $wpdb;
         // Default tables to backup.
         if (pb_backupbuddy::$options['backup_nonwp_tables'] == '1') {
             // Backup all tables.
             $base_dump_mode = 'all';
         } else {
             // Only backup matching prefix.
             $base_dump_mode = 'prefix';
         }
         // Calculate tables to dump based on the provided information. $tables will be an array of tables.
         $tables = $this->_calculate_tables($base_dump_mode, $this->_backup['additional_table_includes'], $this->_backup['additional_table_excludes']);
         // Tables we will try to break out into standalone steps if possible.
         $breakout_tables_defaults = array($wpdb->prefix . 'posts', $wpdb->prefix . 'postmeta');
         // Step through tables we want to break out and figure out which ones were indeed set to be backed up and break them out.
         $breakout_tables_calculated = array();
         // Calculated next.
         if (pb_backupbuddy::$options['breakout_tables'] == '0') {
             // Breaking out DISABLED.
             pb_backupbuddy::status('details', 'Breaking out tables DISABLED based on settings.');
         } else {
             // Breaking out ENABLED.
             pb_backupbuddy::status('details', 'Breaking out tables ENABLED based on settings. Tables to be broken out into individual steps: `' . implode(', ', $breakout_tables_defaults) . '`.');
             foreach ((array) $breakout_tables_defaults as $breakout_tables_default) {
                 if (in_array($breakout_tables_default, $tables)) {
                     $breakout_tables_calculated[] = $breakout_tables_default;
                     $tables = array_diff($tables, array($breakout_tables_default));
                     // Remove from main table backup list.
                 }
             }
         }
         unset($breakout_tables_defaults);
         // No longer needed.
         $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array($tables), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         // Set up backup steps for additional broken out tables.
         foreach ($breakout_tables_calculated as $breakout_table) {
             $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array(array($breakout_table)), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         }
     } else {
         pb_backupbuddy::status('message', __('Skipping database dump based on advanced options.', 'it-l10n-backupbuddy'));
     }
     $this->_backup['steps'][] = array('function' => 'backup_zip_files', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     if ($type == 'export') {
         $this->_backup['steps'][] = array('function' => 'ms_cleanup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     $this->_backup['steps'][] = array('function' => 'post_backup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     // Prepend and append pre backup and post backup steps.
     $this->_backup['steps'] = array_merge($pre_backup, $this->_backup['steps'], $post_backup);
     /********* End setting up steps array. *********/
     /********* Begin directory creation and security. *********/
     pb_backupbuddy::anti_directory_browsing($this->_backup['backup_directory']);
     // Prepare temporary directory for holding SQL and data file.
     if (!file_exists($this->_backup['temp_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temp_directory']) === false) {
             pb_backupbuddy::status('error', 'Error #9002. Unable to create temporary storage directory (' . $this->_backup['temp_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temp_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temp_directory'] . ')');
         return false;
     }
     pb_backupbuddy::anti_directory_browsing(ABSPATH . 'wp-content/uploads/backupbuddy_temp/');
     // Prepare temporary directory for holding ZIP file while it is being generated.
     $this->_backup['temporary_zip_directory'] = pb_backupbuddy::$options['backup_directory'] . 'temp_zip_' . $this->_backup['serial'] . '/';
     if (!file_exists($this->_backup['temporary_zip_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temporary_zip_directory']) === false) {
             pb_backupbuddy::status('details', 'Error #9002. Unable to create temporary ZIP storage directory (' . $this->_backup['temporary_zip_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temporary_zip_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temporary_zip_directory'] . ')');
         return false;
     }
     /********* End directory creation and security *********/
     //$this->echo();
     // Schedule cleanup of temporary files and such for XX hours in the future just in case everything goes wrong we dont leave junk too long.
     wp_schedule_single_event(time() + 48 * 60 * 60, pb_backupbuddy::cron_tag('final_cleanup'), array($serial));
     // Generate backup DAT (data) file containing details about the backup.
     if ($this->backup_create_dat_file($trigger) !== true) {
         pb_backupbuddy::status('details', __('Problem creating DAT file.', 'it-l10n-backupbuddy'));
         return false;
     }
     // Generating ImportBuddy file to include in the backup for FULL BACKUPS ONLY currently. Cannot put in DB because it would be in root and be excluded or conflict on extraction.
     if ($type == 'full') {
         pb_backupbuddy::status('details', 'Generating ImportBuddy tool to include in backup archive: `' . $this->_backup['temp_directory'] . 'importbuddy.php`.');
         pb_backupbuddy::$classes['core']->importbuddy($this->_backup['temp_directory'] . 'importbuddy.php');
         pb_backupbuddy::status('details', 'ImportBuddy generation complete.');
     }
     // Save all of this.
     pb_backupbuddy::save();
     pb_backupbuddy::status('details', __('Finished pre-backup procedures.', 'it-l10n-backupbuddy'));
     pb_backupbuddy::status('action', 'finish_settings');
     return true;
 }
Esempio n. 14
0
 public static function check_high_security_mode($die_on_fail = false)
 {
     // Handle high security mode archives directory .htaccess system. If high security backup directory mode: Make sure backup archives are NOT downloadable by default publicly. This is only lifted for ~8 seconds during a backup download for security. Overwrites any existing .htaccess in this location.
     if (pb_backupbuddy::$options['lock_archives_directory'] == '0') {
         // Normal security mode. Put normal .htaccess.
         pb_backupbuddy::status('details', 'Removing .htaccess high security mode for backups directory. Normal mode .htaccess to be added next.');
         // Remove high security .htaccess.
         if (file_exists(backupbuddy_core::getBackupDirectory() . '.htaccess')) {
             $unlink_status = @unlink(backupbuddy_core::getBackupDirectory() . '.htaccess');
             if ($unlink_status === false) {
                 pb_backupbuddy::alert('Error #844594. Unable to temporarily remove .htaccess security protection on archives directory to allow downloading. Please verify permissions of the BackupBuddy archives directory or manually download via FTP.');
             }
         }
         // Place normal .htaccess.
         pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getBackupDirectory(), $die_on_fail);
     } else {
         // High security mode. Make sure high security .htaccess in place.
         pb_backupbuddy::status('details', 'Adding .htaccess high security mode for backups directory.');
         $htaccess_creation_status = @file_put_contents(backupbuddy_core::getBackupDirectory() . '.htaccess', 'deny from all');
         if ($htaccess_creation_status === false) {
             pb_backupbuddy::alert('Error #344894545. Security Warning! Unable to create security file (.htaccess) in backups archive directory. This file prevents unauthorized downloading of backups should someone be able to guess the backup location and filenames. This is unlikely but for best security should be in place. Please verify permissions on the backups directory.');
         }
     }
 }
Esempio n. 15
0
 public function verify_directories()
 {
     $success = true;
     // Keep backup directory up to date.
     if (pb_backupbuddy::$options['backup_directory'] == '' || !@is_writable(pb_backupbuddy::$options['backup_directory'])) {
         $default_backup_dir = ABSPATH . 'wp-content/uploads/backupbuddy_backups/';
         pb_backupbuddy::status('details', 'Backup directory invalid. Updating from `' . pb_backupbuddy::$options['backup_directory'] . '` to the default `' . $default_backup_dir . '`.');
         pb_backupbuddy::$options['backup_directory'] = $default_backup_dir;
         pb_backupbuddy::save();
     }
     $response = pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['backup_directory'], $die = false);
     if (false === $response) {
         $success = false;
     }
     // Keep log directory up to date.
     if (pb_backupbuddy::$options['log_directory'] == '' || !@is_writable(pb_backupbuddy::$options['log_directory'])) {
         $default_log_dir = ABSPATH . 'wp-content/uploads/pb_backupbuddy/';
         pb_backupbuddy::status('details', 'Log directory invalid. Updating from `' . pb_backupbuddy::$options['log_directory'] . '` to the default `' . $default_log_dir . '`.');
         pb_backupbuddy::$options['log_directory'] = $default_log_dir;
         pb_backupbuddy::save();
     }
     pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['log_directory'], $die = false);
     if (false === $response) {
         $success = false;
     }
     // Keep temp directory up to date.
     if (pb_backupbuddy::$options['temp_directory'] != ABSPATH . 'wp-content/uploads/backupbuddy_temp/') {
         pb_backupbuddy::status('details', 'Temporary directory has changed. Updating from `' . pb_backupbuddy::$options['temp_directory'] . '` to `' . ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . '`.');
         pb_backupbuddy::$options['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/';
         pb_backupbuddy::save();
     }
     pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['temp_directory'], $die = false);
     if (false === $response) {
         $success = false;
     }
     global $pb_backupbuddy_directory_verification;
     $pb_backupbuddy_directory_verification = $success;
     return $success;
 }
}
unset($needs_saving);
// ********** END 3.0.43 -> 3.1 DATA MIGRATION **********
// ********** BEGIN 3.1.8.2 -> 3.1.8.3 DATA MIGRATION **********
if (pb_backupbuddy::$options['data_version'] < 4) {
    pb_backupbuddy::$options['data_version'] = '4';
    // Update data structure version to 4.
    pb_backupbuddy::$options['role_access'] = 'activate_plugins';
    // Change default role from `administrator` to `activate_plugins` capability.
    pb_backupbuddy::save();
}
// ********** END 3.1.8.2 -> 3.1.8.3 DATA MIGRATION **********
// ********** BEGIN 3.3.0 -> 3.3.0.1 BACKUP DATASTRUCTURE OPTIONS to FILEOPTIONS MIGRATION **********
if (pb_backupbuddy::$options['data_version'] < 5) {
    if (isset(pb_backupbuddy::$options['backups']) && count(pb_backupbuddy::$options['backups']) > 0) {
        pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getLogDirectory() . 'fileoptions/');
        require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
        foreach (pb_backupbuddy::$options['backups'] as $serial => $backup) {
            $backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
            $backup_options->options = $backup;
            if (true === $backup_options->save()) {
                unset(pb_backupbuddy::$options['backups'][$serial]);
            }
            unset($backup_options);
        }
    }
    pb_backupbuddy::$options['data_version'] = '5';
    pb_backupbuddy::save();
}
// ********** END 3.3.0 -> 3.3.0.1 BACKUP DATASTRUCTURE OPTIONS to FILEOPTIONS MIGRATION **********
// ********** BEGIN 4.0 UPGRADE **********
Esempio n. 17
0
 function pre_backup($serial, $type, $trigger, $pre_backup = array(), $post_backup = array(), $schedule_title = '', $export_plugins = array())
 {
     // Log some status information.
     pb_backupbuddy::status('details', __('Performing pre-backup procedures.', 'it-l10n-backupbuddy'));
     if ($type == 'full') {
         pb_backupbuddy::status('message', __('Full backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'db') {
         pb_backupbuddy::status('message', __('Database only backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'export') {
         pb_backupbuddy::status('message', __('Multisite Site Export mode.', 'it-l10n-backupbuddy'));
     } else {
         pb_backupbuddy::status('error', __('Unknown backup mode.', 'it-l10n-backupbuddy'));
     }
     // Delete all backup archives if this troubleshooting option is enabled.
     if (pb_backupbuddy::$options['delete_archives_pre_backup'] == '1') {
         pb_backupbuddy::status('message', 'Deleting all existing backups prior to backup as configured on the settings page.');
         $file_list = glob(pb_backupbuddy::$options['backup_directory'] . 'backup*.zip');
         if (is_array($file_list) && !empty($file_list)) {
             foreach ($file_list as $file) {
                 if (@unlink($file) === true) {
                     pb_backupbuddy::status('details', 'Deleted backup archive `' . basename($file) . '` based on settings to delete all backups.');
                 } else {
                     pb_backupbuddy::status('details', 'Unable to delete backup archive `' . basename($file) . '` based on settings to delete all backups. Verify permissions.');
                 }
             }
         }
     }
     // Generate unique serial ID.
     pb_backupbuddy::status('details', 'Backup serial generated: `' . $serial . '`.');
     $this->_backup =& pb_backupbuddy::$options['backups'][$serial];
     // Set reference.
     // Cleanup internal stats.
     pb_backupbuddy::status('details', 'Resetting statistics for last backup time and number of edits since last backup.');
     pb_backupbuddy::$options['last_backup'] = time();
     // Reset time since last backup.
     pb_backupbuddy::$options['edits_since_last'] = 0;
     // Reset edit stats for notifying user of how many posts/pages edited since last backup happened.
     pb_backupbuddy::$options['last_backup_serial'] = $serial;
     // Prepare some values for setting up the backup data.
     $siteurl_stripped = pb_backupbuddy::$classes['core']->backup_prefix();
     if (pb_backupbuddy::$options['force_compatibility'] == '1') {
         $force_compatibility = true;
     } else {
         $force_compatibility = false;
     }
     // Set up the backup data.
     $this->_backup = array('serial' => $serial, 'backup_mode' => pb_backupbuddy::$options['backup_mode'], 'type' => $type, 'start_time' => time(), 'finish_time' => 0, 'updated_time' => time(), 'status' => array(), 'schedule_title' => $schedule_title, 'backup_directory' => pb_backupbuddy::$options['backup_directory'], 'archive_file' => pb_backupbuddy::$options['backup_directory'] . 'backup-' . $siteurl_stripped . '-' . str_replace('-', '_', date('Y-m-d')) . '-' . $serial . '.zip', 'trigger' => $trigger, 'force_compatibility' => $force_compatibility, 'steps' => array(), 'integrity' => array(), 'temp_directory' => '', 'backup_root' => '', 'export_plugins' => array(), 'additional_table_includes' => array(), 'additional_table_excludes' => array());
     // Figure out paths.
     if ($this->_backup['type'] == 'full') {
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         $this->_backup['backup_root'] = ABSPATH;
         // ABSPATH contains trailing slash.
     } elseif ($this->_backup['type'] == 'db') {
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         $this->_backup['backup_root'] = $this->_backup['temp_directory'];
     } elseif ($this->_backup['type'] == 'export') {
         // WordPress unzips into wordpress subdirectory by default so must include that in path.
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         // We store temp data for export within the temporary WordPress installation within the temp directory. A bit confusing; sorry about that.
         $this->_backup['backup_root'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/';
     } else {
         pb_backupbuddy::status('error', __('Backup FAILED. Unknown backup type.', 'it-l10n-backupbuddy'));
         pb_backupbuddy::status('action', 'halt_script');
         // Halt JS on page.
     }
     // Plugins to export (only for MS exports).
     if (count($export_plugins) > 0) {
         $this->_backup['export_plugins'] = $export_plugins;
     }
     // Calculate additional database table inclusion/exclusion.
     $additional_includes = explode("\n", pb_backupbuddy::$options['mysqldump_additional_includes']);
     array_walk($additional_includes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_includes'] = $additional_includes;
     $additional_excludes = explode("\n", pb_backupbuddy::$options['mysqldump_additional_excludes']);
     array_walk($additional_excludes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_excludes'] = $additional_excludes;
     /********* Begin setting up steps array. *********/
     if ($type == 'export') {
         pb_backupbuddy::status('details', 'Setting up export-specific steps.');
         $this->_backup['steps'][] = array('function' => 'ms_download_extract_wordpress', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_create_wp_config', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_plugins', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_themes', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_media', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_users_table', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     if (pb_backupbuddy::$options['skip_database_dump'] != '1') {
         // Backup database if not skipping.
         $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     } else {
         pb_backupbuddy::status('message', __('Skipping database dump based on advanced options.', 'it-l10n-backupbuddy'));
     }
     $this->_backup['steps'][] = array('function' => 'backup_zip_files', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     if ($type == 'export') {
         $this->_backup['steps'][] = array('function' => 'ms_cleanup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     $this->_backup['steps'][] = array('function' => 'post_backup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     // Prepend and append pre backup and post backup steps.
     $this->_backup['steps'] = array_merge($pre_backup, $this->_backup['steps'], $post_backup);
     /********* End setting up steps array. *********/
     /********* Begin directory creation and security. *********/
     pb_backupbuddy::anti_directory_browsing($this->_backup['backup_directory']);
     // Prepare temporary directory for holding SQL and data file.
     if (!file_exists($this->_backup['temp_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temp_directory']) === false) {
             pb_backupbuddy::status('details', sprintf(__('Error #9002: Unable to create temporary storage directory (%s).', 'it-l10n-backupbuddy'), $this->_backup['temp_directory']));
             $this->error('Unable to create temporary storage directory (' . $this->_backup['temp_directory'] . ')', '9002');
             return false;
         }
     }
     if (!is_writable($this->_backup['temp_directory'])) {
         pb_backupbuddy::status('details', sprintf(__('Error #9015: Temp data directory is not writable. Check your permissions. (%s).', 'it-l10n-backupbuddy'), $this->_backup['temp_directory']));
         $this->error('Temp data directory is not writable. Check your permissions. (' . $this->_backup['temp_directory'] . ')', '9015');
         return false;
     }
     pb_backupbuddy::anti_directory_browsing(ABSPATH . 'wp-content/uploads/backupbuddy_temp/');
     // Prepare temporary directory for holding ZIP file while it is being generated.
     $this->_backup['temporary_zip_directory'] = pb_backupbuddy::$options['backup_directory'] . 'temp_zip_' . $this->_backup['serial'] . '/';
     if (!file_exists($this->_backup['temporary_zip_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temporary_zip_directory']) === false) {
             pb_backupbuddy::status('details', sprintf(__('Error #9002: Unable to create temporary ZIP storage directory (%s).', 'it-l10n-backupbuddy'), $this->_backup['temporary_zip_directory']));
             $this->error('Unable to create temporary ZIP storage directory (' . $this->_backup['temporary_zip_directory'] . ')', '9002');
             return false;
         }
     }
     if (!is_writable($this->_backup['temporary_zip_directory'])) {
         pb_backupbuddy::status('details', sprintf(__('Error #9015: Temp data directory is not writable. Check your permissions. (%s).', 'it-l10n-backupbuddy'), $this->_backup['temporary_zip_directory']));
         $this->error('Temp data directory is not writable. Check your permissions. (' . $this->_backup['temporary_zip_directory'] . ')', '9015');
         return false;
     }
     /********* End directory creation and security *********/
     // Schedule cleanup of temporary files and such for XX hours in the future just in case everything goes wrong we dont leave junk too long.
     wp_schedule_single_event(time() + 48 * 60 * 60, pb_backupbuddy::cron_tag('final_cleanup'), array($serial));
     // Generate backup DAT (data) file containing details about the backup.
     if ($this->backup_create_dat_file($trigger) !== true) {
         pb_backupbuddy::status('details', __('Problem creating DAT file.', 'it-l10n-backupbuddy'));
         return false;
     }
     // Generating ImportBuddy file to include in the backup for FULL BACKUPS ONLY currently. Cannot put in DB because it would be in root and be excluded or conflict on extraction.
     if ($type == 'full') {
         pb_backupbuddy::status('details', 'Generating ImportBuddy script to include in backup archive: `' . $this->_backup['temp_directory'] . 'importbuddy.php`.');
         pb_backupbuddy::$classes['core']->importbuddy($this->_backup['temp_directory'] . 'importbuddy.php');
         pb_backupbuddy::status('details', 'ImportBuddy generation complete.');
     }
     // Save all of this.
     pb_backupbuddy::save();
     pb_backupbuddy::status('details', __('Finished pre-backup procedures.', 'it-l10n-backupbuddy'));
     pb_backupbuddy::status('action', 'finish_settings');
     return true;
 }
 function pre_backup($serial, $archiveFile, $profile, $trigger, $pre_backup = array(), $post_backup = array(), $schedule_title = '', $export_plugins = array(), $deployDirection, $deployDestinationSettings)
 {
     pb_backupbuddy::status('startFunction', json_encode(array('function' => 'pre_backup', 'title' => 'Getting ready to backup')));
     $type = $profile['type'];
     // Log some status information.
     pb_backupbuddy::status('details', __('Performing pre-backup procedures.', 'it-l10n-backupbuddy'));
     if ($type == 'full') {
         pb_backupbuddy::status('message', __('Full backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'db') {
         pb_backupbuddy::status('message', __('Database only backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'files') {
         pb_backupbuddy::status('message', __('Files only backup mode.', 'it-l10n-backupbuddy'));
         //$profile['skip_database_dump'] = '1';
     } elseif ($type == 'export') {
         pb_backupbuddy::status('message', __('Multisite subsite export mode.', 'it-l10n-backupbuddy'));
     } else {
         pb_backupbuddy::status('error', 'Error #8587383: Unknown backup mode `' . htmlentities($type) . '`.');
     }
     if ('' != $deployDirection) {
         pb_backupbuddy::status('details', 'Deployment direction: `' . $deployDirection . '`.');
     }
     if ('1' == pb_backupbuddy::$options['prevent_flush']) {
         pb_backupbuddy::status('details', 'Flushing will be skipped based on advanced settings.');
     } else {
         pb_backupbuddy::status('details', 'Flushing will not be skipped (default).');
     }
     // Schedule daily housekeeping.
     if (false === wp_next_scheduled(pb_backupbuddy::cron_tag('housekeeping'))) {
         // if schedule does not exist...
         backupbuddy_core::schedule_event(time() + 60 * 60 * 2, 'daily', pb_backupbuddy::cron_tag('housekeeping'), array());
         // Add schedule.
     }
     // Verify directories.
     pb_backupbuddy::status('details', 'Verifying directories ...');
     if (false === backupbuddy_core::verify_directories()) {
         pb_backupbuddy::status('error', 'Error #18573. Error verifying directories. See details above. Backup halted.');
         pb_backupbuddy::status('haltScript', '');
         // Halt JS on page.
         die;
     } else {
         pb_backupbuddy::status('details', 'Directories verified.');
     }
     // Delete all backup archives if this troubleshooting option is enabled.
     if (pb_backupbuddy::$options['delete_archives_pre_backup'] == '1') {
         pb_backupbuddy::status('message', 'Deleting all existing backups prior to backup as configured on the settings page.');
         $file_list = glob(backupbuddy_core::getBackupDirectory() . 'backup*.zip');
         if (is_array($file_list) && !empty($file_list)) {
             foreach ($file_list as $file) {
                 if (@unlink($file) === true) {
                     pb_backupbuddy::status('details', 'Deleted backup archive `' . basename($file) . '` based on settings to delete all backups.');
                 } else {
                     pb_backupbuddy::status('details', 'Unable to delete backup archive `' . basename($file) . '` based on settings to delete all backups. Verify permissions.');
                 }
             }
         }
     }
     // Generate unique serial ID.
     pb_backupbuddy::status('details', 'Backup serial generated: `' . $serial . '`.');
     pb_backupbuddy::status('details', 'About to load fileoptions data in create mode.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #40.');
     $this->_backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
     if (true !== ($result = $this->_backup_options->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034 A. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         pb_backupbuddy::status('haltScript', '');
         // Halt JS on page.
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $this->_backup =& $this->_backup_options->options;
     // Set reference.
     // Cleanup internal stats. Deployments should not impact stats.
     if ('' == $deployDirection) {
         pb_backupbuddy::status('details', 'Updating statistics for last backup start.');
         pb_backupbuddy::$options['last_backup_start'] = time();
         // Reset time since last backup.
         pb_backupbuddy::$options['last_backup_serial'] = $serial;
         pb_backupbuddy::save();
     }
     // Output active plugins list for debugging...
     $activePlugins = get_option('active_plugins');
     pb_backupbuddy::status('details', 'Active WordPress plugins: `' . implode('; ', $activePlugins) . '`.');
     pb_backupbuddy::status('startSubFunction', json_encode(array('function' => 'wp_plugins_found', 'title' => 'Found ' . count($activePlugins) . ' active WordPress plugins.')));
     unset($activePlugins);
     // Compression to bool.
     /*
     if ( $profile['compression'] == '1' ) {
     	$profile['compression'] = true;
     } else {
     	$profile['compression'] = false;
     }
     */
     if (pb_backupbuddy::$options['compression'] == '1') {
         $compression = true;
     } else {
         $compression = false;
     }
     $archiveURL = '';
     $abspath = str_replace('\\', '/', ABSPATH);
     // Change slashes to handle Windows as we store backup_directory with Linux-style slashes even on Windows.
     $backup_dir = str_replace('\\', '/', backupbuddy_core::getBackupDirectory());
     if (FALSE !== stristr($backup_dir, $abspath)) {
         // Make sure file to download is in a publicly accessible location (beneath WP web root technically).
         $sitepath = str_replace($abspath, '', $backup_dir);
         $archiveURL = rtrim(site_url(), '/\\') . '/' . trim($sitepath, '/\\') . '/' . basename($archiveFile);
     }
     $forceSingleDatabaseFile = false;
     if ('1' == pb_backupbuddy::$options['force_single_db_file']) {
         $forceSingleDatabaseFile = true;
     }
     // Set up the backup data.
     $this->_backup = array('data_version' => 1, 'backupbuddy_version' => pb_backupbuddy::settings('version'), 'serial' => $serial, 'init_complete' => false, 'backup_mode' => $profile['backup_mode'], 'type' => $type, 'profile' => $profile, 'default_profile' => pb_backupbuddy::$options['profiles'][0], 'start_time' => time(), 'finish_time' => 0, 'updated_time' => time(), 'status' => array(), 'max_execution_time' => backupbuddy_core::adjustedMaxExecutionTime(), 'archive_size' => 0, 'schedule_title' => $schedule_title, 'backup_directory' => backupbuddy_core::getBackupDirectory(), 'archive_file' => $archiveFile, 'archive_url' => $archiveURL, 'trigger' => $trigger, 'zip_method_strategy' => pb_backupbuddy::$options['zip_method_strategy'], 'compression' => $compression, 'ignore_zip_warnings' => pb_backupbuddy::$options['ignore_zip_warnings'], 'ignore_zip_symlinks' => pb_backupbuddy::$options['ignore_zip_symlinks'], 'steps' => array(), 'integrity' => array(), 'temp_directory' => '', 'backup_root' => '', 'export_plugins' => array(), 'additional_table_includes' => array(), 'additional_table_excludes' => array(), 'directory_exclusions' => backupbuddy_core::get_directory_exclusions($profile, false, $serial), 'table_sizes' => array(), 'breakout_tables' => array(), 'force_single_db_file' => $forceSingleDatabaseFile, 'deployment_log' => '', 'deployment_direction' => $deployDirection, 'deployment_destination' => $deployDestinationSettings, 'runnerUID' => get_current_user_id());
     pb_backupbuddy::status('startSubFunction', json_encode(array('function' => 'file_excludes', 'title' => 'Found ' . count($this->_backup['directory_exclusions']) . ' file or directory exclusions.')));
     // Warn if excluding key paths.
     $alertFileExcludes = backupbuddy_core::alert_core_file_excludes($this->_backup['directory_exclusions']);
     foreach ($alertFileExcludes as $alertFileExcludeId => $alertFileExclude) {
         pb_backupbuddy::status('warning', $alertFileExclude);
     }
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     // Figure out paths.
     if ($this->_backup['type'] == 'full' || $this->_backup['type'] == 'files') {
         $this->_backup['temp_directory'] = backupbuddy_core::getTempDirectory() . $serial . '/';
         $this->_backup['backup_root'] = ABSPATH;
         // ABSPATH contains trailing slash.
     } elseif ($this->_backup['type'] == 'db') {
         $this->_backup['temp_directory'] = backupbuddy_core::getTempDirectory() . $serial . '/';
         $this->_backup['backup_root'] = $this->_backup['temp_directory'];
     } elseif ($this->_backup['type'] == 'export') {
         // WordPress unzips into wordpress subdirectory by default so must include that in path.
         $this->_backup['temp_directory'] = backupbuddy_core::getTempDirectory() . $serial . '/wordpress/wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         // We store temp data for export within the temporary WordPress installation within the temp directory. A bit confusing; sorry about that.
         $this->_backup['backup_root'] = backupbuddy_core::getTempDirectory() . $serial . '/wordpress/';
     } else {
         pb_backupbuddy::status('error', __('Backup FAILED. Unknown backup type.', 'it-l10n-backupbuddy'));
         pb_backupbuddy::status('haltScript', '');
         // Halt JS on page.
     }
     pb_backupbuddy::status('details', 'Temp directory: `' . $this->_backup['temp_directory'] . '`.');
     pb_backupbuddy::status('details', 'Backup root: `' . $this->_backup['backup_root'] . '`.');
     // Plugins to export (only for MS exports).
     if (count($export_plugins) > 0) {
         $this->_backup['export_plugins'] = $export_plugins;
     }
     // Calculate additional database table inclusion/exclusion.
     $additional_includes = explode("\n", $profile['mysqldump_additional_includes']);
     array_walk($additional_includes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_includes'] = array_unique($additional_includes);
     // removes duplicates.
     $additional_excludes = explode("\n", $profile['mysqldump_additional_excludes']);
     array_walk($additional_excludes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_excludes'] = array_unique($additional_excludes);
     // removes duplicates.
     unset($additional_includes);
     unset($additional_excludes);
     /********* Begin setting up steps array. *********/
     if ($type == 'export') {
         pb_backupbuddy::status('details', 'Setting up export-specific steps.');
         $this->_backup['steps'][] = array('function' => 'ms_download_extract_wordpress', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_create_wp_config', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_plugins', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_themes', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_media', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_users_table', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     if ('pull' != $deployDirection && '1' != $profile['skip_database_dump'] && $profile['type'] != 'files') {
         // Backup database if not skipping AND not a files only backup.
         global $wpdb;
         // Default tables to backup.
         if ($type == 'export') {
             // Multisite Subsite export only dumps tables specific to this subsite prefix.
             $base_dump_mode = 'prefix';
         } else {
             // Non-multisite export so use profile to determine tables to backup.
             if ($profile['backup_nonwp_tables'] == '1') {
                 // Backup all tables.
                 $base_dump_mode = 'all';
             } elseif ($profile['backup_nonwp_tables'] == '2') {
                 // Backup no tables by default. Relies on listed additional tables.
                 $base_dump_mode = 'none';
             } else {
                 // Only backup matching prefix.
                 $base_dump_mode = 'prefix';
             }
         }
         $additional_tables = $this->_backup['additional_table_includes'];
         if ($type == 'export') {
             global $wpdb;
             array_push($additional_tables, $wpdb->prefix . "users");
             array_push($additional_tables, $wpdb->prefix . "usermeta");
         }
         // Warn if excluding key WP tables.
         $tableExcludes = backupbuddy_core::alert_core_table_excludes($this->_backup['additional_table_excludes']);
         foreach ($tableExcludes as $tableExcludeId => $tableExclude) {
             pb_backupbuddy::status('warning', $tableExclude);
         }
         // Calculate tables to dump based on the provided information. $tables will be an array of tables.
         $tables = $this->_calculate_tables($base_dump_mode, $additional_tables, $this->_backup['additional_table_excludes']);
         pb_backupbuddy::status('startSubFunction', json_encode(array('function' => 'calculate_tables', 'title' => 'Found ' . count($tables) . ' tables to backup based on settings.', 'more' => 'Tables: ' . implode(', ', $tables))));
         // If calculations show NO database tables should be backed up then change mode to skip database dump.
         if (0 == count($tables)) {
             pb_backupbuddy::status('warning', 'WARNING #857272: No database tables will be backed up based on current settings. This will not be a complete backup. Adjust settings if this is not intended and use with caution. Skipping database dump step.');
             $profile['skip_database_dump'] = '1';
             $this->_backup['profile']['skip_database_dump'] = '1';
         } else {
             // One or more tables set to backup.
             // Obtain tables sizes. Surround each table name by a single quote and implode with commas for SQL query to get sizes.
             $tables_formatted = $tables;
             foreach ($tables_formatted as &$table_formatted) {
                 $table_formatted = "'{$table_formatted}'";
             }
             $tables_formatted = implode(',', $tables_formatted);
             $sql = "SHOW TABLE STATUS WHERE Name IN({$tables_formatted});";
             $rows = $wpdb->get_results($sql, ARRAY_A);
             if (false === $rows) {
                 pb_backupbuddy::alert('Error #85473474: Unable to retrieve table status. Query: `' . $sql . '`.', true);
                 return false;
             }
             $totalDatabaseSize = 0;
             foreach ($rows as $row) {
                 $this->_backup['table_sizes'][$row['Name']] = $row['Data_length'] + $row['Index_length'];
                 $totalDatabaseSize += $this->_backup['table_sizes'][$row['Name']];
             }
             unset($rows);
             unset($tables_formatted);
             $databaseSize = pb_backupbuddy::$format->file_size($totalDatabaseSize);
             pb_backupbuddy::status('details', 'Total calculated database size: `' . $databaseSize . '`.');
             // Step through tables we want to break out and figure out which ones were indeed set to be backed up and break them out.
             if (pb_backupbuddy::$options['breakout_tables'] == '0') {
                 // Breaking out DISABLED.
                 pb_backupbuddy::status('details', 'Breaking out tables DISABLED based on settings.');
             } else {
                 // Breaking out ENABLED.
                 // Tables we will try to break out into standalone steps if possible.
                 $breakout_tables_defaults = array($wpdb->prefix . 'posts', $wpdb->prefix . 'postmeta');
                 pb_backupbuddy::status('details', 'Breaking out tables ENABLED based on settings. Tables to be broken out into individual steps: `' . implode(', ', $breakout_tables_defaults) . '`.');
                 foreach ((array) $breakout_tables_defaults as $breakout_tables_default) {
                     if (in_array($breakout_tables_default, $tables)) {
                         $this->_backup['breakout_tables'][] = $breakout_tables_default;
                         $tables = array_diff($tables, array($breakout_tables_default));
                         // Remove from main table backup list.
                     }
                 }
                 unset($breakout_tables_defaults);
                 // No longer needed.
             }
             $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array($tables), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
             // Set up backup steps for additional broken out tables.
             foreach ((array) $this->_backup['breakout_tables'] as $breakout_table) {
                 $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array(array($breakout_table)), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
             }
         }
         // end there being tables to backup.
     } else {
         pb_backupbuddy::status('message', __('Skipping database dump based on settings / profile type.', 'it-l10n-backupbuddy') . ' Backup type: `' . $type . '`.');
     }
     if ('pull' != $deployDirection) {
         $this->_backup['steps'][] = array('function' => 'backup_zip_files', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         if ($type == 'export') {
             $this->_backup['steps'][] = array('function' => 'ms_cleanup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         }
         if ($profile['integrity_check'] == '1') {
             pb_backupbuddy::status('details', __('Integrity check will be performed based on settings for this profile.', 'it-l10n-backupbuddy'));
             $this->_backup['steps'][] = array('function' => 'integrity_check', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         } else {
             pb_backupbuddy::status('details', __('Skipping integrity check step based on settings for this profile.', 'it-l10n-backupbuddy'));
         }
     }
     $this->_backup['steps'][] = array('function' => 'post_backup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     // Prepend and append pre backup and post backup steps.
     $this->_backup['steps'] = array_merge($pre_backup, $this->_backup['steps'], $post_backup);
     /********* End setting up steps array. *********/
     // Save what we have so far so that any errors below will end up displayed to user.
     $this->_backup_options->save();
     /********* Begin directory creation and security. *********/
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getBackupDirectory());
     // Prepare temporary directory for holding SQL and data file.
     if (backupbuddy_core::getTempDirectory() == '') {
         pb_backupbuddy::status('error', 'Error #54534344. Temp directory blank. Please deactivate then reactivate plugin to reset.');
         return false;
     }
     if (!file_exists($this->_backup['temp_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temp_directory']) === false) {
             pb_backupbuddy::status('error', 'Error #9002b. Unable to create temporary storage directory (' . $this->_backup['temp_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temp_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temp_directory'] . ')');
         return false;
     }
     pb_backupbuddy::anti_directory_browsing(ABSPATH . 'wp-content/uploads/backupbuddy_temp/');
     // Prepare temporary directory for holding ZIP file while it is being generated.
     $this->_backup['temporary_zip_directory'] = backupbuddy_core::getBackupDirectory() . 'temp_zip_' . $this->_backup['serial'] . '/';
     if (!file_exists($this->_backup['temporary_zip_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temporary_zip_directory']) === false) {
             pb_backupbuddy::status('details', 'Error #9002c. Unable to create temporary ZIP storage directory (' . $this->_backup['temporary_zip_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temporary_zip_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temporary_zip_directory'] . ')');
         return false;
     }
     /********* End directory creation and security *********/
     // Generate backup DAT (data) file containing details about the backup.
     if ($this->backup_create_dat_file($trigger) !== true) {
         pb_backupbuddy::status('details', __('Problem creating DAT file.', 'it-l10n-backupbuddy'));
         return false;
     }
     // Generating ImportBuddy file to include in the backup for FULL BACKUPS ONLY currently. Cannot put in DB because it would be in root and be excluded or conflict on extraction.
     if ($type == 'full') {
         if (pb_backupbuddy::$options['include_importbuddy'] == '1') {
             pb_backupbuddy::status('details', 'Generating ImportBuddy tool to include in backup archive: `' . $this->_backup['temp_directory'] . 'importbuddy.php`.');
             pb_backupbuddy::status('startAction', 'importbuddyCreation');
             backupbuddy_core::importbuddy($this->_backup['temp_directory'] . 'importbuddy.php');
             pb_backupbuddy::status('finishAction', 'importbuddyCreation');
             pb_backupbuddy::status('details', 'ImportBuddy generation complete.');
         } else {
             // dont include importbuddy.
             pb_backupbuddy::status('details', 'ImportBuddy tool inclusion in ZIP backup archive skipped based on settings or backup type.');
         }
     }
     // Save all of this.
     $this->_backup['init_complete'] = true;
     // pre_backup() completed.
     $this->_backup_options->save();
     pb_backupbuddy::status('details', __('Finished pre-backup procedures.', 'it-l10n-backupbuddy'));
     pb_backupbuddy::status('milestone', 'finish_settings');
     pb_backupbuddy::status('finishFunction', json_encode(array('function' => 'pre_backup')));
     return true;
 }
Esempio n. 19
0
 public static function test($settings)
 {
     $settings = self::_normalizeSettings($settings);
     if (false === ($settings = self::_connect($settings))) {
         $error = 'Unable to connect with Google Drive. See log for details.';
         echo $error;
         pb_backupbuddy::status('error', $error);
         return false;
     }
     pb_backupbuddy::status('details', 'Testing Google Drive destination. Sending ImportBuddy.php.');
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     $files = array(dirname(dirname(__FILE__)) . '/remote-send-test.php');
     $results = self::send($settings, $files, '', $delete_local = false, $delete_remote_after = true);
     @unlink($importbuddy_temp);
     if (true === $results) {
         echo 'Success sending test file to Google Drive. ';
         return true;
     } else {
         echo 'Failure sending test file to Google Drive.';
         // Detailed errors are send via remote_test.php response.
         return false;
     }
 }
Esempio n. 20
0
    function restore_file_view()
    {
        pb_backupbuddy::$ui->ajax_header(true, false);
        // js, no padding
        $archive_file = pb_backupbuddy::_GET('archive');
        // archive to extract from.
        $file = pb_backupbuddy::_GET('file');
        // file to extract.
        $serial = backupbuddy_core::get_serial_from_file($archive_file);
        // serial of archive.
        $temp_file = uniqid();
        // temp filename to extract into.
        require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
        $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
        // Calculate temp directory & lock it down.
        $temp_dir = get_temp_dir();
        $destination = $temp_dir . 'backupbuddy-' . $serial;
        if (!file_exists($destination) && false === mkdir($destination)) {
            $error = 'Error #458485945: Unable to create temporary location.';
            pb_backupbuddy::status('error', $error);
            die($error);
        }
        // If temp directory is within webroot then lock it down.
        $temp_dir = str_replace('\\', '/', $temp_dir);
        // Normalize for Windows.
        $temp_dir = rtrim($temp_dir, '/\\') . '/';
        // Enforce single trailing slash.
        if (FALSE !== stristr($temp_dir, ABSPATH)) {
            // Temp dir is within webroot.
            pb_backupbuddy::anti_directory_browsing($destination);
        }
        unset($temp_dir);
        $message = 'Extracting "' . $file . '" from archive "' . $archive_file . '" into temporary file "' . $destination . '". ';
        echo '<!-- ';
        pb_backupbuddy::status('details', $message);
        echo $message;
        $extractions = array($file => $temp_file);
        $extract_result = $zipbuddy->extract(backupbuddy_core::getBackupDirectory() . $archive_file, $destination, $extractions);
        if (false === $extract_result) {
            // failed.
            echo ' -->';
            $error = 'Error #584984458. Unable to extract.';
            pb_backupbuddy::status('error', $error);
            die($error);
        } else {
            // success.
            _e('Success.', 'it-l10n-backupbuddy');
            echo ' -->';
            ?>
			<textarea readonly="readonly" wrap="off" style="width: 100%; min-height: 175px; height: 100%; margin: 0;"><?php 
            echo file_get_contents($destination . '/' . $temp_file);
            ?>
</textarea>
			<?php 
            //unlink( $destination . '/' . $temp_file );
        }
        // Try to cleanup.
        if (file_exists($destination)) {
            if (false === pb_backupbuddy::$filesystem->unlink_recursive($destination)) {
                pb_backupbuddy::status('details', 'Unable to delete temporary holding directory `' . $destination . '`.');
            } else {
                pb_backupbuddy::status('details', 'Cleaned up temporary files.');
            }
        }
        pb_backupbuddy::$ui->ajax_footer();
        die;
    }
Esempio n. 21
0
 function pre_backup($serial, $profile, $trigger, $pre_backup = array(), $post_backup = array(), $schedule_title = '', $export_plugins = array())
 {
     $type = $profile['type'];
     // Log some status information.
     pb_backupbuddy::status('details', __('Performing pre-backup procedures.', 'it-l10n-backupbuddy'));
     if ($type == 'full') {
         pb_backupbuddy::status('message', __('Full backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'db') {
         pb_backupbuddy::status('message', __('Database only backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'export') {
         pb_backupbuddy::status('message', __('Multisite Site Export mode.', 'it-l10n-backupbuddy'));
     } else {
         pb_backupbuddy::status('error', __('Unknown backup mode.', 'it-l10n-backupbuddy'));
     }
     // Schedule daily housekeeping.
     if (false === wp_next_scheduled(pb_backupbuddy::cron_tag('housekeeping'))) {
         // if schedule does not exist...
         pb_backupbuddy::$classes['core']->schedule_event(time() + 60 * 60 * 2, 'daily', pb_backupbuddy::cron_tag('housekeeping'), array());
         // Add schedule.
     }
     // Delete all backup archives if this troubleshooting option is enabled.
     if (pb_backupbuddy::$options['delete_archives_pre_backup'] == '1') {
         pb_backupbuddy::status('message', 'Deleting all existing backups prior to backup as configured on the settings page.');
         $file_list = glob(pb_backupbuddy::$options['backup_directory'] . 'backup*.zip');
         if (is_array($file_list) && !empty($file_list)) {
             foreach ($file_list as $file) {
                 if (@unlink($file) === true) {
                     pb_backupbuddy::status('details', 'Deleted backup archive `' . basename($file) . '` based on settings to delete all backups.');
                 } else {
                     pb_backupbuddy::status('details', 'Unable to delete backup archive `' . basename($file) . '` based on settings to delete all backups. Verify permissions.');
                 }
             }
         }
     }
     // Generate unique serial ID.
     pb_backupbuddy::status('details', 'Backup serial generated: `' . $serial . '`.');
     pb_backupbuddy::status('details', 'About to load fileoptions data in create mode.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $this->_backup_options = new pb_backupbuddy_fileoptions(pb_backupbuddy::$options['log_directory'] . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
     if (true !== ($result = $this->_backup_options->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034 A. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         pb_backupbuddy::status('action', 'halt_script');
         // Halt JS on page.
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $this->_backup =& $this->_backup_options->options;
     // Set reference.
     // Cleanup internal stats.
     pb_backupbuddy::status('details', 'Resetting statistics for last backup time and number of edits since last backup.');
     pb_backupbuddy::$options['last_backup_start'] = time();
     // Reset time since last backup.
     pb_backupbuddy::$options['edits_since_last'] = 0;
     // Reset edit stats for notifying user of how many posts/pages edited since last backup happened.
     pb_backupbuddy::$options['last_backup_serial'] = $serial;
     pb_backupbuddy::save();
     // Prepare some values for setting up the backup data.
     $siteurl_stripped = pb_backupbuddy::$classes['core']->backup_prefix();
     // Calculate customizable section of archive filename (date vs date+time).
     if (pb_backupbuddy::$options['archive_name_format'] == 'datetime') {
         // "datetime" = Date + time.
         $backupfile_datetime = date(self::ARCHIVE_NAME_FORMAT_DATETIME, pb_backupbuddy::$format->localize_time(time()));
     } else {
         // "date" = date only (the default).
         $backupfile_datetime = date(self::ARCHIVE_NAME_FORMAT_DATE, pb_backupbuddy::$format->localize_time(time()));
     }
     // Compression to bool.
     /*
     if ( $profile['compression'] == '1' ) {
     	$profile['compression'] = true;
     } else {
     	$profile['compression'] = false;
     }
     */
     if (pb_backupbuddy::$options['compression'] == '1') {
         $compression = true;
     } else {
         $compression = false;
     }
     // Set up the backup data.
     $this->_backup = array('backupbuddy_version' => pb_backupbuddy::settings('version'), 'serial' => $serial, 'init_complete' => false, 'backup_mode' => pb_backupbuddy::$options['backup_mode'], 'type' => $type, 'profile' => $profile, 'start_time' => time(), 'finish_time' => 0, 'updated_time' => time(), 'status' => array(), 'archive_size' => 0, 'schedule_title' => $schedule_title, 'backup_directory' => pb_backupbuddy::$options['backup_directory'], 'archive_file' => pb_backupbuddy::$options['backup_directory'] . 'backup-' . $siteurl_stripped . '-' . $backupfile_datetime . '-' . $type . '-' . $serial . '.zip', 'trigger' => $trigger, 'zip_method_strategy' => pb_backupbuddy::$options['zip_method_strategy'], 'compression' => $compression, 'ignore_zip_warnings' => pb_backupbuddy::$options['ignore_zip_warnings'], 'ignore_zip_symlinks' => pb_backupbuddy::$options['ignore_zip_symlinks'], 'steps' => array(), 'integrity' => array(), 'temp_directory' => '', 'backup_root' => '', 'export_plugins' => array(), 'additional_table_includes' => array(), 'additional_table_excludes' => array(), 'directory_exclusions' => pb_backupbuddy::$classes['core']->get_directory_exclusions($profile, false), 'table_sizes' => array(), 'breakout_tables' => array());
     // Figure out paths.
     if ($this->_backup['type'] == 'full') {
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         $this->_backup['backup_root'] = ABSPATH;
         // ABSPATH contains trailing slash.
     } elseif ($this->_backup['type'] == 'db') {
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         $this->_backup['backup_root'] = $this->_backup['temp_directory'];
     } elseif ($this->_backup['type'] == 'export') {
         // WordPress unzips into wordpress subdirectory by default so must include that in path.
         $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         // We store temp data for export within the temporary WordPress installation within the temp directory. A bit confusing; sorry about that.
         $this->_backup['backup_root'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/';
     } else {
         pb_backupbuddy::status('error', __('Backup FAILED. Unknown backup type.', 'it-l10n-backupbuddy'));
         pb_backupbuddy::status('action', 'halt_script');
         // Halt JS on page.
     }
     // Plugins to export (only for MS exports).
     if (count($export_plugins) > 0) {
         $this->_backup['export_plugins'] = $export_plugins;
     }
     // Calculate additional database table inclusion/exclusion.
     $additional_includes = explode("\n", $profile['mysqldump_additional_includes']);
     array_walk($additional_includes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_includes'] = array_unique($additional_includes);
     // removes duplicates.
     $additional_excludes = explode("\n", $profile['mysqldump_additional_excludes']);
     array_walk($additional_excludes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_excludes'] = array_unique($additional_excludes);
     // removes duplicates.
     unset($additional_includes);
     unset($additional_excludes);
     /********* Begin setting up steps array. *********/
     if ($type == 'export') {
         pb_backupbuddy::status('details', 'Setting up export-specific steps.');
         $this->_backup['steps'][] = array('function' => 'ms_download_extract_wordpress', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_create_wp_config', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_plugins', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_themes', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_media', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_users_table', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     if ($profile['skip_database_dump'] != '1') {
         // Backup database if not skipping.
         global $wpdb;
         // Default tables to backup.
         if ($profile['backup_nonwp_tables'] == '1') {
             // Backup all tables.
             $base_dump_mode = 'all';
         } else {
             // Only backup matching prefix.
             $base_dump_mode = 'prefix';
         }
         $additional_tables = $this->_backup['additional_table_includes'];
         if ($type == 'export') {
             global $wpdb;
             array_push($additional_tables, $wpdb->prefix . "users");
             array_push($additional_tables, $wpdb->prefix . "usermeta");
         }
         // Calculate tables to dump based on the provided information. $tables will be an array of tables.
         $tables = $this->_calculate_tables($base_dump_mode, $additional_tables, $this->_backup['additional_table_excludes']);
         // Obtain tables sizes. Surround each table name by a single quote and implode with commas for SQL query to get sizes.
         $tables_formatted = $tables;
         foreach ($tables_formatted as &$table_formatted) {
             $table_formatted = "'{$table_formatted}'";
         }
         $tables_formatted = implode(',', $tables_formatted);
         $result = mysql_query("SHOW TABLE STATUS WHERE Name IN({$tables_formatted});");
         while ($rs = mysql_fetch_array($result)) {
             $this->_backup['table_sizes'][$rs['Name']] = $rs['Data_length'] + $rs['Index_length'];
         }
         unset($tables_formatted);
         // Tables we will try to break out into standalone steps if possible.
         $breakout_tables_defaults = array($wpdb->prefix . 'posts', $wpdb->prefix . 'postmeta');
         // Step through tables we want to break out and figure out which ones were indeed set to be backed up and break them out.
         if (pb_backupbuddy::$options['breakout_tables'] == '0') {
             // Breaking out DISABLED.
             pb_backupbuddy::status('details', 'Breaking out tables DISABLED based on settings.');
         } else {
             // Breaking out ENABLED.
             pb_backupbuddy::status('details', 'Breaking out tables ENABLED based on settings. Tables to be broken out into individual steps: `' . implode(', ', $breakout_tables_defaults) . '`.');
             foreach ((array) $breakout_tables_defaults as $breakout_tables_default) {
                 if (in_array($breakout_tables_default, $tables)) {
                     $this->_backup['breakout_tables'][] = $breakout_tables_default;
                     $tables = array_diff($tables, array($breakout_tables_default));
                     // Remove from main table backup list.
                 }
             }
         }
         unset($breakout_tables_defaults);
         // No longer needed.
         $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array($tables), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         // Set up backup steps for additional broken out tables.
         foreach ((array) $this->_backup['breakout_tables'] as $breakout_table) {
             $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array(array($breakout_table)), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         }
     } else {
         pb_backupbuddy::status('message', __('Skipping database dump based on advanced options.', 'it-l10n-backupbuddy'));
     }
     $this->_backup['steps'][] = array('function' => 'backup_zip_files', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     if ($type == 'export') {
         $this->_backup['steps'][] = array('function' => 'ms_cleanup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     if ($profile['integrity_check'] == '1') {
         pb_backupbuddy::status('details', __('Integrity check will be performed based on settings for this profile.', 'it-l10n-backupbuddy'));
         $this->_backup['steps'][] = array('function' => 'integrity_check', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     } else {
         pb_backupbuddy::status('details', __('Skipping integrity check step based on settings for this profile.', 'it-l10n-backupbuddy'));
     }
     $this->_backup['steps'][] = array('function' => 'post_backup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     // Prepend and append pre backup and post backup steps.
     $this->_backup['steps'] = array_merge($pre_backup, $this->_backup['steps'], $post_backup);
     /********* End setting up steps array. *********/
     // Save what we have so far so that any errors below will end up displayed to user.
     $this->_backup_options->save();
     /********* Begin directory creation and security. *********/
     pb_backupbuddy::anti_directory_browsing($this->_backup['backup_directory']);
     // Prepare temporary directory for holding SQL and data file.
     if (pb_backupbuddy::$options['temp_directory'] == '') {
         pb_backupbuddy::status('error', 'Error #54534344. Temp directory blank. Please deactivate then reactivate plugin to reset.');
         return false;
     }
     if (!file_exists($this->_backup['temp_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temp_directory']) === false) {
             pb_backupbuddy::status('error', 'Error #9002b. Unable to create temporary storage directory (' . $this->_backup['temp_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temp_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temp_directory'] . ')');
         return false;
     }
     pb_backupbuddy::anti_directory_browsing(ABSPATH . 'wp-content/uploads/backupbuddy_temp/');
     // Prepare temporary directory for holding ZIP file while it is being generated.
     $this->_backup['temporary_zip_directory'] = pb_backupbuddy::$options['backup_directory'] . 'temp_zip_' . $this->_backup['serial'] . '/';
     if (!file_exists($this->_backup['temporary_zip_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temporary_zip_directory']) === false) {
             pb_backupbuddy::status('details', 'Error #9002c. Unable to create temporary ZIP storage directory (' . $this->_backup['temporary_zip_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temporary_zip_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temporary_zip_directory'] . ')');
         return false;
     }
     /********* End directory creation and security *********/
     // Generate backup DAT (data) file containing details about the backup.
     if ($this->backup_create_dat_file($trigger) !== true) {
         pb_backupbuddy::status('details', __('Problem creating DAT file.', 'it-l10n-backupbuddy'));
         return false;
     }
     // Generating ImportBuddy file to include in the backup for FULL BACKUPS ONLY currently. Cannot put in DB because it would be in root and be excluded or conflict on extraction.
     if ($type == 'full') {
         if (pb_backupbuddy::$options['include_importbuddy'] == '1') {
             pb_backupbuddy::status('details', 'Generating ImportBuddy tool to include in backup archive: `' . $this->_backup['temp_directory'] . 'importbuddy.php`.');
             pb_backupbuddy::$classes['core']->importbuddy($this->_backup['temp_directory'] . 'importbuddy.php');
             pb_backupbuddy::status('details', 'ImportBuddy generation complete.');
         } else {
             // dont include importbuddy.
             pb_backupbuddy::status('details', 'ImportBuddy tool inclusion in ZIP backup archive skipped based on settings.');
         }
     }
     // Save all of this.
     $this->_backup['init_complete'] = true;
     // pre_backup() completed.
     //error_log( print_r( $this->_backup, true ) );
     $this->_backup_options->save();
     //pb_backupbuddy::save();
     pb_backupbuddy::status('details', __('Finished pre-backup procedures.', 'it-l10n-backupbuddy'));
     pb_backupbuddy::status('action', 'finish_settings');
     return true;
 }
 private static function _getFilePathByType($type)
 {
     if ('backup' == $type) {
         $rootDir = backupbuddy_core::getBackupDirectory();
         // Include trailing slash.
         pb_backupbuddy::anti_directory_browsing($rootDir, $die = false);
     } elseif ('media' == $type) {
         $wp_upload_dir = wp_upload_dir();
         $rootDir = $wp_upload_dir['basedir'] . '/';
         unset($wp_upload_dir);
     } elseif ('plugin' == $type) {
         $rootDir = wp_normalize_path(WP_PLUGIN_DIR) . '/';
     } elseif ('theme' == $type) {
         $rootDir = get_template_directory() . '/';
     } elseif ('childTheme' == $type) {
         $rootDir = get_stylesheet_directory() . '/';
     } elseif ('test' == $type) {
         $rootDir = backupbuddy_core::getTempDirectory();
     } else {
         $error = 'Error #84934984. You must specify a sendfile type: Unknown file type `' . htmlentities($type) . '`.';
         pb_backupbuddy::status('error', $error);
         error_log('BackupBuddy API error: ' . $error);
         die(json_encode(array('success' => false, 'error' => $message)));
     }
     return $rootDir;
 }
Esempio n. 23
0
 private static function _sendFile($type = '')
 {
     if ('' == $type) {
         $message = 'Error #84934984. You must specify a sendfile type.';
         pb_backupbuddy::status('error', $message);
         die(json_encode(array('success' => false, 'error' => $message)));
     }
     if ('backup' == $type) {
         $rootDir = backupbuddy_core::getTempDirectory();
         // Include trailing slash.
         pb_backupbuddy::anti_directory_browsing($rootDir, $die = false);
     } elseif ('media' == $type) {
         $wp_upload_dir = wp_upload_dir();
         $rootDir = $wp_upload_dir['basedir'] . '/';
         unset($wp_upload_dir);
     } elseif ('plugin' == $type) {
         $rootDir = wp_normalize_path(WP_PLUGIN_DIR) . '/';
     } elseif ('theme' == $type) {
         //$rootDir = WP_CONTENT_DIR . '/themes/';
         $rootDir = get_template_directory() . '/';
     }
     error_log('API saving file to dir: `' . $rootDir . '`.');
     $cleanFile = str_replace(array('\\', '/'), '', stripslashes_deep(pb_backupbuddy::_POST('filename')));
     $filePath = pb_backupbuddy::_POST('filepath');
     if ('' != $filePath) {
         // Filepath specified so goes in a subdirectory under the rootDir.
         if ($cleanFile != basename($filePath)) {
             $message = 'Error #493844: The specified filename within the filepath parameter does not match the supplied filename parameter.';
             pb_backupbuddy::status('error', $message);
             die(json_encode(array('success' => false, 'error' => $message)));
         } else {
             // Filename with path.
             $subFilePath = $filePath;
         }
     } else {
         // Just the filename. No path.
         $subFilePath = $cleanFile;
     }
     $saveFile = $rootDir . $subFilePath;
     // Check if directory exists & create if needed.
     $saveDir = dirname($saveFile);
     if (!is_dir($saveDir)) {
         if (true !== pb_backupbuddy::$filesystem->mkdir($saveDir)) {
             $message = 'Error #327832: Unable to create directory `' . $saveDir . '`. Check permissions or manually create. Halting to preserve deployment integrity';
             pb_backupbuddy::status('error', $message);
             die(json_encode(array('success' => false, 'error' => $message)));
         }
     }
     // Open/create file for write/append.
     if (false === ($fs = fopen($saveFile, 'c'))) {
         $message = 'Error #489339848: Unable to fopen file `' . $saveFile . '`.';
         pb_backupbuddy::status('error', $message);
         die(json_encode(array('success' => false, 'error' => $message)));
     }
     // Seek to position (if applicable).
     if (0 != fseek($fs, pb_backupbuddy::_POST('seekto'))) {
         @fclose($fs);
         $message = 'Error #8584884: Unable to fseek file.';
         pb_backupbuddy::status('error', $message);
         die(json_encode(array('success' => false, 'error' => $message)));
     }
     // Check data length.
     $gotLength = strlen(pb_backupbuddy::_POST('filedata'));
     if (pb_backupbuddy::_POST('filedatalen') != $gotLength) {
         @fclose($fs);
         $message = 'Error #4355445: Received data of length `' . $gotLength . '` did not match sent length of `' . pb_backupbuddy::_POST('filedatalen') . '`. Data may have been truncated.';
         pb_backupbuddy::status('error', $message);
         die(json_encode(array('success' => false, 'error' => $message)));
     }
     // Check hash.
     if (pb_backupbuddy::_POST('filecrc') != sprintf("%u", crc32(pb_backupbuddy::_POST('filedata')))) {
         @fclose($fs);
         $message = 'Error #473472: CRC of received data did not match source CRC. Data corrupted in transfer? Sent length: `' . pb_backupbuddy::_POST('filedatalen') . '`. Received length: `' . $gotLength . '`.';
         pb_backupbuddy::status('error', $message);
         die(json_encode(array('success' => false, 'error' => $message)));
     }
     // Write to file.
     if (false === ($bytesWritten = fwrite($fs, base64_decode(pb_backupbuddy::_POST('filedata'))))) {
         @fclose($fs);
         @unlink($saveFile);
         $message = 'Error #3984394: Error writing to file `' . $saveFile . '`.';
         pb_backupbuddy::status('error', $message);
         die(json_encode(array('success' => false, 'error' => $message)));
     } else {
         @fclose($fs);
         $message = 'Wrote `' . $bytesWritten . '` bytes.';
         pb_backupbuddy::status('details', $message);
         if ('1' == pb_backupbuddy::_POST('filetest')) {
             @unlink($saveFile);
         } else {
             if ('1' == pb_backupbuddy::_POST('filedone')) {
                 $destFile = ABSPATH . basename($saveFile);
                 /*
                 if ( false === @copy( $saveFile, $destFile ) ) {
                 	pb_backupbuddy::status( 'error', 'Error #948454: Unable to copy temporary file `' . $saveFile . '` to `' . $destFile . '`.' );
                 }
                 @unlink( $saveFile );
                 */
                 die(json_encode(array('success' => true, 'message' => $message)));
             }
         }
         die(json_encode(array('success' => true, 'message' => $message)));
     }
 }
Esempio n. 24
0
}
// end plugin_information().
// User forced cleanup.
if ('' != pb_backupbuddy::_GET('cleanup_now')) {
    pb_backupbuddy::alert('Performing cleanup procedures now trimming old files and data.');
    backupbuddy_core::periodic_cleanup(0);
    // clean up everything.
}
// Delete temporary files directory.
if ('' != pb_backupbuddy::_GET('delete_tempfiles_now')) {
    $tempDir = backupbuddy_core::getTempDirectory();
    $logDir = backupbuddy_core::getLogDirectory();
    pb_backupbuddy::alert('Deleting all files contained within `' . $tempDir . '` and `' . $logDir . '`.');
    pb_backupbuddy::$filesystem->unlink_recursive($tempDir);
    pb_backupbuddy::$filesystem->unlink_recursive($logDir);
    pb_backupbuddy::anti_directory_browsing($logDir, $die = false);
    // Put log dir back in place.
}
// Reset log.
if (pb_backupbuddy::_GET('reset_log') != '') {
    if (file_exists($log_file)) {
        @unlink($log_file);
    }
    if (file_exists($log_file)) {
        // Didnt unlink.
        pb_backupbuddy::alert('Unable to clear log file. Please verify permissions on file `' . $log_file . '`.');
    } else {
        // Unlinked.
        pb_backupbuddy::alert('Cleared log file.');
    }
}
Esempio n. 25
0
    public function restore_file_restore()
    {
        $success = false;
        pb_backupbuddy::$ui->ajax_header(true, false);
        // js, no padding
        ?>
		<script type="text/javascript">
			function pb_status_append( status_string ) {
				target_id = 'pb_backupbuddy_status'; // importbuddy_status or pb_backupbuddy_status
				if( jQuery( '#' + target_id ).length == 0 ) { // No status box yet so suppress.
					return;
				}
				jQuery( '#' + target_id ).append( "\n" + status_string );
				textareaelem = document.getElementById( target_id );
				textareaelem.scrollTop = textareaelem.scrollHeight;
			}
		</script>
		<?php 
        global $pb_backupbuddy_js_status;
        $pb_backupbuddy_js_status = true;
        echo pb_backupbuddy::status_box('Restoring . . .');
        echo '<div id="pb_backupbuddy_working" style="width: 100px;"><br><center><img src="' . pb_backupbuddy::plugin_url() . '/images/working.gif" title="Working... Please wait as this may take a moment..."></center></div>';
        pb_backupbuddy::set_status_serial('restore');
        global $wp_version;
        pb_backupbuddy::status('details', 'BackupBuddy v' . pb_backupbuddy::settings('version') . ' using WordPress v' . $wp_version . ' on ' . PHP_OS . '.');
        $archive_file = pb_backupbuddy::_GET('archive');
        // archive to extract from.
        $files = pb_backupbuddy::_GET('files');
        // file to extract.
        $files_array = explode(',', $files);
        $files = array();
        foreach ($files_array as $file) {
            if (substr($file, -1) == '/') {
                // If directory then add wildcard.
                $file = $file . '*';
            }
            $files[$file] = $file;
        }
        unset($files_array);
        $serial = backupbuddy_core::get_serial_from_file($archive_file);
        // serial of archive.
        foreach ($files as $file) {
            $file = str_replace('*', '', $file);
            // Remove any wildcard.
            if (file_exists(ABSPATH . $file) && is_dir(ABSPATH . $file)) {
                if (($file_count = @scandir(ABSPATH . $file)) && count($file_count) > 2) {
                    pb_backupbuddy::status('error', __('Error #9036. The destination directory being restored already exists and is NOT empty. The directory will not be restored to prevent inadvertently losing files within the existing directory. Delete existing directory first if you wish to proceed or restore individual files.', 'it-l10n-backupbuddy') . ' Existing directory: `' . ABSPATH . $file . '`.');
                    echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
                    pb_backupbuddy::flush();
                    pb_backupbuddy::$ui->ajax_footer();
                    die;
                }
            }
        }
        require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
        $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
        // Calculate temp directory & lock it down.
        $temp_dir = get_temp_dir();
        $destination = $temp_dir . 'backupbuddy-' . $serial;
        if (!file_exists($destination) && false === mkdir($destination, 0777, true)) {
            $error = 'Error #458485945: Unable to create temporary location.';
            pb_backupbuddy::status('error', $error);
            echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
            pb_backupbuddy::flush();
            pb_backupbuddy::$ui->ajax_footer();
            die;
        }
        // If temp directory is within webroot then lock it down.
        $temp_dir = str_replace('\\', '/', $temp_dir);
        // Normalize for Windows.
        $temp_dir = rtrim($temp_dir, '/\\') . '/';
        // Enforce single trailing slash.
        if (FALSE !== stristr($temp_dir, ABSPATH)) {
            // Temp dir is within webroot.
            pb_backupbuddy::anti_directory_browsing($destination);
        }
        unset($temp_dir);
        pb_backupbuddy::status('details', 'Extracting into temporary directory "' . $destination . '".');
        pb_backupbuddy::status('details', 'Files to extract: `' . htmlentities(pb_backupbuddy::_GET('files')) . '`.');
        // Make sure temp subdirectories exist.
        /*
        foreach( $files as $file => $null ) {
        	mkdir( $destination . '/' . basename( $file ), 0777, true );
        }
        */
        pb_backupbuddy::flush();
        $extract_success = true;
        $extract_result = $zipbuddy->extract(backupbuddy_core::getBackupDirectory() . $archive_file, $destination, $files);
        if (false === $extract_result) {
            // failed.
            pb_backupbuddy::status('error', 'Error #584984458b. Unable to extract.');
            $extract_success = false;
        } else {
            // success.
            // Verify all files/directories to be extracted exist in temp destination directory. If any missing then delete everything and bail out.
            foreach ($files as &$file) {
                $file = str_replace('*', '', $file);
                // Remove any wildcard.
                if (!file_exists($destination . '/' . $file)) {
                    // Cleanup.
                    foreach ($files as $file) {
                        @trigger_error('');
                        // Clear out last error.
                        @unlink($destination . '/' . $file);
                        $last_error = error_get_last();
                        if (is_array($last_error)) {
                            pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                        }
                    }
                    pb_backupbuddy::status('error', 'Error #854783474. One or more expected files / directories missing.');
                    $extract_success = false;
                    break;
                }
            }
            unset($file);
        }
        if (true === $extract_success) {
            // Made it this far so files all exist. Move them all.
            foreach ($files as $file) {
                @trigger_error('');
                // Clear out last error.
                if (false === @rename($destination . '/' . $file, ABSPATH . $file)) {
                    $last_error = error_get_last();
                    if (is_array($last_error)) {
                        //print_r( $last_error );
                        pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                    }
                    $error = 'Error #9035. Unable to move restored file `' . $destination . '/' . $file . '` to `' . ABSPATH . $file . '`. Verify permissions on destination location & that the destination directory/file does not already exist.';
                    pb_backupbuddy::status('error', $error);
                } else {
                    $details = 'Moved `' . $destination . '/' . $file . '` to `' . ABSPATH . $file . '`.<br>';
                    pb_backupbuddy::status('details', $details);
                    $success = true;
                }
            }
        }
        // end extract succeeded.
        // Try to cleanup.
        if (file_exists($destination)) {
            if (false === pb_backupbuddy::$filesystem->unlink_recursive($destination)) {
                pb_backupbuddy::status('details', 'Unable to delete temporary holding directory `' . $destination . '`.');
            } else {
                pb_backupbuddy::status('details', 'Cleaned up temporary files.');
            }
        }
        if (true === $success) {
            pb_backupbuddy::status('message', 'Restore completed successfully.');
        }
        echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
        pb_backupbuddy::flush();
        pb_backupbuddy::$ui->ajax_footer();
        die;
    }
Esempio n. 26
0
 function periodic_cleanup($backup_age_limit = 43200, $die_on_fail = true)
 {
     if (!isset(pb_backupbuddy::$options)) {
         $this->load();
     }
     // TODO: Check for orphaned .gz files in root from PCLZip.
     // TODO: Cleanup any orphaned temp ZIP creation directories under the backups directory. wp-content/uploads/backupbuddy_backups/temp_zip_XXSERIALXX/
     // Cleanup backup itegrity portion of array.
     $this->trim_backups_integrity_stats();
     // Cleanup logs in pb_backupbuddy dirctory.
     $log_directory = WP_CONTENT_DIR . '/uploads/pb_' . pb_backupbuddy::settings('slug') . '/';
     $files = glob($log_directory . '*.txt');
     if (is_array($files) && !empty($files)) {
         // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
         foreach ($files as $file) {
             $file_stats = stat($file);
             if (time() - $file_stats['mtime'] > $backup_age_limit) {
                 // If older than 12 hours, delete the log.
                 @unlink($file);
             }
         }
     }
     // Cleanup excess backup stats.
     if (count(pb_backupbuddy::$options['backups']) > 3) {
         // Keep a minimum number of backups in array for stats.
         $number_backups = count(pb_backupbuddy::$options['backups']);
         $kept_loop_count = 0;
         $needs_save = false;
         foreach (pb_backupbuddy::$options['backups'] as $backup_serial => $backup) {
             if ($number_backups - $kept_loop_count > 3) {
                 if (isset($backup['archive_file']) && !file_exists($backup['archive_file'])) {
                     unset(pb_backupbuddy::$options['backups'][$backup_serial]);
                     $needs_save = true;
                 } else {
                     $kept_loop_count++;
                 }
             }
         }
         if ($needs_save === true) {
             //echo 'saved';
             pb_backupbuddy::save();
         }
     }
     // Cleanup any temporary local destinations.
     foreach (pb_backupbuddy::$options['remote_destinations'] as $destination_id => $destination) {
         if ($destination['type'] == 'local' && $destination['temporary'] === true) {
             // If local and temporary.
             if (time() - $destination['created'] > $backup_age_limit) {
                 // Older than 12 hours; clear out!
                 pb_backupbuddy::status('details', 'Cleaned up stale local destination `' . $destination_id . '`.');
                 unset(pb_backupbuddy::$options['remote_destinations'][$destination_id]);
                 pb_backupbuddy::save();
             }
         }
     }
     // Cleanup excess remote sending stats.
     $this->trim_remote_send_stats();
     // Check for orphaned backups in the data structure that havent been updates in 12+ hours & cleanup after them.
     foreach ((array) pb_backupbuddy::$options['backups'] as $backup_serial => $backup) {
         if (isset($backup['updated_time'])) {
             if (time() - $backup['updated_time'] > $backup_age_limit) {
                 // If more than 12 hours has passed...
                 pb_backupbuddy::status('details', 'Cleaned up stale backup `' . $backup_serial . '`.');
                 $this->final_cleanup($backup_serial);
             }
         }
     }
     // Verify existance of anti-directory browsing files in backup directory.
     pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['backup_directory'], $die_on_fail);
     // Verify existance of anti-directory browsing files in status log directory.
     $status_directory = WP_CONTENT_DIR . '/uploads/pb_' . pb_backupbuddy::settings('slug') . '/';
     pb_backupbuddy::anti_directory_browsing($status_directory, $die_on_fail);
     // Handle high security mode archives directory .htaccess system. If high security backup directory mode: Make sure backup archives are NOT downloadable by default publicly. This is only lifted for ~8 seconds during a backup download for security. Overwrites any existing .htaccess in this location.
     if (pb_backupbuddy::$options['lock_archives_directory'] == '0') {
         // Normal security mode. Put normal .htaccess.
         pb_backupbuddy::status('details', 'Removing .htaccess high security mode for backups directory. Normal mode .htaccess to be added next.');
         // Remove high security .htaccess.
         if (file_exists(pb_backupbuddy::$options['backup_directory'] . '.htaccess')) {
             $unlink_status = @unlink(pb_backupbuddy::$options['backup_directory'] . '.htaccess');
             if ($unlink_status === false) {
                 pb_backupbuddy::alert('Error #844594. Unable to temporarily remove .htaccess security protection on archives directory to allow downloading. Please verify permissions of the BackupBuddy archives directory or manually download via FTP.');
             }
         }
         // Place normal .htaccess.
         pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['backup_directory'], $die_on_fail);
     } else {
         // High security mode. Make sure high security .htaccess in place.
         pb_backupbuddy::status('details', 'Adding .htaccess high security mode for backups directory.');
         $htaccess_creation_status = @file_put_contents(pb_backupbuddy::$options['backup_directory'] . '.htaccess', 'deny from all');
         if ($htaccess_creation_status === false) {
             pb_backupbuddy::alert('Error #344894545. Security Warning! Unable to create security file (.htaccess) in backups archive directory. This file prevents unauthorized downloading of backups should someone be able to guess the backup location and filenames. This is unlikely but for best security should be in place. Please verify permissions on the backups directory.');
         }
     }
     // Verify existance of anti-directory browsing files in temporary directory.
     pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['temp_directory'], $die_on_fail);
     // Remove any copy of importbuddy.php in root.
     if (file_exists(ABSPATH . 'importbuddy.php')) {
         pb_backupbuddy::status('details', 'Unlinked importbuddy.php in root of site.');
         unlink(ABSPATH . 'importbuddy.php');
     }
     // Remove any copy of importbuddy directory in root.
     if (file_exists(ABSPATH . 'importbuddy/')) {
         pb_backupbuddy::status('details', 'Unlinked importbuddy directory recursively in root of site.');
         pb_backupbuddy::$filesystem->unlink_recursive(ABSPATH . 'importbuddy/');
     }
 }
Esempio n. 27
0
 public static function verify_directories($skipTempGeneration = false)
 {
     $success = true;
     // Update backup directory if unable to write to the defined one.
     if (!@is_writable(backupbuddy_core::getBackupDirectory())) {
         pb_backupbuddy::status('details', 'Backup directory invalid. Updating from `' . backupbuddy_core::getBackupDirectory() . '` to default.');
         pb_backupbuddy::$options['backup_directory'] = '';
         // Reset to default (blank).
         pb_backupbuddy::save();
     }
     $response = pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getBackupDirectory(), $die = false);
     if (false === $response) {
         $success = false;
     }
     // Update log directory if unable to write to the defined one.
     if (!@is_writable(backupbuddy_core::getLogDirectory())) {
         pb_backupbuddy::status('details', 'Log directory invalid. Updating from `' . backupbuddy_core::getLogDirectory() . '` to default.');
         pb_backupbuddy::$options['log_directory'] = '';
         // Reset to default (blank).
         pb_backupbuddy::save();
     }
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getLogDirectory(), $die = false);
     if (false === $response) {
         $success = false;
     }
     // Update temp directory if unable to write to the defined one.
     if (true !== $skipTempGeneration) {
         if (!@is_writable(backupbuddy_core::getTempDirectory())) {
             pb_backupbuddy::status('details', 'Temporary directory invalid. Updating from `' . backupbuddy_core::getTempDirectory() . '` to default.');
             pb_backupbuddy::$options['temp_directory'] = '';
             pb_backupbuddy::save();
         }
         pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
         if (false === $response) {
             $success = false;
         }
     }
     // If temp directory exists (should only be transient but just in case it is hanging around) make sure it's secured. BB will try to delete this directory but if it can't it will at least be checked to be secure.
     if (file_exists(backupbuddy_core::getTempDirectory())) {
         pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     }
     global $pb_backupbuddy_directory_verification;
     $pb_backupbuddy_directory_verification = $success;
     return $success;
 }
Esempio n. 28
0
    }
    unset($fileoptions_obj);
}
// Handle high security mode archives directory .htaccess system. If high security backup directory mode: Make sure backup archives are NOT downloadable by default publicly. This is only lifted for ~8 seconds during a backup download for security. Overwrites any existing .htaccess in this location.
if (pb_backupbuddy::$options['lock_archives_directory'] == '0') {
    // Normal security mode. Put normal .htaccess.
    pb_backupbuddy::status('details', 'Removing .htaccess high security mode for backups directory. Normal mode .htaccess to be added next.');
    // Remove high security .htaccess.
    if (file_exists(backupbuddy_core::getBackupDirectory() . '.htaccess')) {
        $unlink_status = @unlink(backupbuddy_core::getBackupDirectory() . '.htaccess');
        if ($unlink_status === false) {
            pb_backupbuddy::alert('Error #844594. Unable to temporarily remove .htaccess security protection on archives directory to allow downloading. Please verify permissions of the BackupBuddy archives directory or manually download via FTP.');
        }
    }
    // Place normal .htaccess.
    pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getBackupDirectory(), $die_on_fail);
} else {
    // High security mode. Make sure high security .htaccess in place.
    pb_backupbuddy::status('details', 'Adding .htaccess high security mode for backups directory.');
    $htaccess_creation_status = @file_put_contents(backupbuddy_core::getBackupDirectory() . '.htaccess', 'deny from all');
    if ($htaccess_creation_status === false) {
        pb_backupbuddy::alert('Error #344894545. Security Warning! Unable to create security file (.htaccess) in backups archive directory. This file prevents unauthorized downloading of backups should someone be able to guess the backup location and filenames. This is unlikely but for best security should be in place. Please verify permissions on the backups directory.');
    }
}
$temp_dir = get_temp_dir();
// Remove any copy of importbuddy.php in root.
pb_backupbuddy::status('details', 'Cleaning up any importbuddy scripts in site root if it exists & is not very recent.');
$importbuddyFiles = glob($temp_dir . 'importbuddy*.php');
if (!is_array($importbuddyFiles)) {
    $importbuddyFiles = array();
}
Esempio n. 29
0
    pb_backupbuddy::save();
}
// ********** END 3.0.43 -> 3.1 DATA MIGRATION **********
// ********** BEGIN 3.1.8.2 -> 3.1.8.3 DATA MIGRATION **********
if (pb_backupbuddy::$options['data_version'] < 4) {
    pb_backupbuddy::$options['data_version'] = '4';
    // Update data structure version to 4.
    pb_backupbuddy::$options['role_access'] = 'activate_plugins';
    // Change default role from `administrator` to `activate_plugins` capability.
    pb_backupbuddy::save();
}
// ********** END 3.1.8.2 -> 3.1.8.3 DATA MIGRATION **********
// ********** BEGIN 3.3.0 -> 3.3.0.1 BACKUP DATASTRUCTURE OPTIONS to FILEOPTIONS MIGRATION **********
if (pb_backupbuddy::$options['data_version'] < 5) {
    if (isset(pb_backupbuddy::$options['backups']) && count(pb_backupbuddy::$options['backups']) > 0) {
        pb_backupbuddy::anti_directory_browsing(pb_backupbuddy::$options['log_directory'] . 'fileoptions/');
        require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
        foreach (pb_backupbuddy::$options['backups'] as $serial => $backup) {
            $backup_options = new pb_backupbuddy_fileoptions(pb_backupbuddy::$options['log_directory'] . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
            $backup_options->options = $backup;
            if (true === $backup_options->save()) {
                unset(pb_backupbuddy::$options['backups'][$serial]);
            }
            unset($backup_options);
        }
    }
    pb_backupbuddy::$options['data_version'] = '5';
    pb_backupbuddy::save();
}
// ********** END 3.3.0 -> 3.3.0.1 BACKUP DATASTRUCTURE OPTIONS to FILEOPTIONS MIGRATION **********
// ********** BEGIN 4.0 UPGRADE **********