Example #1
0
 function stats()
 {
     echo '<style type="text/css">';
     echo '	.pb_fancy {';
     echo '		font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif;';
     echo '		font-size: 18px;';
     echo '		color: #21759B;';
     echo '	}';
     echo '</style>';
     echo '<div>';
     $backup_url = 'admin.php?page=pb_backupbuddy_backup';
     $files = glob(backupbuddy_core::getBackupDirectory() . 'backup*.zip');
     if (!is_array($files) || empty($files)) {
         $files = array();
     }
     echo sprintf(__('You currently have %s stored backups.', 'it-l10n-backupbuddy'), '<span class="pb_fancy"><a href="' . $backup_url . '">' . count($files) . '</a></span>');
     if (pb_backupbuddy::$options['last_backup_finish'] == 0) {
         echo ' ', __('You have not successfully created any backups.', 'it-l10n-backupbuddy');
     } else {
         echo ' ', sprintf(__(' Your most recent successful backup was %s ago.', 'it-l10n-backupbuddy'), '<span class="pb_fancy"><a href="' . $backup_url . '">' . pb_backupbuddy::$format->time_ago(pb_backupbuddy::$options['last_backup_finish']) . '</a></span>');
     }
     echo ' ', sprintf(__('There have been %s post/page modifications since your last backup.', 'it-l10n-backupbuddy'), '<span class="pb_fancy"><a href="' . $backup_url . '">' . pb_backupbuddy::$options['edits_since_last'] . '</a></span>');
     echo ' <span class="pb_fancy"><a href="' . $backup_url . '">', __('Go create a backup!', 'it-l10n-backupbuddy'), '</a></span>';
     echo '</div>';
 }
 public static function calculateArchiveFilename($serial, $type)
 {
     // Prepare some values for setting up the backup data.
     $siteurl_stripped = backupbuddy_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(backupbuddy_constants::ARCHIVE_NAME_FORMAT_DATETIME, pb_backupbuddy::$format->localize_time(time()));
     } else {
         // "date" = date only (the default).
         $backupfile_datetime = date(backupbuddy_constants::ARCHIVE_NAME_FORMAT_DATE, pb_backupbuddy::$format->localize_time(time()));
     }
     $archiveFile = backupbuddy_core::getBackupDirectory() . 'backup-' . $siteurl_stripped . '-' . $backupfile_datetime . '-' . $type . '-' . $serial . '.zip';
     pb_backupbuddy::status('details', 'Calculated archive file: `' . $archiveFile . '`.');
     return $archiveFile;
 }
<?php

// Incoming variables: $backups generated via core.php backups_list() function.
// $listing_mode should be either:  default,  migrate
$hover_actions = array();
// If download URL is within site root then allow downloading via web.
$backup_directory = backupbuddy_core::getBackupDirectory();
// Normalize for Windows paths.
$backup_directory = str_replace('\\', '/', $backup_directory);
$backup_directory = rtrim($backup_directory, '/\\') . '/';
// Enforce single trailing slash.
if ($listing_mode != 'restore_files' && FALSE !== stristr($backup_directory, ABSPATH)) {
    $hover_actions[pb_backupbuddy::ajax_url('download_archive') . '&backupbuddy_backup='] = __('Download', 'it-l10n-backupbuddy');
}
if ($listing_mode == 'restore_files') {
    $hover_actions[pb_backupbuddy::ajax_url('download_archive') . '&zip_viewer='] = __('Browse & Restore Files', 'it-l10n-backupbuddy');
    $hover_actions['note'] = __('Note', 'it-l10n-backupbuddy');
    $bulk_actions = array();
}
if ($listing_mode == 'default') {
    $hover_actions['send'] = __('Send', 'it-l10n-backupbuddy');
    $hover_actions['zip_viewer'] = __('Browse & Restore Files', 'it-l10n-backupbuddy');
    $hover_actions['note'] = __('Note', 'it-l10n-backupbuddy');
    $hover_actions['hash'] = __('Checksum', 'it-l10n-backupbuddy');
    $bulk_actions = array('delete_backup' => __('Delete', 'it-l10n-backupbuddy'));
}
if ($listing_mode == 'migrate') {
    $hover_actions['migrate'] = __('Migrate', 'it-l10n-backupbuddy');
    $hover_actions[pb_backupbuddy::ajax_url('download_archive') . '&backupbuddy_backup='] = __('Download', 'it-l10n-backupbuddy');
    $hover_actions['note'] = __('Note', 'it-l10n-backupbuddy');
    $bulk_actions = array();
// 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>
Example #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;
     }
 }
