Пример #1
0
 function stats()
 {
     echo '<style type="text/css">';
     echo '	.pb_fancy {';
     echo '		font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif;';
     echo '		font-size: 18px;';
     echo '		color: #21759B;';
     echo '	}';
     echo '</style>';
     echo '<div>';
     $backup_url = 'admin.php?page=pb_backupbuddy_backup';
     $files = glob(backupbuddy_core::getBackupDirectory() . 'backup*.zip');
     if (!is_array($files) || empty($files)) {
         $files = array();
     }
     echo sprintf(__('You currently have %s stored backups.', 'it-l10n-backupbuddy'), '<span class="pb_fancy"><a href="' . $backup_url . '">' . count($files) . '</a></span>');
     if (pb_backupbuddy::$options['last_backup_finish'] == 0) {
         echo ' ', __('You have not successfully created any backups.', 'it-l10n-backupbuddy');
     } else {
         echo ' ', sprintf(__(' Your most recent successful backup was %s ago.', 'it-l10n-backupbuddy'), '<span class="pb_fancy"><a href="' . $backup_url . '">' . pb_backupbuddy::$format->time_ago(pb_backupbuddy::$options['last_backup_finish']) . '</a></span>');
     }
     echo ' ', sprintf(__('There have been %s post/page modifications since your last backup.', 'it-l10n-backupbuddy'), '<span class="pb_fancy"><a href="' . $backup_url . '">' . pb_backupbuddy::$options['edits_since_last'] . '</a></span>');
     echo ' <span class="pb_fancy"><a href="' . $backup_url . '">', __('Go create a backup!', 'it-l10n-backupbuddy'), '</a></span>';
     echo '</div>';
 }
Пример #2
0
 public static function test($settings)
 {
     $email = $settings['address'];
     pb_backupbuddy::status('details', 'Testing email destination. Sending ImportBuddy.php.');
     $importbuddy_temp = backupbuddy_core::getTempDirectory() . 'importbuddy_' . pb_backupbuddy::random_string(10) . '.php.tmp';
     // Full path & filename to temporary importbuddy
     backupbuddy_core::importbuddy($importbuddy_temp);
     // Create temporary importbuddy.
     $files = array($importbuddy_temp);
     if (pb_backupbuddy::$options['email_return'] != '') {
         $email_return = pb_backupbuddy::$options['email_return'];
     } else {
         $email_return = get_option('admin_email');
     }
     $headers = 'From: BackupBuddy <' . $email_return . '>' . "\r\n";
     $wp_mail_result = wp_mail($email, 'BackupBuddy Test', 'BackupBuddy destination test for ' . site_url(), $headers, $files);
     pb_backupbuddy::status('details', 'Sent test email.');
     @unlink($importbuddy_temp);
     if ($wp_mail_result === true) {
         // WP sent. Hopefully it makes it!
         return true;
     } else {
         // WP couldn't try to send.
         echo 'WordPress was unable to attempt to send email. Check your WordPress & server settings.';
         return false;
     }
 }
Пример #3
0
 public function generate_queue($root = '', $generate_sha1 = true)
 {
     if ($root == '') {
         $root = backupbuddy_core::getLogDirectory();
     }
     echo 'mem:' . memory_get_usage(true) . '<br>';
     $files = (array) pb_backupbuddy::$filesystem->deepglob($root);
     echo 'mem:' . memory_get_usage(true) . '<br>';
     $root_len = strlen($root);
     $new_files = array();
     foreach ($files as $file_id => &$file) {
         $stat = stat($file);
         if (FALSE === $stat) {
             pb_backupbuddy::status('error', 'Unable to read file `' . $file . '` stat.');
         }
         $new_file = substr($file, $root_len);
         $sha1 = '';
         if (true === $generate_sha1 && $stat['size'] < 1073741824) {
             // < 100mb
             $sha1 = sha1_file($file);
         }
         $new_files[$new_file] = array('scanned' => time(), 'size' => $stat['size'], 'modified' => $stat['mtime'], 'sha1' => $sha1);
         unset($files[$file_id]);
         // Better to free memory or leave out for performance?
     }
     unset($files);
     echo 'mem:' . memory_get_usage(true) . '<br>';
     function pb_queuearray_size_compare($a, $b)
     {
         return $a['size'] > $b['size'];
     }
     uasort($new_files, 'pb_queuearray_size_compare');
     echo '<pre>';
     print_r($new_files);
     echo '</pre>';
     // fileoptions file live_signatures.txt
     //backupbuddy_core::st_stable_options( 'xxx', 'test', 5 );
     // get file listing of site: glob and store in an array
     // open previously generated master list (master file listing since last queue generation).
     // loop through and compare file specs to specs in master list. ( anything changed AND not yet in queue AND not maxed out send attempts ) gets added into $queue_files[];
     // add master file to end of list so it will be backed up as soon files are finished sending. to keep it up to date.
     // sort list smallest to largest
     // store in $queue_files[] in format:
     /*
     	array(
     		'size'		=>	434344,
     		'attempts'	=>	0,
     		
     	);
     */
     // open current queue file (if exists)
     // combine new files into queue
     // serialize $queue_files
     // base64 encode
     // write to queue file
     pb_backupbuddy::status('details', '12 new or modified files added into Stash queue.');
     // Schedule process_queue() to run in 30 seconds from now _IF_ not already scheduled to run.
 }
 public function run($arguments)
 {
     $arguments = Ithemes_Sync_Functions::merge_defaults($arguments, $this->default_arguments);
     pb_backupbuddy::$options['remote_destinations'][] = $arguments['settings'];
     pb_backupbuddy::save();
     $newDestination = array();
     $newDestination['title'] = $arguments['settings']['title'];
     $newDestination['type'] = $arguments['settings']['type'];
     backupbuddy_core::addNotification('destination_created', 'Remote destination created', 'A new remote destination "' . $newDestination['title'] . '" has been created.', $newDestination);
     $highest_destination_index = end(array_keys(pb_backupbuddy::$options['remote_destinations']));
     return array('api' => '1', 'status' => 'ok', 'message' => 'Destination added.', 'destination_id' => $highest_destination_index);
 }
