Beispiel #1
0
 private static function _load_tables($force_reload = false, $get_contents_only = false)
 {
     if (is_object(self::$_tablesObj) && true !== $force_reload) {
         return self::$_tablesObj;
     }
     if (true === $force_reload) {
         unset(self::$_tablesObj);
     }
     $read_only = false;
     $ignore_lock = self::_fileoptions_lock_ignore_timeout_value();
     if (true === $get_contents_only) {
         $read_only = true;
         $ignore_lock = false;
     }
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $tablesObj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'live/tables-' . pb_backupbuddy::$options['log_serial'] . '.txt', $read_only, $ignore_lock, $create_file = true, $live_mode = true);
     if (true !== ($result = $tablesObj->is_ok())) {
         pb_backupbuddy::status('error', 'Error #435554390. Unable to create or access fileoptions file. Details: `' . $result . '`. Waiting a moment before ending.');
         sleep(3);
         // Wait a moment to give time for temporary issues to resolve.
         return false;
     }
     // Set defaults.
     if (!is_array($tablesObj->options)) {
         $tablesObj->options = array();
     }
     // Getting contents only.
     if (true === $get_contents_only) {
         return $tablesObj->options;
     }
     // Set class variables with references to object and options within.
     self::$_tablesObj =& $tablesObj;
     self::$_tables =& $tablesObj->options;
     return true;
 }