Example #6
0
 function process_ftp_copy($backup, $ftp_server, $ftp_username, $ftp_password, $ftp_directory, $port = '21', $ftps = '0')
 {
     pb_backupbuddy::set_greedy_script_limits();
     if (!class_exists('backupbuddy_core')) {
         require_once pb_backupbuddy::plugin_path() . '/classes/core.php';
     }
     // Connect to server.
     if ($ftps == '1') {
         // Connect with FTPs.
         if (function_exists('ftp_ssl_connect')) {
             $conn_id = ftp_ssl_connect($ftp_server, $port);
             if ($conn_id === false) {
                 pb_backupbuddy::status('details', 'Unable to connect to FTPS  (check address/FTPS support).', 'error');
                 return false;
             } else {
                 pb_backupbuddy::status('details', 'Connected to FTPs.');
             }
         } else {
             pb_backupbuddy::status('details', 'Your web server doesnt support FTPS in PHP.', 'error');
             return false;
         }
     } else {
         // Connect with FTP (normal).
         if (function_exists('ftp_connect')) {
             $conn_id = ftp_connect($ftp_server, $port);
             if ($conn_id === false) {
                 pb_backupbuddy::status('details', 'ERROR: Unable to connect to FTP (check address).', 'error');
                 return false;
             } else {
                 pb_backupbuddy::status('details', 'Connected to FTP.');
             }
         } else {
             pb_backupbuddy::status('details', 'Your web server doesnt support FTP in PHP.', 'error');
             return false;
         }
     }
     // login with username and password
     $login_result = ftp_login($conn_id, $ftp_username, $ftp_password);
     // try to download $server_file and save to $local_file
     $destination_file = backupbuddy_core::getBackupDirectory() . $backup;
     if (file_exists($destination_file)) {
         $destination_file = str_replace('backup-', 'backup_copy_' . pb_backupbuddy::random_string(5) . '-', $destination_file);
     }
     if (ftp_get($conn_id, $destination_file, $ftp_directory . $backup, FTP_BINARY)) {
         pb_backupbuddy::status('message', 'Successfully wrote remote file locally to `' . $destination_file . '`.');
     } else {
         pb_backupbuddy::status('error', 'Error writing remote file locally to `' . $destination_file . '`.');
     }
     // close this connection
     ftp_close($conn_id);
 }
 private static function _verb_renderImportBuddy()
 {
     $backupFile = pb_backupbuddy::_POST('backupFile');
     $password = md5(md5(pb_backupbuddy::_POST('backupbuddy_api_key')));
     // Store this serial in settings to cleanup any temp db tables in the future with this serial with periodic cleanup.
     $backupSerial = backupbuddy_core::get_serial_from_file($backupFile);
     pb_backupbuddy::$options['rollback_cleanups'][$backupSerial] = time();
     pb_backupbuddy::save();
     $importFileSerial = backupbuddy_core::deploymentImportBuddy($password, backupbuddy_core::getBackupDirectory() . $backupFile);
     if (is_array($importFileSerial)) {
         die(json_encode(array('success' => false, 'error' => $importFileSerial[1])));
     } else {
         die(json_encode(array('success' => true, 'importFileSerial' => $importFileSerial)));
     }
 }
Example #8
0
    public function restore_file_restore()
    {
        $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);
        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 
        $success = false;
        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.
        require pb_backupbuddy::plugin_path() . '/classes/_restoreFiles.php';
        $result = backupbuddy_restore_files::restore(backupbuddy_core::getBackupDirectory() . $archive_file, $files, $finalPath = ABSPATH);
        echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
        pb_backupbuddy::flush();
        if (false === $result) {
        } else {
        }
        pb_backupbuddy::$ui->ajax_footer();
        pb_backupbuddy::$ui->ajax_footer();
        die;
    }