Пример #5
0
function bb_build_remote_destinations($destinations_list)
{
    $remote_destinations = explode('|', $destinations_list);
    $remote_destinations_html = '';
    foreach ($remote_destinations as $destination) {
        if (isset($destination) && $destination != '') {
            $remote_destinations_html .= '<li id="pb_remotedestination_' . $destination . '">';
            if (!isset(pb_backupbuddy::$options['remote_destinations'][$destination])) {
                $remote_destinations_html .= '{destination no longer exists}';
            } else {
                $remote_destinations_html .= pb_backupbuddy::$options['remote_destinations'][$destination]['title'];
                $remote_destinations_html .= ' (' . backupbuddy_core::pretty_destination_type(pb_backupbuddy::$options['remote_destinations'][$destination]['type']) . ') ';
            }
            $remote_destinations_html .= '<img class="pb_remotedestionation_delete" src="' . pb_backupbuddy::plugin_url() . '/images/redminus.png" style="vertical-align: -3px; cursor: pointer;" title="' . __('Remove remote destination from this schedule.', 'it-l10n-backupbuddy') . '" />';
            $remote_destinations_html .= '</li>';
        }
    }
    $remote_destinations = '<ul id="pb_backupbuddy_remotedestinations_list">' . $remote_destinations_html . '</ul>';
    return $remote_destinations;
}
Пример #6
0
function shutdown_function()
{
    // Get error message.
    // Error types: http://php.net/manual/en/errorfunc.constants.php
    $e = error_get_last();
    if ($e === NULL) {
        // No error of any kind.
        return;
    } else {
        // Some type of error.
        if (!is_array($e) || $e['type'] != E_ERROR && $e['type'] != E_USER_ERROR) {
            // Return if not a fatal error.
            //echo '<!-- ' . print_r( $e, true ) . ' -->' . "\n";
            return;
        }
    }
    // Calculate log directory.
    $log_directory = backupbuddy_core::getLogDirectory();
    // Also handle when in importbuddy.
    $main_file = $log_directory . 'log-' . pb_backupbuddy::$options['log_serial'] . '.txt';
    // Determine if writing to a serial log.
    if (pb_backupbuddy::$_status_serial != '') {
        $serial = pb_backupbuddy::$_status_serial;
        $serial_file = $log_directory . 'status-' . $serial . '_' . pb_backupbuddy::$options['log_serial'] . '.txt';
        $write_serial = true;
    } else {
        $write_serial = false;
    }
    // Format error message.
    $e_string = '----- FATAL ERROR ----- A fatal PHP error was encountered: ';
    foreach ((array) $e as $e_line_title => $e_line) {
        $e_string .= $e_line_title . ' => ' . $e_line . "; ";
    }
    $e_string = rtrim($e_string, '; ') . '.';
    // Write to log.
    @file_put_contents($main_file, $e_string, FILE_APPEND);
    // IMPORTBUDDY
    $status = pb_backupbuddy::$format->date(time()) . "\t" . sprintf("%01.2f", round(microtime(true) - pb_backupbuddy::$start_time, 2)) . "\t" . sprintf("%01.2f", round(memory_get_peak_usage() / 1048576, 2)) . "\t" . 'error' . "\t\t" . str_replace(chr(9), '   ', $e_string);
    $status = str_replace('\\', '/', $status);
    echo '<script type="text/javascript">pb_status_append("' . str_replace('"', '&quot;', $status) . '");</script>';
}
 public function run($arguments)
 {
     $arguments = Ithemes_Sync_Functions::merge_defaults($arguments, $this->default_arguments);
     if ('' == $arguments['password']) {
         // no password send in arguments.
         if (!isset(pb_backupbuddy::$options)) {
             pb_backupbuddy::load();
         }
         if ('' == pb_backupbuddy::$options['importbuddy_pass_hash']) {
             // no default password is set on Settings page.
             return array('api' => '0', 'status' => 'error', 'message' => 'No ImportBuddy password was entered and no default has been set on the Settings page.');
         } else {
             // Use default.
             $importbuddy_pass_hash = pb_backupbuddy::$options['importbuddy_pass_hash'];
         }
     } else {
         // Password passed in arguments.
         $importbuddy_pass_hash = md5($arguments['password']);
     }
     require_once pb_backupbuddy::plugin_path() . '/classes/core.php';
     return array('api' => '4', 'status' => 'ok', 'message' => 'ImportBuddy retrieved.', 'importbuddy' => base64_encode(backupbuddy_core::importbuddy('', $importbuddy_pass_hash, $returnNotEcho = true)));
 }
Пример #8
0
/**
 *	get_archives_list()
 *
 *	Returns an array of backup archive zip filenames found.
 *
 *	@return		array		Array of .zip filenames; path NOT included.
 */
function get_archives_list()
{
    Auth::require_authentication();
    if (!isset(pb_backupbuddy::$classes['zipbuddy'])) {
        require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
        pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy(ABSPATH);
    }
    // List backup files in this directory.
    $backup_archives = array();
    $backup_archives_glob = glob(ABSPATH . 'backup*.zip');
    if (!is_array($backup_archives_glob) || empty($backup_archives_glob)) {
        // On failure glob() returns false or an empty array depending on server settings so normalize here.
        $backup_archives_glob = array();
    }
    foreach ($backup_archives_glob as $backup_archive) {
        $comment = pb_backupbuddy::$classes['zipbuddy']->get_comment($backup_archive);
        $comment = backupbuddy_core::normalize_comment_data($comment);
        $this_archive = array('file' => basename($backup_archive), 'comment' => $comment);
        $backup_archives[] = $this_archive;
    }
    unset($backup_archives_glob);
    return $backup_archives;
}
Пример #9
0
 /**
  *	wipePrefix()
  *
  *	Clear out tables matching supplied prefix.
  *
  *	@return			boolean		Currently always true.
  */
 function wipePrefix($prefix, $confirm = false)
 {
     if ($confirm !== true) {
         die('Error #5466566b: Parameter 2 to wipePrefix() must be boolean true to proceed.');
     }
     if ($prefix == '') {
         pb_backupbuddy::status('warning', 'No database prefix specified to wipe.');
         return false;
     }
     pb_backupbuddy::status('message', 'Beginning wipe of database tables matching prefix `' . $prefix . '`...');
     // Connect to database.
     //$this->connect_database();
     global $wpdb;
     $rows = $wpdb->get_results("SELECT table_name FROM information_schema.tables WHERE table_name LIKE '" . backupbuddy_core::dbEscape(str_replace('_', '\\_', $prefix)) . "%' AND table_schema = DATABASE()", ARRAY_A);
     $table_wipe_count = count($rows);
     foreach ($rows as $row) {
         pb_backupbuddy::status('details', 'Dropping table `' . $row['table_name'] . '`.');
         $wpdb->query('DROP TABLE `' . $row['table_name'] . '`');
     }
     unset($rows);
     pb_backupbuddy::status('message', 'Wiped database of ' . $table_wipe_count . ' tables.');
     return true;
 }