Beispiel #2
0
 public static function send($settings = array(), $files = array(), $send_id = '')
 {
     global $pb_backupbuddy_destination_errors;
     if ('1' == $settings['disabled']) {
         $pb_backupbuddy_destination_errors[] = __('Error #48933: This destination is currently disabled. Enable it under this destination\'s Advanced Settings.', 'it-l10n-backupbuddy');
         return false;
     }
     if (!is_array($files)) {
         $files = array($files);
     }
     pb_backupbuddy::status('details', 'FTP class send() function started.');
     self::_init();
     // Connect to server.
     $server = $settings['address'];
     $port = '22';
     // Default sFTP port.
     if (strstr($server, ':')) {
         // Handle custom sFTP port.
         $server_params = explode(':', $server);
         $server = $server_params[0];
         $port = $server_params[1];
     }
     pb_backupbuddy::status('details', 'Connecting to sFTP server...');
     $sftp = new Net_SFTP($server, $port);
     if (!$sftp->login($settings['username'], $settings['password'])) {
         pb_backupbuddy::status('error', 'Connection to sFTP server FAILED.');
         pb_backupbuddy::status('details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.');
         return false;
     } else {
         pb_backupbuddy::status('details', 'Success connecting to sFTP server.');
     }
     pb_backupbuddy::status('details', 'Attempting to create path (if it does not exist)...');
     if (true === $sftp->mkdir($settings['path'])) {
         // Try to make directory.
         pb_backupbuddy::status('details', 'Directory created.');
     } else {
         pb_backupbuddy::status('details', 'Directory not created.');
     }
     // Change to directory.
     pb_backupbuddy::status('details', 'Attempting to change into directory...');
     if (true === $sftp->chdir($settings['path'])) {
         pb_backupbuddy::status('details', 'Changed into directory `' . $settings['path'] . '`. All uploads will be relative to this.');
     } else {
         pb_backupbuddy::status('error', 'Unable to change into specified path. Verify the path is correct with valid permissions.');
         pb_backupbuddy::status('details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.');
         return false;
     }
     // Upload files.
     $total_transfer_size = 0;
     $total_transfer_time = 0;
     foreach ($files as $file) {
         if (!file_exists($file)) {
             pb_backupbuddy::status('error', 'Error #859485495. Could not upload local file `' . $file . '` to send to sFTP as it does not exist. Verify the file exists, permissions of file, parent directory, and that ownership is correct. You may need suphp installed on the server.');
         }
         if (!is_readable($file)) {
             pb_backupbuddy::status('error', 'Error #8594846548. Could not read local file `' . $file . '` to send to sFTP as it is not readable. Verify permissions of file, parent directory, and that ownership is correct. You may need suphp installed on the server.');
         }
         $filesize = filesize($file);
         $total_transfer_size += $filesize;
         $destination_file = basename($file);
         pb_backupbuddy::status('details', 'About to put to sFTP local file `' . $file . '` of size `' . pb_backupbuddy::$format->file_size($filesize) . '` to remote file `' . $destination_file . '`.');
         $send_time = -microtime(true);
         $upload = $sftp->put($destination_file, $file, NET_SFTP_LOCAL_FILE);
         $send_time += microtime(true);
         $total_transfer_time += $send_time;
         if ($upload === false) {
             // Failed sending.
             $error_message = 'ERROR #9012b ( http://ithemes.com/codex/page/BackupBuddy:_Error_Codes#9012 ).  sFTP file upload failed. Check file permissions & disk quota.';
             pb_backupbuddy::status('error', $error_message);
             backupbuddy_core::mail_error($error_message);
             pb_backupbuddy::status('details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.');
             return false;
         } else {
             // Success sending.
             pb_backupbuddy::status('details', 'Success completely sending `' . basename($file) . '` to destination.');
             // Start remote backup limit
             if ($settings['archive_limit'] > 0) {
                 pb_backupbuddy::status('details', 'Archive limit enabled. Getting contents of backup directory.');
                 $contents = $sftp->rawlist($settings['path']);
                 // already in destination directory/path.
                 // Create array of backups
                 $bkupprefix = backupbuddy_core::backup_prefix();
                 $backups = array();
                 foreach ($contents as $filename => $backup) {
                     // check if file is backup
                     $pos = strpos($filename, 'backup-' . $bkupprefix . '-');
                     if ($pos !== FALSE) {
                         $backups[] = array('file' => $filename, 'modified' => $backup['mtime']);
                     }
                 }
                 function backupbuddy_number_sort($a, $b)
                 {
                     return $a['modified'] < $b['modified'];
                 }
                 // Sort by modified using custom sort function above.
                 usort($backups, 'backupbuddy_number_sort');
                 if (count($backups) > $settings['archive_limit']) {
                     pb_backupbuddy::status('details', 'More backups found (' . count($backups) . ') than limit permits (' . $settings['archive_limit'] . ').' . print_r($backups, true));
                     $delete_fail_count = 0;
                     $i = 0;
                     foreach ($backups as $backup) {
                         $i++;
                         if ($i > $settings['archive_limit']) {
                             if (false === $sftp->delete($settings['path'] . '/' . $backup['file'])) {
                                 pb_backupbuddy::status('details', 'Unable to delete excess sFTP file `' . $backup['file'] . '` in path `' . $settings['path'] . '`.');
                                 $delete_fail_count++;
                             } else {
                                 pb_backupbuddy::status('details', 'Deleted excess sFTP file `' . $backup['file'] . '` in path `' . $settings['path'] . '`.');
                             }
                         }
                     }
                     if ($delete_fail_count != 0) {
                         backupbuddy_core::mail_error(sprintf(__('sFTP remote limit could not delete %s backups. Please check and verify file permissions.', 'it-l10n-backupbuddy'), $delete_fail_count));
                         pb_backupbuddy::status('error', 'Unable to delete one or more excess backup archives. File storage limit may be exceeded. Manually clean up backups and check permissions.');
                     } else {
                         pb_backupbuddy::status('details', 'No problems encountered deleting excess backups.');
                     }
                 } else {
                     pb_backupbuddy::status('details', 'Not enough backups found to exceed limit. Skipping limit enforcement.');
                 }
             } else {
                 pb_backupbuddy::status('details', 'No sFTP archive file limit to enforce.');
             }
             // End remote backup limit
         }
     }
     // end $files loop.
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #6.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.843498. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     // Save stats.
     $fileoptions['write_speed'] = $total_transfer_size / $total_transfer_time;
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
pb_backupbuddy::status('details', 'Cleaning up remote send stats.');
backupbuddy_core::trim_remote_send_stats();
// Verify directory existance and anti-directory browsing is in place everywhere.
backupbuddy_core::verify_directories($skipTempGeneration = true);
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
// Mark any backups noted as in progress to timed out if taking too long. Send error email is scheduled and failed or timed out.
// Also, Purge fileoptions files without matching backup file in existance that are older than 30 days.
pb_backupbuddy::status('details', 'Cleaning up old backup fileoptions option files.');
$fileoptions_directory = backupbuddy_core::getLogDirectory() . 'fileoptions/';
$files = glob($fileoptions_directory . '*.txt');
if (!is_array($files)) {
    $files = array();
}
foreach ($files as $file) {
    pb_backupbuddy::status('details', 'Fileoptions instance #43.');
    $backup_options = new pb_backupbuddy_fileoptions($file, $read_only = false);
    if (true !== ($result = $backup_options->is_ok())) {
        pb_backupbuddy::status('error', 'Error retrieving fileoptions file `' . $file . '`. Err 335353266.');
    } else {
        if (isset($backup_options->options['archive_file'])) {
            //error_log( print_r( $backup_options->options, true ) );
            if (FALSE === $backup_options->options['finish_time']) {
                // Failed & already handled sending notification.
            } elseif ($backup_options->options['finish_time'] == -1) {
                // Cancelled manually
            } elseif ($backup_options->options['finish_time'] >= $backup_options->options['start_time'] && 0 != $backup_options->options['start_time']) {
                // Completed
            } else {
                // Timed out or in progress.
                $secondsAgo = time() - $backup_options->options['updated_time'];
                if ($secondsAgo > backupbuddy_constants::TIME_BEFORE_CONSIDERED_TIMEOUT) {
Beispiel #4
0
 function remotesend_abort()
 {
     $send_id = pb_backupbuddy::_GET('send_id');
     $send_id = str_replace('/\\', '', $send_id);
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = true, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.324544. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     $fileoptions['status'] = 'aborted';
     $fileoptions_obj->save();
     die('1');
 }
<?php

backupbuddy_core::verifyAjaxAccess();
// Abort an in-process remote destination send.
/* remotesend_abort()
 *
 * Abort an in-progress demote destination file transfer. Dies with outputting "1" on success.
 *
 */
$send_id = pb_backupbuddy::_GET('send_id');
$send_id = str_replace('/\\', '', $send_id);
pb_backupbuddy::status('details', 'About to load fileoptions data.');
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
pb_backupbuddy::status('details', 'Fileoptions instance #25.');
$fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = true, $create_file = false);
if (true !== ($result = $fileoptions_obj->is_ok())) {
    pb_backupbuddy::status('error', __('Fatal Error #9034.324544. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
    return false;
}
pb_backupbuddy::status('details', 'Fileoptions data loaded.');
$fileoptions =& $fileoptions_obj->options;
$fileoptions['status'] = 'aborted';
$fileoptions_obj->save();
die('1');
Beispiel #6
0
 public static function test($settings)
 {
     $settings = self::_init($settings);
     $sendOK = false;
     $deleteOK = false;
     $send_id = 'TEST-' . pb_backupbuddy::random_string(12);
     // Try sending a file.
     if ('1' == $settings['stash_mode']) {
         // Stash mode.
         $settings['type'] = 'stash2';
     }
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id);
     // 3rd param true forces clearing of any current uploads.
     if (true === $send_response) {
         $send_response = __('Success.', 'it-l10n-backupbuddy');
         $sendOK = true;
     } else {
         global $pb_backupbuddy_destination_errors;
         $send_response = 'Error sending test file to S3 (v2). Details: `' . implode(', ', $pb_backupbuddy_destination_errors) . '`.';
     }
     pb_backupbuddy::add_status_serial('remote_send-' . $send_id);
     // Delete sent file if it was sent.
     $delete_response = 'n/a';
     if (true === $sendOK) {
         pb_backupbuddy::status('details', 'Preparing to delete sent test file.');
         if ('1' == $settings['stash_mode']) {
             // Stash mode.
             if (true === ($delete_response = pb_backupbuddy_destination_stash2::deleteFile($settings, 'remote-send-test.php'))) {
                 // success
                 $delete_response = __('Success.', 'it-l10n-backupbuddy');
                 $deleteOK = true;
             } else {
                 // error
                 $error = 'Unable to delete Stash test file `remote-send-test.php`. Details: `' . $delete_response . '`.';
                 $delete_response = $error;
                 $deleteOK = false;
             }
         } else {
             // S3 mode.
             if (true === ($delete_response = self::deleteFile($settings, 'remote-send-test.php'))) {
                 $delete_response = __('Success.', 'it-l10n-backupbuddy');
                 $deleteOK = true;
             } else {
                 $error = 'Unable to delete test file `remote-send-test.php`. Details: `' . $delete_response . '`.';
                 pb_backupbuddy::status('details', $error);
                 $delete_response = $error;
                 $deleteOK = false;
             }
         }
     } else {
         // end if $sendOK.
         pb_backupbuddy::status('details', 'Skipping test delete due to failed send.');
     }
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #7.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         return self::_error(__('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if (true !== $sendOK || true !== $deleteOK) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     pb_backupbuddy::status('details', 'Finished test function.');
     return true;
 }
// ********** 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 **********
if (pb_backupbuddy::$options['data_version'] < 6) {
    // Migrate profile-specific settings into 'Defaults' key profile.
    pb_backupbuddy::$options['profiles'][0]['skip_database_dump'] = pb_backupbuddy::$options['skip_database_dump'];
Beispiel #8
0
 public static function process_files($state = array())
 {
     $start_time = microtime(true);
     $state = array_merge(array('current_step' => 'update_files_list', 'step_start' => microtime(true), 'sha1' => false), $state);
     $steps = array('update_files_list', 'update_files_details');
     /* STEPS
      *	1. Generate list of files, leaving stats blank.
      *	2. Loop through list. Skip anything set to delete. If scantime is too old, calculate filesize, mtime, and optional sha1. Compare with existing values & update them.  If they changed then mark sent to false.
      *
      * array[filename] => {
      *	size
      *	mtime
      *	sha1
      *	scantime
      *	[sent]
      *	[delete]
      * }
      *
      */
     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 #88.');
     $signaturesObj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'live/files-' . pb_backupbuddy::$options['log_serial'] . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
     if (true !== ($result = $signaturesObj->is_ok())) {
         pb_backupbuddy::status('error', 'Error #382983. Unable to create or access fileoptions file for media. Details: `' . $result . '`.');
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     if (!isset($signaturesObj->options['signatures'])) {
         $signaturesObj->options = array('signatures' => array(), 'stats' => array('totalFiles' => 0, 'pendingSend' => 0, 'pendingDelete' => 0));
     }
     $signatures =& $signaturesObj->options['signatures'];
     if ('update_files_list' == $state['current_step']) {
         self::_process_files_update_files_list($signaturesObj, self::_getOption('file_excludes', true));
     } elseif ('update_files_details' == $state['current_step']) {
     } else {
     }
     echo 'Total time: ' . (microtime(true) - $start_time);
 }
Beispiel #9
0
 public static function send($settings = array(), $files = array(), $send_id = '')
 {
     $limit = $settings['archive_limit'];
     $path = $settings['path'];
     if (!file_exists($settings['path'])) {
         pb_backupbuddy::$filesystem->mkdir($settings['path']);
     }
     $total_transfer_time = 0;
     $total_transfer_size = 0;
     foreach ($files as $file) {
         pb_backupbuddy::status('details', 'Starting send to `' . $path . '`.');
         $filesize = filesize($file);
         $total_transfer_size += $filesize;
         $send_time = -microtime(true);
         if (true !== @copy($file, $path . '/' . basename($file))) {
             pb_backupbuddy::status('error', 'Unable to copy file `' . $file . '` of size `' . pb_backupbuddy::$format->file_size($filesize) . '` to local path `' . $path . '`. Please verify the directory exists and permissions permit writing.');
             backupbuddy_core::mail_error($error_message);
             return false;
         } else {
             pb_backupbuddy::status('details', 'Send success.');
         }
         $send_time += microtime(true);
         $total_transfer_time += $send_time;
         // Start remote backup limit
         if ($limit > 0) {
             pb_backupbuddy::status('details', 'Archive limit of `' . $limit . '` in settings.');
             pb_backupbuddy::status('details', 'path: ' . $path . '*.zip');
             $remote_files = glob($path . '/*.zip');
             if (!is_array($remote_files)) {
                 $remote_files = array();
             }
             usort($remote_files, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
             pb_backupbuddy::status('details', 'Found `' . count($remote_files) . '` backups.');
             // Create array of backups and organize by date
             $bkupprefix = backupbuddy_core::backup_prefix();
             foreach ($remote_files as $file_key => $remote_file) {
                 if (false === stripos($remote_file, 'backup-' . $bkupprefix . '-')) {
                     pb_backupbuddy::status('details', 'backup-' . $bkupprefix . '-' . 'not in file: ' . $remote_file);
                     unset($backups[$file_key]);
                 }
             }
             arsort($remote_files);
             pb_backupbuddy::status('details', 'Found `' . count($remote_files) . '` backups.');
             if (count($remote_files) > $limit) {
                 pb_backupbuddy::status('details', 'More archives (' . count($remote_files) . ') than limit (' . $limit . ') allows. Trimming...');
                 $i = 0;
                 $delete_fail_count = 0;
                 foreach ($remote_files as $remote_file) {
                     $i++;
                     if ($i > $limit) {
                         pb_backupbuddy::status('details', 'Trimming excess file `' . $remote_file . '`...');
                         if (!unlink($remote_file)) {
                             pb_backupbuddy::status('details', 'Unable to delete excess local file `' . $remote_file . '`.');
                             $delete_fail_count++;
                         }
                     }
                 }
                 pb_backupbuddy::status('details', 'Finished trimming excess backups.');
                 if ($delete_fail_count !== 0) {
                     $error_message = 'Local remote limit could not delete ' . $delete_fail_count . ' backups.';
                     pb_backupbuddy::status('error', $error_message);
                     backupbuddy_core::mail_error($error_message);
                 }
             }
         } else {
             pb_backupbuddy::status('details', 'No local destination file limit to enforce.');
         }
         // End remote backup limit
     }
     // end foreach.
     // Load fileoptions to the send.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #11.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.2344848. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     $fileoptions['write_speed'] = $total_transfer_time / $total_transfer_size;
     return true;
 }
backupbuddy_core::verifyAjaxAccess();
// Display backup integrity status.
/* integrity_status()
*
* description
*
*/
$send_id = pb_backupbuddy::_GET('send_id');
$send_di = str_replace('/\\', '', $send_id);
pb_backupbuddy::load();
pb_backupbuddy::$ui->ajax_header();
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
pb_backupbuddy::status('details', 'Fileoptions instance #27.');
$optionsFile = backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt';
$send_options = new pb_backupbuddy_fileoptions($optionsFile, $read_only = true);
if (true !== ($result = $send_options->is_ok())) {
    pb_backupbuddy::alert(__('Unable to access fileoptions data file.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
    die;
}
$start_time = 'Unknown';
$finish_time = 'Unknown';
if (isset($send_options->options['start_time'])) {
    $start_time = pb_backupbuddy::$format->date(pb_backupbuddy::$format->localize_time($send_options->options['start_time'])) . ' <span class="description">(' . pb_backupbuddy::$format->time_ago($send_options->options['start_time']) . ' ago)</span>';
    if ($send_options->options['finish_time'] > 0) {
        $finish_time = pb_backupbuddy::$format->date(pb_backupbuddy::$format->localize_time($send_options->options['finish_time'])) . ' <span class="description">(' . pb_backupbuddy::$format->time_ago($send_options->options['finish_time']) . ' ago)</span>';
    } else {
        // unfinished.
        $finish_time = '<i>Unfinished</i>';
    }
}
Beispiel #11
0
 public static function test($settings)
 {
     $settings = self::_init($settings);
     // Try sending a file.
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id = 'TEST-' . pb_backupbuddy::random_string(12));
     // 3rd param true forces clearing of any current uploads.
     if (false === $send_response) {
         $send_response = 'Error sending test file to S3.';
     } else {
         $send_response = 'Success.';
     }
     // Delete sent file.
     $delete_response = 'Success.';
     try {
         $delete_response = self::$_client->delete_object(array('Bucket' => $settings['bucket'], 'Key' => $settings['directory'] . 'remote-send-test.php'));
         $delete_response = 'Success.';
     } catch (Exception $e) {
         pb_backupbuddy::status('details', 'Unable to delete test S3 file `remote-send-test.php`. Details: `' . $e->getMessage() . '`.');
     }
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #7.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         return self::_error(__('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if ('Success.' != $send_response || 'Success.' != $delete_response) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
Beispiel #12
0
 public static function send($destination_settings, $file, $send_id = '', $delete_after = false)
 {
     if (is_array($file)) {
         // As of v6.1.0.1 no longer accepting multiple files to send.
         $file = $file[0];
     }
     if ('' != $send_id) {
         pb_backupbuddy::add_status_serial('remote_send-' . $send_id);
         pb_backupbuddy::status('details', '----- Initiating master send function for BackupBuddy v' . pb_backupbuddy::settings('version') . '. Post-send deletion: ' . $delete_after);
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         $fileoptions_file = backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt';
         if (!file_exists($fileoptions_file)) {
             //pb_backupbuddy::status( 'details', 'Fileoptions file `' . $fileoptions_file . '` does not exist yet; creating.' );
             //pb_backupbuddy::status( 'details', 'Fileoptions instance #19.' );
             $fileoptions_obj = new pb_backupbuddy_fileoptions($fileoptions_file, $read_only = false, $ignore_lock = true, $create_file = true);
         } else {
             //pb_backupbuddy::status( 'details', 'Fileoptions file exists; loading.' );
             //pb_backupbuddy::status( 'details', 'Fileoptions instance #18.' );
             $fileoptions_obj = new pb_backupbuddy_fileoptions($fileoptions_file, $read_only = false, $ignore_lock = false, $create_file = false);
         }
         if (true !== ($result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Fatal Error #9034.2344848. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
             return false;
         }
         //pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' );
         $fileoptions =& $fileoptions_obj->options;
         if ('' == $fileoptions) {
             // Set defaults.
             $fileoptions = backupbuddy_core::get_remote_send_defaults();
             $fileoptions['type'] = $destination_settings['type'];
             $fileoptions['file'] = $file;
             $fileoptions['retries'] = 0;
         }
         $fileoptions['sendID'] = $send_id;
         $fileoptions['destinationSettings'] = $destination_settings;
         // always store the LATEST settings for resume info and retry function.
         $fileoptions['update_time'] = time();
         $fileoptions['deleteAfter'] = $delete_after;
         $fileoptions_obj->save();
         if (isset($fileoptions['status']) && 'aborted' == $fileoptions['status']) {
             pb_backupbuddy::status('warning', 'Destination send triggered on an ABORTED transfer. Ending send function.');
             return false;
         }
         unset($fileoptions_obj);
     }
     if (false === ($destination = self::_init_destination($destination_settings))) {
         echo '{Error #546893498a. Destination configuration file missing.}';
         if ('' != $send_id) {
             pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
         }
         return false;
     }
     $destination_settings = $destination['settings'];
     // Settings with defaults applied, normalized, etc.
     if (!file_exists($file)) {
         pb_backupbuddy::status('error', 'Error #58459458743. The file that was attempted to be sent to a remote destination, `' . $file . '`, was not found. It either does not exist or permissions prevent accessing it. Check that local backup limits are not causing it to be deleted.');
         if ('' != $send_id) {
             pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
         }
         return false;
     }
     if (!method_exists($destination['class'], 'send')) {
         pb_backupbuddy::status('error', 'Destination class `' . $destination['class'] . '` does not support send operation -- missing function.');
         if ('' != $send_id) {
             pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
         }
         return false;
     }
     global $pb_backupbuddy_destination_errors;
     $pb_backupbuddy_destination_errors = array();
     $result = call_user_func_array("{$destination['class']}::send", array($destination_settings, $file, $send_id, $delete_after));
     /* $result values:
      *		false		Transfer FAILED.
      *		true		Non-chunked transfer succeeded.
      *		array()		array(
      *						multipart_id,				// Unique string ID for multipart send. Empty string if last chunk finished sending successfully.
      *						multipart_status_message
      *					)
      */
     if ($result === false) {
         $error_details = implode('; ', $pb_backupbuddy_destination_errors);
         if ('' != $error_details) {
             $error_details = ' Details: ' . $error_details;
         }
         $log_directory = backupbuddy_core::getLogDirectory();
         $preError = 'There was an error sending to the remote destination titled `' . $destination_settings['title'] . '` of type `' . backupbuddy_core::pretty_destination_type($destination_settings['type']) . '`. One or more files may have not been fully transferred. Please see error details for additional information. If the error persists, enable full error logging and try again for full details and troubleshooting. Details: ' . "\n\n";
         $logFile = $log_directory . 'status-remote_send-' . $send_id . '_' . pb_backupbuddy::$options['log_serial'] . '.txt';
         pb_backupbuddy::status('details', 'Looking for remote send log file to send in error email: `' . $logFile . '`.');
         if (!file_exists($logFile)) {
             pb_backupbuddy::status('details', 'Remote send log file not found.');
             backupbuddy_core::mail_error($preError . $error_details);
         } else {
             // Log exists. Attach.
             pb_backupbuddy::status('details', 'Remote send log file found. Attaching to error email.');
             backupbuddy_core::mail_error($preError . $error_details . "\n\nSee the attached log for details.", '', array($logFile));
         }
         // Save error details into fileoptions for this send.
         //pb_backupbuddy::status( 'details', 'About to load fileoptions data.' );
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         pb_backupbuddy::status('details', 'Fileoptions instance #45.');
         $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
         if (true !== ($fileoptions_result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Error #9034.32731. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $fileoptions_result);
         }
         //pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' );
         $fileoptions =& $fileoptions_obj->options;
         $fileoptions['status'] = 'failed';
         $fileoptions['error'] = 'Error sending.' . $error_details;
         $fileoptions['updated_time'] = time();
         $fileoptions_obj->save();
         unset($fileoptions_obj);
     }
     if (is_array($result)) {
         // Send is multipart.
         pb_backupbuddy::status('details', 'Multipart chunk mode completed a pass of the send function. Resuming will be needed. Result: `' . print_r($result, true) . '`.');
         if ('' != $send_id) {
             //pb_backupbuddy::status( 'details', 'About to load fileoptions data.' );
             require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
             //pb_backupbuddy::status( 'details', 'Fileoptions instance #17.' );
             $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
             if (true !== ($fileoptions_result = $fileoptions_obj->is_ok())) {
                 pb_backupbuddy::status('error', __('Fatal Error #9034.387462. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $fileoptions_result);
                 return false;
             }
             //pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' );
             $fileoptions =& $fileoptions_obj->options;
             $fileoptions['_multipart_status'] = $result[1];
             $fileoptions['updated_time'] = time();
             pb_backupbuddy::status('details', 'Destination debugging details: `' . print_r($fileoptions, true) . '`.');
             $fileoptions_obj->save();
             unset($fileoptions_obj);
             pb_backupbuddy::status('details', 'Next multipart chunk will be processed shortly. Now waiting on its cron...');
         }
     } else {
         // Single all-at-once send.
         if (false === $result) {
             pb_backupbuddy::status('details', 'Completed send function. Failure. Post-send deletion will be skipped if enabled.');
         } elseif (true === $result) {
             pb_backupbuddy::status('details', 'Completed send function. Success.');
         } else {
             pb_backupbuddy::status('warning', 'Completed send function. Unknown result: `' . $result . '`.');
         }
         pb_backupbuddy::status('details', 'About to load fileoptions data.');
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         pb_backupbuddy::status('details', 'Fileoptions instance #16.');
         $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
         if (true !== ($fileoptions_result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Error #9034.387462. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $fileoptions_result);
         }
         pb_backupbuddy::status('details', 'Fileoptions data loaded.');
         $fileoptions =& $fileoptions_obj->options;
         $fileoptions['updated_time'] = time();
         unset($fileoptions_obj);
     }
     // File transfer completely finished successfully.
     if (true === $result) {
         $fileSize = filesize($file);
         $serial = backupbuddy_core::get_serial_from_file($file);
         // Handle deletion of send file if enabled.
         if (true === $delete_after && false !== $result) {
             pb_backupbuddy::status('details', __('Post-send deletion enabled.', 'it-l10n-backupbuddy'));
             if (false === $result) {
                 pb_backupbuddy::status('details', 'Skipping post-send deletion since transfer failed.');
             } else {
                 pb_backupbuddy::status('details', 'Performing post-send deletion since transfer succeeded.');
                 pb_backupbuddy::status('details', 'Deleting local file `' . $file . '`.');
                 // Handle post-send deletion on success.
                 if (file_exists($file)) {
                     $unlink_result = @unlink($file);
                     if (true !== $unlink_result) {
                         pb_backupbuddy::status('error', 'Unable to unlink local file `' . $file . '`.');
                     }
                 }
                 if (file_exists($file)) {
                     // File still exists.
                     pb_backupbuddy::status('details', __('Error. Unable to delete local file `' . $file . '` after send as set in settings.', 'it-l10n-backupbuddy'));
                     backupbuddy_core::mail_error('BackupBuddy was unable to delete local file `' . $file . '` after successful remove transfer though post-remote send deletion is enabled. You may want to delete it manually. This can be caused by permission problems or improper server configuration.');
                 } else {
                     // Deleted.
                     pb_backupbuddy::status('details', __('Deleted local archive after successful remote destination send based on settings.', 'it-l10n-backupbuddy'));
                     pb_backupbuddy::status('archiveDeleted', '');
                 }
             }
         } else {
             pb_backupbuddy::status('details', 'Post-send deletion not enabled.');
         }
         // Send email notification if enabled.
         if ('' != pb_backupbuddy::$options['email_notify_send_finish']) {
             pb_backupbuddy::status('details', __('Sending finished destination send email notification.', 'it-l10n-backupbuddy'));
             $extraReplacements = array();
             $extraReplacements = array('{backup_file}' => $file, '{backup_size}' => $fileSize, '{backup_serial}' => $serial);
             backupbuddy_core::mail_notify_scheduled($serial, 'destinationComplete', __('Destination send complete to', 'it-l10n-backupbuddy') . ' ' . backupbuddy_core::pretty_destination_type($destination_settings['type']), $extraReplacements);
         } else {
             pb_backupbuddy::status('details', __('Finished sending email NOT enabled. Skipping.', 'it-l10n-backupbuddy'));
         }
         // Save notification of final results.
         $data = array();
         $data['serial'] = $serial;
         $data['file'] = $file;
         $data['size'] = $fileSize;
         $data['pretty_size'] = pb_backupbuddy::$format->file_size($fileSize);
         backupbuddy_core::addNotification('remote_send_success', 'Remote file transfer completed', 'A file has successfully completed sending to a remote location.', $data);
     }
     // NOTE: Call this before removing status serial so it shows in log.
     pb_backupbuddy::status('details', 'Ending send() function pass.');
     // Return logging to normal file.
     if ('' != $send_id) {
         pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
     }
     return $result;
 }
Beispiel #13
0
 private static function _processSignatures($type, $newFileSignatures)
 {
     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 #88.');
     $existingSignaturesObj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'live/' . $type . '-' . pb_backupbuddy::$options['log_serial'] . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
     if (true !== ($result = $existingSignaturesObj->is_ok())) {
         pb_backupbuddy::status('error', 'Error #382983. Unable to create or access fileoptions file for media. Details: `' . $result . '`.');
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     if (!isset($existingSignaturesObj->options['signatures'])) {
         $existingSignaturesObj->options = array('signatures' => array(), 'stats' => array('totalFiles' => 0, 'needsSent' => 0, 'needsDelete' => 0));
     }
     $existingSignatures =& $existingSignaturesObj->options['signatures'];
     // Loop through local files to see if they differ from previous scan.
     pb_backupbuddy::status('details', 'Comparing new signatures with existing ones.');
     $addOrUpdateCount = 0;
     foreach ($newFileSignatures as $file => $signature) {
         $addOrUpdateFile = false;
         if (!isset($existingSignatures[$file])) {
             // This is a new file. Append to list.
             $addOrUpdateFile = true;
             $existingSignaturesObj->options['stats']['totalFiles']++;
         } else {
             // File exists on remote. See if content is the same.
             if (isset($signature['sha1']) && $signature['sha1'] != $existingSignatures[$file]['sha1']) {
                 // Hash mismatch. Needs updating.
                 $addOrUpdateFile = true;
             } elseif (!isset($signature['sha1']) || '' == $signature['sha1']) {
                 // sha1 not calculated. size may be too large. compare size to see if changed.
                 if ($signature['size'] != $existingSignatures[$file]['size']) {
                     // size mismatch
                     $addOrUpdateFile = true;
                 }
             }
         }
         // File is new and needs added to list to be sent to remote.
         if (true === $addOrUpdateFile) {
             $existingSignatures[$file] = $signature;
             $signature['added'] = time();
             // When did we first notice file?
             $signature['sent'] = false;
             // Has file been sent to Stash?
             $existingSignaturesObj->options['stats']['needsSent']++;
             pb_backupbuddy::status('details', 'New or modified file found `' . $file . '`.');
             $addOrUpdateCount++;
         }
     }
     // Loop through remote files to see if any no longer exist locally and therefore need deleted.
     $deleteCount = 0;
     foreach ($existingSignatures as $file => $signature) {
         if (!isset($newFileSignatures[$file])) {
             $existingSignatures[$file]['delete'] = true;
             $existingSignaturesObj->options['stats']['needsDelete']++;
             $existingSignaturesObj->options['stats']['totalFiles']--;
             pb_backupbuddy::status('details', 'Remote file that no longer exists locally found. Flagging `' . $file . '` for deletion.');
         }
     }
     // Save.
     pb_backupbuddy::status('details', 'Saving updated `' . $type . '` signatures... Added `' . $addOrUpdateCount . '`. Deleted `' . $deleteCount . '`. Total files: `' . $existingSignaturesObj->options['stats']['totalFiles'] . '`. Needs sent: `' . $existingSignaturesObj->options['stats']['needsSent'] . '`. Needs delete: `' . $existingSignaturesObj->options['stats']['needsDelete'] . '`.');
     $existingSignaturesObj->save();
     pb_backupbuddy::status('details', 'Signatures saved.');
     return true;
 }
Beispiel #14
0
 public static function process_timed_out_sends()
 {
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     // Mark any timed out remote sends as timed out. Attempt resend once.
     $remote_sends = array();
     $send_fileoptions = pb_backupbuddy::$filesystem->glob_by_date(backupbuddy_core::getLogDirectory() . 'fileoptions/send-*.txt');
     if (!is_array($send_fileoptions)) {
         $send_fileoptions = array();
     }
     foreach ($send_fileoptions as $send_fileoption) {
         $send_id = str_replace('.txt', '', str_replace('send-', '', basename($send_fileoption)));
         pb_backupbuddy::status('details', 'About to load fileoptions data.');
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         pb_backupbuddy::status('details', 'Fileoptions instance #23.');
         $fileoptions_file = backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt';
         $fileoptions_obj = new pb_backupbuddy_fileoptions($fileoptions_file, $read_only = false, $ignore_lock = false, $create_file = false);
         if (true !== ($result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Fatal Error #9034.3224442393. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
             return false;
         }
         // Corrupt fileoptions file. Remove.
         if (!isset($fileoptions_obj->options['start_time'])) {
             unset($fileoptions_obj);
             @unlink($fileoptions_file);
             continue;
         }
         // Finish time not set. Shouldn't happen buuuuut.... skip.
         if (!isset($fileoptions_obj->options['finish_time'])) {
             continue;
         }
         // Don't do anything for success, failure, or already-marked as -1 finish time.
         if ('success' == $fileoptions_obj->options['status'] || 'failure' == $fileoptions_obj->options['status'] || -1 == $fileoptions_obj->options['finish_time']) {
             continue;
         }
         // Older format did not include updated_time.
         if (!isset($fileoptions_obj->options['update_time'])) {
             continue;
         }
         $secondsAgo = time() - $fileoptions_obj->options['update_time'];
         if ($secondsAgo > backupbuddy_constants::TIME_BEFORE_CONSIDERED_TIMEOUT) {
             // If 24hrs passed since last update to backup then mark this timeout as failed.
             // Potentially try to resend if not a live_periodic transfer.
             if ('live_periodic' != $fileoptions_obj->options['trigger']) {
                 $isResending = backupbuddy_core::remoteSendRetry($fileoptions_obj, $send_id, pb_backupbuddy::$options['remote_send_timeout_retries']);
                 if (true === $isResending) {
                     // If resending then skip sending any error email just yet...
                     continue;
                 }
                 if ('timeout' != $fileoptions_obj->options['status']) {
                     // Do not send email if status is 'timeout' since either already sent or old-style status marking (pre-v6.0).
                     // Calculate destination title and type for error email.
                     $destination_title = '';
                     $destination_type = '';
                     if (isset(pb_backupbuddy::$options['remote_destinations'][$fileoptions_obj->options['destination']])) {
                         $destination_title = pb_backupbuddy::$options['remote_destinations'][$fileoptions_obj->options['destination']]['title'];
                         $destination_type = backupbuddy_core::pretty_destination_type(pb_backupbuddy::$options['remote_destinations'][$fileoptions_obj->options['destination']]['type']);
                     }
                     $error_message = 'A remote destination send of file `' . basename($fileoptions_obj->options['file']) . '` started `' . pb_backupbuddy::$format->time_ago($fileoptions_obj->options['start_time']) . '` ago sending to the destination titled `' . $destination_title . '` of type `' . $destination_type . '` likely timed out. BackupBuddy will attempt to retry this failed transfer ONCE. If the second atempt succeeds the failed attempt will be replaced in the recent sends list. Check the error log for further details and/or manually send a backup to test for problems.';
                     pb_backupbuddy::status('error', $error_message);
                     if ($secondsAgo < backupbuddy_constants::CLEANUP_MAX_AGE_TO_NOTIFY_TIMEOUT) {
                         // Prevents very old timed out backups from triggering email send.
                         backupbuddy_core::mail_error($error_message);
                     }
                 }
             }
             // Save as timed out.
             $fileoptions_obj->options['status'] = 'timeout';
             $fileoptions_obj->options['finish_time'] = -1;
             $fileoptions_obj->save();
             // If live_periofic then just try to delete the file at this point.
             if ('live_periodic' == $fileoptions_obj->options['trigger']) {
                 unset($fileoptions_obj);
                 @unlink($fileoptions_file);
                 continue;
             }
         }
         unset($fileoptions_obj);
     }
 }
Beispiel #15
0
if (!is_array($recentBackups_list)) {
    $recentBackups_list = array();
}
if (count($recentBackups_list) == 0) {
    _e('No backups have been created recently.', 'it-l10n-backupbuddy');
} else {
    // Backup type.
    $pretty_type = array('full' => 'Full', 'db' => 'Database', 'files' => 'Files');
    // Read in list of backups.
    $recent_backup_count_cap = 5;
    // Max number of recent backups to list.
    $recentBackups = array();
    foreach ($recentBackups_list as $backup_fileoptions) {
        require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
        pb_backupbuddy::status('details', 'Fileoptions instance #1.');
        $backup = new pb_backupbuddy_fileoptions($backup_fileoptions, $read_only = true);
        if (true !== ($result = $backup->is_ok())) {
            pb_backupbuddy::status('error', __('Unable to access fileoptions data file.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
            continue;
        }
        $backup =& $backup->options;
        if (!isset($backup['serial']) || $backup['serial'] == '') {
            continue;
        }
        if ($backup['finish_time'] >= $backup['start_time'] && 0 != $backup['start_time']) {
            $status = '<span class="pb_label pb_label-success">Completed</span>';
        } elseif ($backup['finish_time'] == -1) {
            $status = '<span class="pb_label pb_label-warning">Cancelled</span>';
        } elseif (FALSE === $backup['finish_time']) {
            $status = '<span class="pb_label pb_label-error">Failed (timeout?)</span>';
        } elseif (time() - $backup['updated_time'] > backupbuddy_constants::TIME_BEFORE_CONSIDERED_TIMEOUT) {
Beispiel #16
0
 public function integrity_status()
 {
     $serial = pb_backupbuddy::_GET('serial');
     $serial = str_replace('/\\', '', $serial);
     pb_backupbuddy::load();
     pb_backupbuddy::$ui->ajax_header();
     // Backup overall status.
     /*
     echo 'Backup status: ';
     if ( $integrity['status'] == 'pass' ) { // Pass.
     	echo '<span class="pb_label pb_label-success">Good</span>';
     } else { // Fail.
     	echo '<span class="pb_label pb_label-important">Bad</span>';
     }
     echo '<br>';
     */
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $backup_options = new pb_backupbuddy_fileoptions(pb_backupbuddy::$options['log_directory'] . 'fileoptions/' . $serial . '.txt', $read_only = true);
     if (true !== ($result = $backup_options->is_ok())) {
         pb_backupbuddy::alert(__('Unable to access fileoptions data file.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         die;
     }
     $integrity = $backup_options->options['integrity'];
     //***** BEGIN TESTS AND RESULTS.
     if (isset($integrity['status_details'])) {
         // $integrity['status_details'] is NOT array (old, pre-3.1.9).
         echo '<h3>Integrity Technical Details</h3>';
         echo '<textarea style="width: 100%; height: 175px;" wrap="off">';
         foreach ($integrity as $item_name => $item_value) {
             $item_value = str_replace('<br />', '<br>', $item_value);
             $item_value = str_replace('<br><br>', '<br>', $item_value);
             $item_value = str_replace('<br>', "\n     ", $item_value);
             echo $item_name . ' => ' . $item_value . "\n";
         }
         echo '</textarea><br><br><b>Note:</b> It is normal to see several "file not found" entries as BackupBuddy checks for expected files in multiple locations, expecting to only find each file once in one of those locations.';
     } else {
         // $integrity['status_details'] is array.
         echo '<br>';
         if (isset($integrity['status_details'])) {
             // PRE-v4.0 Tests.
             function pb_pretty_results($value)
             {
                 if ($value === true) {
                     return '<span class="pb_label pb_label-success">Pass</span>';
                 } else {
                     return '<span class="pb_label pb_label-important">Fail</span>';
                 }
             }
             // The tests & their status..
             $tests = array();
             $tests[] = array('BackupBackup data file exists', pb_pretty_results($integrity['status_details']['found_dat']));
             $tests[] = array('Database SQL file exists', pb_pretty_results($integrity['status_details']['found_sql']));
             if ($integrity['detected_type'] == 'full') {
                 // Full backup.
                 $tests[] = array('WordPress wp-config.php exists (full backups only)', pb_pretty_results($integrity['status_details']['found_wpconfig']));
             } else {
                 // DB only.
                 $tests[] = array('WordPress wp-config.php exists (full backups only)', '<span class="pb_label pb_label-success">N/A</span>');
             }
         } else {
             // 4.0+ Tests.
             $tests = array();
             foreach ($integrity['tests'] as $test) {
                 if (true === $test['pass']) {
                     $status_text = '<span class="pb_label pb_label-success">Pass</span>';
                 } 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.
     //***** END TESTS AND RESULTS.
     echo '<br><br>';
     //***** BEGIN STEPS.
     $steps = array();
     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) {
                         $step_name = 'Database dump (breakout: ' . $step['args'][0][0] . ')';
                     } else {
                         $step_name = 'Database dump';
                     }
                 } elseif ($step['function'] == 'backup_zip_files') {
                     if (isset($backup_options->options['steps']['backup_zip_files'])) {
                         $zip_time = $backup_options->options['steps']['backup_zip_files'];
                     } else {
                         $zip_time = 0;
                     }
                     // Calculate write speed in MB/sec for this backup.
                     if ($zip_time == '0') {
                         // Took approx 0 seconds to backup so report this speed.
                         $write_speed = '> ' . pb_backupbuddy::$format->file_size($backup_options->options['integrity']['size']);
                     } else {
                         if ($zip_time == 0) {
                             $write_speed = '';
                         } else {
                             $write_speed = pb_backupbuddy::$format->file_size($backup_options->options['integrity']['size'] / $zip_time) . '/sec';
                         }
                     }
                     $step_name = 'Zip archive creation (Write speed: ' . $write_speed . ')';
                 } elseif ($step['function'] == 'post_backup') {
                     $step_name = 'Post-backup cleanup';
                 } elseif ($step['function'] == 'integrity_check') {
                     $step_name = 'Integrity Check';
                 } else {
                     $step_name = $step['function'];
                 }
                 // Step time taken.
                 $step_time = (string) ($step['finish_time'] - $step['start_time']) . ' seconds';
                 // Compile details for this step into array.
                 $steps[] = array($step_name, $step_time, $step['attempts']);
             }
         }
         // End foreach.
     } else {
         // End if serial in array is set.
         $step_times[] = 'unknown';
     }
     // End if serial in array is NOT set.
     // Total overall time from initiation to end.
     if (isset($backup_options->options['finish_time']) && isset($backup_options->options['start_time']) && $backup_options->options['finish_time'] != 0 && $backup_options->options['start_time'] != 0) {
         $total_time = $backup_options->options['finish_time'] - $backup_options->options['start_time'] . ' seconds';
     } else {
         $total_time = '<i>Unknown</i>';
     }
     $steps[] = array('<b>Total Overall Time</b>', $total_time, 'N/A');
     $columns = array(__('Backup Step', 'it-l10n-backupbuddy'), __('Time Taken', 'it-l10n-backupbuddy'), __('Attempts', 'it-l10n-backupbuddy'));
     if (count($steps) == 0) {
         _e('No step statistics were found for this backup.', 'it-l10n-backupbuddy');
     } else {
         pb_backupbuddy::$ui->list_table($steps, array('columns' => $columns, 'css' => 'width: 100%; min-width: 200px;'));
     }
     echo '<br><br>';
     //***** END STEPS.
     //***** BEGIN COMMENT META.
     if (!isset(pb_backupbuddy::$classes['zipbuddy'])) {
         require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
         pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy(pb_backupbuddy::$options['backup_directory']);
     }
     $comment_meta = array();
     if (isset($backup_options->options['archive_file'])) {
         $comment = pb_backupbuddy::$classes['zipbuddy']->get_comment($backup_options->options['archive_file']);
         $comment = pb_backupbuddy::$classes['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 = pb_backupbuddy::$classes['core']->pretty_meta_info($comment_line_name, $comment_line_value))) {
                 $comment_meta[] = $response;
             }
         }
     }
     if (count($comment_meta) > 0) {
         pb_backupbuddy::$ui->list_table($comment_meta, array('columns' => array('Meta Information', 'Value'), 'css' => 'width: 100%; min-width: 200px;'));
     } else {
         echo '<i>No meta data found in zip comment. Skipping meta information display.</i>';
     }
     //***** END COMMENT META.
     if (isset($backup_options->options['trigger'])) {
         $trigger = $backup_options->options['trigger'];
     } else {
         $trigger = 'Unknown trigger';
     }
     $scanned = pb_backupbuddy::$format->date($integrity['scan_time']);
     echo '<br><br>';
     echo ucfirst($trigger) . " backup {$integrity['file']} last scanned {$scanned}.";
     echo '<br><br><br>';
     echo '<a class="button secondary-button" onclick="jQuery(\'#pb_backupbuddy_advanced_debug\').slideToggle();">Display Advanced Debugging</a>';
     echo '<div id="pb_backupbuddy_advanced_debug" style="display: none;">';
     echo '<textarea style="width: 100%; height: 400px;" wrap="on">';
     echo print_r($backup_options->options, true);
     echo '</textarea><br><br>';
     echo '</div><br><br>';
     pb_backupbuddy::$ui->ajax_footer();
     die;
 }
Beispiel #17
0
 public function final_cleanup($serial)
 {
     if (!isset(pb_backupbuddy::$options)) {
         pb_backupbuddy::load();
     }
     pb_backupbuddy::status('details', 'cron_final_cleanup started');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $backup_options = new pb_backupbuddy_fileoptions(pb_backupbuddy::$options['log_directory'] . 'fileoptions/' . $serial . '.txt', $read_only = true);
     if (true !== ($result = $backup_options->is_ok())) {
         pb_backupbuddy::status('error', 'Unable to open fileoptions file.');
     }
     // Delete temporary data directory.
     if (isset($backup_options->options['temp_directory']) && file_exists($backup_options->options['temp_directory'])) {
         pb_backupbuddy::$filesystem->unlink_recursive($backup_options->options['temp_directory']);
     }
     // Delete temporary zip directory.
     if (isset($backup_options->options['temporary_zip_directory']) && file_exists($backup_options->options['temporary_zip_directory'])) {
         pb_backupbuddy::$filesystem->unlink_recursive($backup_options->options['temporary_zip_directory']);
     }
     // Delete status log text file.
     if (file_exists(pb_backupbuddy::$options['backup_directory'] . 'temp_status_' . $serial . '.txt')) {
         unlink(pb_backupbuddy::$options['backup_directory'] . 'temp_status_' . $serial . '.txt');
     }
 }
<?php

backupbuddy_core::verifyAjaxAccess();
pb_backupbuddy::$ui->ajax_header();
$send_id = pb_backupbuddy::_GET('send_id');
$send_id = str_replace('/\\', '', $send_id);
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
$fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = true, $ignore_lock = false, $create_file = false);
if (true !== ($result = $fileoptions_obj->is_ok())) {
    pb_backupbuddy::status('error', __('Fatal Error #9034.23443. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
    return false;
}
// Don't do anything for success, failure, or already-marked as -1 finish time.
$whyNoSend = '';
if ('success' == $fileoptions_obj->options['status']) {
    $whyNoSend = 'This transfer is already marked as sucessfully completing.';
}
/* elseif ( 'failure' == $fileoptions_obj->options['status'] ) {
	$whyNoSend = 'This transfer is marked as officially failed.';
} elseif ( -1 == $fileoptions_obj->options['finish_time'] ) {
	$whyNoSend = 'This transfer is marked as cancelled.';
} */
if ('' != $whyNoSend) {
    die('Error #8438483:<br><br>This send is not eligable to be resent. ' . $whyNoSend . ' Please re-initiate a send for this file manually with a fresh send.');
}
echo '<center>';
echo '<img src="' . pb_backupbuddy::plugin_url() . '/destinations/' . $fileoptions_obj->options['destinationSettings']['type'] . '/icon50.png">';
echo '<br>';
echo '<h3>Resending to "' . $fileoptions_obj->options['destinationSettings']['title'] . '"</h3>';
echo '<br>';
if (!isset($fileoptions_obj->options['destinationSettings']) || count($fileoptions_obj->options['destinationSettings']) == 0) {
Beispiel #19
0
 public static function send($settings = array(), $files = array(), $send_id = '', $delete_after = false)
 {
     if (!is_array($files)) {
         $files = array($files);
     }
     pb_backupbuddy::status('details', 'Dropbox2 send function started. Remote send id: `' . $send_id . '`.');
     // Normalize settings, apply defaults, etc.
     $settings = self::_normalizeSettings($settings);
     // Connect to Dropbox.
     if (false === self::_connect($settings['access_token'])) {
         // Try to connect. Return false if fail.
         return false;
     }
     $max_chunk_size_bytes = $settings['max_chunk_size'] * 1024 * 1024;
     /***** BEGIN MULTIPART CHUNKED CONTINUE *****/
     // Continue Multipart Chunked Upload
     if ($settings['_chunk_upload_id'] != '') {
         $file = $settings['_chunk_file'];
         pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) preparing to send chunked multipart upload part ' . ($settings['_chunk_sent_count'] + 1) . ' of ' . $settings['_chunk_total_count'] . ' with set chunk size of `' . $settings['max_chunk_size'] . '` MB. Dropbox Upload ID: `' . $settings['_chunk_upload_id'] . '`.');
         pb_backupbuddy::status('details', 'Opening file `' . basename($file) . '` to send.');
         $f = @fopen($file, 'rb');
         if (false === $f) {
             pb_backupbuddy::status('error', 'Error #87954435. Unable to open file `' . $file . '` to send to Dropbox.');
             return false;
         }
         // Seek to next chunk location.
         pb_backupbuddy::status('details', 'Seeking file to byte `' . $settings['_chunk_next_offset'] . '`.');
         if (0 != fseek($f, $settings['_chunk_next_offset'])) {
             // return of 0 is success.
             pb_backupbuddy::status('error', 'Unable to seek file to proper location offset `' . $settings['_chunk_next_offset'] . '`.');
         } else {
             pb_backupbuddy::status('details', 'Seek success.');
         }
         // Read this file chunk into memory.
         pb_backupbuddy::status('details', 'Reading chunk into memory.');
         try {
             $data = self::readFully($f, $settings['_chunk_maxsize']);
         } catch (\Exception $e) {
             pb_backupbuddy::status('error', 'Dropbox Error #484938376: ' . $e->getMessage());
             return false;
         }
         pb_backupbuddy::status('details', 'About to put chunk to Dropbox for continuation.');
         $send_time = -microtime(true);
         try {
             $result = self::$_dbxClient->chunkedUploadContinue($settings['_chunk_upload_id'], $settings['_chunk_next_offset'], $data);
         } catch (\Exception $e) {
             pb_backupbuddy::status('error', 'Dropbox Error #8754646: ' . $e->getMessage());
             return false;
         }
         // Examine response from Dropbox.
         if (true === $result) {
             // Upload success.
             pb_backupbuddy::status('details', 'Chunk upload continuation success with valid offset.');
         } elseif (false === $result) {
             // Failed.
             pb_backupbuddy::status('error', 'Chunk upload continuation failed at offset `' . $settings['_chunk_next_offset'] . '`.');
             return false;
         } elseif (is_numeric($result)) {
             // offset wrong. Update to use this.
             pb_backupbuddy::status('details', 'Chunk upload continuation received an updated offset response of `' . $result . '` when we tried `' . $settings['_chunk_next_offset'] . '`.');
             $settings['_chunk_next_offset'] = $result;
             // Try resending with corrected offset.
             try {
                 $result = self::$_dbxClient->chunkedUploadContinue($settings['_chunk_upload_id'], $settings['_chunk_next_offset'], $data);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error #8263836: ' . $e->getMessage());
                 return false;
             }
         }
         $send_time += microtime(true);
         $data_length = strlen($data);
         unset($data);
         // Calculate some stats to log.
         $chunk_transfer_speed = $data_length / $send_time;
         pb_backupbuddy::status('details', 'Dropbox chunk transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($chunk_transfer_speed) . '`.');
         // Set options for subsequent step chunks.
         $chunked_destination_settings = $settings;
         $chunked_destination_settings['_chunk_offset'] = $data_length;
         $chunked_destination_settings['_chunk_sent_count']++;
         $chunked_destination_settings['_chunk_next_offset'] = $data_length * $chunked_destination_settings['_chunk_sent_count'];
         // First chunk was sent initiationg multipart send.
         $chunked_destination_settings['_chunk_transfer_speeds'][] = $chunk_transfer_speed;
         // Load destination fileoptions.
         pb_backupbuddy::status('details', 'About to load fileoptions data.');
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         pb_backupbuddy::status('details', 'Fileoptions instance #15.');
         $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
         if (true !== ($result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
             return false;
         }
         pb_backupbuddy::status('details', 'Fileoptions data loaded.');
         $fileoptions =& $fileoptions_obj->options;
         // Multipart send completed. Send finished signal to Dropbox to seal the deal.
         if (true === feof($f)) {
             pb_backupbuddy::status('details', 'At end of file. Finishing transfer and notifying Dropbox of file transfer completion.');
             $chunked_destination_settings['_chunk_upload_id'] = '';
             // Unset since chunking finished.
             try {
                 $result = self::$_dbxClient->chunkedUploadFinish($settings['_chunk_upload_id'], $settings['directory'] . '/' . basename($file), dbx\WriteMode::add());
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error #549838979: ' . $e->getMessage());
                 return false;
             }
             pb_backupbuddy::status('details', 'Chunked upload finish results: `' . print_r($result, true) . '`.');
             if (filesize($settings['_chunk_file']) != $result['bytes']) {
                 pb_backupbuddy::status('error', 'Error #8958944. Dropbox reported file size differs from local size. The file upload may have been corrupted.');
                 return false;
             }
             $fileoptions['write_speed'] = array_sum($chunked_destination_settings['_chunk_transfer_speeds']) / $chunked_destination_settings['_chunk_sent_count'];
             $fileoptions['_multipart_status'] = 'Sent part ' . $chunked_destination_settings['_chunk_sent_count'] . ' of ' . $chunked_destination_settings['_chunk_total_count'] . '.';
             $fileoptions['finish_time'] = time();
             $fileoptions['status'] = 'success';
             $fileoptions_obj->save();
             unset($fileoptions_obj);
         }
         fclose($f);
         pb_backupbuddy::status('details', 'Sent chunk number `' . $chunked_destination_settings['_chunk_sent_count'] . '` to Dropbox with upload ID: `' . $chunked_destination_settings['_chunk_upload_id'] . '`. Next offset: `' . $chunked_destination_settings['_chunk_next_offset'] . '`.');
         // Schedule to continue if anything is left to upload for this multipart of any individual files.
         if ($chunked_destination_settings['_chunk_upload_id'] != '' || count($files) > 0) {
             pb_backupbuddy::status('details', 'Dropbox multipart upload has more parts left. Scheduling next part send.');
             $cronTime = time();
             $cronArgs = array($chunked_destination_settings, $files, $send_id, $delete_after);
             $cronHashID = md5($cronTime . serialize($cronArgs));
             $cronArgs[] = $cronHashID;
             $schedule_result = backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs);
             if (true === $schedule_result) {
                 pb_backupbuddy::status('details', 'Next Dropbox chunk step cron event scheduled.');
             } else {
                 pb_backupbuddy::status('error', 'Next Dropbox chunk step cron even FAILED to be scheduled.');
             }
             spawn_cron(time() + 150);
             // Adds > 60 seconds to get around once per minute cron running limit.
             update_option('_transient_doing_cron', 0);
             // Prevent cron-blocking for next item.
             return array($chunked_destination_settings['_chunk_upload_id'], 'Sent ' . $chunked_destination_settings['_chunk_sent_count'] . ' of ' . $chunked_destination_settings['_chunk_total_count'] . ' parts.');
         }
     }
     // end continue multipart chunked upload.
     /***** END MULTIPART CHUNKED CONTINUE *****/
     pb_backupbuddy::status('details', 'Looping through files to send to Dropbox.');
     foreach ($files as $file_id => $file) {
         $file_size = filesize($file);
         pb_backupbuddy::status('details', 'Opening file `' . basename($file) . '` to send.');
         $f = @fopen($file, 'rb');
         if (false === $f) {
             pb_backupbuddy::status('error', 'Error #8457573. Unable to open file `' . $file . '` to send to Dropbox.');
             return false;
         }
         if ($settings['max_chunk_size'] >= 5 && $file_size / 1024 / 1024 > $settings['max_chunk_size']) {
             // chunked send.
             pb_backupbuddy::status('details', 'File exceeds chunking limit of `' . $settings['max_chunk_size'] . '` MB. Using chunked upload for this file transfer.');
             // Read first file chunk into memory.
             pb_backupbuddy::status('details', 'Reading first chunk into memory.');
             try {
                 $data = self::readFully($f, $max_chunk_size_bytes);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error #5684574373: ' . $e->getMessage());
                 return false;
             }
             // Start chunk upload to get upload ID. Sends first chunk piece.
             $send_time = -microtime(true);
             pb_backupbuddy::status('details', 'About to start chunked upload & put first chunk of file `' . basename($file) . '` to Dropbox (PHP 5.3+).');
             try {
                 $result = self::$_dbxClient->chunkedUploadStart($data);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error: ' . $e->getMessage());
                 return false;
             }
             $send_time += microtime(true);
             @fclose($f);
             $data_length = strlen($data);
             unset($data);
             // Calculate some stats to log.
             $chunk_transfer_speed = $data_length / $send_time;
             pb_backupbuddy::status('details', 'Dropbox chunk transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($chunk_transfer_speed) . '`.');
             // Set options for subsequent step chunks.
             $chunked_destination_settings = $settings;
             $chunked_destination_settings['_chunk_file'] = $file;
             $chunked_destination_settings['_chunk_maxsize'] = $max_chunk_size_bytes;
             $chunked_destination_settings['_chunk_upload_id'] = $result;
             $chunked_destination_settings['_chunk_offset'] = $data_length;
             $chunked_destination_settings['_chunk_next_offset'] = $data_length;
             // First chunk was sent initiationg multipart send.
             $chunked_destination_settings['_chunk_sent_count'] = 1;
             $chunked_destination_settings['_chunk_total_count'] = ceil($file_size / $max_chunk_size_bytes);
             $chunked_destination_settings['_chunk_transfer_speeds'][] = $chunk_transfer_speed;
             pb_backupbuddy::status('details', 'Sent first chunk to Dropbox with upload ID: `' . $chunked_destination_settings['_chunk_upload_id'] . '`. Offset: `' . $chunked_destination_settings['_chunk_offset'] . '`.');
             // Remove this file from list to send before passing $files to schedule next cron. Multipart will handle this from here on out.
             unset($files[$file_id]);
             // Schedule next chunk to send.
             pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) scheduling send of next part(s).');
             $cronTime = time();
             $cronArgs = array($chunked_destination_settings, $files, $send_id, $delete_after);
             $cronHashID = md5($cronTime . serialize($cronArgs));
             $cronArgs[] = $cronHashID;
             if (false === backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs)) {
                 pb_backupbuddy::status('error', 'Error #948844: Unable to schedule next Dropbox2 cron chunk.');
                 return false;
             } else {
                 pb_backupbuddy::status('details', 'Success scheduling next cron chunk.');
             }
             spawn_cron(time() + 150);
             // Adds > 60 seconds to get around once per minute cron running limit.
             update_option('_transient_doing_cron', 0);
             // Prevent cron-blocking for next item.
             pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) scheduled send of next part(s). Done for this cycle.');
             return array($chunked_destination_settings['_chunk_upload_id'], 'Sent 1 of ' . $chunked_destination_settings['_chunk_total_count'] . ' parts.');
         } else {
             // normal (non-chunked) send.
             pb_backupbuddy::status('details', 'Dropbox send not set to be chunked.');
             pb_backupbuddy::status('details', 'About to put file `' . basename($file) . '` (' . pb_backupbuddy::$format->file_size($file_size) . ') to Dropbox (PHP 5.3+).');
             $send_time = -microtime(true);
             try {
                 $result = self::$_dbxClient->uploadFile($settings['directory'] . '/' . basename($file), dbx\WriteMode::add(), $f);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error: ' . $e->getMessage());
                 return false;
             }
             $send_time += microtime(true);
             @fclose($f);
             pb_backupbuddy::status('details', 'About to load fileoptions data.');
             require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
             pb_backupbuddy::status('details', 'Fileoptions instance #14.');
             $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
             if (true !== ($result = $fileoptions_obj->is_ok())) {
                 pb_backupbuddy::status('error', __('Fatal Error #9034.2344848. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
                 return false;
             }
             pb_backupbuddy::status('details', 'Fileoptions data loaded.');
             $fileoptions =& $fileoptions_obj->options;
             // Calculate some stats to log.
             $data_length = $file_size;
             $transfer_speed = $data_length / $send_time;
             pb_backupbuddy::status('details', 'Dropbox (non-chunked) transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($transfer_speed) . '/sec`.');
             $fileoptions['write_speed'] = $transfer_speed;
             $fileoptions_obj->save();
             unset($fileoptions_obj);
         }
         // end normal (non-chunked) send.
         pb_backupbuddy::status('message', 'Success sending `' . basename($file) . '` to Dropbox!');
         // Start remote backup limit
         if ($settings['archive_limit'] > 0) {
             pb_backupbuddy::status('details', 'Dropbox file limit in place. Proceeding with enforcement.');
             $meta_data = self::$_dbxClient->getMetadataWithChildren($settings['directory']);
             // Create array of backups and organize by date
             $bkupprefix = backupbuddy_core::backup_prefix();
             $backups = array();
             foreach ((array) $meta_data['contents'] as $looping_file) {
                 if ($looping_file['is_dir'] == '1') {
                     // JUST IN CASE. IGNORE anything that is a directory.
                     continue;
                 }
                 // check if file is backup
                 if (strpos($looping_file['path'], 'backup-' . $bkupprefix . '-') !== false) {
                     // Appears to be a backup file.
                     $backups[$looping_file['path']] = strtotime($looping_file['modified']);
                 }
             }
             arsort($backups);
             if (count($backups) > $settings['archive_limit']) {
                 pb_backupbuddy::status('details', 'Dropbox backup file count of `' . count($backups) . '` exceeds limit of `' . $settings['archive_limit'] . '`.');
                 $i = 0;
                 $delete_fail_count = 0;
                 foreach ($backups as $buname => $butime) {
                     $i++;
                     if ($i > $settings['archive_limit']) {
                         if (!self::$_dbxClient->delete($buname)) {
                             // Try to delete backup on Dropbox. Increment failure count if unable to.
                             pb_backupbuddy::status('details', 'Unable to delete excess Dropbox file: `' . $buname . '`');
                             $delete_fail_count++;
                         } else {
                             pb_backupbuddy::status('details', 'Deleted excess Dropbox file: `' . $buname . '`');
                         }
                     }
                 }
                 if ($delete_fail_count !== 0) {
                     backupbuddy_core::mail_error(sprintf(__('Dropbox remote limit could not delete %s backups.', 'it-l10n-backupbuddy'), $delete_fail_count));
                 }
             }
         } else {
             pb_backupbuddy::status('details', 'No Dropbox file limit to enforce.');
         }
         // End remote backup limit
     }
     // end foreach.
     pb_backupbuddy::status('details', 'All files sent.');
     return true;
     // Success if made it this far.
 }
 public static function send($destination_settings, $files, $send_id = '', $delete_after = false)
 {
     if ('' != $send_id) {
         pb_backupbuddy::add_status_serial('remote_send-' . $send_id);
         pb_backupbuddy::status('details', '----- Initiating master send function. Post-send deletion: ' . $delete_after);
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         $fileoptions_file = backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt';
         if (!file_exists($fileoptions_file)) {
             //pb_backupbuddy::status( 'details', 'Fileoptions file `' . $fileoptions_file . '` does not exist yet; creating.' );
             //pb_backupbuddy::status( 'details', 'Fileoptions instance #19.' );
             $fileoptions_obj = new pb_backupbuddy_fileoptions($fileoptions_file, $read_only = false, $ignore_lock = true, $create_file = true);
         } else {
             //pb_backupbuddy::status( 'details', 'Fileoptions file exists; loading.' );
             //pb_backupbuddy::status( 'details', 'Fileoptions instance #18.' );
             $fileoptions_obj = new pb_backupbuddy_fileoptions($fileoptions_file, $read_only = false, $ignore_lock = false, $create_file = false);
         }
         if (true !== ($result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Fatal Error #9034.2344848. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
             return false;
         }
         //pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' );
         $fileoptions =& $fileoptions_obj->options;
         if ('' == $fileoptions) {
             $fileoptions = backupbuddy_core::get_remote_send_defaults();
             $fileoptions['type'] = $destination_settings['type'];
             if (!is_array($files)) {
                 $fileoptions['file'] = $files;
             } else {
                 $fileoptions['file'] = $files[0];
             }
             $fileoptions_obj->save();
         }
         if (isset($fileoptions['status']) && 'aborted' == $fileoptions['status']) {
             pb_backupbuddy::status('warning', 'Destination send triggered on an ABORTED transfer. Ending send function.');
             return false;
         }
         unset($fileoptions_obj);
     }
     if (false === ($destination = self::_init_destination($destination_settings))) {
         echo '{Error #546893498a. Destination configuration file missing.}';
         if ('' != $send_id) {
             pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
         }
         return false;
     }
     $destination_settings = $destination['settings'];
     // Settings with defaults applied, normalized, etc.
     //$destination_info = $destination['info'];
     if (!is_array($files)) {
         $files = array($files);
     }
     $originalFiles = $files;
     $files_with_sizes = '';
     foreach ($files as $index => $file) {
         if ('' == $file) {
             unset($files[$index]);
             continue;
             // Not actually a file to send.
         }
         if (!file_exists($file)) {
             pb_backupbuddy::status('error', 'Error #58459458743. The file that was attempted to be sent to a remote destination, `' . $file . '`, was not found. It either does not exist or permissions prevent accessing it.');
             if ('' != $send_id) {
                 pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
             }
             return false;
         }
         $files_with_sizes .= $file . ' (' . pb_backupbuddy::$format->file_size(filesize($file)) . '); ';
     }
     //pb_backupbuddy::status( 'details', 'Sending files `' . $files_with_sizes . '` to destination type `' . $destination_settings['type'] . '` titled `' . $destination_settings['title'] . '`.' );
     unset($files_with_sizes);
     if (!method_exists($destination['class'], 'send')) {
         pb_backupbuddy::status('error', 'Destination class `' . $destination['class'] . '` does not support send operation -- missing function.');
         if ('' != $send_id) {
             pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
         }
         return false;
     }
     //pb_backupbuddy::status( 'details', 'Calling send function.' );
     //$result = $destination_class::send( $destination_settings, $files );
     global $pb_backupbuddy_destination_errors;
     $pb_backupbuddy_destination_errors = array();
     $result = call_user_func_array("{$destination['class']}::send", array($destination_settings, $files, $send_id, $delete_after));
     if ($result === false) {
         $error_details = implode('; ', $pb_backupbuddy_destination_errors);
         if ('' != $error_details) {
             $error_details = ' Details: ' . $error_details;
         }
         $log_directory = backupbuddy_core::getLogDirectory();
         $preError = 'There was an error sending to the remote destination. One or more files may have not been fully transferred. Please see error details for additional information. If the error persists, enable full error logging and try again for full details and troubleshooting. Details: ' . "\n\n";
         $logFile = $log_directory . 'status-remote_send-' . $send_id . '_' . backupbuddy_core::get_serial_from_file($file) . '.txt';
         pb_backupbuddy::status('details', 'Looking for remote send log file `' . $logFile . '`.');
         if (!file_exists($logFile)) {
             pb_backupbuddy::status('details', 'Remote send log file not found.');
             backupbuddy_core::mail_error($preError . $error_details);
         } else {
             // Log exists. Attach.
             pb_backupbuddy::status('details', 'Remote send log file found. Attaching to error email.');
             backupbuddy_core::mail_error($preError . $error_details . "\n\nSee the attached log for details.", '', array($logFile));
         }
         // Save error details into fileoptions for this send.
         //pb_backupbuddy::status( 'details', 'About to load fileoptions data.' );
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         pb_backupbuddy::status('details', 'Fileoptions instance #45.');
         $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
         if (true !== ($fileoptions_result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Error #9034.32731. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $fileoptions_result);
         }
         //pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' );
         $fileoptions =& $fileoptions_obj->options;
         $fileoptions['error'] = 'Error sending.' . $error_details;
         $fileoptions_obj->save();
         unset($fileoptions_obj);
     }
     if (is_array($result)) {
         // Send is multipart.
         pb_backupbuddy::status('details', 'Multipart chunk mode completed a pass of the send function. Resuming will be needed. Result: `' . print_r($result, true) . '`.');
         if ('' != $send_id) {
             //pb_backupbuddy::status( 'details', 'About to load fileoptions data.' );
             require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
             //pb_backupbuddy::status( 'details', 'Fileoptions instance #17.' );
             $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
             if (true !== ($fileoptions_result = $fileoptions_obj->is_ok())) {
                 pb_backupbuddy::status('error', __('Fatal Error #9034.387462. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $fileoptions_result);
                 return false;
             }
             //pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' );
             $fileoptions =& $fileoptions_obj->options;
             $fileoptions['_multipart_status'] = $result[1];
             pb_backupbuddy::status('details', 'Destination debugging details: `' . print_r($fileoptions, true) . '`.');
             $fileoptions_obj->save();
             unset($fileoptions_obj);
             pb_backupbuddy::status('details', 'Next multipart chunk will be processed shortly. Now waiting on its cron...');
         }
     } else {
         // Single all-at-once send.
         if (false === $result) {
             pb_backupbuddy::status('details', 'Completed send function. Failure.');
         } elseif (true === $result) {
             pb_backupbuddy::status('details', 'Completed send function. Success.');
         } else {
             pb_backupbuddy::status('warning', 'Completed send function. Unknown result: `' . $result . '`.');
         }
         if (true === $delete_after) {
             pb_backupbuddy::status('details', __('Post-send deletion enabled.', 'it-l10n-backupbuddy'));
             if (false === $result) {
                 pb_backupbuddy::status('details', 'Skipping post-send deletion since transfer failed.');
             } else {
                 pb_backupbuddy::status('details', 'Performing post-send deletion since transfer succeeded.');
                 pb_backupbuddy::status('details', 'About to load fileoptions data.');
                 require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
                 pb_backupbuddy::status('details', 'Fileoptions instance #16.');
                 $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
                 if (true !== ($fileoptions_result = $fileoptions_obj->is_ok())) {
                     pb_backupbuddy::status('error', __('Error #9034.387462. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $fileoptions_result);
                 }
                 pb_backupbuddy::status('details', 'Fileoptions data loaded.');
                 $fileoptions =& $fileoptions_obj->options;
                 array_push($originalFiles, $fileoptions['file']);
                 // Add file (maybe multipart) into files to clean up.
                 foreach ($originalFiles as $file) {
                     pb_backupbuddy::status('details', 'Deleting local file `' . $file . '`.');
                     // Handle post-send deletion on success.
                     if (file_exists($file)) {
                         $unlink_result = @unlink($file);
                         if (true !== $unlink_result) {
                             pb_backupbuddy::status('error', 'Unable to unlink local file `' . $file . '`.');
                         }
                     }
                     if (file_exists($file)) {
                         // File still exists.
                         pb_backupbuddy::status('details', __('Error. Unable to delete local file `' . $file . '` after send as set in settings.', 'it-l10n-backupbuddy'));
                         backupbuddy_core::mail_error('BackupBuddy was unable to delete local file `' . $file . '` after successful remove transfer though post-remote send deletion is enabled. You may want to delete it manually. This can be caused by permission problems or improper server configuration.');
                     } else {
                         // Deleted.
                         pb_backupbuddy::status('details', __('Deleted local archive after successful remote destination send based on settings.', 'it-l10n-backupbuddy'));
                         pb_backupbuddy::status('archiveDeleted', '');
                     }
                 }
             }
         } else {
             pb_backupbuddy::status('details', 'Post-send deletion not enabled.');
         }
     }
     // NOTE: Call this before removing status serial so it shows in log.
     //pb_backupbuddy::status( 'details', 'Finishing send() function.' );
     if ('' != $send_id) {
         pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
     }
     return $result;
 }
 public function deploy_sendWait($state, $sendFile, $sendPath, $sendType, $nextStep)
 {
     $maxSendTime = 60 * 5;
     if ('' == $sendFile) {
         // File failed. Proceed to next.
         $this->insert_next_step($nextStep);
     }
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #38.');
     $identifier = $this->_backup['serial'] . '_' . md5($sendFile . $sendType);
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $identifier . '.txt', $read_only = false, $ignore_lock = true, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034 E. 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.');
     $fileoptions =& $fileoptions_obj->options;
     // Set reference.
     if ('0' == $fileoptions['finish_time']) {
         // Not finished yet. Insert next chunk to wait.
         $timeAgo = time() - $fileoptions['start_time'];
         if ($timeAgo > $maxSendTime) {
             pb_backupbuddy::status('error', 'Error #4948348: Maximum allowed file send time of `' . $maxSendTime . '` seconds passed. Halting.');
             pb_backupbuddy::status('haltScript', '');
             // Halt JS on page.
         }
         pb_backupbuddy::status('details', 'File send not yet finished. Started `' . $timeAgo . '` seconds ago. Inserting wait.');
         $newStep = array('function' => 'deploy_sendWait', 'args' => array($state, $sendFile, $sendPath, $sendType, $nextStep), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->insert_next_step($newStep);
     } else {
         // Finished. Go to next step.
         $this->insert_next_step($nextStep);
     }
     return true;
 }
Beispiel #22
0
 public static function send($settings = array(), $files = array(), $clear_uploads = false)
 {
     global $pb_backupbuddy_destination_errors;
     if (!is_array($files)) {
         $files = array($files);
     }
     if ($clear_uploads === false) {
         // Uncomment the following line to override and always clear.
         //$clear_uploads = true;
     }
     $itxapi_username = $settings['itxapi_username'];
     $itxapi_password = $settings['itxapi_password'];
     $db_archive_limit = $settings['db_archive_limit'];
     $full_archive_limit = $settings['full_archive_limit'];
     $max_chunk_size = $settings['max_chunk_size'];
     $remote_path = self::get_remote_path($settings['directory']);
     // Has leading and trailng slashes.
     if ($settings['ssl'] == '0') {
         $disable_ssl = true;
     } else {
         $disable_ssl = false;
     }
     $multipart_id = $settings['_multipart_id'];
     $multipart_counts = $settings['_multipart_counts'];
     pb_backupbuddy::status('details', 'Stash remote path set to `' . $remote_path . '`.');
     require_once dirname(__FILE__) . '/lib/class.itx_helper.php';
     require_once dirname(dirname(__FILE__)) . '/_s3lib/aws-sdk/sdk.class.php';
     // Stash API talk.
     $stash = new ITXAPI_Helper(pb_backupbuddy_destination_stash::ITXAPI_KEY, pb_backupbuddy_destination_stash::ITXAPI_URL, $itxapi_username, $itxapi_password);
     $manage_data = pb_backupbuddy_destination_stash::get_manage_data($settings);
     //print_r( $manage_data );
     //die();
     // Wipe all current uploads.
     if ($clear_uploads === true) {
         pb_backupbuddy::status('details', 'Clearing any current uploads via Stash call to `abort-all`.');
         $abort_url = $stash->get_upload_url(null, 'abort-all');
         $request = new RequestCore($abort_url);
         //pb_backupbuddy::status('details', print_r( $request , true ) );
         $response = $request->send_request(true);
     }
     // Process multipart transfer that we already initiated in a previous PHP load.
     if ($multipart_id != '') {
         // Multipart upload initiated and needs parts sent.
         // Create S3 instance.
         pb_backupbuddy::status('details', 'Creating Stash S3 instance.');
         $s3 = new AmazonS3($settings['_multipart_upload_data']['credentials']);
         // the key, secret, token
         if ($disable_ssl === true) {
             @$s3->disable_ssl(true);
         }
         pb_backupbuddy::status('details', 'Stash S3 instance created.');
         $this_part_number = $settings['_multipart_partnumber'] + 1;
         pb_backupbuddy::status('details', 'Stash beginning upload of part `' . $this_part_number . '` of `' . count($settings['_multipart_counts']) . '` parts of file `' . $settings['_multipart_file'] . '` with multipart ID `' . $settings['_multipart_id'] . '`.');
         $response = $s3->upload_part($settings['_multipart_upload_data']['bucket'], $settings['_multipart_upload_data']['object'], $settings['_multipart_id'], array('expect' => '100-continue', 'fileUpload' => $settings['_multipart_file'], 'partNumber' => $this_part_number, 'seekTo' => (int) $settings['_multipart_counts'][$settings['_multipart_partnumber']]['seekTo'], 'length' => (int) $settings['_multipart_counts'][$settings['_multipart_partnumber']]['length']));
         if (!$response->isOK()) {
             $this_error = 'Stash unable to upload file part for multipart upload `' . $settings['_multipart_id'] . '`. Details: `' . print_r($response, true) . '`.';
             $pb_backupbuddy_destination_errors[] = $this_error;
             pb_backupbuddy::status('error', $this_error);
             return false;
         }
         // Update stats.
         foreach (pb_backupbuddy::$options['remote_sends'] as $identifier => $remote_send) {
             if (isset($remote_send['_multipart_id']) && $remote_send['_multipart_id'] == $multipart_id) {
                 // this item.
                 pb_backupbuddy::$options['remote_sends'][$identifier]['_multipart_status'] = 'Sent part ' . $this_part_number . ' of ' . count($settings['_multipart_counts']) . '.';
                 if ($this_part_number == count($settings['_multipart_counts'])) {
                     pb_backupbuddy::$options['remote_sends'][$identifier]['_multipart_status'] .= '<br>Success.';
                     pb_backupbuddy::$options['remote_sends'][$identifier]['finish_time'] = time();
                 }
                 pb_backupbuddy::save();
                 break;
             }
         }
         // Made it here so success sending part. Increment for next part to send.
         $settings['_multipart_partnumber']++;
         if (!isset($settings['_multipart_counts'][$settings['_multipart_partnumber']])) {
             // No more parts exist for this file. Tell S3 the multipart upload is complete and move on.
             pb_backupbuddy::status('details', 'Stash getting parts with etags to notify S3 of completed multipart send.');
             $etag_parts = $s3->list_parts($settings['_multipart_upload_data']['bucket'], $settings['_multipart_upload_data']['object'], $settings['_multipart_id']);
             pb_backupbuddy::status('details', 'Stash got parts list. Notifying S3 of multipart upload completion.');
             $response = $s3->complete_multipart_upload($settings['_multipart_upload_data']['bucket'], $settings['_multipart_upload_data']['object'], $settings['_multipart_id'], $etag_parts);
             if (!$response->isOK()) {
                 $this_error = 'Stash unable to notify S3 of completion of all parts for multipart upload `' . $settings['_multipart_id'] . '`.';
                 $pb_backupbuddy_destination_errors[] = $this_error;
                 pb_backupbuddy::status('error', $this_error);
                 return false;
             } else {
                 pb_backupbuddy::status('details', 'Stash notified S3 of multipart completion.');
             }
             // Notify Stash API that things were succesful.
             $done_url = $stash->get_upload_url($settings['_multipart_file'], 'done', $remote_path . $settings['_multipart_backup_type_dir'] . basename($settings['_multipart_file']));
             pb_backupbuddy::status('details', 'Notifying Stash of completed multipart upload with done url `' . $done_url . '`.');
             $request = new RequestCore($done_url);
             $response = $request->send_request(true);
             if (!$response->isOK()) {
                 $this_error = 'Error #756834682. Could not finalize Stash upload. Response code: `' . $response->get_response_code() . '`; Response body: `' . $response->get_response_body() . '`; Response headers: `' . $response->get_response_header() . '`.';
                 $pb_backupbuddy_destination_errors[] = $this_error;
                 pb_backupbuddy::status('error', $this_error);
                 return false;
             } else {
                 // Good server response.
                 // See if we got an optional json response.
                 $upload_data = @json_decode($response->body, true);
                 if (isset($upload_data['error'])) {
                     $this_error = 'Stash error(s): `' . implode(' - ', $upload_data['error']) . '`.';
                     $pb_backupbuddy_destination_errors[] = $this_error;
                     pb_backupbuddy::status('error', $this_error);
                     return false;
                 }
                 pb_backupbuddy::status('details', 'Stash success sending file `' . basename($settings['_multipart_file']) . '`. File uploaded via multipart across `' . $this_part_number . '` parts and reported to Stash as completed.');
             }
             pb_backupbuddy::status('details', 'Stash has no more parts left for this multipart upload. Clearing multipart instance variables.');
             $settings['_multipart_partnumber'] = 0;
             $settings['_multipart_id'] = '';
             $settings['_multipart_file'] = '';
             $settings['_multipart_counts'] = array();
             $settings['_multipart_upload_data'] = array();
         }
         delete_transient('pb_backupbuddy_stashquota_' . $settings['itxapi_username']);
         // Delete quota transient since it probably has changed now.
         // Schedule to continue if anything is left to upload for this multipart of any individual files.
         if ($settings['_multipart_id'] != '' || count($files) > 0) {
             pb_backupbuddy::status('details', 'Stash multipart upload has more parts left. Scheduling next part send.');
             pb_backupbuddy::$classes['core']->schedule_single_event(time(), pb_backupbuddy::cron_tag('destination_send'), array($settings, $files, 'multipart', false));
             spawn_cron(time() + 150);
             // Adds > 60 seconds to get around once per minute cron running limit.
             update_option('_transient_doing_cron', 0);
             // Prevent cron-blocking for next item.
             pb_backupbuddy::status('details', 'Stash scheduled send of next part(s). Done for this cycle.');
             return array($settings['_multipart_id'], 'Sent ' . $this_part_number . ' of ' . count($multipart_destination_settings['_multipart_counts'] . ' parts.'));
         }
     }
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     // Upload each file.
     foreach ($files as $file_id => $file) {
         // Determine backup type directory (if zip).
         $backup_type_dir = '';
         $backup_type = '';
         if (stristr($file, '.zip') !== false) {
             // If a zip try to determine backup type.
             pb_backupbuddy::status('details', 'Stash: Zip file. Detecting backup type if possible.');
             $serial = pb_backupbuddy::$classes['core']->get_serial_from_file($file);
             // See if we can get backup type from fileoptions data.
             $backup_options = new pb_backupbuddy_fileoptions(pb_backupbuddy::$options['log_directory'] . 'fileoptions/' . $serial . '.txt', $read_only = true, $ignore_lock = true);
             if (true !== ($result = $backup_options->is_ok())) {
                 pb_backupbuddy::status('error', 'Unable to open fileoptions file `' . pb_backupbuddy::$options['log_directory'] . 'fileoptions/' . $serial . '.txt' . '`.');
             } else {
                 if (isset($backup_options->options['integrity']['detected_type'])) {
                     pb_backupbuddy::status('details', 'Stash: Detected backup type as `' . $backup_options->options['integrity']['detected_type'] . '` via integrity check data.');
                     $backup_type_dir = $backup_options->options['integrity']['detected_type'] . '/';
                     $backup_type = $backup_options->options['integrity']['detected_type'];
                 }
             }
             // If still do not know backup type then attempt to deduce it from filename.
             if ($backup_type == '') {
                 if (stristr($file, '-db-') !== false) {
                     pb_backupbuddy::status('details', 'Stash: Detected backup type as `db` via filename.');
                     $backup_type_dir = 'db/';
                     $backup_type = 'db';
                 } elseif (stristr($file, '-full-') !== false) {
                     pb_backupbuddy::status('details', 'Stash: Detected backup type as `full` via filename.');
                     $backup_type_dir = 'full/';
                     $backup_type = 'full';
                 } else {
                     pb_backupbuddy::status('details', 'Stash: Could not detect backup type via integrity details nor filename.');
                 }
             }
         }
         // Interact with Stash API.
         pb_backupbuddy::status('details', 'Determining Stash upload URL for `' . $file . '`.` with destination remote path `' . $remote_path . $backup_type_dir . basename($file) . '`.');
         $upload_url = $stash->get_upload_url($file, 'request', $remote_path . $backup_type_dir . basename($file));
         pb_backupbuddy::status('details', 'Determined upload url: `' . $upload_url . '`.');
         $request = new RequestCore($upload_url);
         pb_backupbuddy::status('details', 'Sending Stash API request.');
         $response = $request->send_request(true);
         // Validate response.
         if (!$response->isOK()) {
             $this_error = 'Stash request for upload credentials failed.';
             $pb_backupbuddy_destination_errors[] = $this_error;
             pb_backupbuddy::status('error', $this_error);
             return false;
         }
         if (!($upload_data = json_decode($response->body, true))) {
             $this_error = 'Stash API did not give a valid JSON response.';
             $pb_backupbuddy_destination_errors[] = $this_error;
             pb_backupbuddy::status('error', $this_error);
             return false;
         }
         if (isset($upload_data['error'])) {
             $this_error = 'Stash error(s): `' . implode(' - ', $upload_data['error']) . '`.';
             $pb_backupbuddy_destination_errors[] = $this_error;
             pb_backupbuddy::status('error', $this_error);
             return false;
         }
         // Create S3 instance.
         pb_backupbuddy::status('details', 'Creating Stash S3 instance.');
         $s3 = new AmazonS3($upload_data['credentials']);
         // the key, secret, token
         if ($disable_ssl === true) {
             @$s3->disable_ssl(true);
         }
         pb_backupbuddy::status('details', 'Stash S3 instance created.');
         // Handle chunking of file into a multipart upload (if applicable).
         $file_size = filesize($file);
         if ($max_chunk_size >= 5 && $file_size / 1024 / 1024 > $max_chunk_size) {
             // minimum chunk size is 5mb. Anything under 5mb we will not chunk.
             pb_backupbuddy::status('details', 'Stash file size of ' . $file_size / 1024 / 1024 . 'MB exceeds max chunk size of ' . $max_chunk_size . 'MB set in settings for sending file as multipart upload.');
             // Initiate multipart upload with S3.
             pb_backupbuddy::status('details', 'Initiating Stash multipart upload.');
             $response = $s3->initiate_multipart_upload($upload_data['bucket'], $upload_data['object'], array('encryption' => 'AES256'));
             if (!$response->isOK()) {
                 $this_error = 'Stash was unable to initiate multipart upload.';
                 $pb_backupbuddy_destination_errors[] = $this_error;
                 pb_backupbuddy::status('error', $this_error);
                 return false;
             } else {
                 $upload_id = (string) $response->body->UploadId;
                 pb_backupbuddy::status('details', 'Stash initiated multipart upload with ID `' . $upload_id . '`.');
             }
             // Get chunk parts for multipart transfer.
             pb_backupbuddy::status('details', 'Stash getting multipart counts.');
             $parts = $s3->get_multipart_counts($file_size, $max_chunk_size * 1024 * 1024);
             // Size of chunks expected to be in bytes.
             $multipart_destination_settings = $settings;
             $multipart_destination_settings['_multipart_id'] = $upload_id;
             $multipart_destination_settings['_multipart_partnumber'] = 0;
             $multipart_destination_settings['_multipart_file'] = $file;
             $multipart_destination_settings['_multipart_counts'] = $parts;
             $multipart_destination_settings['_multipart_upload_data'] = $upload_data;
             $multipart_destination_settings['_multipart_backup_type_dir'] = $backup_type_dir;
             pb_backupbuddy::status('details', 'Stash multipart settings to pass:'******'details', 'Stash scheduling send of next part(s).');
             pb_backupbuddy::$classes['core']->schedule_single_event(time(), pb_backupbuddy::cron_tag('destination_send'), array($multipart_destination_settings, $files, 'multipart', false));
             spawn_cron(time() + 150);
             // Adds > 60 seconds to get around once per minute cron running limit.
             update_option('_transient_doing_cron', 0);
             // Prevent cron-blocking for next item.
             pb_backupbuddy::status('details', 'Stash scheduled send of next part(s). Done for this cycle.');
             return array($upload_id, 'Starting send of ' . count($multipart_destination_settings['_multipart_counts']) . ' parts.');
         } else {
             if ($max_chunk_size != '0') {
                 pb_backupbuddy::status('details', 'File size of ' . $file_size / 1024 / 1024 . 'MB is less than the max chunk size of ' . $max_chunk_size . 'MB; not chunking into multipart upload.');
             } else {
                 pb_backupbuddy::status('details', 'Max chunk size set to zero so not chunking into multipart upload.');
             }
         }
         // SEND file.
         pb_backupbuddy::status('details', 'About to put (upload) object to Stash.');
         $response = $s3->create_object($upload_data['bucket'], $upload_data['object'], array('fileUpload' => $file, 'encryption' => 'AES256'));
         //  we can also utilize the multi-part-upload to create an object
         //  $response = $s3->create_mpu_object($upload_data['bucket'], $upload_data['object'], array('fileUpload'=>$upload_file));
         // Validate response. On failure notify Stash API that things went wrong.
         if (!$response->isOK()) {
             pb_backupbuddy::status('details', 'Sending upload abort.');
             $request = new RequestCore($abort_url);
             $response = $request->send_request(true);
             $this_error = 'Could not upload to Stash, attempt aborted.';
             $pb_backupbuddy_destination_errors[] = $this_error;
             pb_backupbuddy::status('error', $this_error);
             return false;
         } else {
             //	pb_backupbuddy::status( 'details', 'Stash file upload speed: ' . ( $response->header['_info']['speed_upload'] / 1024 / 1024 ) . 'MB/sec. This number may be invalid for small file transfers.' );
             pb_backupbuddy::status('details', 'Stash put success. Need to nofity Stash of upload completion. Details: `' . print_r($response, true) . '`.');
         }
         delete_transient('pb_backupbuddy_stashquota_' . $settings['itxapi_username']);
         // Delete quota transient since it probably has changed now.
         // Notify Stash API that things were succesful.
         $done_url = $stash->get_upload_url($file, 'done', $remote_path . $backup_type_dir . basename($file));
         pb_backupbuddy::status('details', 'Notifying Stash of completed upload with done url `' . $done_url . '`.');
         $request = new RequestCore($done_url);
         $response = $request->send_request(true);
         if (!$response->isOK()) {
             $this_error = 'Error #247568834682. Could not finalize Stash upload. Response code: `' . $response->get_response_code() . '`; Response body: `' . $response->get_response_body() . '`; Response headers: `' . $response->get_response_header() . '`.';
             $pb_backupbuddy_destination_errors[] = $this_error;
             pb_backupbuddy::status('error', $this_error);
             return false;
         } else {
             // Good server response.
             // See if we got an optional json response.
             $upload_data = @json_decode($response->body, true);
             if (isset($upload_data['error'])) {
                 // Some kind of error.
                 $this_error = 'Stash error(s): `' . implode(' - ', $upload_data['error']) . '`.';
                 $pb_backupbuddy_destination_errors[] = $this_error;
                 pb_backupbuddy::status('error', $this_error);
                 return false;
             }
             unset($files[$file_id]);
             // Remove from list of files we have not sent yet.
             pb_backupbuddy::status('details', 'Stash success sending file `' . basename($file) . '`. File uploaded and reported to Stash as completed.');
         }
         // Enforce archive limits if applicable.
         if ($backup_type == 'full') {
             $limit = $full_archive_limit;
             pb_backupbuddy::status('details', 'Stash full backup archive limit of `' . $limit . '` based on destination settings.');
         } elseif ($backup_type == 'db') {
             $limit = $db_archive_limit;
             pb_backupbuddy::status('details', 'Stash database backup archive limit of `' . $limit . '` based on destination settings.');
         } else {
             $limit = 0;
             pb_backupbuddy::status('error', 'Error #54854895. Stash was unable to determine backup type so archive limits NOT enforced for this backup.');
         }
         if ($limit > 0) {
             pb_backupbuddy::status('details', 'Stash archive limit enforcement beginning.');
             // S3 object for managing files.
             $s3_manage = new AmazonS3($manage_data['credentials']);
             if ($disable_ssl === true) {
                 @$s3_manage->disable_ssl(true);
             }
             // Get file listing.
             $response_manage = $s3_manage->list_objects($manage_data['bucket'], array('prefix' => $manage_data['subkey'] . $remote_path . $backup_type_dir));
             // list all the files in the subscriber account
             // Create array of backups and organize by date
             $prefix = pb_backupbuddy::$classes['core']->backup_prefix();
             // List backups associated with this site by date.
             $backups = array();
             foreach ($response_manage->body->Contents as $object) {
                 $file = str_replace($manage_data['subkey'] . $remote_path . $backup_type_dir, '', $object->Key);
                 // Stash stores files in a directory per site so no need to check prefix here! if ( false !== strpos( $file, 'backup-' . $prefix . '-' ) ) { // if backup has this site prefix...
                 $backups[$file] = strtotime($object->LastModified);
                 //}
             }
             arsort($backups);
             //error_log( 'backups: ' . print_r( $backups, true ) );
             pb_backupbuddy::status('details', 'Stash found `' . count($backups) . '` backups of this type when checking archive limits.');
             if (count($backups) > $limit) {
                 pb_backupbuddy::status('details', 'More archives (' . count($backups) . ') than limit (' . $limit . ') allows. Trimming...');
                 $i = 0;
                 $delete_fail_count = 0;
                 foreach ($backups as $buname => $butime) {
                     $i++;
                     if ($i > $limit) {
                         pb_backupbuddy::status('details', 'Trimming excess file `' . $buname . '`...');
                         $response = $s3_manage->delete_object($manage_data['bucket'], $manage_data['subkey'] . $remote_path . $backup_type_dir . $buname);
                         if (!$response->isOK()) {
                             pb_backupbuddy::status('details', 'Unable to delete excess Stash file `' . $buname . '`. Details: `' . print_r($response, true) . '`.');
                             $delete_fail_count++;
                         }
                     }
                 }
                 pb_backupbuddy::status('details', 'Finished trimming excess backups.');
                 if ($delete_fail_count !== 0) {
                     $error_message = 'Stash remote limit could not delete ' . $delete_fail_count . ' backups.';
                     pb_backupbuddy::status('error', $error_message);
                     pb_backupbuddy::$classes['core']->mail_error($error_message);
                 }
             }
             pb_backupbuddy::status('details', 'Stash completed archive limiting.');
         } else {
             pb_backupbuddy::status('details', 'No Stash archive file limit to enforce.');
         }
         // End remote backup limit
     }
     // end foreach.
     // Success if we made it this far.
     return true;
 }
			return false;
		});
	});
</script>
<?php 
backupbuddy_core::trim_remote_send_stats();
$remote_sends = array();
$send_fileoptions = pb_backupbuddy::$filesystem->glob_by_date(backupbuddy_core::getLogDirectory() . 'fileoptions/send-*.txt');
if (!is_array($send_fileoptions)) {
    $send_fileoptions = array();
}
foreach ($send_fileoptions as $send_fileoption) {
    $send_id = str_replace('.txt', '', str_replace('send-', '', basename($send_fileoption)));
    pb_backupbuddy::status('details', 'About to load fileoptions data.');
    require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
    $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = true, $ignore_lock = true, $create_file = false);
    if (true !== ($result = $fileoptions_obj->is_ok())) {
        pb_backupbuddy::status('error', __('Fatal Error #9034.32393. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
        return false;
    }
    pb_backupbuddy::status('details', 'Fileoptions data loaded.');
    $remote_sends[$send_id] = $fileoptions_obj->options;
    unset($fileoptions_obj);
}
$sends = array();
//echo '<pre>' . print_r( $remote_sends, true ) . '</pre>';
foreach ($remote_sends as $send_id => $remote_send) {
    // Set up some variables based on whether file finished sending yet or not.
    if ($remote_send['finish_time'] > 0) {
        // Finished sending.
        $time_ago = pb_backupbuddy::$format->time_ago($remote_send['finish_time']) . ' ago; <b>took ';
Beispiel #24
0
 public static function send($settings = array(), $files = array(), $send_id = '', $delete_after = false, $delete_remote_after = false)
 {
     global $pb_backupbuddy_destination_errors;
     if ('1' == $settings['disabled']) {
         $pb_backupbuddy_destination_errors[] = __('Error #48933: This destination is currently disabled. Enable it under this destination\'s Advanced Settings.', 'it-l10n-backupbuddy');
         return false;
     }
     if (!is_array($files)) {
         $files = array($files);
     }
     pb_backupbuddy::status('details', 'Google Drive send() function started. Settings: `' . print_r($settings, true) . '`.');
     self::$_timeStart = microtime(true);
     $settings = self::_normalizeSettings($settings);
     if (false === ($settings = self::_connect($settings))) {
         // $settings =
         return self::_error('Error #38923923: Unable to connect with Google Drive. See log for details.');
     }
     $folderID = $settings['folderID'];
     if ('' == $folderID) {
         $folderID = 'root';
     }
     $chunkSizeBytes = $settings['max_burst'] * 1024 * 1024;
     // Send X mb at a time to limit memory usage.
     foreach ($files as $file) {
         // Determine backup type for limiting later.
         $backup_type = '';
         if (stristr($file, '-db-') !== false) {
             $backup_type = 'db';
         } elseif (stristr($file, '-full-') !== false) {
             $backup_type = 'full';
         } elseif (stristr($file, '-files-') !== false) {
             $backup_type = 'files';
         } elseif (stristr($file, '-export-') !== false) {
             $backup_type = 'export';
         }
         if (!file_exists($file)) {
             return self::_error('Error #37792: File selected to send not found: `' . $file . '`.');
         }
         $fileSize = filesize($file);
         $fileinfo = pathinfo($file);
         $fileextension = $fileinfo['extension'];
         if ('zip' == $fileextension) {
             $mimeType = 'application/zip';
         } elseif ('php' == $fileextension) {
             $mimeType = 'application/x-httpd-php';
         } else {
             $mimeType = '';
         }
         pb_backupbuddy::status('details', 'About to upload file `' . $file . '` of size `' . $fileSize . '` with mimetype `' . $mimeType . '` into folder `' . $folderID . '`. Internal chunk size of `' . $chunkSizeBytes . '` bytes.');
         if ($fileSize > $chunkSizeBytes) {
             pb_backupbuddy::status('details', 'File size `' . pb_backupbuddy::$format->file_size($fileSize) . '` exceeds max burst size `' . $settings['max_burst'] . ' MB` so this will be sent in bursts. If time limit nears then send will be chunked across multiple PHP loads.');
             $settings['_chunks_total'] = ceil($fileSize / $chunkSizeBytes);
         }
         if (0 == $settings['_chunks_total']) {
             $settings['_chunks_total'] = 1;
         }
         //Insert a file
         $driveFile = new Google_Service_Drive_DriveFile();
         $driveFile->setTitle(basename($file));
         $driveFile->setDescription('BackupBuddy file');
         $driveFile->setMimeType($mimeType);
         // Set the parent folder.
         if ('root' != $folderID) {
             $parentsCollectionData = new Google_Service_Drive_ParentReference();
             $parentsCollectionData->setId($folderID);
             $driveFile->setParents(array($parentsCollectionData));
         }
         self::$_client->setDefer(true);
         try {
             $insertRequest = self::$_drive->files->insert($driveFile);
         } catch (Exception $e) {
             pb_backupbuddy::alert('Error #3232783268336: initiating upload. Details: ' . $e->getMessage());
             return false;
         }
         // Handle getting resume information to see if resuming is still an option.
         $resumable = false;
         if ('' != $settings['_media_resumeUri']) {
             $headers = array('content-range' => 'bytes */' . $fileSize);
             $request = new Google_Http_Request($settings['_media_resumeUri'], 'PUT', $headers, '');
             $response = self::$_client->getIo()->makeRequest($request);
             if (308 == $response->getResponseHttpCode()) {
                 $range = $response->getResponseHeader('range');
                 if (!empty($range) && preg_match('/bytes=0-(\\d+)$/', $range, $matches)) {
                     $resumable = true;
                     pb_backupbuddy::status('details', 'Last send reported next byte to be `' . $settings['_media_progress'] . '`.');
                     $settings['_media_progress'] = $matches[1] + 1;
                     pb_backupbuddy::status('details', 'Google Drive resuming is available. Google Drive reports next byte to be `' . $settings['_media_progress'] . '`. Range: `' . $range . '`.');
                 }
             }
             if (!$resumable) {
                 pb_backupbuddy::status('details', 'Google Drive could not resume. Too much time may have passed or some other cause.');
             }
             if ($settings['_media_progress'] >= $fileSize) {
                 pb_backupbuddy::status('details', 'Google Drive resuming not needed. Remote file meets or exceeds file size. Completed.');
                 return true;
             }
         }
         // See https://developers.google.com/api-client-library/php/guide/media_upload
         try {
             $media = new Google_Http_MediaFileUpload(self::$_client, $insertRequest, $mimeType, null, true, $chunkSizeBytes);
         } catch (Exception $e) {
             pb_backupbuddy::alert('Error #3893273937: initiating upload. Details: ' . $e->getMessage());
             return;
         }
         $media->setFileSize($fileSize);
         // Reset these internal variables. NOTE: These are by default private. Must modify MediaFileUpload.php to make this possible by setting these vars public. Thanks Google!
         if ('' != $settings['_media_resumeUri']) {
             $media->resumeUri = $settings['_media_resumeUri'];
             $media->progress = $settings['_media_progress'];
         }
         pb_backupbuddy::status('details', 'Opening file for sending in binary mode.');
         $fs = fopen($file, 'rb');
         // If chunked resuming then seek to the correct place in the file.
         if ('' != $settings['_media_progress'] && $settings['_media_progress'] > 0) {
             // Resuming send of a partially transferred file.
             if (0 !== fseek($fs, $settings['_media_progress'])) {
                 // Go off the resume point as given by Google in case it didnt all make it. //$settings['resume_point'] ) ) { // Returns 0 on success.
                 pb_backupbuddy::status('error', 'Error #3872733: Failed to seek file to resume point `' . $settings['_media_progress'] . '` via fseek().');
                 return false;
             }
             $prevPointer = $settings['_media_progress'];
             //$settings['resume_point'];
         } else {
             // New file send.
             $prevPointer = 0;
         }
         $needProcessChunking = false;
         // Set true if we need to spawn off resuming to a new PHP page load.
         $uploadStatus = false;
         while (!$uploadStatus && !feof($fs)) {
             $chunk = fread($fs, $chunkSizeBytes);
             pb_backupbuddy::status('details', 'Chunk of size `' . pb_backupbuddy::$format->file_size($chunkSizeBytes) . '` read into memory. Total bytes summed: `' . ($settings['_media_progress'] + strlen($chunk)) . '` of filesize: `' . $fileSize . '`.');
             pb_backupbuddy::status('details', 'Sending burst file data next. If next message is not "Burst file data sent" then the send likely timed out. Try reducing burst size. Sending now...');
             // Send chunk of data.
             try {
                 $uploadStatus = $media->nextChunk($chunk);
             } catch (Exception $e) {
                 global $pb_backupbuddy_destination_errors;
                 $pb_backupbuddy_destination_errors[] = $e->getMessage();
                 $error = $e->getMessage();
                 pb_backupbuddy::status('error', 'Error #8239832: Error sending burst data. Details: `' . $error . '`.');
                 return false;
             }
             $settings['_chunks_sent']++;
             self::$_chunksSentThisRound++;
             pb_backupbuddy::status('details', 'Burst file data sent.');
             $maxTime = $settings['max_time'];
             if ('' == $maxTime || !is_numeric($maxTime)) {
                 pb_backupbuddy::status('details', 'Max time not set in settings so detecting server max PHP runtime.');
                 $maxTime = backupbuddy_core::detectMaxExecutionTime();
             }
             //return;
             // Handle splitting up across multiple PHP page loads if needed.
             if (!feof($fs) && 0 != $maxTime) {
                 // More data remains so see if we need to consider chunking to a new PHP process.
                 // If we are within X second of reaching maximum PHP runtime then stop here so that it can be picked up in another PHP process...
                 $totalSizeSent = self::$_chunksSentThisRound * $chunkSizeBytes;
                 // Total bytes sent this PHP load.
                 $bytesPerSec = $totalSizeSent / (microtime(true) - self::$_timeStart);
                 $timeRemaining = $maxTime - (microtime(true) - self::$_timeStart + self::TIME_WIGGLE_ROOM);
                 if ($timeRemaining < 0) {
                     $timeRemaining = 0;
                 }
                 $bytesWeCouldSendWithTimeLeft = $bytesPerSec * $timeRemaining;
                 pb_backupbuddy::status('details', 'Total sent: `' . pb_backupbuddy::$format->file_size($totalSizeSent) . '`. Speed (per sec): `' . pb_backupbuddy::$format->file_size($bytesPerSec) . '`. Time Remaining (w/ wiggle): `' . $timeRemaining . '`. Size that could potentially be sent with remaining time: `' . pb_backupbuddy::$format->file_size($bytesWeCouldSendWithTimeLeft) . '` with chunk size of `' . pb_backupbuddy::$format->file_size($chunkSizeBytes) . '`.');
                 if ($bytesWeCouldSendWithTimeLeft < $chunkSizeBytes) {
                     // We can send more than a whole chunk (including wiggle room) so send another bit.
                     pb_backupbuddy::status('message', 'Not enough time left (~`' . $timeRemaining . '`) with max time of `' . $maxTime . '` sec to send another chunk at `' . pb_backupbuddy::$format->file_size($bytesPerSec) . '` / sec. Ran for ' . round(microtime(true) - self::$_timeStart, 3) . ' sec. Proceeding to use chunking.');
                     @fclose($fs);
                     // Tells next chunk where to pick up.
                     if (isset($chunksTotal)) {
                         $settings['_chunks_total'] = $chunksTotal;
                     }
                     // Grab these vars from the class.  Note that we changed these vars from private to public to make chunked resuming possible.
                     $settings['_media_resumeUri'] = $media->resumeUri;
                     $settings['_media_progress'] = $media->progress;
                     // Schedule cron.
                     $cronTime = time();
                     $cronArgs = array($settings, $files, $send_id, $delete_after);
                     $cronHashID = md5($cronTime . serialize($cronArgs));
                     $cronArgs[] = $cronHashID;
                     $schedule_result = backupbuddy_core::schedule_single_event($cronTime, 'destination_send', $cronArgs);
                     if (true === $schedule_result) {
                         pb_backupbuddy::status('details', 'Next Site chunk step cron event scheduled.');
                     } else {
                         pb_backupbuddy::status('error', 'Next Site chunk step cron even FAILED to be scheduled.');
                     }
                     spawn_cron(time() + 150);
                     // Adds > 60 seconds to get around once per minute cron running limit.
                     update_option('_transient_doing_cron', 0);
                     // Prevent cron-blocking for next item.
                     return array($prevPointer, 'Sent part ' . $settings['_chunks_sent'] . ' of ~' . $settings['_chunks_total'] . ' parts.');
                     // filepointer location, elapsed time during the import
                 } else {
                     // End if.
                     pb_backupbuddy::status('details', 'Not approaching limits.');
                 }
             } else {
                 pb_backupbuddy::status('details', 'No more data remains (eg for chunking) so finishing up.');
                 if ('' != $send_id) {
                     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
                     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
                     if (true !== ($result = $fileoptions_obj->is_ok())) {
                         pb_backupbuddy::status('error', __('Fatal Error #9034.397237. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
                         return false;
                     }
                     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
                     $fileoptions =& $fileoptions_obj->options;
                     $fileoptions['_multipart_status'] = 'Sent part ' . $settings['_chunks_sent'] . ' of ~' . $settings['_chunks_total'] . ' parts.';
                     $fileoptions['finish_time'] = microtime(true);
                     $fileoptions['status'] = 'success';
                     $fileoptions_obj->save();
                     unset($fileoptions_obj);
                 }
             }
         }
         fclose($fs);
         self::$_client->setDefer(false);
         if (false == $uploadStatus) {
             global $pb_backupbuddy_destination_errors;
             $pb_backupbuddy_destination_errors[] = 'Error #84347474 sending. Details: ' . $uploadStatus;
             return false;
         } else {
             // Success.
             if (true === $delete_remote_after) {
                 self::deleteFile($settings, $uploadStatus->id);
             }
         }
     }
     // end foreach.
     $db_archive_limit = $settings['db_archive_limit'];
     $full_archive_limit = $settings['full_archive_limit'];
     $files_archive_limit = $settings['files_archive_limit'];
     // BEGIN FILE LIMIT PROCESSING. Enforce archive limits if applicable.
     if ($backup_type == 'full') {
         $limit = $full_archive_limit;
     } elseif ($backup_type == 'db') {
         $limit = $db_archive_limit;
     } elseif ($backup_type == 'files') {
         $limit = $files_archive_limit;
     } else {
         $limit = 0;
         pb_backupbuddy::status('warning', 'Warning #34352453244. Google Drive was unable to determine backup type (reported: `' . $backup_type . '`) so archive limits NOT enforced for this backup.');
     }
     pb_backupbuddy::status('details', 'Google Drive database backup archive limit of `' . $limit . '` of type `' . $backup_type . '` based on destination settings.');
     if ($limit > 0) {
         pb_backupbuddy::status('details', 'Google Drive archive limit enforcement beginning.');
         // Get file listing.
         $searchCount = 1;
         $remoteFiles = array();
         while (count($remoteFiles) == 0 && $searchCount < 5) {
             pb_backupbuddy::status('details', 'Checking archive limits. Attempt ' . $searchCount . '.');
             $remoteFiles = pb_backupbuddy_destination_gdrive::listFiles($settings, "title contains 'backup-' AND title contains '-" . $backup_type . "-' AND '" . $folderID . "' IN parents AND trashed=false");
             //"title contains 'backup' and trashed=false" );
             sleep(1);
             $searchCount++;
         }
         // List backups associated with this site by date.
         $backups = array();
         $prefix = backupbuddy_core::backup_prefix();
         foreach ($remoteFiles as $remoteFile) {
             if ('application/vnd.google-apps.folder' == $remoteFile->mimeType) {
                 // Ignore folders.
                 continue;
             }
             if (strpos($remoteFile->originalFilename, 'backup-' . $prefix . '-') !== false) {
                 // Appears to be a backup file for this site.
                 $backups[$remoteFile->id] = strtotime($remoteFile->modifiedDate);
             }
         }
         arsort($backups);
         pb_backupbuddy::status('details', 'Google Drive found `' . count($backups) . '` backups of this type when checking archive limits.');
         if (count($backups) > $limit) {
             pb_backupbuddy::status('details', 'More archives (' . count($backups) . ') than limit (' . $limit . ') allows. Trimming...');
             $i = 0;
             $delete_fail_count = 0;
             foreach ($backups as $buname => $butime) {
                 $i++;
                 if ($i > $limit) {
                     pb_backupbuddy::status('details', 'Trimming excess file `' . $buname . '`...');
                     if (true !== self::deleteFile($settings, $buname)) {
                         pb_backupbuddy::status('details', 'Unable to delete excess Google Drive file `' . $buname . '`. Details: `' . print_r($pb_backupbuddy_destination_errors, true) . '`.');
                         $delete_fail_count++;
                     }
                 }
             }
             pb_backupbuddy::status('details', 'Finished trimming excess backups.');
             if ($delete_fail_count !== 0) {
                 $error_message = 'Google Drive remote limit could not delete ' . $delete_fail_count . ' backups.';
                 pb_backupbuddy::status('error', $error_message);
                 backupbuddy_core::mail_error($error_message);
             }
         }
         pb_backupbuddy::status('details', 'Google Drive completed archive limiting.');
     } else {
         pb_backupbuddy::status('details', 'No Google Drive archive file limit to enforce.');
     }
     // End remote backup limit
     // Made it this far then success.
     return true;
 }
Beispiel #25
0
 public static function getBackupTypeFromFile($file, $quiet = false)
 {
     if (false === $quiet) {
         pb_backupbuddy::status('details', 'Detecting backup type if possible.');
     }
     // Try to figure out type via filename.
     if (stristr($file, '-db-') !== false) {
         $type = 'db';
     } elseif (stristr($file, '-full-') !== false) {
         $type = 'full';
     } elseif (stristr($file, '-files-') !== false) {
         $type = 'files';
     }
     if (isset($type)) {
         if (false === $quiet) {
             pb_backupbuddy::status('details', 'Detected backup type as `' . $type . '` via filename.');
         }
         return $type;
     }
     // See if we can get backup type from fileoptions data.
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $fileoptionsFile = backupbuddy_core::getLogDirectory() . 'fileoptions/' . backupbuddy_core::get_serial_from_file($file) . '.txt';
     $backup_options = new pb_backupbuddy_fileoptions($fileoptionsFile, $read_only = true, $ignore_lock = true);
     if (true !== ($result = $backup_options->is_ok())) {
         //pb_backupbuddy::status( 'warning', 'Warning only: Unable to open fileoptions file `' . $fileoptionsFile . '`. This may be normal.' );
     } else {
         if (isset($backup_options->options['integrity']['detected_type'])) {
             if (false === $quiet) {
                 pb_backupbuddy::status('details', 'Detected backup type as `' . $backup_options->options['integrity']['detected_type'] . '` via integrity check data.');
             }
             return $backup_options->options['integrity']['detected_type'];
         }
     }
     return '';
     // Type unknown.
 }
Beispiel #26
0
 public static function test($settings)
 {
     if ($settings['address'] == '' || $settings['username'] == '' || $settings['password'] == '') {
         return __('Missing required input.', 'it-l10n-backupbuddy');
     }
     // Try sending a file.
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id = 'TEST-' . pb_backupbuddy::random_string(12));
     // 3rd param true forces clearing of any current uploads.
     if (false === $send_response) {
         $send_response = 'Error sending test file to FTP.';
     } else {
         $send_response = 'Success.';
     }
     // Now we will need to go and cleanup this potentially uploaded file.
     $delete_response = 'Error deleting test file from FTP.';
     // Default.
     // Settings.
     $server = $settings['address'];
     $username = $settings['username'];
     $password = $settings['password'];
     $path = $settings['path'];
     $ftps = $settings['ftps'];
     if ($settings['active_mode'] == '0') {
         $active_mode = false;
     } else {
         $active_mode = true;
     }
     $url = $settings['url'];
     // optional url for using with migration.
     $port = '21';
     if (strstr($server, ':')) {
         $server_params = explode(':', $server);
         $server = $server_params[0];
         $port = $server_params[1];
     }
     // Connect.
     if ($ftps == '0') {
         $conn_id = @ftp_connect($server, $port, 10);
         // timeout of 10 seconds.
         if ($conn_id === false) {
             $error = __('Unable to connect to FTP address `' . $server . '` on port `' . $port . '`.', 'it-l10n-backupbuddy');
             $error .= "\n" . __('Verify the server address and port (default 21). Verify your host allows outgoing FTP connections.', 'it-l10n-backupbuddy');
             return $send_response . ' ' . $error;
         }
     } else {
         if (function_exists('ftp_ssl_connect')) {
             $conn_id = @ftp_ssl_connect($server, $port);
             if ($conn_id === false) {
                 return $send_response . ' ' . __('Destination server does not support FTPS?', 'it-l10n-backupbuddy');
             }
         } else {
             return $send_response . ' ' . __('Your web server doesnt support FTPS.', 'it-l10n-backupbuddy');
         }
     }
     $login_result = @ftp_login($conn_id, $username, $password);
     if (!$conn_id || !$login_result) {
         pb_backupbuddy::status('details', 'FTP test: Invalid user/pass.');
         $response = __('Unable to login. Bad user/pass.', 'it-l10n-backupbuddy');
         if ($ftps != '0') {
             $response .= "\n\nNote: You have FTPs enabled. You may get this error if your host does not support encryption at this address/port.";
         }
         return $send_response . ' ' . $response;
     }
     pb_backupbuddy::status('details', 'FTP test: Success logging in.');
     // Handle active/pasive mode.
     if ($active_mode === true) {
         // do nothing, active is default.
         pb_backupbuddy::status('details', 'Active FTP mode based on settings.');
     } elseif ($active_mode === false) {
         // Turn passive mode on.
         pb_backupbuddy::status('details', 'Passive FTP mode based on settings.');
         ftp_pasv($conn_id, true);
     } else {
         pb_backupbuddy::status('error', 'Unknown FTP active/passive mode: `' . $active_mode . '`.');
     }
     // Delete test file.
     pb_backupbuddy::status('details', 'FTP test: Deleting temp test file.');
     if (true === ftp_delete($conn_id, $path . '/remote-send-test.php')) {
         $delete_response = 'Success.';
     }
     // Close FTP connection.
     pb_backupbuddy::status('details', 'FTP test: Closing FTP connection.');
     @ftp_close($conn_id);
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #12.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.72373. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if ('Success.' != $send_response || 'Success.' != $delete_response) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
Beispiel #27
0
 public static function send($settings = array(), $files = array(), $send_id = '', $delete_after = false)
 {
     global $pb_backupbuddy_destination_errors;
     if ('1' == $settings['disabled']) {
         $pb_backupbuddy_destination_errors[] = __('Error #48933: This destination is currently disabled. Enable it under this destination\'s Advanced Settings.', 'it-l10n-backupbuddy');
         return false;
     }
     if (!is_array($files)) {
         $files = array($files);
     }
     self::$_timeStart = microtime(true);
     if (count($files) > 1) {
         $message = 'Error #84545894585: This destination currently only supports one file per send.';
         pb_backupbuddy::status('error', $message);
         global $pb_backupbuddy_destination_errors;
         $pb_backupbuddy_destination_errors[] = $message;
         return false;
     }
     require_once pb_backupbuddy::plugin_path() . '/classes/remote_api.php';
     $apiSettings = backupbuddy_remote_api::key_to_array($settings['api_key']);
     if (site_url() == $apiSettings['siteurl']) {
         $message = 'Error #4389843. You are trying to use this site\'s own API key. You must use the API key from the remote destination site.';
         pb_backupbuddy::status('error', $message);
         global $pb_backupbuddy_destination_errors;
         $pb_backupbuddy_destination_errors[] = $message;
         return false;
     }
     $apiURL = $apiSettings['siteurl'];
     $file = $files[0];
     $filePath = '';
     if ('' != $settings['sendFilePath']) {
         $filePath = $settings['sendFilePath'];
     }
     $maxPayload = $settings['max_payload'] * 1024 * 1024;
     // Convert to bytes.
     $encodeReducedPayload = floor(($settings['max_payload'] - $settings['max_payload'] * 0.37) * 1024 * 1024);
     // Take into account 37% base64 encoding overhead. Convert to bytes. Remove any decimals down via floor.
     // Open file for reading.
     if (FALSE === ($fs = @fopen($file, 'r'))) {
         pb_backupbuddy::status('error', 'Error #438934894: Unable to open file `' . $file . '` for reading.');
         return false;
     }
     // If chunked resuming then seek to the correct place in the file.
     if ('' != $settings['resume_point'] && $settings['resume_point'] > 0) {
         // Resuming send of a partially transferred file.
         if (0 !== fseek($fs, $settings['resume_point'])) {
             // Returns 0 on success.
             pb_backupbuddy::status('error', 'Error #327834783: Failed to seek file to resume point `' . $settings['resume_point'] . '` via fseek().');
             return false;
         }
         $prevPointer = $settings['resume_point'];
     } else {
         // New file send.
         $size = filesize($file);
         $encodedSize = $size * 0.37 + $size;
         pb_backupbuddy::status('details', 'File size of file to send: ' . pb_backupbuddy::$format->file_size($size) . '. After encoding overhead: ' . pb_backupbuddy::$format->file_size($encodedSize));
         if ($encodedSize > $maxPayload) {
             $settings['chunks_total'] = ceil($encodedSize / $maxPayload);
             // $maxPayload );
             pb_backupbuddy::status('details', 'This file + encoding exceeds the maximum per-chunk payload size so will be read in and sent in chunks of ' . $settings['max_payload'] . 'MB (' . $maxPayload . ' bytes) totaling approximately ' . $settings['chunks_total'] . ' chunks.');
         } else {
             pb_backupbuddy::status('details', 'This file + encoding does not exceed per-chunk payload size of ' . $settings['max_payload'] . 'MB (' . $maxPayload . ' bytes) so sending in one pass.');
         }
         $prevPointer = 0;
     }
     pb_backupbuddy::status('details', 'Reading in `' . $encodeReducedPayload . '` bytes at a time to send.');
     $dataRemains = true;
     //$loopCount = 0;
     //$loopTimeSum = 0; // Used for average send time per chunk.
     while (TRUE === $dataRemains && FALSE !== ($fileData = fread($fs, $encodeReducedPayload))) {
         // Grab one chunk of data at a time.
         pb_backupbuddy::status('details', 'Read in file data.');
         if (feof($fs)) {
             pb_backupbuddy::status('details', 'Read to end of file (feof true). No more chunks left after this send.');
             $dataRemains = false;
         }
         $isFileTest = false;
         if (false !== stristr(basename($file), 'remote-send-test.php')) {
             $isFileTest = true;
             $settings['sendType'] = 'test';
         }
         if (true === $dataRemains) {
             $isFileDone = false;
         } else {
             $isFileDone = true;
         }
         if (!isset($size)) {
             $size = '';
         }
         pb_backupbuddy::status('details', 'Connecting to remote server to send data.');
         $response = backupbuddy_remote_api::remoteCall($apiSettings, 'sendFile_' . $settings['sendType'], array(), $settings['max_time'], $file, $fileData, $prevPointer, $isFileTest, $isFileDone, $size, $filePath);
         unset($fileData);
         // Free up memory.
         $settings['chunks_sent']++;
         if (true === $dataRemains) {
             // More chunks remain.
             pb_backupbuddy::status('details', 'Connection finished sending part ' . $settings['chunks_sent'] . ' of ~' . $settings['chunks_total'] . '.');
         } else {
             // No more chunks remain.
             pb_backupbuddy::status('details', 'Connection finished sending final part ' . $settings['chunks_sent'] . '.');
         }
         if (false === $response) {
             echo implode(', ', backupbuddy_remote_api::getErrors()) . ' ';
             pb_backupbuddy::status('error', 'Errors encountered details: ' . implode(', ', backupbuddy_remote_api::getErrors()));
             global $pb_backupbuddy_destination_errors;
             $pb_backupbuddy_destination_errors[] = backupbuddy_remote_api::getErrors();
             return false;
             //implode( ', ', backupbuddy_remote_api::getErrors() );
         }
         if (FALSE === ($prevPointer = ftell($fs))) {
             pb_backupbuddy::status('error', 'Error #438347844: Unable to get ftell pointer of file handle for passing to prevPointer.');
             @fclose($fs);
             return false;
         } else {
             pb_backupbuddy::status('details', 'File pointer: `' . $prevPointer . '`.');
         }
         if (true === $dataRemains) {
             // More data remains so see if we need to consider chunking to a new PHP process.
             // If we are within X second of reaching maximum PHP runtime then stop here so that it can be picked up in another PHP process...
             if (microtime(true) - self::$_timeStart + self::TIME_WIGGLE_ROOM >= $settings['max_time']) {
                 pb_backupbuddy::status('message', 'Approaching limit of available PHP chunking time of `' . $settings['max_time'] . '` sec. Ran for ' . round(microtime(true) - self::$_timeStart, 3) . ' sec. Proceeding to use chunking.');
                 @fclose($fs);
                 // Tells next chunk where to pick up.
                 $settings['resume_point'] = $prevPointer;
                 // Schedule cron.
                 $cronTime = time();
                 $cronArgs = array($settings, $files, $send_id, $delete_after);
                 $cronHashID = md5($cronTime . serialize($cronArgs));
                 $cronArgs[] = $cronHashID;
                 $schedule_result = backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs);
                 if (true === $schedule_result) {
                     pb_backupbuddy::status('details', 'Next Site chunk step cron event scheduled.');
                 } else {
                     pb_backupbuddy::status('error', 'Next Site chunk step cron even FAILED to be scheduled.');
                 }
                 spawn_cron(time() + 150);
                 // Adds > 60 seconds to get around once per minute cron running limit.
                 update_option('_transient_doing_cron', 0);
                 // Prevent cron-blocking for next item.
                 return array($prevPointer, 'Sent part ' . $settings['chunks_sent'] . ' of ~' . $settings['chunks_total'] . ' parts.');
                 // filepointer location, elapsed time during the import
             } else {
                 // End if.
                 pb_backupbuddy::status('details', 'Not approaching time limit.');
             }
         } else {
             pb_backupbuddy::status('details', 'No more data remains (eg for chunking) so finishing up.');
         }
     }
     // end while data remains in file.
     // Update fileoptions stats.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #20.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.279327. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     $fileoptions['finish_time'] = microtime(true);
     $fileoptions['status'] = 'success';
     $fileoptions['_multipart_status'] = 'Sent all parts.';
     if (isset($uploaded_speed)) {
         $fileoptions['write_speed'] = $uploaded_speed;
     }
     $fileoptions_obj->save();
     unset($fileoptions);
     // Made it this far so completed!
     pb_backupbuddy::status('message', 'Finished sending file. Took ' . round(microtime(true) - self::$_timeStart, 3) . ' seconds this round.');
     pb_backupbuddy::status('deployFileSent', 'File sent.');
     return true;
 }
Beispiel #28
0
 public static function test($settings)
 {
     if (class_exists('CFRuntime')) {
         die('CFRuntime already defined. Another plugin may be incorrectly loading its copy of S3 libraries on BackupBuddy pages.');
     }
     require_once dirname(dirname(__FILE__)) . '/_s3lib/aws-sdk/sdk.class.php';
     $remote_path = self::get_remote_path($settings['directory']);
     // Has leading and trailng slashes.
     $settings['bucket'] = strtolower($settings['bucket']);
     // Buckets must be lowercase.
     /*
     if ( FALSE !== strpos( $settings['bucket'], ' ' ) ) {
     	$message = 'Bucket names cannot have spaces in them.';
     	return $message;
     }
     */
     // Try sending a file.
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id = 'TEST-' . pb_backupbuddy::random_string(12));
     // 3rd param true forces clearing of any current uploads.
     if (false === $send_response) {
         $send_response = 'Error sending test file to S3.';
     } else {
         $send_response = 'Success.';
     }
     // S3 object for managing files.
     $credentials = pb_backupbuddy_destination_s3::get_credentials($settings);
     $s3_manage = new AmazonS3($credentials);
     if ($settings['ssl'] == 0) {
         @$s3_manage->disable_ssl(true);
     }
     // Verify bucket exists; create if not. Also set region to the region bucket exists in.
     if (false === self::_prepareBucketAndRegion($s3_manage, $settings)) {
         return false;
     }
     // Delete sent file.
     $delete_response = 'Success.';
     $delete_response = $s3_manage->delete_object($credentials['bucket'], $remote_path . 'remote-send-test.php');
     if (!$delete_response->isOK()) {
         $delete_response = 'Unable to delete test S3 file `remote-send-test.php`.';
         pb_backupbuddy::status('details', $delete_response . ' Details: `' . print_r($delete_response, true) . '`.');
     } else {
         $delete_response = 'Success.';
     }
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #7.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if ('Success.' != $send_response || 'Success.' != $delete_response) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
Beispiel #29
0
 public static function test($settings)
 {
     $remote_path = self::get_remote_path($settings['directory']);
     // Has leading and trailng slashes.
     $manage_data = pb_backupbuddy_destination_stash::get_manage_data($settings);
     if (!is_array($manage_data['credentials'])) {
         // Credentials were somehow faulty. User changed password after prior page? Unlikely but you never know...
         $error_msg = 'Error #8484383c: Your authentication credentials for Stash failed. Verify your login and password to Stash. You may need to update the Stash destination settings. Perhaps you recently changed your password?';
         pb_backupbuddy::status('error', $error_msg);
         return $error_msg;
     }
     // Try sending a file.
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id = 'TEST-' . pb_backupbuddy::random_string(12));
     // 3rd param true forces clearing of any current uploads.
     if (false === $send_response) {
         $send_response = 'Error sending test file to Stash.';
     } else {
         $send_response = 'Success.';
     }
     // S3 object for managing files.
     $credentials = pb_backupbuddy_destination_stash::get_manage_data($settings);
     $s3_manage = new AmazonS3($manage_data['credentials']);
     if ($settings['ssl'] == 0) {
         @$s3_manage->disable_ssl(true);
     }
     // Delete sent file.
     $delete_response = 'Success.';
     $delete_response = $s3_manage->delete_object($manage_data['bucket'], $manage_data['subkey'] . $remote_path . 'remote-send-test.php');
     if (!$delete_response->isOK()) {
         $delete_response = 'Unable to delete test Stash file `remote-send-test.php`. Details: `' . print_r($response, true) . '`.';
         pb_backupbuddy::status('details', $delete_response);
     } else {
         $delete_response = 'Success.';
     }
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if ('Success.' != $send_response || 'Success.' != $delete_response) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
Beispiel #30
0
 public static function send($destination_settings, $files, $send_id = '')
 {
     if ('' != $send_id) {
         pb_backupbuddy::add_status_serial('remote_send-' . $send_id);
         pb_backupbuddy::status('details', '----- Initiating master send function.');
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         $fileoptions_file = backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt';
         if (!file_exists($fileoptions_file)) {
             pb_backupbuddy::status('details', 'Fileoptions file `' . $fileoptions_file . '` does not exist yet; creating.');
             $fileoptions_obj = new pb_backupbuddy_fileoptions($fileoptions_file, $read_only = false, $ignore_lock = true, $create_file = true);
         } else {
             pb_backupbuddy::status('details', 'Fileoptions file exists; loading.');
             $fileoptions_obj = new pb_backupbuddy_fileoptions($fileoptions_file, $read_only = false, $ignore_lock = false, $create_file = false);
         }
         if (true !== ($result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Fatal Error #9034.2344848. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
             return false;
         }
         pb_backupbuddy::status('details', 'Fileoptions data loaded.');
         $fileoptions =& $fileoptions_obj->options;
         if ('' == $fileoptions) {
             $fileoptions = backupbuddy_core::get_remote_send_defaults();
             $fileoptions['type'] = $destination_settings['type'];
             if (!is_array($files)) {
                 $fileoptions['file'] = $files;
             } else {
                 $fileoptions['file'] = $files[0];
             }
             $fileoptions_obj->save();
         }
         if (isset($fileoptions['status']) && 'aborted' == $fileoptions['status']) {
             pb_backupbuddy::status('warning', 'Destination send triggered on an ABORTED transfer. Ending send function.');
             return false;
         }
         unset($fileoptions_obj);
     }
     if (false === ($destination = self::_init_destination($destination_settings))) {
         echo '{Error #546893498a. Destination configuration file missing.}';
         if ('' != $send_id) {
             pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
         }
         return false;
     }
     $destination_settings = $destination['settings'];
     // Settings with defaults applied, normalized, etc.
     //$destination_info = $destination['info'];
     if (!is_array($files)) {
         $files = array($files);
     }
     $files_with_sizes = '';
     foreach ($files as $index => $file) {
         if ('' == $file) {
             unset($files[$index]);
             continue;
             // Not actually a file to send.
         }
         if (!file_exists($file)) {
             pb_backupbuddy::status('error', 'Error #58459458743. The file that was attempted to be sent to a remote destination, `' . $file . '`, was not found. It either does not exist or permissions prevent accessing it.');
             if ('' != $send_id) {
                 pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
             }
             return false;
         }
         $files_with_sizes .= $file . ' (' . pb_backupbuddy::$format->file_size(filesize($file)) . '); ';
     }
     pb_backupbuddy::status('details', 'Sending files `' . $files_with_sizes . '` to destination type `' . $destination_settings['type'] . '` titled `' . $destination_settings['title'] . '`.');
     unset($files_with_sizes);
     if (!method_exists($destination['class'], 'send')) {
         pb_backupbuddy::status('error', 'Destination class `' . $destination['class'] . '` does not support send operation -- missing function.');
         if ('' != $send_id) {
             pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
         }
         return false;
     }
     pb_backupbuddy::status('details', 'Calling send function.');
     //$result = $destination_class::send( $destination_settings, $files );
     global $pb_backupbuddy_destination_errors;
     $pb_backupbuddy_destination_errors = array();
     $result = call_user_func_array("{$destination['class']}::send", array($destination_settings, $files, $send_id));
     if ($result === false) {
         $error_details = implode('; ', $pb_backupbuddy_destination_errors);
         backupbuddy_core::mail_error('There was an error sending to the remote destination. One or more files may have not been fully transferred. Please see error details for additional information. If the error persists, enable full error logging and try again for full details and troubleshooting. Details: ' . "\n\n" . $error_details);
     }
     if (is_array($result)) {
         // Send is multipart.
         pb_backupbuddy::status('details', 'Completed send function. Multipart chunk mode. Result: `' . print_r($result, true) . '`.');
         if ('' != $send_id) {
             pb_backupbuddy::status('details', 'About to load fileoptions data.');
             require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
             $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
             if (true !== ($fileoptions_result = $fileoptions_obj->is_ok())) {
                 pb_backupbuddy::status('error', __('Fatal Error #9034.387462. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $fileoptions_result);
                 return false;
             }
             pb_backupbuddy::status('details', 'Fileoptions data loaded.');
             $fileoptions =& $fileoptions_obj->options;
             $fileoptions['_multipart_status'] = $result[1];
             pb_backupbuddy::status('details', 'Destination debugging details: `' . print_r($fileoptions, true) . '`.');
             $fileoptions_obj->save();
             unset($fileoptions_obj);
             pb_backupbuddy::status('details', 'Next multipart chunk will be sent shortly...');
         }
     } else {
         // Single all-at-once send.
         pb_backupbuddy::status('details', 'Completed send function. Result: `' . $result . '`.');
     }
     if ('' != $send_id) {
         pb_backupbuddy::remove_status_serial('remote_send-' . $send_id);
     }
     return $result;
 }