Example #9
0
             pb_backupbuddy::status('warning', 'The function `' . $step['function'] . '` is taking an abnormally long time to complete (' . $thisRunTime . ' seconds). The backup may have failed. If it does not increase in the next few minutes it most likely timed out. See the Status Log for details.', $serial);
         }
     } elseif ($step['start_time'] == 0) {
         // Step that has not started yet.
         // Do nothing.
     } elseif ($step['start_time'] == -1) {
         // Step marked for skipping (backup stop button hit).
         // Do nothing.
     } else {
         // Last case: Finished. Skip.
         // Do nothing.
     }
 }
 //***** End outputting status of the current step.
 //***** Begin output of temp zip file size.
 $temporary_zip_directory = backupbuddy_core::getBackupDirectory() . 'temp_zip_' . $serial . '/';
 if (file_exists($temporary_zip_directory)) {
     // Temp zip file.
     $directory = opendir($temporary_zip_directory);
     while ($file = readdir($directory)) {
         if ($file != '.' && $file != '..' && $file != 'exclusions.txt' && !preg_match('/.*\\.txt/', $file) && !preg_match('/pclzip.*\\.gz/', $file)) {
             $stats = stat($temporary_zip_directory . $file);
             $writeSpeedText = '';
             if ($zipRunTime > 0) {
                 $writeSpeed = $stats['size'] / $zipRunTime;
                 $writeSpeedText = '. ' . __('Approximate creation speed', 'it-l10n-backupbuddy') . ': ' . pb_backupbuddy::$format->file_size($writeSpeed) . '/sec';
             }
             pb_backupbuddy::status('details', __('Temporary ZIP file size', 'it-l10n-backupbuddy') . ': ' . pb_backupbuddy::$format->file_size($stats['size']) . $writeSpeedText, $serial);
             pb_backupbuddy::status('archiveSize', pb_backupbuddy::$format->file_size($stats['size']), $serial);
         }
     }
Example #10
0
 function post_backup($fail_mode = false, $cancel_backup = false)
 {
     pb_backupbuddy::status('message', __('Cleaning up after backup.', 'it-l10n-backupbuddy'));
     // Delete temporary data directory.
     if (file_exists($this->_backup['temp_directory'])) {
         pb_backupbuddy::status('details', __('Removing temp data directory.', 'it-l10n-backupbuddy'));
         pb_backupbuddy::$filesystem->unlink_recursive($this->_backup['temp_directory']);
     }
     // Delete temporary ZIP directory.
     if (file_exists(backupbuddy_core::getBackupDirectory() . 'temp_zip_' . $this->_backup['serial'] . '/')) {
         pb_backupbuddy::status('details', __('Removing temp zip directory.', 'it-l10n-backupbuddy'));
         pb_backupbuddy::$filesystem->unlink_recursive(backupbuddy_core::getBackupDirectory() . 'temp_zip_' . $this->_backup['serial'] . '/');
     }
     if (true === $fail_mode) {
         pb_backupbuddy::status('warning', 'Backup archive limiting has been skipped since there was an error to avoid deleting potentially good backups to make room for a potentially bad backup.');
     } else {
         $this->trim_old_archives();
         // Clean up any old excess archives pushing us over defined limits in settings.
     }
     if (true === $cancel_backup) {
         pb_backupbuddy::status('details', 'Backup stopped so deleting backup ZIP file.');
         $unlink_result = @unlink($this->_backup['archive_file']);
         if (true === $unlink_result) {
             pb_backupbuddy::status('details', 'Deleted stopped backup file.');
         } else {
             pb_backupbuddy::status('error', 'Unable to delete stopped backup file. You should delete it manually as it may be damaged from stopping mid-backup. File to delete: `' . $this->_backup['archive_file'] . '`.');
         }
         $this->_backup['finish_time'] = -1;
         //pb_backupbuddy::save();
         $this->_backup_options->save();
     } else {
         // Not cancelled.
         $this->_backup['archive_size'] = filesize($this->_backup['archive_file']);
         pb_backupbuddy::status('details', __('Final ZIP file size', 'it-l10n-backupbuddy') . ': ' . pb_backupbuddy::$format->file_size($this->_backup['archive_size']));
         pb_backupbuddy::status('action', 'archive_size^' . pb_backupbuddy::$format->file_size($this->_backup['archive_size']));
         if ($fail_mode === false) {
             // Not cancelled and did not fail so mark finish time.
             //error_log( print_r( $this->_backup_options->options, true ) );
             $archiveFile = basename($this->_backup_options->options['archive_file']);
             // Calculate backup download URL, if any.
             //$downloadURL = pb_backupbuddy::ajax_url( 'download_archive' ) . '&backupbuddy_backup=' . $archiveFile;
             $downloadURL = '';
             $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).
                 //pb_backupbuddy::status( 'details', 'mydir: `' . $backup_dir . '`, abs: `' . $abspath . '`.');
                 $sitepath = str_replace($abspath, '', $backup_dir);
                 $downloadURL = rtrim(site_url(), '/\\') . '/' . trim($sitepath, '/\\') . '/' . $archiveFile;
             }
             $integrityIsOK = '-1';
             if (isset($this->_backup_options->options['integrity']['is_ok'])) {
                 $integrityIsOK = $this->_backup_options->options['integrity']['is_ok'];
             }
             $destinations = array();
             foreach ($this->_backup_options->options['steps'] as $step) {
                 if ('send_remote_destination' == $step['function']) {
                     $destinations[] = array('id' => $step['args'][0], 'title' => pb_backupbuddy::$options['remote_destinations'][$step['args'][0]]['title'], 'type' => pb_backupbuddy::$options['remote_destinations'][$step['args'][0]]['type']);
                 }
             }
             $finishTime = time();
             pb_backupbuddy::$options['last_backup_finish'] = $finishTime;
             pb_backupbuddy::$options['last_backup_stats'] = array('archiveFile' => $archiveFile, 'archiveURL' => $downloadURL, 'archiveSize' => $this->_backup['archive_size'], 'start' => pb_backupbuddy::$options['last_backup_start'], 'finish' => $finishTime, 'type' => $this->_backup_options->options['profile']['type'], 'profileTitle' => htmlentities($this->_backup_options->options['profile']['title']), 'scheduleTitle' => $this->_backup_options->options['schedule_title'], 'integrityStatus' => $integrityIsOK, 'destinations' => $destinations);
             //error_log( print_r( pb_backupbuddy::$options['last_backup_stats'], true ) );
             pb_backupbuddy::save();
         }
     }
     if ($this->_backup['trigger'] == 'manual') {
         // No more manual notifications. Removed Feb 2012 before 3.0.
     } elseif ($this->_backup['trigger'] == 'scheduled') {
         if (false === $fail_mode && false === $cancel_backup) {
             pb_backupbuddy::status('details', __('Sending scheduled backup complete email notification.', 'it-l10n-backupbuddy'));
             $message = 'completed successfully in ' . pb_backupbuddy::$format->time_duration(time() - $this->_backup['start_time']) . ".\n";
             backupbuddy_core::mail_notify_scheduled($this->_backup['serial'], 'complete', __('Scheduled backup', 'it-l10n-backupbuddy') . ' "' . $this->_backup['schedule_title'] . '" ' . $message);
         }
     } else {
         pb_backupbuddy::status('error', 'Error #4343434. Unknown backup trigger.');
     }
     pb_backupbuddy::status('message', __('Finished cleaning up.', 'it-l10n-backupbuddy'));
     if (true === $cancel_backup) {
         pb_backupbuddy::status('details', 'Backup cancellation complete.');
         return false;
     } else {
         if (true === $fail_mode) {
             pb_backupbuddy::status('details', __('As this backup did not pass the integrity check you should verify it manually or re-scan. Integrity checks can fail on good backups due to permissions, large file size exceeding memory limits, etc. You may manually disable integrity check on the Settings page but you will no longer be notified of potentially bad backups.', 'it-l10n-backupbuddy'));
         } else {
             pb_backupbuddy::status('action', 'archive_url^' . basename($this->_backup['archive_file']));
         }
     }
     return true;
 }
Example #11
0
     $backup_directory = backupbuddy_core::_getBackupDirectoryDefault();
 }
 $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'] = backupbuddy_core::getBackupDirectory();
         // Set back to previous value (aka unchanged).
     }
 }
 if (backupbuddy_core::getBackupDirectory() != $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 = backupbuddy_core::getBackupDirectory();
     $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++;
             $serial = backupbuddy_core::get_serial_from_file(basename($old_backup));
Example #12
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;
    }
Example #13
0
<?php

// Incoming vars: $backupFile, $step
if (!current_user_can(pb_backupbuddy::$options['role_access'])) {
    die('Error #473623. Access Denied.');
}
require_once pb_backupbuddy::plugin_path() . '/classes/restore.php';
$rollback = new backupbuddy_restore('rollback');
$status = $rollback->start(backupbuddy_core::getBackupDirectory() . $backupFile);
if (false === $status) {
    $errors = $rollback->getErrors();
    if (count($errors) > 0) {
        pb_backupbuddy::alert('Errors were encountered: ' . implode(', ', $errors) . ' If seeking support please click to Show Advanced Details above and provide a copy of the log.');
    }
    return;
}
$restoreData = $rollback->getState();
?>


<?php 
_e("This will roll back this site's database to the state contained within the selected backup file. Verify details below to make sure this is the correct database to roll back to. Current database tables will be a given a temporary prefix.  You will be given the opportunity to confirm changes before making them permanent. <b>Tip!</b> Create a Database or Full Backup before proceeding.", 'it-l10n-backupbuddy');
?>
<br><br>