Пример #10
0
 private function _priorRollbackCleanup()
 {
     $this->_before(__FUNCTION__);
     pb_backupbuddy::status('details', 'Checking for any prior failed rollback data to clean up.');
     global $wpdb;
     $shortSerial = substr($this->_state['serial'], 0, 4);
     // NEW prefix
     $sql = "SELECT table_name FROM information_schema.tables WHERE table_name LIKE 'BBnew-" . $shortSerial . "\\_%' AND table_schema = DATABASE()";
     $results = $wpdb->get_results($sql, ARRAY_A);
     pb_backupbuddy::status('details', 'Found ' . count($results) . ' tables to drop with the prefix `BBnew-' . $shortSerial . '_`.');
     $dropCount = 0;
     foreach ($results as $result) {
         if (false === $wpdb->query("DROP TABLE `" . backupbuddy_core::dbEscape($result['table_name']) . "`")) {
             $this->_error('Unable to delete table `' . $result['table_name'] . '`.');
         } else {
             $dropCount++;
         }
     }
     pb_backupbuddy::status('details', 'Dropped `' . $dropCount . '` new tables.');
     // OLD prefix
     $sql = "SELECT table_name FROM information_schema.tables WHERE table_name LIKE 'BBold-" . $shortSerial . "\\_%' AND table_schema = DATABASE()";
     $results = $wpdb->get_results($sql, ARRAY_A);
     pb_backupbuddy::status('details', 'Found ' . count($results) . ' tables to drop with the prefix `BBold-' . $shortSerial . '_`.');
     $dropCount = 0;
     foreach ($results as $result) {
         if (false === $wpdb->query("DROP TABLE `" . backupbuddy_core::dbEscape($result['table_name']) . "`")) {
             $this->_error('Unable to delete table `' . $result['table_name'] . '`.');
         } else {
             $dropCount++;
         }
     }
     pb_backupbuddy::status('details', 'Dropped `' . $dropCount . '` old tables.');
     pb_backupbuddy::status('details', 'Finished prior rollback cleanup.');
 }
