Example #1
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;
     }
 }
 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)));
 }
Example #3
0
 public static function deploymentImportBuddy($password, $backupFile, $additionalStateInfo = '')
 {
     if (!file_exists($backupFile)) {
         $error = 'Error #43848378: Backup file `' . $backupFile . '` not found uploaded.';
         pb_backupbuddy::status('error', $error);
         return array(false, $error);
     }
     $backupSerial = backupbuddy_core::get_serial_from_file($backupFile);
     $importFileSerial = pb_backupbuddy::random_string(15);
     $importFilename = 'importbuddy-' . $importFileSerial . '.php';
     backupbuddy_core::importbuddy(ABSPATH . $importFilename, $password);
     // Render default config file overrides. Overrrides default restore.php state data.
     $state = array();
     global $wpdb;
     $state['type'] = 'deploy';
     $state['archive'] = $backupFile;
     $state['siteurl'] = preg_replace('|/*$|', '', site_url());
     // Strip trailing slashes.
     $state['homeurl'] = preg_replace('|/*$|', '', home_url());
     // Strip trailing slashes.
     $state['restoreFiles'] = false;
     $state['migrateHtaccess'] = false;
     $state['remote_api'] = pb_backupbuddy::$options['remote_api'];
     // For use by importbuddy api auth. Enables remote api in this importbuddy.
     $state['databaseSettings']['server'] = DB_HOST;
     $state['databaseSettings']['database'] = DB_NAME;
     $state['databaseSettings']['username'] = DB_USER;
     $state['databaseSettings']['password'] = DB_PASSWORD;
     $state['databaseSettings']['prefix'] = $wpdb->prefix;
     $state['databaseSettings']['renamePrefix'] = true;
     $state['cleanup']['deleteImportBuddy'] = true;
     $state['cleanup']['deleteImportLog'] = true;
     if (is_array($additionalStateInfo)) {
         $state = array_merge($state, $additionalStateInfo);
     }
     // Write default state overrides.
     $state_file = ABSPATH . 'importbuddy-' . $importFileSerial . '-state.php';
     if (false === ($file_handle = @fopen($state_file, 'w'))) {
         $error = 'Error #8384784: Temp state file is not creatable/writable. Check your permissions. (' . $state_file . ')';
         pb_backupbuddy::status('error', $error);
         return array(false, $error);
     }
     fwrite($file_handle, "<?php die('Access Denied.'); // <!-- ?>\n" . base64_encode(serialize($state)));
     fclose($file_handle);
     $undoFile = 'backupbuddy_deploy_undo-' . $backupSerial . '.php';
     //$undoURL = rtrim( site_url(), '/\\' ) . '/' . $undoFile;
     if (false === copy(pb_backupbuddy::plugin_path() . '/classes/_rollback_undo.php', ABSPATH . $undoFile)) {
         $error = 'Error #3289447: Unable to write undo file `' . ABSPATH . $undoFile . '`. Check permissions on directory.';
         pb_backupbuddy::status('error', $error);
         return array(false, $error);
     }
     return $importFileSerial;
 }
