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.
 }
Example #2
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>';
}
Example #3
0
 public function destination_send($destination_settings, $files, $send_id = '', $delete_after = false, $identifier = '', $isRetry = false)
 {
     pb_backupbuddy::status('details', 'Beginning cron destination_send. Unique ID: `' . $identifier . '`.');
     if ('' != $identifier) {
         $lockFile = backupbuddy_core::getLogDirectory() . 'cronSend-' . $identifier . '.lock';
         pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getTempDirectory(), $die = false);
         if (@file_exists($lockFile)) {
             // Lock exists already. Duplicate run?
             $attempts = @file_get_contents($lockFile);
             $attempts++;
             pb_backupbuddy::status('warning', 'Lock file exists and now shows ' . $attempts . ' attempts.');
             $attempts = @file_get_contents($lockFile, $attempts);
             return;
         } else {
             // No lock yet.
             if (false === @file_put_contents($lockFile, '1')) {
                 pb_backupbuddy::status('warning', 'Unable to create destination send lock file `' . $lockFile . '`.');
             } else {
                 pb_backupbuddy::status('details', 'Create destination send lock file `' . $lockFile . '`.');
             }
         }
     }
     pb_backupbuddy::status('details', 'Launching destination send via cron.');
     if (!class_exists('backupbuddy_core')) {
         require_once pb_backupbuddy::plugin_path() . '/classes/core.php';
     }
     if (true === backupbuddy_core::destination_send($destination_settings, $files, $send_id, $delete_after, $isRetry)) {
         // completely finished, go ahead and clean up lock file.
         /* DO not delete here as we need to keep this locked down a little longer...
         			if ( '' != $identifier ) {
         				if ( true === @unlink( $lockFile ) ) {
         					pb_backupbuddy::status( 'details', 'Removed destination lock file.' );
         				} else {
         					pb_backupbuddy::status( 'warning', 'Unable to remove destination lock file `' . $lockFile . '`.' );
         				}
         			}
         			*/
     }
 }
        }
    }
}
// end foreach.
// Mark any timed out remote sends as timed out.
$remote_sends = array();
$send_fileoptions = pb_backupbuddy::$filesystem->glob_by_date(backupbuddy_core::getLogDirectory() . 'fileoptions/send-*.txt');
if (!is_array($send_fileoptions)) {
    $send_fileoptions = array();
}
foreach ($send_fileoptions as $send_fileoption) {
    $send_id = str_replace('.txt', '', str_replace('send-', '', basename($send_fileoption)));
    pb_backupbuddy::status('details', 'About to load fileoptions data.');
    require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
    pb_backupbuddy::status('details', 'Fileoptions instance #23.');
    $fileoptions_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.32393. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
        return false;
    }
    // Don't do anything for success, failure, or already-marked as -1 finish time.
    if ('success' == $fileoptions_obj->options['status'] || 'failure' == $fileoptions_obj->options['status'] || -1 == $fileoptions_obj->options['finish_time']) {
        continue;
    }
    // Older format did not include updated_time.
    if (!isset($fileoptions_obj->options['update_time'])) {
        continue;
    }
    $secondsAgo = time() - $fileoptions_obj->options['update_time'];
    if ($secondsAgo > backupbuddy_constants::TIME_BEFORE_CONSIDERED_TIMEOUT) {
        // If 24hrs passed since last update to backup then mark this timeout as failed.
Example #5
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;
 }