Пример #11
0
// Register BackupBuddy API. As of BackupBuddy v5.0. Access credentials will be checked within callback.
add_action('wp_ajax_backupbuddy_api', array(pb_backupbuddy::$_ajax, 'api'));
add_action('wp_ajax_nopriv_backupbuddy_api', array(pb_backupbuddy::$_ajax, 'api'));
/********** DASHBOARD (admin) **********/
// Display stats in Dashboard.
//if ( pb_backupbuddy::$options['dashboard_stats'] == '1' ) {
if (!is_multisite() || is_multisite() && is_network_admin()) {
    // Only show if standalon OR in main network admin.
    pb_backupbuddy::add_dashboard_widget('stats', 'BackupBuddy v' . pb_backupbuddy::settings('version'), 'godmode');
}
//}
/********** FILTERS (admin) **********/
pb_backupbuddy::add_filter('plugin_row_meta', 10, 2);
/********** PAGES (admin) **********/
$icon = '';
if (is_multisite() && backupbuddy_core::is_network_activated() && !defined('PB_DEMO_MODE')) {
    // Multisite installation.
    if (defined('PB_BACKUPBUDDY_MULTISITE_EXPERIMENT') && PB_BACKUPBUDDY_MULTISITE_EXPERIMENT == TRUE) {
        // comparing with bool but loose so string is acceptable.
        if (is_network_admin()) {
            // Network Admin pages
            pb_backupbuddy::add_page('', 'backup', array(pb_backupbuddy::settings('name'), __('Backup', 'it-l10n-backupbuddy')), 'manage_network', $icon);
            pb_backupbuddy::add_page('backup', 'migrate_restore', __('Migrate, Restore', 'it-l10n-backupbuddy'), 'manage_network');
            pb_backupbuddy::add_page('backup', 'destinations', __('Remote Destinations', 'it-l10n-backupbuddy'), pb_backupbuddy::$options['role_access']);
            pb_backupbuddy::add_page('backup', 'multisite_import', __('MS Import (beta)', 'it-l10n-backupbuddy'), 'manage_network');
            pb_backupbuddy::add_page('backup', 'server_tools', __('Server Tools', 'it-l10n-backupbuddy'), 'manage_network');
            pb_backupbuddy::add_page('backup', 'malware_scan', __('Malware Scan', 'it-l10n-backupbuddy'), 'manage_network');
            pb_backupbuddy::add_page('backup', 'scheduling', __('Schedules', 'it-l10n-backupbuddy'), 'manage_network');
            pb_backupbuddy::add_page('backup', 'settings', __('Settings', 'it-l10n-backupbuddy'), 'manage_network');
        } else {
            // Subsite pages.
Пример #12
0
<?php

backupbuddy_core::verifyAjaxAccess();
// Note: importbuddy, backup files, etc should have already been cleaned up by importbuddy itself at this point.
$serial = pb_backupbuddy::_POST('serial');
$direction = pb_backupbuddy::_POST('direction');
pb_backupbuddy::load();
if ('pull' == $direction) {
    // Local so clean up here.
    backupbuddy_core::cleanup_temp_tables($serial);
    die('1');
} elseif ('push' == $direction) {
    // Remote so call API to clean up.
    require_once pb_backupbuddy::plugin_path() . '/classes/remote_api.php';
    $destinationID = pb_backupbuddy::_POST('destinationID');
    if (!isset(pb_backupbuddy::$options['remote_destinations'][$destinationID])) {
        die('Error #8383983: Invalid destination ID `' . htmlentities($destinationID) . '`.');
    }
    $destinationArray = pb_backupbuddy::$options['remote_destinations'][$destinationID];
    if ('site' != $destinationArray['type']) {
        die('Error #8378332: Destination with ID `' . htmlentities($destinationID) . '` not of "site" type.');
    }
    $apiKey = $destinationArray['api_key'];
    $apiSettings = backupbuddy_remote_api::key_to_array($apiKey);
    if (false === ($response = backupbuddy_remote_api::remoteCall($apiSettings, 'confirmDeployment', array('serial' => $serial), 10, null, null, null, null, null, null, null, $returnRaw = true))) {
        $message = 'Error #2378378324. Unable to confirm remote deployment with serial `' . $serial . '` via remote API.';
        pb_backupbuddy::status('error', $message);
        die($message);
    } else {
        if (false === ($response = json_decode($response, true))) {
            $message = 'Error #239872373. Unable to decode remote deployment response with serial `' . $serial . '` via remote API. Remote server response: `' . print_r($response) . '`.';
Пример #13
0
            // End foreach.
            unset($item);
            unset($item_name);
        }
        // End foreach.
        unset($event);
        unset($hook_name);
    }
    // End if is_numeric.
}
// End foreach.
unset($cron_item);
unset($time);
// Cleanup any old notifications.
$notifications = backupbuddy_core::getNotifications();
// Load notifications.
$updateNotifications = false;
$maxTimeDiff = pb_backupbuddy::$options['max_notifications_age_days'] * 24 * 60 * 60;
foreach ($notifications as $i => $notification) {
    if (time() - $notification['time'] > $maxTimeDiff) {
        unset($notifications[$i]);
        $updateNotifications = true;
    }
}
if (true === $updateNotifications) {
    pb_backupbuddy::status('details', 'Periodic cleanup: Replacing notifications.');
    backupbuddy_core::replaceNotifications($notifications);
}
@clearstatcache();
// Clears file info stat cache.
pb_backupbuddy::status('message', 'Finished cleanup procedure.');
		if( jQuery( '#' + target_id ).length == 0 ) { // No status box yet so suppress.
			return;
		}
		jQuery( '#' + target_id ).append( "\n" + message );
		textareaelem = document.getElementById( target_id );
		textareaelem.scrollTop = textareaelem.scrollHeight;
	}
	
	function backupbuddy_hourpad(n) { return ("0" + n).slice(-2); }
</script>
<?php 
$success = false;
global $pb_backupbuddy_js_status;
$pb_backupbuddy_js_status = true;
echo pb_backupbuddy::status_box('Restoring . . .');
echo '<div id="pb_backupbuddy_working" style="width: 100px;"><br><center><img src="' . pb_backupbuddy::plugin_url() . '/images/working.gif" title="Working... Please wait as this may take a moment..."></center></div>';
pb_backupbuddy::set_status_serial('restore');
global $wp_version;
pb_backupbuddy::status('details', 'BackupBuddy v' . pb_backupbuddy::settings('version') . ' using WordPress v' . $wp_version . ' on ' . PHP_OS . '.');
$archive_file = pb_backupbuddy::_GET('archive');
// archive to extract from.
require pb_backupbuddy::plugin_path() . '/classes/_restoreFiles.php';
$result = backupbuddy_restore_files::restore(backupbuddy_core::getBackupDirectory() . $archive_file, $files, $finalPath = ABSPATH);
echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
pb_backupbuddy::flush();
if (false === $result) {
} else {
}
pb_backupbuddy::$ui->ajax_footer();
pb_backupbuddy::$ui->ajax_footer();
die;
Пример #15
0
 /**
  *	pluginbuddy_filesystem->deepglob()
  *
  *	Like the glob() function except walks down into paths to create a full listing of all results in the directory and all subdirectories.
  *	This is essentially a recursive glob() although it does not use recursion to perform this.
  *
  *	@param		string		$dir		Path to pass to glob and walk through.
  *	@param		array 		$excludes	Array of directories to exclude, relative to the $dir.  Include beginning slash.
  *	@return		array					Returns array of all matches found.
  */
 function deepglob($dir, $excludes = array())
 {
     $dir = rtrim($dir, '/\\');
     // Make sure no trailing slash.
     $excludes = str_replace($dir, '', $excludes);
     $dir_len = strlen($dir);
     $items = glob($dir . '/*');
     if (false === $items) {
         $items = array();
     }
     for ($i = 0; $i < count($items); $i++) {
         // If this file/directory begins with an exclusion then jump to next file/directory.
         foreach ($excludes as $exclude) {
             if (backupbuddy_core::startsWith(substr($items[$i], $dir_len), $exclude)) {
                 unset($items[$i]);
                 continue 2;
             }
         }
         if (is_dir($items[$i])) {
             $add = glob($items[$i] . '/*');
             if (false === $add) {
                 $add = array();
             }
             $items = array_merge($items, $add);
         }
     }
     return $items;
 }
Пример #16
0
    echo esc_attr($i);
    ?>
'><?php 
    echo esc_html(basename($file));
    ?>
</label><br />
			<?php 
}
if (count($files) == 0) {
    _e('No BackupBuddy backups found in the root directory of the site.', 'it-l10n-backupbuddy');
    echo '<br>';
}
echo '<br>';
echo 'Existing backups in this site\'s backup directory:';
echo '<br>';
$files = glob(backupbuddy_core::getBackupDirectory() . 'backup*.zip');
if (!is_array($files) || empty($files)) {
    $files = array();
}
foreach ($files as $i => $file) {
    ?>
			<input style="width: auto;" type='radio' id='backup_<?php 
    echo esc_attr($i);
    ?>
' value='<?php 
    echo esc_attr($file);
    ?>
'
			<?php 
    if (count($files) == 1) {
        echo ' CHECKED';
Пример #17
0
// Change slashes to handle Windows as we store backup_directory with Linux-style slashes even on Windows.
$backup_dir = str_replace('\\', '/', backupbuddy_core::getBackupDirectory());
// Make sure file to download is in a publicly accessible location (beneath WP web root technically).
if (FALSE === stristr($backup_dir, $abspath)) {
    die('Error #5432532. You cannot download backups stored outside of the WordPress web root. Please use FTP or other means.');
}
// Made it this far so download dir is within this WP install.
$sitepath = str_replace($abspath, '', $backup_dir);
$download_url = rtrim(site_url(), '/\\') . '/' . trim($sitepath, '/\\') . '/' . pb_backupbuddy::_GET('backupbuddy_backup');
if (pb_backupbuddy::$options['lock_archives_directory'] == '1') {
    // High security mode.
    if (file_exists(backupbuddy_core::getBackupDirectory() . '.htaccess')) {
        $unlink_status = @unlink(backupbuddy_core::getBackupDirectory() . '.htaccess');
        if ($unlink_status === false) {
            die('Error #844594. Unable to temporarily remove .htaccess security protection on archives directory to allow downloading. Please verify permissions of the BackupBuddy archives directory or manually download via FTP.');
        }
    }
    header('Location: ' . $download_url);
    ob_clean();
    flush();
    sleep(8);
    // Wait 8 seconds before creating security file.
    $htaccess_creation_status = @file_put_contents(backupbuddy_core::getBackupDirectory() . '.htaccess', 'deny from all');
    if ($htaccess_creation_status === false) {
        die('Error #344894545. Security Warning! Unable to create security file (.htaccess) in backups archive directory. This file prevents unauthorized downloading of backups should someone be able to guess the backup location and filenames. This is unlikely but for best security should be in place. Please verify permissions on the backups directory.');
    }
} else {
    // Normal mode.
    header('Location: ' . $download_url);
}
die;
<?php

backupbuddy_core::verifyAjaxAccess();
pb_backupbuddy::load();
if (false === ($results = backupbuddy_core::php_memory_test_results())) {
    $tested_memory_sofar = '';
    $test_file = backupbuddy_core::getLogDirectory() . 'php_memory_test.txt';
    if (file_exists($test_file)) {
        if (false !== ($tested_memory = @file_get_contents($test_file))) {
            if (is_numeric(trim($tested_memory))) {
                $tested_memory_sofar = ' ' . $tested_memory . ' ' . __('MB so far.', 'it-l10n-backupbuddy');
            }
        }
    }
    die(__('This may take a few minutes...', 'it-l10n-backupbuddy') . $tested_memory_sofar);
} else {
    die($results);
}
Пример #19
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;
 }
Пример #20
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;
 }
Пример #21
0
<?php

backupbuddy_core::versions_confirm();
pb_backupbuddy::load_script('jquery');
Пример #22
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;
 }