Example #4
0
 public function importbuddy()
 {
     $pass_hash = '';
     $password = stripslashes(pb_backupbuddy::_GET('p'));
     if ($password != '') {
         $pass_hash = md5($password);
         if (pb_backupbuddy::$options['importbuddy_pass_hash'] == '') {
             // if no default pass is set then we set this as default.
             pb_backupbuddy::$options['importbuddy_pass_hash'] = $pass_hash;
             pb_backupbuddy::$options['importbuddy_pass_length'] = strlen($password);
             // length of pass pre-hash.
             pb_backupbuddy::save();
         }
     }
     backupbuddy_core::importbuddy('', $pass_hash);
     // Outputs importbuddy to browser for download.
     die;
 }
 function pre_backup($serial, $archiveFile, $profile, $trigger, $pre_backup = array(), $post_backup = array(), $schedule_title = '', $export_plugins = array(), $deployDirection, $deployDestinationSettings)
 {
     pb_backupbuddy::status('startFunction', json_encode(array('function' => 'pre_backup', 'title' => 'Getting ready to backup')));
     $type = $profile['type'];
     // Log some status information.
     pb_backupbuddy::status('details', __('Performing pre-backup procedures.', 'it-l10n-backupbuddy'));
     if ($type == 'full') {
         pb_backupbuddy::status('message', __('Full backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'db') {
         pb_backupbuddy::status('message', __('Database only backup mode.', 'it-l10n-backupbuddy'));
     } elseif ($type == 'files') {
         pb_backupbuddy::status('message', __('Files only backup mode.', 'it-l10n-backupbuddy'));
         //$profile['skip_database_dump'] = '1';
     } elseif ($type == 'export') {
         pb_backupbuddy::status('message', __('Multisite subsite export mode.', 'it-l10n-backupbuddy'));
     } else {
         pb_backupbuddy::status('error', 'Error #8587383: Unknown backup mode `' . htmlentities($type) . '`.');
     }
     if ('' != $deployDirection) {
         pb_backupbuddy::status('details', 'Deployment direction: `' . $deployDirection . '`.');
     }
     if ('1' == pb_backupbuddy::$options['prevent_flush']) {
         pb_backupbuddy::status('details', 'Flushing will be skipped based on advanced settings.');
     } else {
         pb_backupbuddy::status('details', 'Flushing will not be skipped (default).');
     }
     // Schedule daily housekeeping.
     if (false === wp_next_scheduled(pb_backupbuddy::cron_tag('housekeeping'))) {
         // if schedule does not exist...
         backupbuddy_core::schedule_event(time() + 60 * 60 * 2, 'daily', pb_backupbuddy::cron_tag('housekeeping'), array());
         // Add schedule.
     }
     // Verify directories.
     pb_backupbuddy::status('details', 'Verifying directories ...');
     if (false === backupbuddy_core::verify_directories()) {
         pb_backupbuddy::status('error', 'Error #18573. Error verifying directories. See details above. Backup halted.');
         pb_backupbuddy::status('haltScript', '');
         // Halt JS on page.
         die;
     } else {
         pb_backupbuddy::status('details', 'Directories verified.');
     }
     // Delete all backup archives if this troubleshooting option is enabled.
     if (pb_backupbuddy::$options['delete_archives_pre_backup'] == '1') {
         pb_backupbuddy::status('message', 'Deleting all existing backups prior to backup as configured on the settings page.');
         $file_list = glob(backupbuddy_core::getBackupDirectory() . 'backup*.zip');
         if (is_array($file_list) && !empty($file_list)) {
             foreach ($file_list as $file) {
                 if (@unlink($file) === true) {
                     pb_backupbuddy::status('details', 'Deleted backup archive `' . basename($file) . '` based on settings to delete all backups.');
                 } else {
                     pb_backupbuddy::status('details', 'Unable to delete backup archive `' . basename($file) . '` based on settings to delete all backups. Verify permissions.');
                 }
             }
         }
     }
     // Generate unique serial ID.
     pb_backupbuddy::status('details', 'Backup serial generated: `' . $serial . '`.');
     pb_backupbuddy::status('details', 'About to load fileoptions data in create mode.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #40.');
     $this->_backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
     if (true !== ($result = $this->_backup_options->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034 A. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         pb_backupbuddy::status('haltScript', '');
         // Halt JS on page.
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $this->_backup =& $this->_backup_options->options;
     // Set reference.
     // Cleanup internal stats. Deployments should not impact stats.
     if ('' == $deployDirection) {
         pb_backupbuddy::status('details', 'Updating statistics for last backup start.');
         pb_backupbuddy::$options['last_backup_start'] = time();
         // Reset time since last backup.
         pb_backupbuddy::$options['last_backup_serial'] = $serial;
         pb_backupbuddy::save();
     }
     // Output active plugins list for debugging...
     $activePlugins = get_option('active_plugins');
     pb_backupbuddy::status('details', 'Active WordPress plugins: `' . implode('; ', $activePlugins) . '`.');
     pb_backupbuddy::status('startSubFunction', json_encode(array('function' => 'wp_plugins_found', 'title' => 'Found ' . count($activePlugins) . ' active WordPress plugins.')));
     unset($activePlugins);
     // Compression to bool.
     /*
     if ( $profile['compression'] == '1' ) {
     	$profile['compression'] = true;
     } else {
     	$profile['compression'] = false;
     }
     */
     if (pb_backupbuddy::$options['compression'] == '1') {
         $compression = true;
     } else {
         $compression = false;
     }
     $archiveURL = '';
     $abspath = str_replace('\\', '/', ABSPATH);
     // Change slashes to handle Windows as we store backup_directory with Linux-style slashes even on Windows.
     $backup_dir = str_replace('\\', '/', backupbuddy_core::getBackupDirectory());
     if (FALSE !== stristr($backup_dir, $abspath)) {
         // Make sure file to download is in a publicly accessible location (beneath WP web root technically).
         $sitepath = str_replace($abspath, '', $backup_dir);
         $archiveURL = rtrim(site_url(), '/\\') . '/' . trim($sitepath, '/\\') . '/' . basename($archiveFile);
     }
     $forceSingleDatabaseFile = false;
     if ('1' == pb_backupbuddy::$options['force_single_db_file']) {
         $forceSingleDatabaseFile = true;
     }
     // Set up the backup data.
     $this->_backup = array('data_version' => 1, 'backupbuddy_version' => pb_backupbuddy::settings('version'), 'serial' => $serial, 'init_complete' => false, 'backup_mode' => $profile['backup_mode'], 'type' => $type, 'profile' => $profile, 'default_profile' => pb_backupbuddy::$options['profiles'][0], 'start_time' => time(), 'finish_time' => 0, 'updated_time' => time(), 'status' => array(), 'max_execution_time' => backupbuddy_core::adjustedMaxExecutionTime(), 'archive_size' => 0, 'schedule_title' => $schedule_title, 'backup_directory' => backupbuddy_core::getBackupDirectory(), 'archive_file' => $archiveFile, 'archive_url' => $archiveURL, 'trigger' => $trigger, 'zip_method_strategy' => pb_backupbuddy::$options['zip_method_strategy'], 'compression' => $compression, 'ignore_zip_warnings' => pb_backupbuddy::$options['ignore_zip_warnings'], 'ignore_zip_symlinks' => pb_backupbuddy::$options['ignore_zip_symlinks'], 'steps' => array(), 'integrity' => array(), 'temp_directory' => '', 'backup_root' => '', 'export_plugins' => array(), 'additional_table_includes' => array(), 'additional_table_excludes' => array(), 'directory_exclusions' => backupbuddy_core::get_directory_exclusions($profile, false, $serial), 'table_sizes' => array(), 'breakout_tables' => array(), 'force_single_db_file' => $forceSingleDatabaseFile, 'deployment_log' => '', 'deployment_direction' => $deployDirection, 'deployment_destination' => $deployDestinationSettings, 'runnerUID' => get_current_user_id());
     pb_backupbuddy::status('startSubFunction', json_encode(array('function' => 'file_excludes', 'title' => 'Found ' . count($this->_backup['directory_exclusions']) . ' file or directory exclusions.')));
     // Warn if excluding key paths.
     $alertFileExcludes = backupbuddy_core::alert_core_file_excludes($this->_backup['directory_exclusions']);
     foreach ($alertFileExcludes as $alertFileExcludeId => $alertFileExclude) {
         pb_backupbuddy::status('warning', $alertFileExclude);
     }
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     // Figure out paths.
     if ($this->_backup['type'] == 'full' || $this->_backup['type'] == 'files') {
         $this->_backup['temp_directory'] = backupbuddy_core::getTempDirectory() . $serial . '/';
         $this->_backup['backup_root'] = ABSPATH;
         // ABSPATH contains trailing slash.
     } elseif ($this->_backup['type'] == 'db') {
         $this->_backup['temp_directory'] = backupbuddy_core::getTempDirectory() . $serial . '/';
         $this->_backup['backup_root'] = $this->_backup['temp_directory'];
     } elseif ($this->_backup['type'] == 'export') {
         // WordPress unzips into wordpress subdirectory by default so must include that in path.
         $this->_backup['temp_directory'] = backupbuddy_core::getTempDirectory() . $serial . '/wordpress/wp-content/uploads/backupbuddy_temp/' . $serial . '/';
         // We store temp data for export within the temporary WordPress installation within the temp directory. A bit confusing; sorry about that.
         $this->_backup['backup_root'] = backupbuddy_core::getTempDirectory() . $serial . '/wordpress/';
     } else {
         pb_backupbuddy::status('error', __('Backup FAILED. Unknown backup type.', 'it-l10n-backupbuddy'));
         pb_backupbuddy::status('haltScript', '');
         // Halt JS on page.
     }
     pb_backupbuddy::status('details', 'Temp directory: `' . $this->_backup['temp_directory'] . '`.');
     pb_backupbuddy::status('details', 'Backup root: `' . $this->_backup['backup_root'] . '`.');
     // Plugins to export (only for MS exports).
     if (count($export_plugins) > 0) {
         $this->_backup['export_plugins'] = $export_plugins;
     }
     // Calculate additional database table inclusion/exclusion.
     $additional_includes = explode("\n", $profile['mysqldump_additional_includes']);
     array_walk($additional_includes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_includes'] = array_unique($additional_includes);
     // removes duplicates.
     $additional_excludes = explode("\n", $profile['mysqldump_additional_excludes']);
     array_walk($additional_excludes, create_function('&$val', '$val = trim($val);'));
     $this->_backup['additional_table_excludes'] = array_unique($additional_excludes);
     // removes duplicates.
     unset($additional_includes);
     unset($additional_excludes);
     /********* Begin setting up steps array. *********/
     if ($type == 'export') {
         pb_backupbuddy::status('details', 'Setting up export-specific steps.');
         $this->_backup['steps'][] = array('function' => 'ms_download_extract_wordpress', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_create_wp_config', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_plugins', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_themes', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_media', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->_backup['steps'][] = array('function' => 'ms_copy_users_table', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     }
     if ('pull' != $deployDirection && '1' != $profile['skip_database_dump'] && $profile['type'] != 'files') {
         // Backup database if not skipping AND not a files only backup.
         global $wpdb;
         // Default tables to backup.
         if ($type == 'export') {
             // Multisite Subsite export only dumps tables specific to this subsite prefix.
             $base_dump_mode = 'prefix';
         } else {
             // Non-multisite export so use profile to determine tables to backup.
             if ($profile['backup_nonwp_tables'] == '1') {
                 // Backup all tables.
                 $base_dump_mode = 'all';
             } elseif ($profile['backup_nonwp_tables'] == '2') {
                 // Backup no tables by default. Relies on listed additional tables.
                 $base_dump_mode = 'none';
             } else {
                 // Only backup matching prefix.
                 $base_dump_mode = 'prefix';
             }
         }
         $additional_tables = $this->_backup['additional_table_includes'];
         if ($type == 'export') {
             global $wpdb;
             array_push($additional_tables, $wpdb->prefix . "users");
             array_push($additional_tables, $wpdb->prefix . "usermeta");
         }
         // Warn if excluding key WP tables.
         $tableExcludes = backupbuddy_core::alert_core_table_excludes($this->_backup['additional_table_excludes']);
         foreach ($tableExcludes as $tableExcludeId => $tableExclude) {
             pb_backupbuddy::status('warning', $tableExclude);
         }
         // Calculate tables to dump based on the provided information. $tables will be an array of tables.
         $tables = $this->_calculate_tables($base_dump_mode, $additional_tables, $this->_backup['additional_table_excludes']);
         pb_backupbuddy::status('startSubFunction', json_encode(array('function' => 'calculate_tables', 'title' => 'Found ' . count($tables) . ' tables to backup based on settings.', 'more' => 'Tables: ' . implode(', ', $tables))));
         // If calculations show NO database tables should be backed up then change mode to skip database dump.
         if (0 == count($tables)) {
             pb_backupbuddy::status('warning', 'WARNING #857272: No database tables will be backed up based on current settings. This will not be a complete backup. Adjust settings if this is not intended and use with caution. Skipping database dump step.');
             $profile['skip_database_dump'] = '1';
             $this->_backup['profile']['skip_database_dump'] = '1';
         } else {
             // One or more tables set to backup.
             // Obtain tables sizes. Surround each table name by a single quote and implode with commas for SQL query to get sizes.
             $tables_formatted = $tables;
             foreach ($tables_formatted as &$table_formatted) {
                 $table_formatted = "'{$table_formatted}'";
             }
             $tables_formatted = implode(',', $tables_formatted);
             $sql = "SHOW TABLE STATUS WHERE Name IN({$tables_formatted});";
             $rows = $wpdb->get_results($sql, ARRAY_A);
             if (false === $rows) {
                 pb_backupbuddy::alert('Error #85473474: Unable to retrieve table status. Query: `' . $sql . '`.', true);
                 return false;
             }
             $totalDatabaseSize = 0;
             foreach ($rows as $row) {
                 $this->_backup['table_sizes'][$row['Name']] = $row['Data_length'] + $row['Index_length'];
                 $totalDatabaseSize += $this->_backup['table_sizes'][$row['Name']];
             }
             unset($rows);
             unset($tables_formatted);
             $databaseSize = pb_backupbuddy::$format->file_size($totalDatabaseSize);
             pb_backupbuddy::status('details', 'Total calculated database size: `' . $databaseSize . '`.');
             // Step through tables we want to break out and figure out which ones were indeed set to be backed up and break them out.
             if (pb_backupbuddy::$options['breakout_tables'] == '0') {
                 // Breaking out DISABLED.
                 pb_backupbuddy::status('details', 'Breaking out tables DISABLED based on settings.');
             } else {
                 // Breaking out ENABLED.
                 // Tables we will try to break out into standalone steps if possible.
                 $breakout_tables_defaults = array($wpdb->prefix . 'posts', $wpdb->prefix . 'postmeta');
                 pb_backupbuddy::status('details', 'Breaking out tables ENABLED based on settings. Tables to be broken out into individual steps: `' . implode(', ', $breakout_tables_defaults) . '`.');
                 foreach ((array) $breakout_tables_defaults as $breakout_tables_default) {
                     if (in_array($breakout_tables_default, $tables)) {
                         $this->_backup['breakout_tables'][] = $breakout_tables_default;
                         $tables = array_diff($tables, array($breakout_tables_default));
                         // Remove from main table backup list.
                     }
                 }
                 unset($breakout_tables_defaults);
                 // No longer needed.
             }
             $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array($tables), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
             // Set up backup steps for additional broken out tables.
             foreach ((array) $this->_backup['breakout_tables'] as $breakout_table) {
                 $this->_backup['steps'][] = array('function' => 'backup_create_database_dump', 'args' => array(array($breakout_table)), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
             }
         }
         // end there being tables to backup.
     } else {
         pb_backupbuddy::status('message', __('Skipping database dump based on settings / profile type.', 'it-l10n-backupbuddy') . ' Backup type: `' . $type . '`.');
     }
     if ('pull' != $deployDirection) {
         $this->_backup['steps'][] = array('function' => 'backup_zip_files', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         if ($type == 'export') {
             $this->_backup['steps'][] = array('function' => 'ms_cleanup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         }
         if ($profile['integrity_check'] == '1') {
             pb_backupbuddy::status('details', __('Integrity check will be performed based on settings for this profile.', 'it-l10n-backupbuddy'));
             $this->_backup['steps'][] = array('function' => 'integrity_check', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         } else {
             pb_backupbuddy::status('details', __('Skipping integrity check step based on settings for this profile.', 'it-l10n-backupbuddy'));
         }
     }
     $this->_backup['steps'][] = array('function' => 'post_backup', 'args' => array(), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
     // Prepend and append pre backup and post backup steps.
     $this->_backup['steps'] = array_merge($pre_backup, $this->_backup['steps'], $post_backup);
     /********* End setting up steps array. *********/
     // Save what we have so far so that any errors below will end up displayed to user.
     $this->_backup_options->save();
     /********* Begin directory creation and security. *********/
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getBackupDirectory());
     // Prepare temporary directory for holding SQL and data file.
     if (backupbuddy_core::getTempDirectory() == '') {
         pb_backupbuddy::status('error', 'Error #54534344. Temp directory blank. Please deactivate then reactivate plugin to reset.');
         return false;
     }
     if (!file_exists($this->_backup['temp_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temp_directory']) === false) {
             pb_backupbuddy::status('error', 'Error #9002b. Unable to create temporary storage directory (' . $this->_backup['temp_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temp_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temp_directory'] . ')');
         return false;
     }
     pb_backupbuddy::anti_directory_browsing(ABSPATH . 'wp-content/uploads/backupbuddy_temp/');
     // Prepare temporary directory for holding ZIP file while it is being generated.
     $this->_backup['temporary_zip_directory'] = backupbuddy_core::getBackupDirectory() . 'temp_zip_' . $this->_backup['serial'] . '/';
     if (!file_exists($this->_backup['temporary_zip_directory'])) {
         if (pb_backupbuddy::$filesystem->mkdir($this->_backup['temporary_zip_directory']) === false) {
             pb_backupbuddy::status('details', 'Error #9002c. Unable to create temporary ZIP storage directory (' . $this->_backup['temporary_zip_directory'] . ')');
             return false;
         }
     }
     if (!is_writable($this->_backup['temporary_zip_directory'])) {
         pb_backupbuddy::status('error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temporary_zip_directory'] . ')');
         return false;
     }
     /********* End directory creation and security *********/
     // Generate backup DAT (data) file containing details about the backup.
     if ($this->backup_create_dat_file($trigger) !== true) {
         pb_backupbuddy::status('details', __('Problem creating DAT file.', 'it-l10n-backupbuddy'));
         return false;
     }
     // Generating ImportBuddy file to include in the backup for FULL BACKUPS ONLY currently. Cannot put in DB because it would be in root and be excluded or conflict on extraction.
     if ($type == 'full') {
         if (pb_backupbuddy::$options['include_importbuddy'] == '1') {
             pb_backupbuddy::status('details', 'Generating ImportBuddy tool to include in backup archive: `' . $this->_backup['temp_directory'] . 'importbuddy.php`.');
             pb_backupbuddy::status('startAction', 'importbuddyCreation');
             backupbuddy_core::importbuddy($this->_backup['temp_directory'] . 'importbuddy.php');
             pb_backupbuddy::status('finishAction', 'importbuddyCreation');
             pb_backupbuddy::status('details', 'ImportBuddy generation complete.');
         } else {
             // dont include importbuddy.
             pb_backupbuddy::status('details', 'ImportBuddy tool inclusion in ZIP backup archive skipped based on settings or backup type.');
         }
     }
     // Save all of this.
     $this->_backup['init_complete'] = true;
     // pre_backup() completed.
     $this->_backup_options->save();
     pb_backupbuddy::status('details', __('Finished pre-backup procedures.', 'it-l10n-backupbuddy'));
     pb_backupbuddy::status('milestone', 'finish_settings');
     pb_backupbuddy::status('finishFunction', json_encode(array('function' => 'pre_backup')));
     return true;
 }
Example #6
0
 private static function _verb_renderImportBuddy()
 {
     $tempDir = backupbuddy_core::getTempDirectory();
     $tempFile = $tempDir . str_replace(array('\\', '/'), '', pb_backupbuddy::_POST('backupFile'));
     if (!file_exists($tempFile)) {
         die(json_encode(array('success' => false, 'error' => 'Error #43848378: Backup file `' . $tempFile . '` not found uploaded.')));
     }
     $importFileSerial = pb_backupbuddy::random_string(15);
     $importFilename = 'importbuddy-' . $importFileSerial . '.php';
     backupbuddy_core::importbuddy(ABSPATH . $importFilename, $password = md5(md5(pb_backupbuddy::_POST('backupbuddy_api_key'))));
     // Render default config file overrides. Overrrides default restore.php state data.
     $state = array();
     global $wpdb;
     $state['type'] = 'deploy';
     $state['archive'] = $tempDir . pb_backupbuddy::_POST('backupFile');
     $state['siteurl'] = site_url();
     $state['homeurl'] = home_url();
     $state['restoreFiles'] = false;
     $state['migrateHtaccess'] = false;
     $state['remote_api'] = pb_backupbuddy::$options['remote_api'];
     // For use by importbuddy api auth. Enables remote api in this importbuddy.
     $state['databaseSettings']['server'] = DB_HOST;
     $state['databaseSettings']['database'] = DB_NAME;
     $state['databaseSettings']['username'] = DB_USER;
     $state['databaseSettings']['password'] = DB_PASSWORD;
     $state['databaseSettings']['prefix'] = $wpdb->prefix;
     $state['databaseSettings']['renamePrefix'] = true;
     // Write default state overrides.
     $state_file = ABSPATH . 'importbuddy-' . $importFileSerial . '-state.php';
     if (false === ($file_handle = @fopen($state_file, 'w'))) {
         pb_backupbuddy::status('error', 'Error #8384784: Temp state file is not creatable/writable. Check your permissions. (' . $state_file . ')');
         return false;
     }
     fwrite($file_handle, "<?php die('Access Denied.'); // <!-- ?>\n" . base64_encode(serialize($state)));
     fclose($file_handle);
     die(json_encode(array('success' => true, 'importFileSerial' => $importFileSerial)));
 }
</script>
<?php 
// END TOUR.
// Check if performing an actual migration now. If so then load file and skip the rest of this page.
if (pb_backupbuddy::_GET('callback_data') != '' && pb_backupbuddy::_GET('callback_data') != 'importbuddy.php') {
    require_once '_migrate.php';
    return;
}
// Handle remote sending ImportBuddy.
if (pb_backupbuddy::_GET('callback_data') == 'importbuddy.php') {
    pb_backupbuddy::alert('<span id="pb_backupbuddy_ib_sent">Sending ImportBuddy file. This may take several seconds. Please wait ...</span>');
    pb_backupbuddy::flush();
    pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
    $importbuddy_file = backupbuddy_core::getTempDirectory() . 'importbuddy.php';
    // Render ImportBuddy to temp location.
    backupbuddy_core::importbuddy($importbuddy_file);
    if (file_exists($importbuddy_file)) {
        $response = backupbuddy_core::send_remote_destination($_GET['destination'], $importbuddy_file, $trigger = 'manual');
    } else {
        pb_backupbuddy::alert('Error #4589: Local importbuddy.php file not found for sending. Check directory permissions and / or manually migrating by downloading importbuddy.php.');
        $response = false;
    }
    if (file_exists($importbuddy_file)) {
        if (false === unlink($importbuddy_file)) {
            // Delete temporary ImportBuddy file.
            pb_backupbuddy::alert('Unable to delete file. For security please manually delete it: `' . $importbuddy_file . '`.');
        }
    }
    if ($response === true) {
        ?>
		<script type="text/javascript">
 public static function test($settings)
 {
     $settings = self::_normalizeSettings($settings);
     if (false === ($settings = self::_connect($settings))) {
         $error = 'Unable to connect with Google Drive. See log for details.';
         echo $error;
         pb_backupbuddy::status('error', $error);
         return false;
     }
     pb_backupbuddy::status('details', 'Testing Google Drive destination. Sending ImportBuddy.php.');
     pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
     $importbuddy_temp = backupbuddy_core::getTempDirectory() . 'importbuddy_' . pb_backupbuddy::random_string(10) . '.php.tmp';
     // Full path & filename to temporary importbuddy
     backupbuddy_core::importbuddy($importbuddy_temp);
     // Create temporary importbuddy.
     $files = array($importbuddy_temp);
     $results = self::send($settings, $files, '', $delete_remote_after = true);
     @unlink($importbuddy_temp);
     if (true === $results) {
         echo 'Success sending test file to Google Drive. ';
         return true;
     } else {
         global $pb_backupbuddy_destination_errors;
         echo 'Failure sending test file to Google Drive. Details: `' . implode(', ', $pb_backupbuddy_destination_errors) . '`.';
         return false;
     }
 }
<?php

backupbuddy_core::verifyAjaxAccess();
$pass_hash = '';
$password = stripslashes(pb_backupbuddy::_GET('p'));
if ($password != '') {
    $pass_hash = md5($password);
    if (pb_backupbuddy::$options['importbuddy_pass_hash'] == '') {
        // if no default pass is set then we set this as default.
        pb_backupbuddy::$options['importbuddy_pass_hash'] = $pass_hash;
        pb_backupbuddy::$options['importbuddy_pass_length'] = strlen($password);
        // length of pass pre-hash.
        pb_backupbuddy::save();
    }
}
backupbuddy_core::importbuddy('', $pass_hash);
// Outputs importbuddy to browser for download.
die;
Example #10
0
 private static function _step_send_pending_db_snapshots($startAt = 0)
 {
     // Load state into self::$_state & fileoptions object into self::$_stateObj.
     if (false === self::_load_state()) {
         return false;
     }
     if (false === self::_load_tables()) {
         return false;
     }
     if (0 != $startAt) {
         pb_backupbuddy::status('details', 'Resuming snapshot send at point `' . $startAt . '`.');
     }
     require_once pb_backupbuddy::plugin_path() . '/destinations/bootstrap.php';
     backupbuddy_live::update_db_live_activity_time();
     // On first pass create and send backupbuddy_dat.php and importbuddy.php.
     if (0 == $startAt) {
         // Render backupbuddy_dat.php
         $dat_file = backupbuddy_live::getLiveDatabaseSnapshotDir() . 'backupbuddy_dat.php';
         // Make sure directory exists.
         if (!file_exists(dirname($dat_file))) {
             if (false === pb_backupbuddy_filesystem::mkdir(dirname($dat_file))) {
                 pb_backupbuddy::status('warning', 'Warning #34893498434: Unable to mkdir("' . $dat_file . '").');
             }
         }
         $tableSizes = array();
         foreach (self::$_tables as $tableName => $table) {
             $tableSizes[$tableName] = $table['s'];
         }
         $table_results = backupbuddy_live::_calculate_table_includes_excludes_basedump();
         $dat_settings = array('backup_type' => 'live', 'profile' => array(), 'serial' => '', 'breakout_tables' => backupbuddy_live::calculateTables(), 'table_sizes' => $tableSizes, 'force_single_db_file' => false, 'trigger' => 'live', 'db_excludes' => $table_results[1], 'db_includes' => $table_results[0]);
         pb_backupbuddy::status('details', 'Rendering DAT file to `' . $dat_file . '`.');
         if (!is_array(backupbuddy_core::render_dat_contents($dat_settings, $dat_file))) {
             $error = 'Error #47949743: Since DAT file could not be written aborting. Check permissions writing to `' . $dat_file . '`.';
             pb_backupbuddy::status('error', $error);
             return $error;
         }
         // Render importbuddy.php
         $importbuddy_file = backupbuddy_live::getLiveDatabaseSnapshotDir() . 'importbuddy.php';
         pb_backupbuddy::status('details', 'Rendering importbuddy file to `' . $importbuddy_file . '`.');
         if (false === backupbuddy_core::importbuddy($importbuddy_file, $pass = NULL)) {
             // NULL pass leaves #PASSWORD# placeholder in place.
             pb_backupbuddy::status('warning', 'Warning #348438345: Unable to render importbuddy. Not backing up importbuddy.php.');
         }
         // Load destination settings.
         $destination_settings = self::get_destination_settings();
         // Send DAT file.
         $send_id = 'live_' . md5($dat_file) . '-' . pb_backupbuddy::random_string(6);
         $destination_settings['_database_table'] = 'backupbuddy_dat.php';
         if (false === pb_backupbuddy_destinations::send($destination_settings, $dat_file, $send_id, $delete_after = true, $isRetry = false, $trigger = 'live_periodic', $destination_id = backupbuddy_live::getLiveID())) {
             $error = 'Error #389398: Unable to send DAT file to Live servers. See error log above for details.';
             pb_backupbuddy::status('error', $error);
             backupbuddy_core::addNotification('live_error', 'BackupBuddy Stash Live Error', $error);
         }
         // Send importbuddy.
         $send_id = 'live_' . md5($importbuddy_file) . '-' . pb_backupbuddy::random_string(6);
         $destination_settings['_database_table'] = 'importbuddy.php';
         if (false === pb_backupbuddy_destinations::send($destination_settings, $importbuddy_file, $send_id, $delete_after = true, $isRetry = false, $trigger = 'live_periodic', $destination_id = backupbuddy_live::getLiveID())) {
             pb_backupbuddy::status('error', 'Error #329327: Unable to send importbuddy file to Live servers. See error log above for details.');
         }
     }
     // Loop through files in the catalog.
     $loopCount = 0;
     $checkCount = 0;
     $sendTimeSum = 0;
     $sendSizeSum = 0;
     $sendsStarted = 0;
     $sendsSucceeded = 0;
     $sendsMultiparted = 0;
     $sendsFailed = 0;
     $alreadyBackedUp = 0;
     $tooManySendFails = 0;
     $lastSendThisPass = false;
     $sendMoreRemain = false;
     foreach (self::$_tables as $table => &$tableDetails) {
         $loopCount++;
         if (0 != $startAt) {
             // Resuming...
             if ($loopCount < $startAt) {
                 continue;
             }
         }
         $checkCount++;
         // If backed up after modified time then it's up to date. Skip.
         if ($tableDetails['b'] > $tableDetails['m']) {
             pb_backupbuddy::status('details', 'Skipping send of table `' . $table . '` because it has already been sent since SQL file was made.');
             $alreadyBackedUp++;
             continue;
         }
         // Calculate table file.
         $tableFile = backupbuddy_live::getLiveDatabaseSnapshotDir() . $table . '.sql';
         // If too many attempts have passed then skip.
         if ($tableDetails['t'] >= self::MAX_SEND_ATTEMPTS) {
             pb_backupbuddy::status('error', 'Error #389328: This database file has failed transfer too many times. Skipping until next restart of periodic proces. File: `' . $tableFile . '`. Size: `' . pb_backupbuddy::$format->file_size(filesize($tableFile)) . '`.');
             $tooManySendFails++;
             continue;
         }
         // Load destination settings.
         $destination_settings = self::get_destination_settings();
         // If too many remote sends have failed today then give up for now since something is likely wrong.
         if (self::$_state['stats']['recent_send_fails'] > $destination_settings['max_daily_failures']) {
             $error = 'Error #4937743: Too many file transfer failures have occurred. Halting sends for today.';
             backupbuddy_core::addNotification('live_error', 'BackupBuddy Stash Live Error', $error);
             self::$_state['step']['last_status'] = $error;
             pb_backupbuddy::status('error', $error);
             return false;
         }
         // If this is not the first file we've sent this pass, see if we have enough time for more.
         if ($sendSizeSum > 0) {
             // Check if it appears we have enough time to send at least a full single chunk in this pass or if we need to pass off to a subsequent run.
             $send_speed = $sendSizeSum / 1048576 / $sendTimeSum;
             // Estimated speed at which we can send files out. Unit: MB / sec.
             $time_elapsed = microtime(true) - pb_backupbuddy::$start_time;
             $time_remaining = $destination_settings['max_time'] - ($time_elapsed + self::TIME_WIGGLE_ROOM);
             // Estimated time remaining before PHP times out. Unit: seconds.
             $size_possible_with_remaining_time = $send_speed * $time_remaining;
             // Size possible to send with remaining time (takes into account wiggle room).
             $size_to_send = $tableDetails['s'] / 1048576;
             // Size we want to send this pass. Unit: MB.
             if ($destination_settings['max_burst'] < $size_to_send) {
                 // If the chunksize is smaller than the full file then cap at sending that much.
                 $size_to_send = $destination_settings['max_burst'];
             }
             if ($size_possible_with_remaining_time < $size_to_send) {
                 // File (or chunk) is bigger than what we have time to send.
                 $lastSendThisPass = true;
                 $sendMoreRemain = true;
                 $send_speed_status = 'Not enough time to send more. To continue in next live_periodic pass.';
             } else {
                 $send_speed_status = 'Enough time to send more. Preparing for send.';
             }
             pb_backupbuddy::status('details', 'Not the first DB file to send this pass. Send speed: `' . $send_speed . '` MB/sec. Time elapsed: `' . $time_elapsed . '` sec. Time remaining: `' . $time_remaining . '` sec based on reported max time of `' . $destination_settings['max_time'] . '` sec with wiggle room `' . self::TIME_WIGGLE_ROOM . '` sec. Size possible with remaining time: `' . $size_possible_with_remaining_time . '` MB. Size to chunk (greater of filesize or chunk): `' . $size_to_send . '` MB. Conclusion: `' . $send_speed_status . '`.');
         }
         // end subsequent send time check.
         // NOT out of time so send this.
         if (true !== $lastSendThisPass) {
             // Run cleanup on send files.
             require_once pb_backupbuddy::plugin_path() . '/classes/housekeeping.php';
             backupbuddy_housekeeping::trim_remote_send_stats($file_prefix = 'send-live_', $limit = $destination_settings['max_send_details_limit'], '', $purge_log = true);
             // Only keep last X send fileoptions.
             // Moved to trim_remote_send_stats(). backupbuddy_housekeeping::purge_logs( $file_prefix = 'status-remote_send-live_', $limit = $destination_settings['max_send_details_limit'] ); // Only keep last X send logs.
             // Increment try count for transfer attempts and save.
             $tableDetails['t']++;
             self::$_tablesObj->save();
             // Send file. AFTER success sending this Stash2 destination will automatically trigger the live_periodic processing _IF_ multipart send. If success or fail the we come back here to potentially send more files in the same PHP pass so small files don't each need their own PHP page run.  Unless the process has restarted then this will still be the 'next' function to run.
             $send_id = 'live_' . md5($tableFile) . '-' . pb_backupbuddy::random_string(6);
             pb_backupbuddy::status('details', 'Live starting send function.');
             $sendTimeStart = microtime(true);
             // Mark table as unsent just before sending new version.
             $tableDetails['b'] = 0;
             // Close catalog & state while sending if > X size to prevent collisions.
             if ($tableDetails['s'] > self::CLOSE_CATALOG_WHEN_SENDING_FILESIZE) {
                 self::$_tablesObj = '';
                 self::$_stateObj = '';
             }
             // Set database table name into settings so send confirmation knows where to update sent timestamp.
             $destination_settings['_database_table'] = $table;
             // Send file to remote.
             $sendsStarted++;
             $result = pb_backupbuddy_destinations::send($destination_settings, $tableFile, $send_id, $delete_after = true, $isRetry = false, $trigger = 'live_periodic', $destination_id = backupbuddy_live::getLiveID());
             // Re-open catalog (if closed).
             self::_load_tables();
             self::_load_state();
             $sendTimeFinish = microtime(true);
             if (true === $result) {
                 $sendsSucceeded++;
                 $result_status = 'Success sending in single pass.';
                 $sendTimeSum += $sendTimeFinish - $sendTimeStart;
                 // Add to time sent sending.
                 // Set a minimum threshold so small files don't make server appear slower than reality due to overhead.
                 $minimum_size_threshold = self::MINIMUM_SIZE_THRESHOLD_FOR_SPEED_CALC;
                 // Pretend file is at least 500k each.
                 if ($tableDetails['s'] < $minimum_size_threshold) {
                     $sendSizeSum += $minimum_size_threshold;
                 } else {
                     $sendSizeSum += $tableDetails['s'];
                     // Add to size of data sent.
                 }
             } elseif (false === $result) {
                 $sendsFailed++;
                 self::$_state['stats']['recent_send_fails']++;
                 $result_status = 'Failure sending in single/first pass. See log above for error details. Failed sends today: `' . self::$_state['stats']['recent_send_fails'] . '`.';
             } elseif (is_array($result)) {
                 $sendsMultiparted++;
                 $result_status = 'Chunking commenced. Ending sends for this pass.';
                 $lastSendThisPass = true;
             }
             pb_backupbuddy::status('details', 'Live ended send database function. Status: ' . $result_status . '.');
         }
         // Check if we are done sending for this PHP pass/run.
         if (true === $lastSendThisPass) {
             break;
         }
     }
     // End foreach signatures.
     pb_backupbuddy::status('details', 'Snapshot send details for this round: Checked `' . $loopCount . '` tables, transfers started: `' . $sendsStarted . '`, transfers succeeded: `' . $sendsSucceeded . '`, transfers multiparted: `' . $sendsMultiparted . '`, transfers failed: `' . $sendsFailed . '`, skipped because already backed up: `' . $alreadyBackedUp . '`, skipped because too many send failures: `' . $tooManySendFails . '`.');
     // Schedule next run if we still have more files to potentially send.
     if (true === $sendMoreRemain) {
         return array('Sending queued tables', array($loopCount));
     } else {
         // No more files.
         return true;
     }
 }