Example #6
0
            pb_backupbuddy::status('details', 'Cleaned up stale local destination `' . $destination_id . '`.');
            unset(pb_backupbuddy::$options['remote_destinations'][$destination_id]);
            pb_backupbuddy::save();
        }
    }
}
// Cleanup excess remote sending stats.
pb_backupbuddy::status('details', 'Cleaning up remote send stats.');
backupbuddy_core::trim_remote_send_stats($backup_age_limit);
// Verify directory existance and anti-directory browsing is in place everywhere.
backupbuddy_core::verify_directories($skipTempGeneration = true);
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
// Mark any backups noted as in progress to timed out if taking too long. Send error email is scheduled and failed or timed out.
// Also, Purge fileoptions files without matching backup file in existance that are older than 30 days.
pb_backupbuddy::status('details', 'Cleaning up old backup fileoptions option files.');
$fileoptions_directory = backupbuddy_core::getLogDirectory() . 'fileoptions/';
$files = glob($fileoptions_directory . '*.txt');
if (!is_array($files)) {
    $files = array();
}
foreach ($files as $file) {
    pb_backupbuddy::status('details', 'Fileoptions instance #43.');
    $backup_options = new pb_backupbuddy_fileoptions($file, $read_only = true);
    if (true !== ($result = $backup_options->is_ok())) {
        pb_backupbuddy::status('error', 'Error retrieving fileoptions file `' . $file . '`. Err 335353266.');
    } else {
        if (isset($backup_options->options['archive_file'])) {
            //error_log( print_r( $backup_options->options, true ) );
            if ($backup_options->options['finish_time'] >= $backup_options->options['start_time'] && 0 != $backup_options->options['start_time']) {
                // Completed
            } elseif ($backup_options->options['finish_time'] == -1) {
 } elseif ($remote_send['status'] == 'timeout') {
     $status = '<span class="pb_label pb_label-warning">In progress or timed out</span>';
     // <a class="pb_backupbuddy_remotesend_abort" href="' . pb_backupbuddy::ajax_url( 'remotesend_abort' ) . '&send_id=' . $send_id  . '">( Abort )</a>';
 } elseif ($remote_send['status'] == 'aborted') {
     $status = '<span class="pb_label pb_label-warning">Aborted by user</span>';
 } elseif ($remote_send['status'] == 'multipart') {
     $status = '<span class="pb_label pb_label-info">Multipart transfer</span>';
     // <a class="pb_backupbuddy_remotesend_abort" href="' . pb_backupbuddy::ajax_url( 'remotesend_abort' ) . '&send_id=' . $send_id  . '">( Abort )</a>';
 } else {
     $status = '<span class="pb_label pb_label-important">' . ucfirst($remote_send['status']) . '</span>';
 }
 if (isset($remote_send['_multipart_status'])) {
     $status .= '<br>' . $remote_send['_multipart_status'];
 }
 // Display 'View Log' link if log available for this send.
 $log_file = backupbuddy_core::getLogDirectory() . 'status-remote_send-' . $send_id . '_' . pb_backupbuddy::$options['log_serial'] . '.txt';
 if (file_exists($log_file)) {
     $status .= '<br><a title="' . __('Backup Process Technical Details', 'it-l10n-backupbuddy') . '" href="' . pb_backupbuddy::ajax_url('remotesend_details') . '&send_id=' . $send_id . '&#038;TB_iframe=1&#038;width=640&#038;height=600" class="thickbox">View Log</a>';
 }
 // Determine destination.
 if (isset(pb_backupbuddy::$options['remote_destinations'][$remote_send['destination']])) {
     // Valid destination.
     $destination = pb_backupbuddy::$options['remote_destinations'][$remote_send['destination']]['title'] . ' (' . pb_backupbuddy::$options['remote_destinations'][$remote_send['destination']]['type'] . ')';
 } else {
     // Invalid destination (been deleted since send?).
     $destination = '<span class="description">Unknown</span>';
 }
 $write_speed = '';
 if (isset($remote_send['write_speed']) && '' != $remote_send['write_speed']) {
     $write_speed = 'Transfer Speed: ' . pb_backupbuddy::$format->file_size($remote_send['write_speed']) . '/sec<br>';
 }
Example #8
0
 $parent_class_test['status'] = __('OK', 'it-l10n-backupbuddy');
 array_push($tests, $parent_class_test);
 /***** BEGIN AVERAGE WRITE SPEED *****/
 require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
 $write_speed_samples = 0;
 $write_speed_sum = 0;
 $backups = glob(backupbuddy_core::getBackupDirectory() . '*.zip');
 if (!is_array($backups)) {
     $backups = array();
 }
 foreach ($backups as $backup) {
     $serial = backupbuddy_core::get_serial_from_file($backup);
     pb_backupbuddy::status('details', 'Fileoptions instance #22.');
     $backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = true);
     if (true !== ($result = $backup_options->is_ok())) {
         pb_backupbuddy::status('warning', 'Unable to open fileoptions file `' . backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt' . '`. Details: `' . $result . '`.');
     }
     if (isset($backup_options->options['integrity']) && isset($backup_options->options['integrity']['size'])) {
         $write_speed_samples++;
         $size = $backup_options->options['integrity']['size'];
         $time_taken = 0;
         if (isset($backup_options->options['steps'])) {
             foreach ($backup_options->options['steps'] as $step) {
                 if ($step['function'] == 'backup_zip_files') {
                     $time_taken = $step['finish_time'] - $step['start_time'];
                     break;
                 }
             }
             // End foreach.
         }
         // End if steps isset.
Example #9
0
File: init.php Project: russtx/tac
 public static function send($settings = array(), $files = array(), $send_id = '', $delete_after = false)
 {
     if (!is_array($files)) {
         $files = array($files);
     }
     pb_backupbuddy::status('details', 'Dropbox2 send function started. Remote send id: `' . $send_id . '`.');
     // Normalize settings, apply defaults, etc.
     $settings = self::_normalizeSettings($settings);
     // Connect to Dropbox.
     if (false === self::_connect($settings['access_token'])) {
         // Try to connect. Return false if fail.
         return false;
     }
     $max_chunk_size_bytes = $settings['max_chunk_size'] * 1024 * 1024;
     /***** BEGIN MULTIPART CHUNKED CONTINUE *****/
     // Continue Multipart Chunked Upload
     if ($settings['_chunk_upload_id'] != '') {
         $file = $settings['_chunk_file'];
         pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) preparing to send chunked multipart upload part ' . ($settings['_chunk_sent_count'] + 1) . ' of ' . $settings['_chunk_total_count'] . ' with set chunk size of `' . $settings['max_chunk_size'] . '` MB. Dropbox Upload ID: `' . $settings['_chunk_upload_id'] . '`.');
         pb_backupbuddy::status('details', 'Opening file `' . basename($file) . '` to send.');
         $f = @fopen($file, 'rb');
         if (false === $f) {
             pb_backupbuddy::status('error', 'Error #87954435. Unable to open file `' . $file . '` to send to Dropbox.');
             return false;
         }
         // Seek to next chunk location.
         pb_backupbuddy::status('details', 'Seeking file to byte `' . $settings['_chunk_next_offset'] . '`.');
         if (0 != fseek($f, $settings['_chunk_next_offset'])) {
             // return of 0 is success.
             pb_backupbuddy::status('error', 'Unable to seek file to proper location offset `' . $settings['_chunk_next_offset'] . '`.');
         } else {
             pb_backupbuddy::status('details', 'Seek success.');
         }
         // Read this file chunk into memory.
         pb_backupbuddy::status('details', 'Reading chunk into memory.');
         try {
             $data = self::readFully($f, $settings['_chunk_maxsize']);
         } catch (\Exception $e) {
             pb_backupbuddy::status('error', 'Dropbox Error #484938376: ' . $e->getMessage());
             return false;
         }
         pb_backupbuddy::status('details', 'About to put chunk to Dropbox for continuation.');
         $send_time = -microtime(true);
         try {
             $result = self::$_dbxClient->chunkedUploadContinue($settings['_chunk_upload_id'], $settings['_chunk_next_offset'], $data);
         } catch (\Exception $e) {
             pb_backupbuddy::status('error', 'Dropbox Error #8754646: ' . $e->getMessage());
             return false;
         }
         // Examine response from Dropbox.
         if (true === $result) {
             // Upload success.
             pb_backupbuddy::status('details', 'Chunk upload continuation success with valid offset.');
         } elseif (false === $result) {
             // Failed.
             pb_backupbuddy::status('error', 'Chunk upload continuation failed at offset `' . $settings['_chunk_next_offset'] . '`.');
             return false;
         } elseif (is_numeric($result)) {
             // offset wrong. Update to use this.
             pb_backupbuddy::status('details', 'Chunk upload continuation received an updated offset response of `' . $result . '` when we tried `' . $settings['_chunk_next_offset'] . '`.');
             $settings['_chunk_next_offset'] = $result;
             // Try resending with corrected offset.
             try {
                 $result = self::$_dbxClient->chunkedUploadContinue($settings['_chunk_upload_id'], $settings['_chunk_next_offset'], $data);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error #8263836: ' . $e->getMessage());
                 return false;
             }
         }
         $send_time += microtime(true);
         $data_length = strlen($data);
         unset($data);
         // Calculate some stats to log.
         $chunk_transfer_speed = $data_length / $send_time;
         pb_backupbuddy::status('details', 'Dropbox chunk transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($chunk_transfer_speed) . '`.');
         // Set options for subsequent step chunks.
         $chunked_destination_settings = $settings;
         $chunked_destination_settings['_chunk_offset'] = $data_length;
         $chunked_destination_settings['_chunk_sent_count']++;
         $chunked_destination_settings['_chunk_next_offset'] = $data_length * $chunked_destination_settings['_chunk_sent_count'];
         // First chunk was sent initiationg multipart send.
         $chunked_destination_settings['_chunk_transfer_speeds'][] = $chunk_transfer_speed;
         // Load destination fileoptions.
         pb_backupbuddy::status('details', 'About to load fileoptions data.');
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         pb_backupbuddy::status('details', 'Fileoptions instance #15.');
         $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
         if (true !== ($result = $fileoptions_obj->is_ok())) {
             pb_backupbuddy::status('error', __('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
             return false;
         }
         pb_backupbuddy::status('details', 'Fileoptions data loaded.');
         $fileoptions =& $fileoptions_obj->options;
         // Multipart send completed. Send finished signal to Dropbox to seal the deal.
         if (true === feof($f)) {
             pb_backupbuddy::status('details', 'At end of file. Finishing transfer and notifying Dropbox of file transfer completion.');
             $chunked_destination_settings['_chunk_upload_id'] = '';
             // Unset since chunking finished.
             try {
                 $result = self::$_dbxClient->chunkedUploadFinish($settings['_chunk_upload_id'], $settings['directory'] . '/' . basename($file), dbx\WriteMode::add());
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error #549838979: ' . $e->getMessage());
                 return false;
             }
             pb_backupbuddy::status('details', 'Chunked upload finish results: `' . print_r($result, true) . '`.');
             if (filesize($settings['_chunk_file']) != $result['bytes']) {
                 pb_backupbuddy::status('error', 'Error #8958944. Dropbox reported file size differs from local size. The file upload may have been corrupted.');
                 return false;
             }
             $fileoptions['write_speed'] = array_sum($chunked_destination_settings['_chunk_transfer_speeds']) / $chunked_destination_settings['_chunk_sent_count'];
             $fileoptions['_multipart_status'] = 'Sent part ' . $chunked_destination_settings['_chunk_sent_count'] . ' of ' . $chunked_destination_settings['_chunk_total_count'] . '.';
             $fileoptions['finish_time'] = time();
             $fileoptions['status'] = 'success';
             $fileoptions_obj->save();
             unset($fileoptions_obj);
         }
         fclose($f);
         pb_backupbuddy::status('details', 'Sent chunk number `' . $chunked_destination_settings['_chunk_sent_count'] . '` to Dropbox with upload ID: `' . $chunked_destination_settings['_chunk_upload_id'] . '`. Next offset: `' . $chunked_destination_settings['_chunk_next_offset'] . '`.');
         // Schedule to continue if anything is left to upload for this multipart of any individual files.
         if ($chunked_destination_settings['_chunk_upload_id'] != '' || count($files) > 0) {
             pb_backupbuddy::status('details', 'Dropbox multipart upload has more parts left. Scheduling next part send.');
             $cronTime = time();
             $cronArgs = array($chunked_destination_settings, $files, $send_id, $delete_after);
             $cronHashID = md5($cronTime . serialize($cronArgs));
             $cronArgs[] = $cronHashID;
             $schedule_result = backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs);
             if (true === $schedule_result) {
                 pb_backupbuddy::status('details', 'Next Dropbox chunk step cron event scheduled.');
             } else {
                 pb_backupbuddy::status('error', 'Next Dropbox chunk step cron even FAILED to be scheduled.');
             }
             spawn_cron(time() + 150);
             // Adds > 60 seconds to get around once per minute cron running limit.
             update_option('_transient_doing_cron', 0);
             // Prevent cron-blocking for next item.
             return array($chunked_destination_settings['_chunk_upload_id'], 'Sent ' . $chunked_destination_settings['_chunk_sent_count'] . ' of ' . $chunked_destination_settings['_chunk_total_count'] . ' parts.');
         }
     }
     // end continue multipart chunked upload.
     /***** END MULTIPART CHUNKED CONTINUE *****/
     pb_backupbuddy::status('details', 'Looping through files to send to Dropbox.');
     foreach ($files as $file_id => $file) {
         $file_size = filesize($file);
         pb_backupbuddy::status('details', 'Opening file `' . basename($file) . '` to send.');
         $f = @fopen($file, 'rb');
         if (false === $f) {
             pb_backupbuddy::status('error', 'Error #8457573. Unable to open file `' . $file . '` to send to Dropbox.');
             return false;
         }
         if ($settings['max_chunk_size'] >= 5 && $file_size / 1024 / 1024 > $settings['max_chunk_size']) {
             // chunked send.
             pb_backupbuddy::status('details', 'File exceeds chunking limit of `' . $settings['max_chunk_size'] . '` MB. Using chunked upload for this file transfer.');
             // Read first file chunk into memory.
             pb_backupbuddy::status('details', 'Reading first chunk into memory.');
             try {
                 $data = self::readFully($f, $max_chunk_size_bytes);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error #5684574373: ' . $e->getMessage());
                 return false;
             }
             // Start chunk upload to get upload ID. Sends first chunk piece.
             $send_time = -microtime(true);
             pb_backupbuddy::status('details', 'About to start chunked upload & put first chunk of file `' . basename($file) . '` to Dropbox (PHP 5.3+).');
             try {
                 $result = self::$_dbxClient->chunkedUploadStart($data);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error: ' . $e->getMessage());
                 return false;
             }
             $send_time += microtime(true);
             @fclose($f);
             $data_length = strlen($data);
             unset($data);
             // Calculate some stats to log.
             $chunk_transfer_speed = $data_length / $send_time;
             pb_backupbuddy::status('details', 'Dropbox chunk transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($chunk_transfer_speed) . '`.');
             // Set options for subsequent step chunks.
             $chunked_destination_settings = $settings;
             $chunked_destination_settings['_chunk_file'] = $file;
             $chunked_destination_settings['_chunk_maxsize'] = $max_chunk_size_bytes;
             $chunked_destination_settings['_chunk_upload_id'] = $result;
             $chunked_destination_settings['_chunk_offset'] = $data_length;
             $chunked_destination_settings['_chunk_next_offset'] = $data_length;
             // First chunk was sent initiationg multipart send.
             $chunked_destination_settings['_chunk_sent_count'] = 1;
             $chunked_destination_settings['_chunk_total_count'] = ceil($file_size / $max_chunk_size_bytes);
             $chunked_destination_settings['_chunk_transfer_speeds'][] = $chunk_transfer_speed;
             pb_backupbuddy::status('details', 'Sent first chunk to Dropbox with upload ID: `' . $chunked_destination_settings['_chunk_upload_id'] . '`. Offset: `' . $chunked_destination_settings['_chunk_offset'] . '`.');
             // Remove this file from list to send before passing $files to schedule next cron. Multipart will handle this from here on out.
             unset($files[$file_id]);
             // Schedule next chunk to send.
             pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) scheduling send of next part(s).');
             $cronTime = time();
             $cronArgs = array($chunked_destination_settings, $files, $send_id, $delete_after);
             $cronHashID = md5($cronTime . serialize($cronArgs));
             $cronArgs[] = $cronHashID;
             if (false === backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs)) {
                 pb_backupbuddy::status('error', 'Error #948844: Unable to schedule next Dropbox2 cron chunk.');
                 return false;
             } else {
                 pb_backupbuddy::status('details', 'Success scheduling next cron chunk.');
             }
             spawn_cron(time() + 150);
             // Adds > 60 seconds to get around once per minute cron running limit.
             update_option('_transient_doing_cron', 0);
             // Prevent cron-blocking for next item.
             pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) scheduled send of next part(s). Done for this cycle.');
             return array($chunked_destination_settings['_chunk_upload_id'], 'Sent 1 of ' . $chunked_destination_settings['_chunk_total_count'] . ' parts.');
         } else {
             // normal (non-chunked) send.
             pb_backupbuddy::status('details', 'Dropbox send not set to be chunked.');
             pb_backupbuddy::status('details', 'About to put file `' . basename($file) . '` (' . pb_backupbuddy::$format->file_size($file_size) . ') to Dropbox (PHP 5.3+).');
             $send_time = -microtime(true);
             try {
                 $result = self::$_dbxClient->uploadFile($settings['directory'] . '/' . basename($file), dbx\WriteMode::add(), $f);
             } catch (\Exception $e) {
                 pb_backupbuddy::status('error', 'Dropbox Error: ' . $e->getMessage());
                 return false;
             }
             $send_time += microtime(true);
             @fclose($f);
             pb_backupbuddy::status('details', 'About to load fileoptions data.');
             require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
             pb_backupbuddy::status('details', 'Fileoptions instance #14.');
             $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
             if (true !== ($result = $fileoptions_obj->is_ok())) {
                 pb_backupbuddy::status('error', __('Fatal Error #9034.2344848. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
                 return false;
             }
             pb_backupbuddy::status('details', 'Fileoptions data loaded.');
             $fileoptions =& $fileoptions_obj->options;
             // Calculate some stats to log.
             $data_length = $file_size;
             $transfer_speed = $data_length / $send_time;
             pb_backupbuddy::status('details', 'Dropbox (non-chunked) transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($transfer_speed) . '/sec`.');
             $fileoptions['write_speed'] = $transfer_speed;
             $fileoptions_obj->save();
             unset($fileoptions_obj);
         }
         // end normal (non-chunked) send.
         pb_backupbuddy::status('message', 'Success sending `' . basename($file) . '` to Dropbox!');
         // Start remote backup limit
         if ($settings['archive_limit'] > 0) {
             pb_backupbuddy::status('details', 'Dropbox file limit in place. Proceeding with enforcement.');
             $meta_data = self::$_dbxClient->getMetadataWithChildren($settings['directory']);
             // Create array of backups and organize by date
             $bkupprefix = backupbuddy_core::backup_prefix();
             $backups = array();
             foreach ((array) $meta_data['contents'] as $looping_file) {
                 if ($looping_file['is_dir'] == '1') {
                     // JUST IN CASE. IGNORE anything that is a directory.
                     continue;
                 }
                 // check if file is backup
                 if (strpos($looping_file['path'], 'backup-' . $bkupprefix . '-') !== false) {
                     // Appears to be a backup file.
                     $backups[$looping_file['path']] = strtotime($looping_file['modified']);
                 }
             }
             arsort($backups);
             if (count($backups) > $settings['archive_limit']) {
                 pb_backupbuddy::status('details', 'Dropbox backup file count of `' . count($backups) . '` exceeds limit of `' . $settings['archive_limit'] . '`.');
                 $i = 0;
                 $delete_fail_count = 0;
                 foreach ($backups as $buname => $butime) {
                     $i++;
                     if ($i > $settings['archive_limit']) {
                         if (!self::$_dbxClient->delete($buname)) {
                             // Try to delete backup on Dropbox. Increment failure count if unable to.
                             pb_backupbuddy::status('details', 'Unable to delete excess Dropbox file: `' . $buname . '`');
                             $delete_fail_count++;
                         } else {
                             pb_backupbuddy::status('details', 'Deleted excess Dropbox file: `' . $buname . '`');
                         }
                     }
                 }
                 if ($delete_fail_count !== 0) {
                     backupbuddy_core::mail_error(sprintf(__('Dropbox remote limit could not delete %s backups.', 'it-l10n-backupbuddy'), $delete_fail_count));
                 }
             }
         } else {
             pb_backupbuddy::status('details', 'No Dropbox file limit to enforce.');
         }
         // End remote backup limit
     }
     // end foreach.
     pb_backupbuddy::status('details', 'All files sent.');
     return true;
     // Success if made it this far.
 }
Example #10
0
 public static function test($settings)
 {
     $settings = self::_init($settings);
     $sendOK = false;
     $deleteOK = false;
     $send_id = 'TEST-' . pb_backupbuddy::random_string(12);
     // Try sending a file.
     if ('1' == $settings['stash_mode']) {
         // Stash mode.
         $settings['type'] = 'stash2';
     }
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id);
     // 3rd param true forces clearing of any current uploads.
     if (true === $send_response) {
         $send_response = __('Success.', 'it-l10n-backupbuddy');
         $sendOK = true;
     } else {
         global $pb_backupbuddy_destination_errors;
         $send_response = 'Error sending test file to S3 (v2). Details: `' . implode(', ', $pb_backupbuddy_destination_errors) . '`.';
     }
     pb_backupbuddy::add_status_serial('remote_send-' . $send_id);
     // Delete sent file if it was sent.
     $delete_response = 'n/a';
     if (true === $sendOK) {
         pb_backupbuddy::status('details', 'Preparing to delete sent test file.');
         if ('1' == $settings['stash_mode']) {
             // Stash mode.
             if (true === ($delete_response = pb_backupbuddy_destination_stash2::deleteFile($settings, 'remote-send-test.php'))) {
                 // success
                 $delete_response = __('Success.', 'it-l10n-backupbuddy');
                 $deleteOK = true;
             } else {
                 // error
                 $error = 'Unable to delete Stash test file `remote-send-test.php`. Details: `' . $delete_response . '`.';
                 $delete_response = $error;
                 $deleteOK = false;
             }
         } else {
             // S3 mode.
             if (true === ($delete_response = self::deleteFile($settings, 'remote-send-test.php'))) {
                 $delete_response = __('Success.', 'it-l10n-backupbuddy');
                 $deleteOK = true;
             } else {
                 $error = 'Unable to delete test file `remote-send-test.php`. Details: `' . $delete_response . '`.';
                 pb_backupbuddy::status('details', $error);
                 $delete_response = $error;
                 $deleteOK = false;
             }
         }
     } else {
         // end if $sendOK.
         pb_backupbuddy::status('details', 'Skipping test delete due to failed send.');
     }
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #7.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         return self::_error(__('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if (true !== $sendOK || true !== $deleteOK) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     pb_backupbuddy::status('details', 'Finished test function.');
     return true;
 }
Example #11
0
 function process_backup($serial, $trigger = 'manual')
 {
     pb_backupbuddy::status('details', 'Running process_backup() for serial `' . $serial . '`.');
     // Assign reference to backup data structure for this backup.
     if (!isset($this->_backup_options)) {
         pb_backupbuddy::status('details', 'About to load fileoptions data.');
         $attempt_transient_prefix = 'pb_backupbuddy_lock_attempts-';
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         $this->_backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt');
         if (true !== ($result = $this->_backup_options->is_ok())) {
             // Unable to access fileoptions.
             $attempt_delay_base = 10;
             // Base number of seconds to delay. Each subsequent attempt increases this delay by a multiple of the attempt number.
             $max_attempts = 8;
             // Max number of attempts to try to delay around a file lock. Delay increases each time.
             $this->_backup['serial'] = $serial;
             // Needs to be populated for use by cron schedule step.
             pb_backupbuddy::status('warning', __('Warning #9034 B. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Warning: ' . $result, $serial);
             // Track lock attempts in transient system. This is not vital & since locks may be having issues track this elsewhere.
             $lock_attempts = get_transient($attempt_transient_prefix . $serial);
             if (false === $lock_attempts) {
                 $lock_attempts = 0;
             }
             $lock_attempts++;
             set_transient($attempt_transient_prefix . $serial, $lock_attempts, 60 * 60 * 24);
             // Increment lock attempts. Hold attempt count for 24 hours to help make sure we don't lose attempt count if very low site activity, etc.
             if ($lock_attempts > $max_attempts) {
                 pb_backupbuddy::status('error', 'Backup halted. Maximum number of attempts made attempting to access locked fileoptions file. This may be caused by something causing backup steps to run out of order or file permission issues on the temporary directory holding the file `' . $fileoptions_file . '`. Verify correct permissions.', $serial);
                 pb_backupbuddy::status('action', 'halt_script', $serial);
                 // Halt JS on page.
                 delete_transient($attempt_transient_prefix . $serial);
                 return false;
             }
             $wait_time = $attempt_delay_base * $lock_attempts;
             pb_backupbuddy::status('message', 'A scheduled step attempted to run before the previous step completed. The previous step may have failed or two steps may be attempting to run simultaneously.', $serial);
             pb_backupbuddy::status('message', 'Waiting `' . $wait_time . '` seconds before continuing. Attempt #' . $lock_attempts . ' of ' . $max_attempts . ' max allowed before giving up.', $serial);
             $this->cron_next_step(false, $wait_time);
             return false;
             //pb_backupbuddy::status( 'action', 'halt_script' ); // Halt JS on page.
             //return false;
         } else {
             // Accessed fileoptions. Clear/reset any attempt count.
             delete_transient($attempt_transient_prefix . $serial);
         }
         pb_backupbuddy::status('details', 'Fileoptions data loaded.');
         $this->_backup =& $this->_backup_options->options;
     }
     // Handle cancelled backups (stop button).
     if (true == get_transient('pb_backupbuddy_stop_backup-' . $serial)) {
         // Backup flagged for stoppage. Proceed directly to cleanup.
         pb_backupbuddy::status('message', 'Backup STOPPED. Post backup cleanup step has been scheduled to clean up any temporary files.');
         foreach ($this->_backup['steps'] as $step_id => $step) {
             if ($step['function'] != 'post_backup') {
                 if ($step['start_time'] == 0) {
                     $this->_backup['steps'][$step_id]['start_time'] = -1;
                     // Flag for skipping.
                 }
             } else {
                 // Post backup step.
                 $this->_backup['steps'][$step_id]['args'] = array(true, true);
                 // Run post_backup in fail mode & delete backup file.
             }
         }
         //pb_backupbuddy::save();
         $this->_backup_options->save();
         pb_backupbuddy::status('action', 'halt_script');
         // Halt JS on page.
     }
     $found_next_step = false;
     foreach ((array) $this->_backup['steps'] as $step_index => $step) {
         // Loop through steps finding first step that has not run.
         //pb_backupbuddy::status( 'details', 'step: ' . $step['function'] . 'start: ' . $step['start_time'] );
         if ($step['start_time'] != -1 && $step['start_time'] != 0 && $step['finish_time'] == 0) {
             // A step is not marked for skippage, has begun but has not finished. This should not happen but the WP cron is funky. Wait a while before continuing.
             $this->_backup['steps'][$step_index]['attempts']++;
             // Increment this as an attempt.
             $this->_backup_options->save();
             if ($step['attempts'] < 6) {
                 $wait_time = 60 * $step['attempts'];
                 // Each attempt adds a minute of wait time.
                 pb_backupbuddy::status('message', 'A scheduled step attempted to run before the previous step completed. Waiting `' . $wait_time . '` seconds before continuing for it to catch up. Attempt number `' . $step['attempts'] . '`.');
                 $this->cron_next_step(false, $wait_time);
                 return false;
             } else {
                 // Too many attempts to run this step.
                 pb_backupbuddy::status('error', 'A scheduled step attempted to run before the previous step completed. After several attempts (`' . $step['attempts'] . '`) of failure BackupBuddy has given up. Halting backup.');
                 return false;
             }
             break;
         } elseif ($step['start_time'] == 0) {
             // Step that is not marked for skippage and has not started yet.
             $found_next_step = true;
             $this->_backup['steps'][$step_index]['start_time'] = time();
             // Set this step time to now.
             $this->_backup['steps'][$step_index]['attempts']++;
             // Increment this as an attempt.
             $this->_backup_options->save();
             pb_backupbuddy::status('details', 'Found next step to run: `' . $step['function'] . '`.');
             break;
             // Break out of foreach loop to continue.
         } elseif ($step['start_time'] == -1) {
             // Step flagged for skipping. Do not run.
             pb_backupbuddy::status('details', 'Step `' . $step['function'] . '` flagged for skipping. Skipping.');
         } else {
             // Last case: Finished. Skip.
             // Do nothing for completed steps.
             //pb_backupbuddy::status( 'details', 'Step `' . $step['function'] . '` doing nothing with start `' . $step['start_time'] . '`.' );
         }
     }
     // End foreach().
     if ($found_next_step === false) {
         // No more steps to perform; return.
         pb_backupbuddy::status('details', 'No more steps found.');
         return false;
     }
     //pb_backupbuddy::save();
     pb_backupbuddy::status('details', __('Peak memory usage', 'it-l10n-backupbuddy') . ': ' . round(memory_get_peak_usage() / 1048576, 3) . ' MB');
     /********* Begin Running Step Function **********/
     if (method_exists($this, $step['function'])) {
         $args = '';
         foreach ($step['args'] as $arg) {
             if (is_array($arg)) {
                 $args .= '{' . implode(',', $arg) . '},';
             } else {
                 $args .= implode(',', $step['args']) . ',';
             }
         }
         pb_backupbuddy::status('details', '-----');
         pb_backupbuddy::status('details', 'Starting step function `' . $step['function'] . '` with args `' . $args . '`. Attempt #' . ($step['attempts'] + 1) . '.');
         // attempts 0-indexed.
         $functionTitle = $step['function'];
         $subFunctionTitle = '';
         $functionTitle = backupbuddy_core::prettyFunctionTitle($step['function'], $step['args']);
         pb_backupbuddy::status('action', 'start_function^' . $step['function'] . '^' . $functionTitle);
         if ('' != $subFunctionTitle) {
             pb_backupbuddy::status('action', 'start_subfunction^' . $step['function'] . '_subfunctiontitle^' . $subFunctionTitle);
         }
         $response = call_user_func_array(array(&$this, $step['function']), $step['args']);
     } else {
         pb_backupbuddy::status('error', __('Error #82783745: Invalid function `' . $step['function'] . '`'));
         $response = false;
     }
     /********* End Running Step Function **********/
     //unset( $step );
     if ($response === false) {
         // Function finished but reported failure.
         // Failure caused by backup cancellation.
         if (true == get_transient('pb_backupbuddy_stop_backup-' . $serial)) {
             pb_backupbuddy::status('action', 'halt_script');
             // Halt JS on page.
             return false;
         }
         pb_backupbuddy::status('error', 'Failed function `' . $this->_backup['steps'][$step_index]['function'] . '`. Backup terminated.');
         pb_backupbuddy::status('action', 'error_function^' . $this->_backup['steps'][$step_index]['function']);
         pb_backupbuddy::status('details', __('Peak memory usage', 'it-l10n-backupbuddy') . ': ' . round(memory_get_peak_usage() / 1048576, 3) . ' MB');
         pb_backupbuddy::status('action', 'halt_script');
         // Halt JS on page.
         $args = print_r($this->_backup['steps'][$step_index]['args'], true);
         $attachment = NULL;
         $attachment_note = 'Enable full logging for troubleshooting (a log will be sent with future error emails while enabled).';
         if (pb_backupbuddy::$options['log_level'] == '3') {
             // Full logging enabled.
             // Log file will be attached.
             $log_file = backupbuddy_core::getLogDirectory() . 'status-' . $serial . '_' . pb_backupbuddy::$options['log_serial'] . '.txt';
             if (file_exists($log_file)) {
                 $attachment = $log_file;
                 $attachment_note = 'A log file is attached which may provide further details.';
             } else {
                 $attachment = NULL;
             }
         }
         // Send error notification email.
         backupbuddy_core::mail_error('One or more backup steps reported a failure. ' . $attachment_note . ' Backup failure running function `' . $this->_backup['steps'][$step_index]['function'] . '` with the arguments `' . $args . '` with backup serial `' . $serial . '`. Please run a manual backup of the same type to verify backups are working properly or view the backup status log.', $attachment);
         return false;
     } else {
         // Function finished successfully.
         $this->_backup['steps'][$step_index]['finish_time'] = time();
         $this->_backup['updated_time'] = time();
         $this->_backup_options->save();
         pb_backupbuddy::status('details', sprintf(__('Finished function `%s`. Peak memory usage', 'it-l10n-backupbuddy') . ': ' . round(memory_get_peak_usage() / 1048576, 3) . ' MB', $this->_backup['steps'][$step_index]['function']));
         pb_backupbuddy::status('action', 'finish_function^' . $this->_backup['steps'][$step_index]['function']);
         pb_backupbuddy::status('details', '-----');
         $found_another_step = false;
         foreach ($this->_backup['steps'] as $next_step) {
             // Loop through each step and see if any have not started yet.
             if ($next_step['start_time'] == 0) {
                 // Another unstarted step exists. Schedule it.
                 $found_another_step = true;
                 if ($this->_backup['profile']['backup_mode'] == '2') {
                     // Modern mode with crons.
                     $this->cron_next_step();
                 } else {
                     // classic mode
                     $this->process_backup($this->_backup['serial'], $trigger);
                 }
                 break;
             }
         }
         // End foreach().
         if ($found_another_step == false) {
             pb_backupbuddy::status('details', __('No more backup steps remain. Finishing...', 'it-l10n-backupbuddy'));
             $this->_backup['finish_time'] = time();
             $this->_backup_options->save();
             pb_backupbuddy::status('action', 'start_function^backup_success^Backup completed successfully.');
             pb_backupbuddy::status('action', 'finish_function^backup_success');
         } else {
             pb_backupbuddy::status('details', 'Completed step function `' . $step['function'] . '`.');
             //pb_backupbuddy::status( 'details', 'The next should run in a moment. If it does not please check for plugin conflicts and that the next step is scheduled in the cron on the Server Information page.' );
         }
         return true;
     }
 }
*/
$step = pb_backupbuddy::_POST('step');
$backup_file = pb_backupbuddy::_POST('backup_file');
$url = trim(pb_backupbuddy::_POST('url'));
switch ($step) {
    case 'step1':
        // Make sure backup file has been transferred properly.
        // Find last migration.
        $last_migration_key = get_transient('pb_backupbuddy_migrationkey');
        if (false === $last_migration_key) {
            die(json_encode(array('status_code' => 'failure', 'status_message' => 'Status: Error #54849545. Unable to determine which backup is migrating. Please try again.', 'next_step' => '0')));
        }
        pb_backupbuddy::status('details', 'About to load fileoptions data.');
        require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
        pb_backupbuddy::status('details', 'Fileoptions instance #26.');
        $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $last_migration_key . '.txt', $read_only = true, $ignore_lock = true, $create_file = false);
        if (true !== ($result = $fileoptions_obj->is_ok())) {
            pb_backupbuddy::status('error', __('Fatal Error #9034.2342348. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
            return false;
        }
        pb_backupbuddy::status('details', 'Fileoptions data loaded.');
        $fileoptions =& $fileoptions_obj->options;
        $migrate_send_status = $fileoptions['status'];
        if ($migrate_send_status == 'timeout') {
            $status_message = 'Status: Waiting for backup to finish uploading to server...';
            $next_step = '1';
        } elseif ($migrate_send_status == 'failure') {
            $status_message = 'Status: Sending backup to server failed.';
            $next_step = '0';
        } elseif ($migrate_send_status == 'success') {
            $status_message = 'Status: Success sending backup file.';
Example #13
0
File: init.php Project: russtx/tac
 public static function test($settings)
 {
     if (class_exists('CFRuntime')) {
         die('CFRuntime already defined. Another plugin may be incorrectly loading its copy of S3 libraries on BackupBuddy pages.');
     }
     require_once dirname(dirname(__FILE__)) . '/_s3lib/aws-sdk/sdk.class.php';
     $remote_path = self::get_remote_path($settings['directory']);
     // Has leading and trailng slashes.
     $settings['bucket'] = strtolower($settings['bucket']);
     // Buckets must be lowercase.
     /*
     if ( FALSE !== strpos( $settings['bucket'], ' ' ) ) {
     	$message = 'Bucket names cannot have spaces in them.';
     	return $message;
     }
     */
     // Try sending a file.
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id = 'TEST-' . pb_backupbuddy::random_string(12));
     // 3rd param true forces clearing of any current uploads.
     if (false === $send_response) {
         $send_response = 'Error sending test file to S3.';
     } else {
         $send_response = 'Success.';
     }
     // S3 object for managing files.
     $credentials = pb_backupbuddy_destination_s3::get_credentials($settings);
     $s3_manage = new AmazonS3($credentials);
     if ($settings['ssl'] == 0) {
         @$s3_manage->disable_ssl(true);
     }
     // Verify bucket exists; create if not. Also set region to the region bucket exists in.
     if (false === self::_prepareBucketAndRegion($s3_manage, $settings)) {
         return false;
     }
     // Delete sent file.
     $delete_response = 'Success.';
     $delete_response = $s3_manage->delete_object($credentials['bucket'], $remote_path . 'remote-send-test.php');
     if (!$delete_response->isOK()) {
         $delete_response = 'Unable to delete test S3 file `remote-send-test.php`.';
         pb_backupbuddy::status('details', $delete_response . ' Details: `' . print_r($delete_response, true) . '`.');
     } else {
         $delete_response = 'Success.';
     }
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #7.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if ('Success.' != $send_response || 'Success.' != $delete_response) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
Example #14
0
 // Move all files from old backup to new.
 $old_backups_moved = 0;
 $old_backups = glob($old_backup_dir . 'backup*.zip');
 if (!is_array($old_backups) || empty($old_backups)) {
     // On failure glob() returns false or an empty array depending on server settings so normalize here.
     $old_backups = array();
 }
 foreach ($old_backups as $old_backup) {
     if (false === rename($old_backup, $new_backup_dir . basename($old_backup))) {
         pb_backupbuddy::alert('ERROR: Unable to move backup "' . basename($old_backup) . '" to new storage directory. Manually move it or delete it for security and to prevent it from being backed up within backups.');
     } else {
         // rename success.
         $old_backups_moved++;
         $serial = backupbuddy_core::get_serial_from_file(basename($old_backup));
         require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
         $fileoptions_files = glob(backupbuddy_core::getLogDirectory() . 'fileoptions/*.txt');
         if (!is_array($fileoptions_files)) {
             $fileoptions_files = array();
         }
         foreach ($fileoptions_files as $fileoptions_file) {
             pb_backupbuddy::status('details', 'Fileoptions instance #21.');
             $backup_options = new pb_backupbuddy_fileoptions($fileoptions_file);
             if (true !== ($result = $backup_options->is_ok())) {
                 pb_backupbuddy::status('error', __('Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
                 continue;
             }
             if (isset($backup_options->options[$serial])) {
                 if (isset($backup_options->options['archive_file'])) {
                     $backup_options->options['archive_file'] = str_replace($old_backup_dir, $new_backup_dir, $backup_options->options['archive_file']);
                 }
             }
Example #15
0
 public static function test($settings)
 {
     if ($settings['address'] == '' || $settings['username'] == '' || $settings['password'] == '') {
         return __('Missing required input.', 'it-l10n-backupbuddy');
     }
     // Try sending a file.
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id = 'TEST-' . pb_backupbuddy::random_string(12));
     // 3rd param true forces clearing of any current uploads.
     if (false === $send_response) {
         $send_response = 'Error sending test file to FTP.';
     } else {
         $send_response = 'Success.';
     }
     // Now we will need to go and cleanup this potentially uploaded file.
     $delete_response = 'Error deleting test file from FTP.';
     // Default.
     // Settings.
     $server = $settings['address'];
     $username = $settings['username'];
     $password = $settings['password'];
     $path = $settings['path'];
     $ftps = $settings['ftps'];
     if ($settings['active_mode'] == '0') {
         $active_mode = false;
     } else {
         $active_mode = true;
     }
     $url = $settings['url'];
     // optional url for using with migration.
     $port = '21';
     if (strstr($server, ':')) {
         $server_params = explode(':', $server);
         $server = $server_params[0];
         $port = $server_params[1];
     }
     // Connect.
     if ($ftps == '0') {
         $conn_id = @ftp_connect($server, $port, 10);
         // timeout of 10 seconds.
         if ($conn_id === false) {
             $error = __('Unable to connect to FTP address `' . $server . '` on port `' . $port . '`.', 'it-l10n-backupbuddy');
             $error .= "\n" . __('Verify the server address and port (default 21). Verify your host allows outgoing FTP connections.', 'it-l10n-backupbuddy');
             return $send_response . ' ' . $error;
         }
     } else {
         if (function_exists('ftp_ssl_connect')) {
             $conn_id = @ftp_ssl_connect($server, $port);
             if ($conn_id === false) {
                 return $send_response . ' ' . __('Destination server does not support FTPS?', 'it-l10n-backupbuddy');
             }
         } else {
             return $send_response . ' ' . __('Your web server doesnt support FTPS.', 'it-l10n-backupbuddy');
         }
     }
     $login_result = @ftp_login($conn_id, $username, $password);
     if (!$conn_id || !$login_result) {
         pb_backupbuddy::status('details', 'FTP test: Invalid user/pass.');
         $response = __('Unable to login. Bad user/pass.', 'it-l10n-backupbuddy');
         if ($ftps != '0') {
             $response .= "\n\nNote: You have FTPs enabled. You may get this error if your host does not support encryption at this address/port.";
         }
         return $send_response . ' ' . $response;
     }
     pb_backupbuddy::status('details', 'FTP test: Success logging in.');
     // Handle active/pasive mode.
     if ($active_mode === true) {
         // do nothing, active is default.
         pb_backupbuddy::status('details', 'Active FTP mode based on settings.');
     } elseif ($active_mode === false) {
         // Turn passive mode on.
         pb_backupbuddy::status('details', 'Passive FTP mode based on settings.');
         ftp_pasv($conn_id, true);
     } else {
         pb_backupbuddy::status('error', 'Unknown FTP active/passive mode: `' . $active_mode . '`.');
     }
     // Delete test file.
     pb_backupbuddy::status('details', 'FTP test: Deleting temp test file.');
     if (true === ftp_delete($conn_id, $path . '/remote-send-test.php')) {
         $delete_response = 'Success.';
     }
     // Close FTP connection.
     pb_backupbuddy::status('details', 'FTP test: Closing FTP connection.');
     @ftp_close($conn_id);
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #12.');
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.72373. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if ('Success.' != $send_response || 'Success.' != $delete_response) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
Example #16
0
<?php

if (!is_admin()) {
    die('Access Denied.');
}
$settings_form = new pb_backupbuddy_settings('advanced_settings', '', 'tab=1', 320);
$settings_form->add_setting(array('type' => 'title', 'name' => 'title_basic', 'title' => __('Basic Operation', 'it-l10n-backupbuddy')));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'backup_reminders', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Enable backup reminders for edits', 'it-l10n-backupbuddy'), 'tip' => __('[Default: enabled] - When enabled links will be displayed upon post or page edits and during WordPress upgrades to remind and allow rapid backing up after modifications or before upgrading.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'archive_name_format', 'options' => array('unchecked' => 'date', 'checked' => 'datetime'), 'title' => __('Add time in backup file name', 'it-l10n-backupbuddy'), 'tip' => __('[Default: disabled (date only)] - When enabled your backup filename will display the time the backup was created in addition to the default date. This is useful when making multiple backups in a one day period.', 'it-l10n-backupbuddy'), 'css' => '', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'lock_archives_directory', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Lock archive directory (high security)', 'it-l10n-backupbuddy'), 'tip' => __('[Default: disabled] - When enabled all downloads of archives via the web will be prevented under all circumstances via .htaccess file. If your server permits it, they will only be unlocked temporarily on click to download. If your server does not support this unlocking then you will have to access the archives via the server (such as by FTP).', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '<span class="description"> ' . __('May prevent downloading backups within WordPress on incompatible servers', 'it-l10n-backupbuddy'), 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'include_importbuddy', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Include ImportBuddy in full backup archive', 'it-l10n-backupbuddy'), 'tip' => __('[Default: enabled] - When enabled, the importbuddy.php (restoration tool) file will be included within the backup archive ZIP file in the location `/' . str_replace(ABSPATH, '', backupbuddy_core::getTempDirectory()) . ' xxxxxxxxxx/ importbuddy.php` where the x\'s match the unique random string in the backup ZIP filename.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => ' <span style="white-space: nowrap;"><span class="description">' . __('Located in backup', 'it-l10n-backupbuddy') . ':</span>&nbsp; <span class="code" style="white-space: normal; background: #EAEAEA;"">/' . str_replace(ABSPATH, '', backupbuddy_core::getTempDirectory()) . 'xxxxxxxxxx/importbuddy.php</span>', 'rules' => 'required'));
$log_file = backupbuddy_core::getLogDirectory() . 'log-' . pb_backupbuddy::$options['log_serial'] . '.txt';
$settings_form->add_setting(array('type' => 'select', 'name' => 'log_level', 'title' => __('Logging Level', 'it-l10n-backupbuddy'), 'options' => array('0' => __('None', 'it-l10n-backupbuddy'), '1' => __('Errors Only', 'it-l10n-backupbuddy'), '2' => __('Errors & Warnings', 'it-l10n-backupbuddy'), '3' => __('Everything (troubleshooting mode)', 'it-l10n-backupbuddy')), 'tip' => sprintf(__('[Default: Errors Only] - This option controls how much activity is logged for records or troubleshooting. Logs may be viewed from the Logs / Other tab on the Settings page. Additionally when in Everything / Troubleshooting mode error emails will contain encrypted troubleshooting data for support. Log file: %s', 'it-l10n-backupbuddy'), $log_file), 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'select', 'name' => 'default_backup_tab', 'title' => __('Default backup tab', 'it-l10n-backupbuddy'), 'options' => array('0' => __('Overview', 'it-l10n-backupbuddy'), '1' => __('Status Log', 'it-l10n-backupbuddy')), 'tip' => sprintf(__('[Default: Overview] - The default tab open during a backup is the overview tab. A more technical view is available in the Status tab.', 'it-l10n-backupbuddy')), 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'text', 'name' => 'max_site_log_size', 'title' => __('Maximum log file size', 'it-l10n-backupbuddy'), 'tip' => __('[Default: 10 MB] - If the log file exceeds this size then it will be cleared to prevent it from using too much space.'), 'rules' => 'required|int', 'css' => 'width: 50px;', 'after' => ' MB'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'disable_localization', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Disable language localization', 'it-l10n-backupbuddy'), 'tip' => __('[Default: Unchecked] When checked language localization support will be disabled. BackupBuddy will revert to full English language mode. Use this to display logs in English for support.', 'it-l10n-backupbuddy') . '</span>', 'css' => '', 'after' => '<span class="description"> ' . __('Check to run BackupBuddy in English. This is useful for support.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'title', 'name' => 'title_advanced', 'title' => __('Technical & Server Compatibility', 'it-l10n-backupbuddy')));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'delete_archives_pre_backup', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Delete all backup archives prior to backups', 'it-l10n-backupbuddy'), 'tip' => __('[Default: disabled] - When enabled all local backup archives will be deleted prior to each backup. This is useful if in compatibilty mode to prevent backing up existing files.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '<span class="description"> ' . __('Use is exclusions are malfunctioning or for special purposes.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'disable_https_local_ssl_verify', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Disable local SSL certificate verification', 'it-l10n-backupbuddy'), 'tip' => __('[Default: Disabled] When checked, WordPress will skip local https SSL verification.', 'it-l10n-backupbuddy') . '</span>', 'css' => '', 'after' => '<span class="description"> ' . __('Workaround if local SSL verification fails (ie. for loopback & local CA cert issues).', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'prevent_flush', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Prevent Flushing', 'it-l10n-backupbuddy'), 'tip' => __('[Default: not prevented (unchecked)] - Rarely some servers die unexpectedly when flush() or ob_flush() are called multiple times during the same PHP process. Checking this prevents these from ever being called during backups.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '<span class="description"> ' . __('Check if directed by support.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'save_comment_meta', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Save meta data in comment', 'it-l10n-backupbuddy'), 'tip' => __('[Default: Enabled] When enabled, BackupBuddy will store general backup information in the ZIP comment header such as Site URL, backup type & time, serial, etc. during backup creation.', 'it-l10n-backupbuddy') . '</span>', 'css' => '', 'after' => '<span class="description"> ' . __('If backups hang when saving meta data disabling skips this process.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'profiles#0#integrity_check', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Perform integrity check on backup files', 'it-l10n-backupbuddy'), 'tip' => __('[Default: enabled] - By default each backup file is checked for integrity and completion the first time it is viewed on the Backup page.  On some server configurations this may cause memory problems as the integrity checking process is intensive.  If you are experiencing out of memory errors on the Backup file listing, you can uncheck this to disable this feature.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '<span class="description"> ' . __('Disable if the backup page will not load or backups hang on integrity check.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'backup_cron_rescheduling', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Reschedule missing crons in manual backups', 'it-l10n-backupbuddy'), 'tip' => __('[Default: disabled] - To proceed to subsequent steps during backups BackupBuddy schedules the next step with the WordPress cron system.  If this cron goes missing the backup cannot proceed. This feature instructs BackupBuddy to attempt to re-schedule this cron as it occurs.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '<span class="description"> ' . __('Check if directed by support.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'select', 'name' => 'backup_mode', 'title' => __('Default global backup mode', 'it-l10n-backupbuddy'), 'options' => array('1' => __('Classic (v1.x) - Entire backup in single PHP page load', 'it-l10n-backupbuddy'), '2' => __('Modern (v2.x+) - Split across page loads via WP cron', 'it-l10n-backupbuddy')), 'tip' => __('[Default: Modern] - If you are encountering difficulty backing up due to WordPress cron, HTTP Loopbacks, or other features specific to version 2.x you can try classic mode which runs like BackupBuddy v1.x did.', 'it-l10n-backupbuddy'), 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'title', 'name' => 'title_database', 'title' => __('Database', 'it-l10n-backupbuddy')));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'profiles#0#skip_database_dump', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Skip database dump on backup', 'it-l10n-backupbuddy'), 'tip' => __('[Default: disabled] - (WARNING: This prevents BackupBuddy from backing up the database during any kind of backup. This is for troubleshooting / advanced usage only to work around being unable to backup the database.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '<span class="description"> ' . __('Completely bypass backing up database for all database types. Use caution.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required', 'orientation' => 'vertical'));
$settings_form->add_setting(array('type' => 'select', 'name' => 'database_method_strategy', 'title' => __('Database method strategy', 'it-l10n-backupbuddy'), 'options' => array('php' => __('PHP-based: Supports automated chunked resuming - default', 'it-l10n-backupbuddy'), 'commandline' => __('Commandline: Fast but does not support resuming', 'it-l10n-backupbuddy'), 'all' => __('All Available: ( PHP [chunking] > Commandline via exec()  )', 'it-l10n-backupbuddy')), 'tip' => __('[Default: PHP-based] - Normally use PHP-based which supports chunking (as of BackupBuddy v5) to support larger databases. Commandline-based database dumps use mysqldump which is very fast and efficient but cannot be broken up into smaller steps if it is too large which could result in timeouts on larger servers.', 'it-l10n-backupbuddy'), 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'breakout_tables', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Break out big table dumps into steps', 'it-l10n-backupbuddy'), 'tip' => __('[Default: enabled] When enabled, BackupBuddy will dump some of the commonly larger tables in separate steps. Note this only applies to command-line based dumps as PHP-based dumps automatically support chunking with resume on table and/or row as needed.', 'it-l10n-backupbuddy') . '</span>', 'css' => '', 'after' => '<span class="description"> ' . __('Commandline method: Break up dumping of big tables (chunking)', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
$settings_form->add_setting(array('type' => 'text', 'name' => 'phpmysqldump_maxrows', 'title' => __('Compatibility mode max rows per select', 'it-l10n-backupbuddy'), 'tip' => __('[Default: *blank*] - When BackupBuddy is using compatibility mdoe mysql dumping (via PHP), BackupBuddy selects data from the database. Reducing this number has BackupBuddy grab smaller portions from the database at a time. Leave blank to use built in default (around 2000 rows per select).', 'it-l10n-backupbuddy'), 'css' => 'width: 50px;', 'after' => ' rows. <span class="description"> ' . __('Blank for default.', 'it-l10n-backupbuddy') . ' (~1000 rows/select)</span>', 'rules' => 'int'));
$settings_form->add_setting(array('type' => 'text', 'name' => 'max_execution_time', 'title' => __('Maximum time per chunk', 'it-l10n-backupbuddy'), 'tip' => __('[Default: *blank*] - The maximum amount of time BackupBuddy should allow a database import chunk to run. BackupBuddy by default limits each chunk to your Maximum PHP runtime when using the default PHP-based method. If your database dump step is timing out then lowering this value will instruct the script to limit each `chunk` to allow it to finish within this time period. Raising this value above your servers limits will not increase or override server settings.', 'it-l10n-backupbuddy'), 'css' => 'width: 50px;', 'after' => ' sec. <span class="description"> ' . __('Blank for detected default.', 'it-l10n-backupbuddy') . ' (' . backupbuddy_core::detectMaxExecutionTime() . ' sec)</span>', 'rules' => 'int'));
$settings_form->add_setting(array('type' => 'checkbox', 'name' => 'ignore_command_length_check', 'options' => array('unchecked' => '0', 'checked' => '1'), 'title' => __('Ignore command line length check results', 'it-l10n-backupbuddy'), 'tip' => __('[Default: disabled] - WARNING: BackupBuddy attempts to determine your system\'s maximum command line length to insure that database operation commands do not get inadvertantly cut off. On some systems it is not possible to reliably detect this information which could result infalling back into compatibility mode even though the system is capable of running in normal operational modes. This option instructs BackupBuddy to ignore the results of the command line length check.', 'it-l10n-backupbuddy'), 'css' => '', 'after' => '<span class="description"> ' . __('Check if directed by support.', 'it-l10n-backupbuddy') . '</span>', 'rules' => 'required'));
if (!is_admin()) {
    die('Access denied.');
}
// Display backup integrity status.
/* integrity_status()
*
* description
*
*/
$serial = pb_backupbuddy::_GET('serial');
$serial = str_replace('/\\', '', $serial);
pb_backupbuddy::load();
pb_backupbuddy::$ui->ajax_header();
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
pb_backupbuddy::status('details', 'Fileoptions instance #27.');
$backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = true);
if (true !== ($result = $backup_options->is_ok())) {
    pb_backupbuddy::alert(__('Unable to access fileoptions data file.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
    die;
}
$integrity = $backup_options->options['integrity'];
//echo '<p><b>' . __( 'Backup File', 'it-l10n-backupbuddy' ) . '</b>: ' . $integrity['file'] . '</p>';
$start_time = 'Unknown';
$finish_time = 'Unknown';
if (isset($backup_options->options['start_time'])) {
    $start_time = pb_backupbuddy::$format->date(pb_backupbuddy::$format->localize_time($backup_options->options['start_time'])) . ' <span class="description">(' . pb_backupbuddy::$format->time_ago($backup_options->options['start_time']) . ' ago)</span>';
    if ($backup_options->options['finish_time'] > 0) {
        $finish_time = pb_backupbuddy::$format->date(pb_backupbuddy::$format->localize_time($backup_options->options['finish_time'])) . ' <span class="description">(' . pb_backupbuddy::$format->time_ago($backup_options->options['finish_time']) . ' ago)</span>';
    } else {
        // unfinished.
        $finish_time = '<i>Unfinished</i>';
// ********** BEGIN 3.1.8.2 -> 3.1.8.3 DATA MIGRATION **********
if (pb_backupbuddy::$options['data_version'] < 4) {
    pb_backupbuddy::$options['data_version'] = '4';
    // Update data structure version to 4.
    pb_backupbuddy::$options['role_access'] = 'activate_plugins';
    // Change default role from `administrator` to `activate_plugins` capability.
    pb_backupbuddy::save();
}
// ********** END 3.1.8.2 -> 3.1.8.3 DATA MIGRATION **********
// ********** BEGIN 3.3.0 -> 3.3.0.1 BACKUP DATASTRUCTURE OPTIONS to FILEOPTIONS MIGRATION **********
if (pb_backupbuddy::$options['data_version'] < 5) {
    if (isset(pb_backupbuddy::$options['backups']) && count(pb_backupbuddy::$options['backups']) > 0) {
        pb_backupbuddy::anti_directory_browsing(backupbuddy_core::getLogDirectory() . 'fileoptions/');
        require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
        foreach (pb_backupbuddy::$options['backups'] as $serial => $backup) {
            $backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
            $backup_options->options = $backup;
            if (true === $backup_options->save()) {
                unset(pb_backupbuddy::$options['backups'][$serial]);
            }
            unset($backup_options);
        }
    }
    pb_backupbuddy::$options['data_version'] = '5';
    pb_backupbuddy::save();
}
// ********** END 3.3.0 -> 3.3.0.1 BACKUP DATASTRUCTURE OPTIONS to FILEOPTIONS MIGRATION **********
// ********** BEGIN 4.0 UPGRADE **********
if (pb_backupbuddy::$options['data_version'] < 6) {
    // Migrate profile-specific settings into 'Defaults' key profile.
    pb_backupbuddy::$options['profiles'][0]['skip_database_dump'] = pb_backupbuddy::$options['skip_database_dump'];
Example #19
0
 function remotesend_abort()
 {
     $send_id = pb_backupbuddy::_GET('send_id');
     $send_id = str_replace('/\\', '', $send_id);
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = true, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.324544. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     $fileoptions['status'] = 'aborted';
     $fileoptions_obj->save();
     die('1');
 }
    $createdFileOptions = true;
}
$options = array_merge(array('skip_database_dump' => '0'), (array) $options);
$scan_notes = array();
// Get backup fileoptions.
if ($fileoptions != '') {
    $backup_options =& $fileoptions;
    $backup_options_options =& $backup_options->options;
} else {
    //if ( file_exists( backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt' ) ) {
    require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
    pb_backupbuddy::status('details', 'Fileoptions instance #44.');
    $backup_options = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true);
    // Will create file to hold integrity data if nothing exists.
    if (true !== ($result = $backup_options->is_ok())) {
        pb_backupbuddy::status('error', __('Fatal Error #9034 C. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error on file `' . backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt' . '`: ' . $result);
        pb_backupbuddy::status('haltScript', '');
        // Halt JS on page.
        return false;
    }
    if (!is_array($backup_options->options)) {
        $backup_options->options = array();
    }
    $backup_options_options =& $backup_options->options;
}
// We did not have a fileoptions file so we are rebuilding portions of it using information found in the DAT file.
if (true === $createdFileOptions) {
    $backup_options_options['breakout_tables'] = $options['breakout_tables'];
    $backup_options_options['table_sizes'] = $options['tables_sizes'];
    $backup_options_options['type'] = $options['backup_type'];
    if (isset($options['force_single_db_file'])) {
Example #21
0
 private static function _test_status_log()
 {
     $status_log_file = backupbuddy_core::getLogDirectory() . 'status-live_periodic_' . pb_backupbuddy::$options['log_serial'] . '.txt';
     $status_log_file_contents = file_get_contents($status_log_file);
     self::_find_notices($status_log_file_contents, $status_log_file);
     // Get tail of status log.
     if (file_exists($status_log_file)) {
         self::$_results['live_status_log_tail'] = backupbuddy_core::read_backward_line($status_log_file, self::$_settings['status_log_recent_lines']);
     } else {
         self::$_results['extraneous_log_tail'] = '**Log file `' . $status_log_file . '` not found.**';
     }
 }
 public function deploy_sendWait($state, $sendFile, $sendPath, $sendType, $nextStep)
 {
     $maxSendTime = 60 * 5;
     if ('' == $sendFile) {
         // File failed. Proceed to next.
         $this->insert_next_step($nextStep);
     }
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     pb_backupbuddy::status('details', 'Fileoptions instance #38.');
     $identifier = $this->_backup['serial'] . '_' . md5($sendFile . $sendType);
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $identifier . '.txt', $read_only = false, $ignore_lock = true, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034 E. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         pb_backupbuddy::status('haltScript', '');
         // Halt JS on page.
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     // Set reference.
     if ('0' == $fileoptions['finish_time']) {
         // Not finished yet. Insert next chunk to wait.
         $timeAgo = time() - $fileoptions['start_time'];
         if ($timeAgo > $maxSendTime) {
             pb_backupbuddy::status('error', 'Error #4948348: Maximum allowed file send time of `' . $maxSendTime . '` seconds passed. Halting.');
             pb_backupbuddy::status('haltScript', '');
             // Halt JS on page.
         }
         pb_backupbuddy::status('details', 'File send not yet finished. Started `' . $timeAgo . '` seconds ago. Inserting wait.');
         $newStep = array('function' => 'deploy_sendWait', 'args' => array($state, $sendFile, $sendPath, $sendType, $nextStep), 'start_time' => 0, 'finish_time' => 0, 'attempts' => 0);
         $this->insert_next_step($newStep);
     } else {
         // Finished. Go to next step.
         $this->insert_next_step($nextStep);
     }
     return true;
 }
Example #23
0
 public static function getBackupTypeFromFile($file, $quiet = false)
 {
     if (false === $quiet) {
         pb_backupbuddy::status('details', 'Detecting backup type if possible.');
     }
     // Try to figure out type via filename.
     if (stristr($file, '-db-') !== false) {
         $type = 'db';
     } elseif (stristr($file, '-full-') !== false) {
         $type = 'full';
     } elseif (stristr($file, '-files-') !== false) {
         $type = 'files';
     }
     if (isset($type)) {
         if (false === $quiet) {
             pb_backupbuddy::status('details', 'Detected backup type as `' . $type . '` via filename.');
         }
         return $type;
     }
     // See if we can get backup type from fileoptions data.
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $fileoptionsFile = backupbuddy_core::getLogDirectory() . 'fileoptions/' . backupbuddy_core::get_serial_from_file($file) . '.txt';
     $backup_options = new pb_backupbuddy_fileoptions($fileoptionsFile, $read_only = true, $ignore_lock = true);
     if (true !== ($result = $backup_options->is_ok())) {
         //pb_backupbuddy::status( 'warning', 'Warning only: Unable to open fileoptions file `' . $fileoptionsFile . '`. This may be normal.' );
     } else {
         if (isset($backup_options->options['integrity']['detected_type'])) {
             if (false === $quiet) {
                 pb_backupbuddy::status('details', 'Detected backup type as `' . $backup_options->options['integrity']['detected_type'] . '` via integrity check data.');
             }
             return $backup_options->options['integrity']['detected_type'];
         }
     }
     return '';
     // Type unknown.
 }
Example #24
0
<?php

backupbuddy_core::verifyAjaxAccess();
pb_backupbuddy::$ui->ajax_header();
$serial = pb_backupbuddy::_GET('serial');
$logFile = backupbuddy_core::getLogDirectory() . 'status-' . $serial . '_sum_' . pb_backupbuddy::$options['log_serial'] . '.txt';
if (!file_exists($logFile)) {
    die('Error #858733: Log file `' . $logFile . '` not found or access denied.');
}
$lines = file_get_contents($logFile);
$lines = explode("\n", $lines);
?>

<textarea readonly="readonly" id="backupbuddy_messages" wrap="off" style="width: 100%; min-height: 400px; height: 500px; height: 80%; background: #FFF;"><?php 
foreach ((array) $lines as $rawline) {
    $line = json_decode($rawline, true);
    //print_r( $line );
    if (is_array($line)) {
        $u = '';
        if (isset($line['u'])) {
            // As off v4.2.15.6. TODO: Remove this in a couple of versions once old logs without this will have cycled out.
            $u = '.' . $line['u'];
        }
        echo pb_backupbuddy::$format->date($line['time'], 'G:i:s') . $u . "\t\t";
        echo $line['run'] . "sec\t";
        echo $line['mem'] . "MB\t";
        echo $line['event'] . "\t";
        echo $line['data'] . "\n";
    } else {
        echo $rawline . "\n";
    }
Example #25
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;
 }
/*	file_tree()
*	
*	File tree for viewing zip contents.
*	
*	@return		null
*/
// How long to cache the specific backup file tree information for (seconds)
$max_cache_time = 86400;
// This is the root directory we want the listing for
$root = trim(urldecode(pb_backupbuddy::_POST('dir')));
$root_len = strlen($root);
// This will identify the backup zip file we want to list
$serial = pb_backupbuddy::_GET('serial');
// The fileoptions file that contains the file tree information
require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
$fileoptions_file = backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '-filetree.txt';
// Purge cache if too old.
if (file_exists($fileoptions_file) && time() - filemtime($fileoptions_file) > $max_cache_time) {
    if (false === unlink($fileoptions_file)) {
        pb_backupbuddy::alert('Error #456765545. Unable to wipe cached fileoptions file `' . $fileoptions_file . '`.');
    }
}
$fileoptions = new pb_backupbuddy_fileoptions($fileoptions_file);
// Either we are getting cached file tree information or we need to create afresh
if (true !== ($result = $fileoptions->is_ok())) {
    // Get file listing.
    require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
    pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy(ABSPATH, array(), 'unzip');
    $files = pb_backupbuddy::$classes['zipbuddy']->get_file_list(backupbuddy_core::getBackupDirectory() . str_replace('\\/', '', pb_backupbuddy::_GET('zip_viewer')));
    $fileoptions->options = $files;
    $fileoptions->save();
<?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);
}
Example #28
0
<br><?php 
$tests = array();
$uploads_dirs = wp_upload_dir();
$directories = array(ABSPATH . '', ABSPATH . 'wp-includes/', ABSPATH . 'wp-admin/', WP_CONTENT_DIR . '/themes/', WP_CONTENT_DIR . '/plugins/', WP_CONTENT_DIR . '/', rtrim($uploads_dirs['basedir'], '\\/') . '/', ABSPATH . 'wp-includes/', backupbuddy_core::getBackupDirectory(), backupbuddy_core::getLogDirectory());
if (@file_exists(backupbuddy_core::getTempDirectory())) {
    // This dir is usually transient so may not exist.
    $directories[] = backupbuddy_core::getTempDirectory();
}
foreach ($directories as $directory) {
    $mode_octal_four = '<i>' . __('Unknown', 'it-l10n-backupbuddy') . '</i>';
    $owner = '<i>' . __('Unknown', 'it-l10n-backupbuddy') . '</i>';
    if (!file_exists($directory)) {
        $mode_octal_four = 'Directory does\'t exist';
        $owner = 'n/a';
    }
    $stats = pluginbuddy_stat::stat($directory);
    if (false !== $stats) {
        $mode_octal_four = $stats['mode_octal_four'];
        $owner = $stats['uid'] . ':' . $stats['gid'];
    }
    $this_test = array('title' => '/' . str_replace(ABSPATH, '', $directory), 'suggestion' => '<= 755', 'value' => $mode_octal_four, 'owner' => $owner);
    if (false === $stats || $mode_octal_four > 755) {
        $this_test['status'] = __('WARNING', 'it-l10n-backupbuddy');
    } else {
        $this_test['status'] = __('OK', 'it-l10n-backupbuddy');
    }
    array_push($tests, $this_test);
}
// end foreach.
?>
Example #29
0
 public static function test($settings)
 {
     $remote_path = self::get_remote_path($settings['directory']);
     // Has leading and trailng slashes.
     $manage_data = pb_backupbuddy_destination_stash::get_manage_data($settings);
     if (!is_array($manage_data['credentials'])) {
         // Credentials were somehow faulty. User changed password after prior page? Unlikely but you never know...
         $error_msg = 'Error #8484383c: Your authentication credentials for Stash failed. Verify your login and password to Stash. You may need to update the Stash destination settings. Perhaps you recently changed your password?';
         pb_backupbuddy::status('error', $error_msg);
         return $error_msg;
     }
     // Try sending a file.
     $send_response = pb_backupbuddy_destinations::send($settings, dirname(dirname(__FILE__)) . '/remote-send-test.php', $send_id = 'TEST-' . pb_backupbuddy::random_string(12));
     // 3rd param true forces clearing of any current uploads.
     if (false === $send_response) {
         $send_response = 'Error sending test file to Stash.';
     } else {
         $send_response = 'Success.';
     }
     // S3 object for managing files.
     $credentials = pb_backupbuddy_destination_stash::get_manage_data($settings);
     $s3_manage = new AmazonS3($manage_data['credentials']);
     if ($settings['ssl'] == 0) {
         @$s3_manage->disable_ssl(true);
     }
     // Delete sent file.
     $delete_response = 'Success.';
     $delete_response = $s3_manage->delete_object($manage_data['bucket'], $manage_data['subkey'] . $remote_path . 'remote-send-test.php');
     if (!$delete_response->isOK()) {
         $delete_response = 'Unable to delete test Stash file `remote-send-test.php`. Details: `' . print_r($response, true) . '`.';
         pb_backupbuddy::status('details', $delete_response);
     } else {
         $delete_response = 'Success.';
     }
     // Load destination fileoptions.
     pb_backupbuddy::status('details', 'About to load fileoptions data.');
     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
     if (true !== ($result = $fileoptions_obj->is_ok())) {
         pb_backupbuddy::status('error', __('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
         return false;
     }
     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
     $fileoptions =& $fileoptions_obj->options;
     if ('Success.' != $send_response || 'Success.' != $delete_response) {
         $fileoptions['status'] = 'failure';
         $fileoptions_obj->save();
         unset($fileoptions_obj);
         return 'Send details: `' . $send_response . '`. Delete details: `' . $delete_response . '`.';
     } else {
         $fileoptions['status'] = 'success';
         $fileoptions['finish_time'] = time();
     }
     $fileoptions_obj->save();
     unset($fileoptions_obj);
     return true;
 }
 }
 if (isset($wp_upload_dir['basedir'])) {
     $wp_settings[] = array('Upload Base Directory', $wp_upload_dir['basedir'], 'wp_upload_dir()');
 }
 $wp_settings[] = array('Site URL', site_url(), 'site_url()');
 $wp_settings[] = array('Home URL', home_url(), 'home_url()');
 $wp_settings[] = array('WordPress Root Path', ABSPATH, 'ABSPATH');
 // Multisite extras:
 $wp_settings_multisite = array();
 if (is_multisite()) {
     $wp_settings[] = array('Network Site URL', network_site_url(), 'network_site_url()');
     $wp_settings[] = array('Network Home URL', network_home_url(), 'network_home_url()');
 }
 $wp_settings[] = array('BackupBuddy local storage', backupbuddy_core::getBackupDirectory(), 'BackupBuddy Settings');
 $wp_settings[] = array('BackupBuddy temporary files', backupbuddy_core::getTempDirectory(), 'ABSPATH + Hardcoded location');
 $wp_settings[] = array('BackupBuddy logs', backupbuddy_core::getLogDirectory(), 'Upload Base + BackupBuddy');
 // Display WP settings..
 pb_backupbuddy::$ui->list_table($wp_settings, array('action' => pb_backupbuddy::page_url(), 'columns' => array(__('URLs & Paths', 'it-l10n-backupbuddy'), __('Value', 'it-l10n-backupbuddy'), __('Obtained via', 'it-l10n-backupbuddy')), 'css' => 'width: 100%;'));
 pb_backupbuddy::$ui->end_tab();
 // This page can take a bit to run.
 // Runs AFTER server information is displayed so we can view the default limits for the server.
 pb_backupbuddy::set_greedy_script_limits();
 pb_backupbuddy::$ui->start_tab('database');
 require_once 'server_info/database.php';
 echo '<br><br><a name="database_replace"></a>';
 echo '<div class="pb_htitle">' . 'Advanced: ' . __('Database Mass Text Replacement', 'it-l10n-backupbuddy') . '</div><br>';
 pb_backupbuddy::load_view('_server_tools-database_replace');
 pb_backupbuddy::$ui->end_tab();
 pb_backupbuddy::$ui->start_tab('files');
 require_once 'server_info/site_size.php';
 pb_backupbuddy::$ui->end_tab();