<?php

// Incoming variables: $backups generated via core.php backups_list() function.
// $listing_mode should be either:  default,  migrate
$hover_actions = array();
// If download URL is within site root then allow downloading via web.
$backup_directory = backupbuddy_core::getBackupDirectory();
// Normalize for Windows paths.
$backup_directory = str_replace('\\', '/', $backup_directory);
$backup_directory = rtrim($backup_directory, '/\\') . '/';
// Enforce single trailing slash.
if ($listing_mode != 'restore_files' && FALSE !== stristr($backup_directory, ABSPATH)) {
    $hover_actions[pb_backupbuddy::ajax_url('download_archive') . '&backupbuddy_backup='] = __('Download', 'it-l10n-backupbuddy');
}
if ($listing_mode == 'restore_files') {
    $hover_actions[pb_backupbuddy::ajax_url('download_archive') . '&zip_viewer='] = __('Browse & Restore Files', 'it-l10n-backupbuddy');
    $hover_actions['note'] = __('Note', 'it-l10n-backupbuddy');
    $bulk_actions = array();
}
if ($listing_mode == 'default') {
    $hover_actions['send'] = __('Send', 'it-l10n-backupbuddy');
    $hover_actions['zip_viewer'] = __('Browse & Restore Files', 'it-l10n-backupbuddy');
    $hover_actions['note'] = __('Note', 'it-l10n-backupbuddy');
    $hover_actions['hash'] = __('Checksum', 'it-l10n-backupbuddy');
    $bulk_actions = array('delete_backup' => __('Delete', 'it-l10n-backupbuddy'));
}
if ($listing_mode == 'migrate') {
    $hover_actions['migrate'] = __('Migrate', 'it-l10n-backupbuddy');
    $hover_actions[pb_backupbuddy::ajax_url('download_archive') . '&backupbuddy_backup='] = __('Download', 'it-l10n-backupbuddy');
    $hover_actions['note'] = __('Note', 'it-l10n-backupbuddy');
    $bulk_actions = array();
Пример #24
0
            pb_backupbuddy::alert('Error: Unable to delete `' . $item . '`. Verify permissions.');
        }
    }
    if (count($deleted_files) > 0) {
        pb_backupbuddy::alert('Deleted ' . implode(', ', $deleted_files) . '.');
        delete_transient('pb_backupbuddy_stashquota_' . $itxapi_username);
        // Delete quota transient since it probably has changed now.
    }
    echo '<br>';
}
// Handle copying files to local
if (pb_backupbuddy::_GET('cpy_file') != '') {
    pb_backupbuddy::alert('The remote file is now being copied to your local backups. If the backup gets marked as bad during copying, please wait a bit then click the `Refresh` icon to rescan after the transfer is complete.');
    echo '<br>';
    pb_backupbuddy::status('details', 'Scheduling Cron for creating Stash copy.');
    backupbuddy_core::schedule_single_event(time(), 'process_remote_copy', array('stash', pb_backupbuddy::_GET('cpy_file'), $settings));
    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.
}
// Handle download link
if (pb_backupbuddy::_GET('downloadlink_file') != '') {
    $link = $s3->get_object($manage_data['bucket'], $manage_data['subkey'] . $remote_path . pb_backupbuddy::_GET('downloadlink_file'), array('preauth' => time() + 3600));
    pb_backupbuddy::alert('You may download this backup (' . pb_backupbuddy::_GET('downloadlink_file') . ') with <a href="' . $link . '">this link</a>. The link is valid for one hour.');
    echo '<br>';
}
// QUOTA INFORMATION.
$account_info = pb_backupbuddy_destination_stash::get_quota(array('itxapi_username' => $itxapi_username, 'itxapi_password' => $itxapi_password), false);
/*
echo '<pre>';
Пример #25
0
pb_backupbuddy::$ui->title(__('Deploy Database', 'it-l10n-backupbuddy') . ' &nbsp;&nbsp; <a style="font-size: 0.6em;" href="#" onClick="jQuery(\'#pb_backupbuddy_status_wrap\').toggle();">Display Status Log</a>');
if (!defined('BACKUPBUDDY_API_ENABLE') || TRUE != BACKUPBUDDY_API_ENABLE) {
    pb_backupbuddy::alert("Make sure the following is in your wp-config.php file on this server:<br><textarea style='width: 100%;' disabled='disabled'>define( 'BACKUPBUDDY_API_ENABLE', true ); // Requires API key to access.</textarea>");
    return false;
}
/*
if ( ! defined( 'BACKUPBUDDY_API_SALT' ) || ( 'CHANGEME' == BACKUPBUDDY_API_SALT ) || ( strlen( BACKUPBUDDY_API_SALT ) < 5 ) ) {
	pb_backupbuddy::alert( "Make sure the following is in your wp-config.php file on this server:<br><textarea style='width: 100%;' disabled='disabled'>define( 'BACKUPBUDDY_API_SALT', 'CHANGEME' ); // !!! IMPORTANT !!! Change CHANGEME to the left to a unique password/phrase for generating API keys. 5+ characters.</textarea>" );
	return false;
}
*/
if ('1' == pb_backupbuddy::_POST('regenerate_api_key')) {
    pb_backupbuddy::verify_nonce();
    // Security check.
    pb_backupbuddy::$options['api_key'] = backupbuddy_core::generate_api_key();
    pb_backupbuddy::save();
}
?>

<b>Note:</b> wp-config.php files as well as BackupBuddy settings will NOT be transferred in either direction. Your current BackupBuddy settings, destinations, API keys etc. will remain as they are on both sites.<br><br>

<form method="post">
	<?php 
pb_backupbuddy::nonce();
?>
	<input type="hidden" name="regenerate_api_key" value="1">
	<button class="button secondary-button" onClick="jQuery('.backupbuddy_api_key-hide').toggle(); return false;">Show API Key</button><span class="backupbuddy_api_key-hide" style="display: none;">&nbsp;&nbsp;<input type="submit" name="submit" value="Generate New API Key" class="button button-primary"></span>
	<br>
	<br>
	<div class="backupbuddy_api_key-hide" style="display: none;">