<?php 
if (isset($restoreData['dat']['wordpress_version'])) {
    $wp_version = $restoreData['dat']['wordpress_version'];
} else {
    $wp_version = 'Unknown';
<?php

backupbuddy_core::verifyAjaxAccess();
$backupSerial = pb_backupbuddy::_POST('serial');
$profileID = pb_backupbuddy::_POST('profileID');
$thisStep = pb_backupbuddy::_POST('step');
$stepCounter = pb_backupbuddy::_POST('stepCounter');
if ('0' == $thisStep) {
    $backupFiles = glob(backupbuddy_core::getBackupDirectory() . 'backup*' . $backupSerial . '*.zip');
    if (!is_array($backupFiles)) {
        $backupFiles = array();
    }
    if (count($backupFiles) > 0) {
        $backupFile = $backupFiles[0];
        die(json_encode(array('statusStep' => 'backupComplete', 'stepTitle' => 'Backup finished. File: ' . $backupFile . ' -- Next step start sending the file chunks to remote API server via curl.', 'nextStep' => 'sendFiles')));
    }
    $lastBackupStats = backupbuddy_api::getLatestBackupStats();
    if ($backupSerial != $lastBackupStats['serial']) {
        die(json_encode(array('stepTitle' => 'Waiting for backup to begin.', 'statusStep' => 'waitingBackupBegin')));
    } else {
        // Last backup stats is our deploy backup.
        die(json_encode(array('stepTitle' => $lastBackupStats['processStepTitle'] . ' with profile "' . pb_backupbuddy::$options['profiles'][$profileID]['title'] . '".', 'statusStep' => 'backupStats', 'stats' => $lastBackupStats)));
    }
} elseif ('sendFiles' == $thisStep) {
    if ('0' == $stepCounter) {
        die(json_encode(array('stepTitle' => 'FIRST SENDFILES RUN', 'statusStep' => 'sendFiles', 'nextStep' => 'sendFiles')));
    } else {
        die(json_encode(array('stepTitle' => 'Sending files...', 'statusStep' => 'sendFiles', 'nextStep' => 'sendFiles')));
    }
} else {
    die('Invalid step `' . htmlentities($thisStep) . '`.');
Example #15
0
 public static function getZipMeta($file)
 {
     if (!isset(pb_backupbuddy::$classes['zipbuddy'])) {
         require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
         pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
     }
     $comment_meta = array();
     if (isset($file)) {
         $comment = pb_backupbuddy::$classes['zipbuddy']->get_comment($file);
         $comment = backupbuddy_core::normalize_comment_data($comment);
         $comment_meta = array();
         foreach ($comment as $comment_line_name => $comment_line_value) {
             // Loop through all meta fields in the comment array to display.
             if (false !== ($response = backupbuddy_core::pretty_meta_info($comment_line_name, $comment_line_value))) {
                 $response[0] = '<span title="' . $comment_line_name . '">' . $response[0] . '</span>';
                 $comment_meta[$comment_line_name] = $response;
             }
         }
     }
     if (count($comment_meta) > 0) {
         return $comment_meta;
     } else {
         return false;
     }
 }
Example #16
0
_e('You cannot exclude wp-config.php.', 'it-l10n-backupbuddy');
?>
" );
				} else {
					jQuery( '#pb_backupbuddy_profiles__<?php 
echo $profile_id;
?>
__excludes' ).val( file + "\n" + jQuery( '#pb_backupbuddy_profiles__<?php 
echo $profile_id;
?>
__excludes' ).val() );
				}
			},
			function(directory) {
				if ( ( directory == '/wp-content/' ) || ( directory == '/wp-content/uploads/' ) || ( directory == '<?php 
echo '/' . str_replace(ABSPATH, '', backupbuddy_core::getBackupDirectory());
?>
' ) || ( directory == '<?php 
echo '/' . str_replace(ABSPATH, '', backupbuddy_core::getTempDirectory());
?>
' ) ) {
					alert( "<?php 
_e('You cannot exclude /wp-content/, /wp-content/uploads/, or BackupBuddy directories.  However, you may exclude subdirectories within these. BackupBuddy directories such as backupbuddy_backups are automatically excluded and cannot be added to exclusion list.', 'it-l10n-backupbuddy');
?>
" );
				} else {
					jQuery( '#pb_backupbuddy_profiles__<?php 
echo $profile_id;
?>
__excludes' ).val( directory + "\n" + jQuery( '#pb_backupbuddy_profiles__<?php 
echo $profile_id;
Example #17
0
 $parent_class_test = array('title' => 'Site number of files (Default Exclusions applied)', 'suggestion' => 'n/a', 'value' => '<span id="pb_stats_refresh_objects_excluded">' . $site_objects_excluded . '</span> <a class="pb_backupbuddy_refresh_stats" rel="refresh_objects_excluded" alt="' . pb_backupbuddy::ajax_url('refresh_site_objects_excluded') . '" title="' . __('Refresh', 'it-l10n-backupbuddy') . '"><img src="' . pb_backupbuddy::plugin_url() . '/images/refresh_gray.gif" style="vertical-align: -1px;"> <span class="pb_backupbuddy_loading" style="display: none; margin-left: 10px;"><img src="' . pb_backupbuddy::plugin_url() . '/images/loading.gif" alt="' . __('Loading...', 'it-l10n-backupbuddy') . '" title="' . __('Loading...', 'it-l10n-backupbuddy') . '" width="16" height="16" style="vertical-align: -3px;" /></span></a>', 'tip' => __('Total number of files/folders site (starting in your WordPress main directory) EXCLUDING any directories / files you have marked for exclusion.', 'it-l10n-backupbuddy'));
 $parent_class_test['status'] = __('OK', 'it-l10n-backupbuddy');
 array_push($tests, $parent_class_test);
 // Database Size
 $parent_class_test = array('title' => 'Database Size', 'suggestion' => 'n/a', 'value' => '<span id="pb_stats_refresh_database_size">' . pb_backupbuddy::$format->file_size(pb_backupbuddy::$options['stats']['db_size']) . '</span> <a class="pb_backupbuddy_refresh_stats" rel="refresh_database_size" alt="' . pb_backupbuddy::ajax_url('refresh_database_size') . '" title="' . __('Refresh', 'it-l10n-backupbuddy') . '"><img src="' . pb_backupbuddy::plugin_url() . '/images/refresh_gray.gif" style="vertical-align: -1px;"> <span class="pb_backupbuddy_loading" style="display: none; margin-left: 10px;"><img src="' . pb_backupbuddy::plugin_url() . '/images/loading.gif" alt="' . __('Loading...', 'it-l10n-backupbuddy') . '" title="' . __('Loading...', 'it-l10n-backupbuddy') . '" width="16" height="16" style="vertical-align: -3px;" /></span></a>', 'tip' => __('Total size of your database INCLUDING any excluded tables.', 'it-l10n-backupbuddy'));
 $parent_class_test['status'] = __('OK', 'it-l10n-backupbuddy');
 array_push($tests, $parent_class_test);
 // Database size WITH EXCLUSIONS accounted for.
 $parent_class_test = array('title' => 'Database Size (Default Exclusions applied)', 'suggestion' => 'n/a', 'value' => '<span id="pb_stats_refresh_database_size_excluded">' . pb_backupbuddy::$format->file_size(pb_backupbuddy::$options['stats']['db_size_excluded']) . '</span> <a class="pb_backupbuddy_refresh_stats" rel="refresh_database_size_excluded" alt="' . pb_backupbuddy::ajax_url('refresh_database_size_excluded') . '" title="' . __('Refresh', 'it-l10n-backupbuddy') . '"><img src="' . pb_backupbuddy::plugin_url() . '/images/refresh_gray.gif" style="vertical-align: -1px;"> <span class="pb_backupbuddy_loading" style="display: none; margin-left: 10px;"><img src="' . pb_backupbuddy::plugin_url() . '/images/loading.gif" alt="' . __('Loading...', 'it-l10n-backupbuddy') . '" title="' . __('Loading...', 'it-l10n-backupbuddy') . '" width="16" height="16" style="vertical-align: -3px;" /></span></a>', 'tip' => __('Total size of your database EXCLUDING any tables you have marked for exclusion.', 'it-l10n-backupbuddy'));
 $parent_class_test['status'] = __('OK', 'it-l10n-backupbuddy');
 array_push($tests, $parent_class_test);
 /***** BEGIN AVERAGE WRITE SPEED *****/
 require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
 $write_speed_samples = 0;
 $write_speed_sum = 0;
 $backups = glob(backupbuddy_core::getBackupDirectory() . '*.zip');
 if (!is_array($backups)) {
     $backups = array();
 }
 foreach ($backups as $backup) {
     $serial = backupbuddy_core::get_serial_from_file($backup);
     pb_backupbuddy::status('details', 'Fileoptions instance #22.');
     $backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = true);
     if (true !== ($result = $backup_options->is_ok())) {
         pb_backupbuddy::status('warning', 'Unable to open fileoptions file `' . backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt' . '`. Details: `' . $result . '`.');
     }
     if (isset($backup_options->options['integrity']) && isset($backup_options->options['integrity']['size'])) {
         $write_speed_samples++;
         $size = $backup_options->options['integrity']['size'];
         $time_taken = 0;
         if (isset($backup_options->options['steps'])) {
 public function ms_download_extract_wordpress()
 {
     // Step 1 - Download a copy of WordPress.
     if (!function_exists('download_url')) {
         pb_backupbuddy::status('details', 'download_url() function not available by default. Loading `/wp-admin/includes/file.php`.');
         require_once ABSPATH . 'wp-admin/includes/file.php';
     }
     $wp_url = 'http://wordpress.org/latest.zip';
     pb_backupbuddy::status('details', 'Downloading latest WordPress ZIP file from `' . $wp_url . '`.');
     $wp_file = download_url($wp_url);
     if (is_wp_error($wp_file)) {
         // Grabbing WordPress ZIP failed.
         pb_backupbuddy::status('error', 'Error getting latest WordPress ZIP file: `' . $wp_file->get_error_message() . '`.');
         return false;
     } else {
         // Grabbing WordPress ZIP succeeded.
         //error_log ('nowperror' );
         pb_backupbuddy::status('details', 'Latest WordPress ZIP file successfully downloaded to `' . $wp_file . '`.');
     }
     // Step 2 - Extract WP into a separate directory.
     if (!isset(pb_backupbuddy::$classes['zipbuddy'])) {
         pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
     }
     pb_backupbuddy::status('details', 'About to unzip file `' . $wp_file . '` into `' . $this->_backup['backup_root'] . '`.');
     ob_start();
     pb_backupbuddy::$classes['zipbuddy']->unzip($wp_file, dirname($this->_backup['backup_root']));
     pb_backupbuddy::status('details', 'Unzip complete.');
     pb_backupbuddy::status('details', 'Debugging information: `' . ob_get_clean() . '`');
     @unlink($wp_file);
     if (file_exists($wp_file)) {
         // Check to see if unlink() worked.
         pb_backupbuddy::status('warning', 'Unable to delete temporary WordPress file `' . $wp_file . '`. You may want to delete this after the backup / export completed.');
     }
     return true;
 }
Example #19
0
' + ajax_url_name + '&archive=<?php 
echo strip_tags($file);
?>
&file=' + source_obj_val.attr( 'rel' );
		jQuery( '#pb_backupbuddy_modal_iframe' ).attr( 'src', url );
		jQuery( '#leanModal_a' ).click();
	}
</script>



<?php 
// Set up zipbuddy.
if (!isset(pb_backupbuddy::$classes['zipbuddy'])) {
    require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
    pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
}
pb_backupbuddy::$ui->title('View Backup Contents');
?>



<a class="button secondary-button pb_backupbuddy_restore">Restore Selected</a>
<div style="width: 100%; height: 100%;">
	<div class="jQueryOuterTree" id="pb_backupbuddy_file_browser" style="position: relative; height: 90%; margin-top: 7px; margin-bottom: 7px;">
		<ul class="jqueryFileTree"></ul>
	</div>
	<span style="float: right;" class="description">Select directories to expand or text-based files to view contents.</span>
	<a class="button secondary-button pb_backupbuddy_restore">Restore Selected</a>
	
	<br><br><br><br style="clear: both; height: 0; overflow: hidden;">
// The fileoptions file that contains the file tree information
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
$fileoptions_file = backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '-filetree.txt';
// Purge cache if too old.
if (file_exists($fileoptions_file) && time() - filemtime($fileoptions_file) > $max_cache_time) {
    if (false === unlink($fileoptions_file)) {
        pb_backupbuddy::alert('Error #456765545. Unable to wipe cached fileoptions file `' . $fileoptions_file . '`.');
    }
}
$fileoptions = new pb_backupbuddy_fileoptions($fileoptions_file);
// Either we are getting cached file tree information or we need to create afresh
if (true !== ($result = $fileoptions->is_ok())) {
    // Get file listing.
    require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
    pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy(ABSPATH, array(), 'unzip');
    $files = pb_backupbuddy::$classes['zipbuddy']->get_file_list(backupbuddy_core::getBackupDirectory() . str_replace('\\/', '', pb_backupbuddy::_GET('zip_viewer')));
    $fileoptions->options = $files;
    $fileoptions->save();
} else {
    $files =& $fileoptions->options;
}
// Just make sure we have a sensible files listing
if (!is_array($files)) {
    die('Error #548484.  Unable to retrieve file listing from backup file `' . htmlentities(pb_backupbuddy::_GET('zip_viewer')) . '`.');
}
// To record subdirs of this root
$subdirs = array();
// Strip out any files/subdirs that are not actually directly under the given root
foreach ($files as $key => $file) {
    // If shorter than root length then certainly is not within this (root) directory.
    // It's a quick test that is more effective the longer the root (the deeper you go
Example #21
0
 public static function calculateArchiveFilename($serial, $type, $profile)
 {
     // Prepare some values for setting up the backup data.
     $siteurl_stripped = backupbuddy_core::backup_prefix();
     // Add profile to filename if set in options and exists
     if (empty(pb_backupbuddy::$options['archive_name_profile']) || empty($profile['title'])) {
         $backupfile_profile = '';
     } else {
         $backupfile_profile = sanitize_file_name(strtolower($profile['title'])) . '-';
         $backupfile_profile = str_replace('/', '_', $backupfile_profile);
         $backupfile_profile = str_replace('\\', '_', $backupfile_profile);
         $backupfile_profile = str_replace('.', '_', $backupfile_profile);
         $backupfile_profile = str_replace(' ', '_', $backupfile_profile);
         $backupfile_profile = str_replace('-', '_', $backupfile_profile);
     }
     // Calculate customizable section of archive filename (date vs date+time).
     if (pb_backupbuddy::$options['archive_name_format'] == 'datetime') {
         // "datetime" = Date + time.
         $backupfile_datetime = date(backupbuddy_constants::ARCHIVE_NAME_FORMAT_DATETIME, pb_backupbuddy::$format->localize_time(time()));
     } elseif (pb_backupbuddy::$options['archive_name_format'] == 'datetime24') {
         // "datetime" = Date + time in 24hr format.
         $backupfile_datetime = date(backupbuddy_constants::ARCHIVE_NAME_FORMAT_DATETIME24, pb_backupbuddy::$format->localize_time(time()));
     } elseif (pb_backupbuddy::$options['archive_name_format'] == 'timestamp') {
         // "datetime" = Date + time in 24hr format.
         $backupfile_datetime = pb_backupbuddy::$format->localize_time(time());
     } else {
         // "date" = date only (the default).
         $backupfile_datetime = date(backupbuddy_constants::ARCHIVE_NAME_FORMAT_DATE, pb_backupbuddy::$format->localize_time(time()));
     }
     $archiveFile = backupbuddy_core::getBackupDirectory() . 'backup-' . $siteurl_stripped . '-' . $backupfile_datetime . '-' . $backupfile_profile . $type . '-' . $serial . '.zip';
     pb_backupbuddy::status('details', 'Calculated archive file: `' . $archiveFile . '`.');
     return $archiveFile;
 }
<?php

backupbuddy_core::verifyAjaxAccess();
/*	remote_send()
*	
*	Send backup archive to a remote destination manually. Optionally sends importbuddy.php with files.
*	Sends are scheduled to run in a cron and are passed to the cron.php remote_send() method.
*	
*	@return		null
*/
$success_output = false;
// Set to true onece a leading 1 has been sent to the javascript to indicate success.
$destination_id = pb_backupbuddy::_POST('destination_id');
if (pb_backupbuddy::_POST('file') != 'importbuddy.php') {
    $backup_file = backupbuddy_core::getBackupDirectory() . pb_backupbuddy::_POST('file');
    if (!file_exists($backup_file)) {
        // Error if file to send did not exist!
        $error_message = 'Unable to find file `' . $backup_file . '` to send. File does not appear to exist. You can try again in a moment or turn on full error logging and try again to log for support.';
        pb_backupbuddy::status('error', $error_message);
        echo $error_message;
        die;
    }
    if (is_dir($backup_file)) {
        // Error if a directory is trying to be sent.
        $error_message = 'You are attempting to send a directory, `' . $backup_file . '`. Try again and verify there were no javascript errors.';
        pb_backupbuddy::status('error', $error_message);
        echo $error_message;
        die;
    }
} else {
    $backup_file = '';
Example #23
0
    echo esc_attr($i);
    ?>
'><?php 
    echo esc_html(basename($file));
    ?>
</label><br />
			<?php 
}
if (count($files) == 0) {
    _e('No BackupBuddy backups found in the root directory of the site.', 'it-l10n-backupbuddy');
    echo '<br>';
}
echo '<br>';
echo 'Existing backups in this site\'s backup directory:';
echo '<br>';
$files = glob(backupbuddy_core::getBackupDirectory() . 'backup*.zip');
if (!is_array($files) || empty($files)) {
    $files = array();
}
foreach ($files as $i => $file) {
    ?>
			<input style="width: auto;" type='radio' id='backup_<?php 
    echo esc_attr($i);
    ?>
' value='<?php 
    echo esc_attr($file);
    ?>
'
			<?php 
    if (count($files) == 1) {
        echo ' CHECKED';
Example #24
0
<br><?php 
$tests = array();
$uploads_dirs = wp_upload_dir();
$directories = array(ABSPATH . '', ABSPATH . 'wp-includes/', ABSPATH . 'wp-admin/', WP_CONTENT_DIR . '/themes/', WP_CONTENT_DIR . '/plugins/', WP_CONTENT_DIR . '/', rtrim($uploads_dirs['basedir'], '\\/') . '/', ABSPATH . 'wp-includes/', backupbuddy_core::getBackupDirectory(), backupbuddy_core::getLogDirectory());
if (@file_exists(backupbuddy_core::getTempDirectory())) {
    // This dir is usually transient so may not exist.
    $directories[] = backupbuddy_core::getTempDirectory();
}
foreach ($directories as $directory) {
    $mode_octal_four = '<i>' . __('Unknown', 'it-l10n-backupbuddy') . '</i>';
    $owner = '<i>' . __('Unknown', 'it-l10n-backupbuddy') . '</i>';
    if (!file_exists($directory)) {
        $mode_octal_four = 'Directory does\'t exist';
        $owner = 'n/a';
    }
    $stats = pluginbuddy_stat::stat($directory);
    if (false !== $stats) {
        $mode_octal_four = $stats['mode_octal_four'];
        $owner = $stats['uid'] . ':' . $stats['gid'];
    }
    $this_test = array('title' => '/' . str_replace(ABSPATH, '', $directory), 'suggestion' => '<= 755', 'value' => $mode_octal_four, 'owner' => $owner);
    if (false === $stats || $mode_octal_four > 755) {
        $this_test['status'] = __('WARNING', 'it-l10n-backupbuddy');
    } else {
        $this_test['status'] = __('OK', 'it-l10n-backupbuddy');
    }
    array_push($tests, $this_test);
}
// end foreach.
?>
// Change slashes to handle Windows as we store backup_directory with Linux-style slashes even on Windows.
$backup_dir = str_replace('\\', '/', backupbuddy_core::getBackupDirectory());
// Make sure file to download is in a publicly accessible location (beneath WP web root technically).
if (FALSE === stristr($backup_dir, $abspath)) {
    die('Error #5432532. You cannot download backups stored outside of the WordPress web root. Please use FTP or other means.');
}
// Made it this far so download dir is within this WP install.
$sitepath = str_replace($abspath, '', $backup_dir);
$download_url = rtrim(site_url(), '/\\') . '/' . trim($sitepath, '/\\') . '/' . pb_backupbuddy::_GET('backupbuddy_backup');
if (pb_backupbuddy::$options['lock_archives_directory'] == '1') {
    // High security mode.
    if (file_exists(backupbuddy_core::getBackupDirectory() . '.htaccess')) {
        $unlink_status = @unlink(backupbuddy_core::getBackupDirectory() . '.htaccess');
        if ($unlink_status === false) {
            die('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.');
        }
    }
    header('Location: ' . $download_url);
    ob_clean();
    flush();
    sleep(8);
    // Wait 8 seconds before creating security file.
    $htaccess_creation_status = @file_put_contents(backupbuddy_core::getBackupDirectory() . '.htaccess', 'deny from all');
    if ($htaccess_creation_status === false) {
        die('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.');
    }
} else {
    // Normal mode.
    header('Location: ' . $download_url);
}
die;
 if (isset($wp_upload_dir['baseurl'])) {
     $wp_settings[] = array('Upload Base URL', $wp_upload_dir['baseurl'], 'wp_upload_dir()');
 }
 if (isset($wp_upload_dir['basedir'])) {
     $wp_settings[] = array('Upload Base Directory', $wp_upload_dir['basedir'], 'wp_upload_dir()');
 }
 $wp_settings[] = array('Site URL', site_url(), 'site_url()');
 $wp_settings[] = array('Home URL', home_url(), 'home_url()');
 $wp_settings[] = array('WordPress Root Path', ABSPATH, 'ABSPATH');
 // Multisite extras:
 $wp_settings_multisite = array();
 if (is_multisite()) {
     $wp_settings[] = array('Network Site URL', network_site_url(), 'network_site_url()');
     $wp_settings[] = array('Network Home URL', network_home_url(), 'network_home_url()');
 }
 $wp_settings[] = array('BackupBuddy local storage', backupbuddy_core::getBackupDirectory(), 'BackupBuddy Settings');
 $wp_settings[] = array('BackupBuddy temporary files', backupbuddy_core::getTempDirectory(), 'ABSPATH + Hardcoded location');
 $wp_settings[] = array('BackupBuddy logs', backupbuddy_core::getLogDirectory(), 'Upload Base + BackupBuddy');
 // Display WP settings..
 pb_backupbuddy::$ui->list_table($wp_settings, array('action' => pb_backupbuddy::page_url(), 'columns' => array(__('URLs & Paths', 'it-l10n-backupbuddy'), __('Value', 'it-l10n-backupbuddy'), __('Obtained via', 'it-l10n-backupbuddy')), 'css' => 'width: 100%;'));
 pb_backupbuddy::$ui->end_tab();
 // This page can take a bit to run.
 // Runs AFTER server information is displayed so we can view the default limits for the server.
 pb_backupbuddy::set_greedy_script_limits();
 pb_backupbuddy::$ui->start_tab('database');
 require_once 'server_info/database.php';
 echo '<br><br><a name="database_replace"></a>';
 echo '<div class="pb_htitle">' . 'Advanced: ' . __('Database Mass Text Replacement', 'it-l10n-backupbuddy') . '</div><br>';
 pb_backupbuddy::load_view('_server_tools-database_replace');
 pb_backupbuddy::$ui->end_tab();
 pb_backupbuddy::$ui->start_tab('files');
$possibly_temp_restore_dirs = glob($temp_dir . 'backupbuddy-*');
if (!is_array($possibly_temp_restore_dirs)) {
    $possibly_temp_restore_dirs = array();
}
foreach ($possibly_temp_restore_dirs as $possibly_temp_restore_dir) {
    if (false === pb_backupbuddy::$filesystem->unlink_recursive($possibly_temp_restore_dir)) {
        // Delete.
        pb_backupbuddy::status('details', 'Unable to delete temporary holding directory `' . $possibly_temp_restore_dir . '`.');
    } else {
        pb_backupbuddy::status('details', 'Cleaned up temporary files.');
    }
}
pb_backupbuddy::status('details', 'Individual file / directory restore cleanup complete.');
// 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 `' . backupbuddy_core::getBackupDirectory() . 'temp_zip_XXXX/`.');
$temp_directory = backupbuddy_core::getBackupDirectory() . '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) {
                $message = 'BackupBuddy was unable to clean up (delete) temporary directory/file: `' . $file . '`. You should manually delete it and/or verify proper file permissions to allow BackupBuddy to clean up for you.';
                pb_backupbuddy::status('error', $message);
                backupbuddy_core::mail_error($message);
                } else {
                    $status_text = '<span class="pb_label pb_label-important">Fail</span>';
                }
                $tests[] = array($test['test'], $status_text);
            }
        }
    }
    $columns = array(__('Integrity Test', 'it-l10n-backupbuddy'), __('Status', 'it-l10n-backupbuddy'));
    pb_backupbuddy::$ui->list_table($tests, array('columns' => $columns, 'css' => 'width: 100%; min-width: 200px;'));
}
// end $integrity['status_details'] is an array.
echo '<br><br>';
//***** END TESTS AND RESULTS.
// Output meta info table (if any).
$metaInfo = array();
if (isset($integrity['file']) && false === ($metaInfo = backupbuddy_core::getZipMeta(backupbuddy_core::getBackupDirectory() . $integrity['file']))) {
    // $backup_options->options['archive_file']
    echo '<i>No meta data found in zip comment. Skipping meta information display.</i>';
} else {
    pb_backupbuddy::$ui->list_table($metaInfo, array('columns' => array('Backup Details', 'Value'), 'css' => 'width: 100%; min-width: 200px;'));
}
echo '<br><br>';
//***** BEGIN STEPS.
$steps = array();
$steps[] = array('Start Time', $start_time, '');
if (isset($backup_options->options['steps'])) {
    foreach ($backup_options->options['steps'] as $step) {
        if (isset($step['finish_time']) && $step['finish_time'] != 0) {
            // Step name.
            if ($step['function'] == 'backup_create_database_dump') {
                if (count($step['args'][0]) == 1) {
		if( jQuery( '#' + target_id ).length == 0 ) { // No status box yet so suppress.
			return;
		}
		jQuery( '#' + target_id ).append( "\n" + message );
		textareaelem = document.getElementById( target_id );
		textareaelem.scrollTop = textareaelem.scrollHeight;
	}
	
	function backupbuddy_hourpad(n) { return ("0" + n).slice(-2); }
</script>
<?php 
$success = false;
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.
require pb_backupbuddy::plugin_path() . '/classes/_restoreFiles.php';
$result = backupbuddy_restore_files::restore(backupbuddy_core::getBackupDirectory() . $archive_file, $files, $finalPath = ABSPATH);
echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
pb_backupbuddy::flush();
if (false === $result) {
} else {
}
pb_backupbuddy::$ui->ajax_footer();
pb_backupbuddy::$ui->ajax_footer();
die;
Example #30
0
 public function extractDatabase()
 {
     $this->_before(__FUNCTION__);
     $this->_priorRollbackCleanup();
     pb_backupbuddy::status('details', 'Loading zipbuddy.');
     require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
     $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
     pb_backupbuddy::status('details', 'Zipbuddy loaded.');
     // Find SQL file location in archive.
     pb_backupbuddy::status('details', 'Calculating possible SQL file locations.');
     $possibleSQLLocations = array();
     $possibleSQLLocations[] = trim(rtrim(str_replace('backupbuddy_dat.php', '', $this->_state['datLocation']), '\\/') . '/db_1.sql', '\\/');
     // SQL file most likely is in the same spot the dat file was.
     $possibleSQLLocations[] = 'db_1.sql';
     // DB backup.
     $possibleSQLLocations[] = 'wp-content/uploads/backupbuddy_temp/' . $this->_state['serial'] . '/db_1.sql';
     // Full backup.
     pb_backupbuddy::status('details', 'Possible SQL file locations: `' . implode(';', $possibleSQLLocations) . '`.');
     $possibleSQLLocations = array_unique($possibleSQLLocations);
     foreach ($possibleSQLLocations as $possibleSQLLocation) {
         if (true === $zipbuddy->file_exists($this->_state['archive'], $possibleSQLLocation, $leave_open = true)) {
             $detectedSQLLocation = $possibleSQLLocation;
             break;
         }
     }
     // end foreach.
     pb_backupbuddy::status('details', 'Confirmed SQL file location: `' . $detectedSQLLocation . '`.');
     // Get SQL file.
     $files = array($detectedSQLLocation => 'db_1.sql');
     pb_backupbuddy::$filesystem->unlink_recursive($this->_state['tempPath']);
     // Remove if already exists.
     mkdir($this->_state['tempPath']);
     // Make empty directory.
     require pb_backupbuddy::plugin_path() . '/classes/_restoreFiles.php';
     // Extract SQL file.
     pb_backupbuddy::status('details', 'Extracting SQL file(s).');
     if (false === backupbuddy_restore_files::restore($this->_state['archive'], $files, $this->_state['tempPath'], $zipbuddy)) {
         return $this->_error('Error #85384: Unable to restore one or more database files.');
     }
     pb_backupbuddy::status('details', 'Finished database extraction function.');
     return true;
 }