// If temp directory is within webroot then lock it down.
$temp_dir = str_replace('\\', '/', $temp_dir);
// Normalize for Windows.
$temp_dir = rtrim($temp_dir, '/\\') . '/';
// Enforce single trailing slash.
if (FALSE !== stristr($temp_dir, ABSPATH)) {
    // Temp dir is within webroot.
    pb_backupbuddy::anti_directory_browsing($destination);
}
unset($temp_dir);
$message = 'Extracting "' . $file . '" from archive "' . $archive_file . '" into temporary file "' . $destination . '". ';
echo '<!-- ';
pb_backupbuddy::status('details', $message);
echo $message;
$extractions = array($file => $temp_file);
$extract_result = $zipbuddy->extract(backupbuddy_core::getBackupDirectory() . $archive_file, $destination, $extractions);
if (false === $extract_result) {
    // failed.
    echo ' -->';
    $error = 'Error #584984458. Unable to extract.';
    pb_backupbuddy::status('error', $error);
    die($error);
} else {
    // success.
    _e('Success.', 'it-l10n-backupbuddy');
    echo ' -->';
    ?>
	<textarea readonly="readonly" wrap="off" style="width: 100%; min-height: 175px; height: 100%; margin: 0;"><?php 
    echo file_get_contents($destination . '/' . $temp_file);
    ?>
</textarea>
Пример #27
0
 private function _dump_php($output_directory, $tables, $resume_starting_row = 0)
 {
     //, $base_dump_mode, $additional_excludes ) {
     $this->time_start = microtime(true);
     $last_file_size_output = microtime(true);
     $output_file_size_every_max = 5;
     // Output current SQL file size no more often than this. Only checks if it has been enough time once each burst of max rows per select is processed.
     $max_rows_per_select = $this->_max_rows_per_select;
     if ($resume_starting_row > 0) {
         pb_backupbuddy::status('details', 'Resuming chunked dump at row `' . $resume_starting_row . '`.');
     }
     global $wpdb;
     if (!is_object($wpdb)) {
         pb_backupbuddy::status('error', 'WordPress database object $wpdb did not exist. This should not happen.');
         error_log('WordPress database object $wpdb did not exist. This should not happen. BackupBuddy Error #8945587973.');
         return false;
     }
     // Connect if not connected for importbuddy.
     if (defined('PB_IMPORTBUDDY')) {
         if (!mysql_ping($wpdb->dbh)) {
             $maybePort = '';
             if ('' != $this->_database_port) {
                 $maybePort = ':' . $this->_database_port;
                 pb_backupbuddy::status('details', 'Using custom specified port `' . $this->_database_port . '` in DB_HOST.');
             }
             $wpdb->dbh = mysql_connect($this->_database_host . $maybePort, $this->_database_user, $this->_database_pass);
             mysql_select_db($this->_database_name, $wpdb->dbh);
         }
     }
     $insert_sql = '';
     pb_backupbuddy::status('details', 'Loading DB kicker for use leter in case database goes away.');
     @(include_once pb_backupbuddy::plugin_path() . '/lib/wpdbutils/wpdbutils.php');
     if (class_exists('pluginbuddy_wpdbutils')) {
         global $wpdb;
         $dbhelper = new pluginbuddy_wpdbutils($wpdb);
     } else {
         pb_backupbuddy::status('details', __('Database Server connection status will not be verified as kicker is not available.', 'it-l10n-backupbuddy'));
     }
     global $wpdb;
     // Used later for checking that we are still connected to DB.
     // Iterate through all the tables to backup.
     // TODO: Future ability to break up DB exporting to multiple page loads if needed.
     $remainingTables = $tables;
     foreach ($tables as $table_key => $table) {
         $_count = 0;
         $insert_sql = '';
         if ($resume_starting_row > 0) {
             pb_backupbuddy::status('details', 'Chunked resume on dumping `' . $table . '`. Resuming where left off.');
             $rows_start = $resume_starting_row;
             $resume_starting_row = 0;
             // Don't want to skip anything on next table.
         } else {
             $rows_start = 0;
         }
         pb_backupbuddy::status('details', 'Dumping database table `' . $table . '`. Max rows per select: ' . $max_rows_per_select . '. Starting at row `' . $resume_starting_row . '`.');
         pb_backupbuddy::status('startTableDump', $table);
         if (false === $this->_force_single_db_file) {
             $output_file = $output_directory . $table . '.sql';
         } else {
             pb_backupbuddy::status('details', 'Advanced option to force to single .sql file enabled.');
             $output_file = $output_directory . 'db_1.sql';
         }
         pb_backupbuddy::status('details', 'SQL dump file `' . $output_file . '`.');
         if ('-1' == $this->_maxExecutionTime) {
             pb_backupbuddy::status('details', 'Database max execution time chunking disabled based on -1 passed.');
         } else {
             pb_backupbuddy::status('details', 'mysqlbuddy: PHP-based database dump with max execution time for this run: ' . $this->_maxExecutionTime . ' seconds.');
         }
         if (false === ($file_handle = fopen($output_file, 'a'))) {
             pb_backupbuddy::status('error', 'Error #9018: Database file is not creatable/writable. Check your permissions for file `' . $output_file . '` in directory `' . $output_directory . '`.');
             return false;
         }
         pb_backupbuddy::status('sqlFile', basename($output_file));
         // Tells status checker which file to request size data for when polling server.
         if (0 == $rows_start) {
             $create_table = $wpdb->get_results("SHOW CREATE TABLE `{$table}`", ARRAY_N);
             if ($create_table === false) {
                 pb_backupbuddy::status('error', 'Unable to access and dump database table `' . $table . '`. Table may not exist. Skipping backup of this table.');
                 //backupbuddy_core::mail_error( 'Error #4537384: Unable to access and dump database table `' . $table . '`. Table may not exist. Skipping backup of this table.' );
                 continue;
                 // Skip this iteration as accessing this table failed.
             }
             // Table creation text
             if (!isset($create_table[0])) {
                 pb_backupbuddy::status('error', 'Error #857835: Unable to get table creation SQL for table `' . $table . '`. Result: `' . print_r($create_table) . '`.');
                 return false;
             }
             $create_table_array = $create_table[0];
             unset($create_table);
             $insert_sql .= str_replace("\n", '', $create_table_array[1]) . ";\n";
             // Remove internal linebreaks; only put one at end.
             unset($create_table_array);
             // Disable keys for this table.
             $insert_sql .= "/*!40000 ALTER TABLE `{$table}` DISABLE KEYS */;\n";
         }
         $queryCount = 0;
         $rows_remain = true;
         while (true === $rows_remain) {
             // Row creation text for all rows within this table.
             $query = "SELECT * FROM `{$table}` LIMIT " . $rows_start . ',' . $max_rows_per_select;
             $table_query = $wpdb->get_results($query, ARRAY_N);
             $rows_start += $max_rows_per_select;
             // Next loop we will begin at this offset.
             if ($table_query === false) {
                 pb_backupbuddy::status('error', 'ERROR #85449745. Unable to retrieve data from table `' . $table . '`. This table may be corrupt (try repairing the database) or too large to hold in memory (increase mysql and/or PHP memory). Check your PHP error log for further errors which may provide further information. Not continuing database dump to insure backup integrity.');
                 return false;
             }
             $tableCount = count($table_query);
             pb_backupbuddy::status('details', 'Got `' . $tableCount . '` rows from `' . $table . '` of `' . $max_rows_per_select . '` max.');
             if (0 == $tableCount || $tableCount < $max_rows_per_select) {
                 $rows_remain = false;
             }
             $columns = $wpdb->get_col_info();
             $num_fields = count($columns);
             foreach ($table_query as $fetch_row) {
                 $insert_sql .= "INSERT INTO `{$table}` VALUES(";
                 for ($n = 1; $n <= $num_fields; $n++) {
                     $m = $n - 1;
                     if ($fetch_row[$m] === NULL) {
                         $insert_sql .= "NULL, ";
                     } else {
                         $insert_sql .= "'" . backupbuddy_core::dbEscape($fetch_row[$m]) . "', ";
                     }
                 }
                 $insert_sql = substr($insert_sql, 0, -2);
                 $insert_sql .= ");\n";
                 $writeReturn = fwrite($file_handle, $insert_sql);
                 if (false === $writeReturn || 0 == $writeReturn) {
                     pb_backupbuddy::status('error', 'Error #843948: Unable to write to SQL file. Return error/bytes written: `' . $writeReturn . '`.');
                     @fclose($file_handle);
                     return false;
                 }
                 $insert_sql = '';
                 $_count++;
                 // Show a heartbeat to keep user up to date [and entertained ;)].
                 if (0 === $_count % self::HEARTBEAT_COUNT_LIMIT || 0 === $_count % ceil($max_rows_per_select / 2)) {
                     // Display every X queries based on heartbeat OR at least display every half max rows per select.
                     pb_backupbuddy::status('details', 'Working... Dumped `' . $_count . '` rows from `' . $table . '` so far.');
                 }
             }
             // end foreach table row.
             if (false === $rows_remain) {
                 pb_backupbuddy::status('details', 'Dumped `' . $_count . '` rows total from `' . $table . '`. No rows remain.');
             } else {
                 if (microtime(true) - $last_file_size_output > $output_file_size_every_max) {
                     // It's been long enough to get the current file size of SQL file.
                     // Display final SQL file size.
                     $sql_filesize = pb_backupbuddy::$format->file_size(filesize($output_file));
                     pb_backupbuddy::status('details', 'Current database dump file `' . basename($output_file) . '` size: ' . $sql_filesize . '.');
                     $last_file_size_output = microtime(true);
                 }
             }
             // If we are within X seconds (self::TIME_WIGGLE_ROOM) of reaching maximum PHP runtime then stop here so that it can be picked up in another PHP process...
             if ('-1' != $this->_maxExecutionTime) {
                 if (microtime(true) - pb_backupbuddy::$start_time + self::TIME_WIGGLE_ROOM >= $this->_maxExecutionTime) {
                     // used to use $this->time_start but this did not take into account time used prior to db step.
                     pb_backupbuddy::status('details', 'Approaching limit of available PHP chunking time of `' . $this->_maxExecutionTime . '` sec. PHP ran for ' . round(microtime(true) - pb_backupbuddy::$start_time, 3) . ' sec, database dumping ran for ' . round(microtime(true) - $this->time_start, 3) . ' sec having dumped `' . $_count . '` rows. Proceeding to use chunking on remaining tables: ' . implode(',', $remainingTables));
                     @fclose($file_handle);
                     return array($remainingTables, $rows_start);
                 }
                 // End if.
             }
             // Verify database is still connected and working properly. Sometimes mysql runs out of memory and dies in the above foreach.
             // No point in reconnecting as we can NOT trust that our dump was succesful anymore (it most likely was not).
             if (isset($dbhelper)) {
                 if (!$dbhelper->kick()) {
                     pb_backupbuddy::status('error', __('ERROR #9026: The mySQL server went away unexpectedly during database dump of table `' . $table . '`. This is almost always caused by mySQL running out of memory. The backup integrity can no longer be guaranteed so the backup has been halted.') . ' ' . __('Last table dumped before database server went away: ') . '`' . $table . '`.');
                     @fclose($file_handle);
                     return false;
                 }
             } else {
                 pb_backupbuddy::status('details', 'Database kicker unavailable so connection status unverified.');
             }
         }
         // End while rows remain.
         // Remove the current table from the list of tables to dump as it is done.
         unset($remainingTables[$table_key]);
         // Re-enable keys for this table.
         $insert_sql .= "/*!40000 ALTER TABLE `{$table}` ENABLE KEYS */;\n";
         $writeReturn = fwrite($file_handle, $insert_sql);
         if (false === $writeReturn || 0 == $writeReturn) {
             pb_backupbuddy::status('error', 'Error #843948: Unable to write to SQL file. Return error/bytes written: `' . $writeReturn . '`.');
             @fclose($file_handle);
             return false;
         }
         $insert_sql = '';
         @fclose($file_handle);
         pb_backupbuddy::status('details', 'Finished dumping database table `' . $table . '`.');
         pb_backupbuddy::status('finishTableDump', $table);
         if (isset($output_file)) {
             $stats = stat($output_file);
             pb_backupbuddy::status('details', 'Database SQL dump file (' . basename($output_file) . ') size: ' . pb_backupbuddy::$format->file_size($stats['size']));
             pb_backupbuddy::status('sqlSize', $stats['size']);
         }
         pb_backupbuddy::status('details', 'About to flush...');
         pb_backupbuddy::flush();
         //unset( $tables[$table_key] );
     }
     // end foreach table.
     @fclose($file_handle);
     unset($file_handle);
     pb_backupbuddy::status('details', __('Finished PHP based SQL dump method. Ran for ' . round(microtime(true) - $this->time_start, 3) . ' sec.', 'it-l10n-backupbuddy'));
     return true;
 }
Пример #28
0
 public static function restore($archive_file, $files, $finalPath, &$zipbuddy = null)
 {
     if (!current_user_can(pb_backupbuddy::$options['role_access'])) {
         die('Error #473623. Access Denied.');
     }
     $serial = backupbuddy_core::get_serial_from_file($archive_file);
     // serial of archive.
     $success = false;
     foreach ($files as $file) {
         $file = str_replace('*', '', $file);
         // Remove any wildcard.
         if (file_exists($finalPath . $file) && is_dir($finalPath . $file)) {
             if (($file_count = @scandir($finalPath . $file)) && count($file_count) > 2) {
                 pb_backupbuddy::status('error', __('Error #9036. The destination directory being restored already exists and is NOT empty. The directory will not be restored to prevent inadvertently losing files within the existing directory. Delete existing directory first if you wish to proceed or restore individual files.', 'it-l10n-backupbuddy') . ' Existing directory: `' . $finalPath . $file . '`.');
                 return false;
             }
         }
     }
     if (null === $zipbuddy) {
         require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
         $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
     }
     // Calculate temp directory & lock it down.
     $temp_dir = get_temp_dir();
     $destination = $temp_dir . 'backupbuddy-' . $serial;
     if (!file_exists($destination) && false === mkdir($destination, 0777, true)) {
         $error = 'Error #458485945: Unable to create temporary location.';
         pb_backupbuddy::status('error', $error);
         return false;
     }
     // If temp directory is within webroot then lock it down.
     $temp_dir = str_replace('\\', '/', $temp_dir);
     // Normalize for Windows.
     $temp_dir = rtrim($temp_dir, '/\\') . '/';
     // Enforce single trailing slash.
     if (FALSE !== stristr($temp_dir, ABSPATH)) {
         // Temp dir is within webroot.
         pb_backupbuddy::anti_directory_browsing($destination);
     }
     unset($temp_dir);
     pb_backupbuddy::status('details', 'Extracting into temporary directory "' . $destination . '".');
     $prettyFilesList = array();
     foreach ($files as $fileSource => $fileDestination) {
         $prettyFilesList[] = $fileSource . ' => ' . $fileDestination;
     }
     pb_backupbuddy::status('details', 'Files to extract: `' . htmlentities(implode(', ', $prettyFilesList)) . '`.');
     unset($prettyFilesList);
     pb_backupbuddy::flush();
     // Do the actual extraction.
     $extract_success = true;
     if (false === $zipbuddy->extract($archive_file, $destination, $files)) {
         pb_backupbuddy::status('error', 'Error #584984458b. Unable to extract.');
         $extract_success = false;
     }
     if (true === $extract_success) {
         // Verify all files/directories to be extracted exist in temp destination directory. If any missing then delete everything and bail out.
         foreach ($files as &$file) {
             $file = str_replace('*', '', $file);
             // Remove any wildcard.
             if (!file_exists($destination . '/' . $file)) {
                 // Cleanup.
                 foreach ($files as $file) {
                     @trigger_error('');
                     // Clear out last error.
                     @unlink($destination . '/' . $file);
                     $last_error = error_get_last();
                     if (is_array($last_error)) {
                         pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                     }
                 }
                 pb_backupbuddy::status('error', 'Error #854783474. One or more expected files / directories missing.');
                 $extract_success = false;
                 break;
             }
         }
         unset($file);
         // Made it this far so files all exist. Move them all.
         foreach ($files as $file) {
             @trigger_error('');
             // Clear out last error.
             if (false === @rename($destination . '/' . $file, $finalPath . $file)) {
                 $last_error = error_get_last();
                 if (is_array($last_error)) {
                     //print_r( $last_error );
                     pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                 }
                 $error = 'Error #9035. Unable to move restored file `' . $destination . '/' . $file . '` to `' . $finalPath . $file . '`. Verify permissions on destination location & that the destination directory/file does not already exist.';
                 pb_backupbuddy::status('error', $error);
             } else {
                 $details = 'Moved `' . $destination . '/' . $file . '` to `' . $finalPath . $file . '`.<br>';
                 pb_backupbuddy::status('details', $details);
                 $success = true;
             }
         }
     }
     // end extract success.
     // Try to cleanup.
     if (file_exists($destination)) {
         if (false === pb_backupbuddy::$filesystem->unlink_recursive($destination)) {
             pb_backupbuddy::status('details', 'Unable to delete temporary holding directory `' . $destination . '`.');
         } else {
             pb_backupbuddy::status('details', 'Cleaned up temporary files.');
         }
     }
     if (true === $success) {
         pb_backupbuddy::status('message', 'File retrieval completed successfully.');
         return true;
     } else {
         return false;
     }
 }
Пример #29
0
 if (defined('PB_DEMO_MODE')) {
     pb_backupbuddy::alert('Access denied in demo mode.', true);
 } else {
     $delete_items = pb_backupbuddy::_POST('items');
     $deleted_crons = array();
     // For listing in alert.
     foreach ($delete_items as $delete_item) {
         $cron_parts = explode('|', $delete_item);
         $timestamp = $cron_parts[0];
         $cron_hook = $cron_parts[1];
         $cron_key = $cron_parts[2];
         if (isset($cron[$timestamp][$cron_hook][$cron_key])) {
             // Run cron.
             $cron_array = $cron[$timestamp][$cron_hook][$cron_key];
             // Get cron array based on passed values.
             $result = backupbuddy_core::unschedule_event($timestamp, $cron_hook, $cron_array['args']);
             // Delete the scheduled cron.
             if ($result === FALSE) {
                 pb_backupbuddy::alert('Error #5657667675. Unable to delete CRON job. Please see your BackupBuddy error log for details.');
             }
             $deleted_crons[] = $cron_hook . ' / ' . $cron_key;
             // Add deleted cron to list of deletions for display.
         } else {
             // Cron not found, error.
             pb_backupbuddy::alert('Invalid CRON job. Not found.', true);
         }
     }
     pb_backupbuddy::alert(__('Deleted sheduled CRON event(s):', 'it-l10n-backupbuddy') . '<br>' . implode('<br>', $deleted_crons));
     $cron = get_option('cron');
     // Reset to most up to date status for cron listing below. Takes into account deletions.
 }
Пример #30
0
if ('' != pb_backupbuddy::_GET('downloadlink_file')) {
    $fileMeta = pb_backupbuddy_destination_gdrive::getFileMeta($settings, pb_backupbuddy::_GET('downloadlink_file'));
    pb_backupbuddy::alert('<a href="' . $fileMeta->alternateLink . '" target="_new">Click here</a> to view & download this file from Google Drive. You must log in to Google to access it.');
}
// Copy file to local
if ('' != pb_backupbuddy::_GET('cpy_file')) {
    $destinationFile = $fileMeta = pb_backupbuddy_destination_gdrive::getFileMeta($settings, pb_backupbuddy::_GET('cpy_file'));
    /*
    echo '<pre>';
    print_r( $fileMeta );
    echo '</pre>';
    */
    pb_backupbuddy::alert('The remote file is now being copied to your local backups. If the backup gets marked as bad during copying, please wait a bit then click the `Refresh` icon to rescan after the transfer is complete.');
    echo '<br>';
    pb_backupbuddy::status('details', 'Scheduling Cron for creating Google Drive copy.');
    backupbuddy_core::schedule_single_event(time(), pb_backupbuddy::cron_tag('process_destination_copy'), array($destination, $fileMeta->originalFilename, pb_backupbuddy::_GET('cpy_file')));
    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.
}
?>


<span id="backupbuddy_gdrive_loading"><h3><img src="<?php 
echo pb_backupbuddy::plugin_url();
?>
/images/loading.gif" alt="' . __('Loading...', 'it-l10n-backupbuddy' ) . '" title="' . __('Loading...', 'it-l10n-backupbuddy' ) . '" width="16" height="16" style="vertical-align: -3px;"> <?php 
_e('Loading...', 'it-l10n-backupbuddy');
?>
</h3></span>