Пример #1
0
/**
 *	upload()
 *
 *	Processes uploaded backup file.
 *
 *	@return		array		True on upload success; false otherwise.
 */
function upload()
{
    Auth::require_authentication();
    if (isset($_POST['upload']) && $_POST['upload'] == 'local') {
        $path_parts = pathinfo($_FILES['file']['name']);
        if (strtolower(substr($_FILES['file']['name'], 0, 6)) == 'backup' && strtolower($path_parts['extension']) == 'zip') {
            if (move_uploaded_file($_FILES['file']['tmp_name'], basename($_FILES['file']['name']))) {
                pb_backupbuddy::alert('File Uploaded. Your backup was successfully uploaded.');
                return true;
            } else {
                pb_backupbuddy::alert('Sorry, there was a problem uploading your file.', true);
                return false;
            }
        } else {
            pb_backupbuddy::alert('Only properly named BackupBuddy zip archives with a zip extension may be uploaded.', true);
            return false;
        }
    }
    // DOWNLOAD FILE FROM STASH TO LOCAL.
    if (pb_backupbuddy::_POST('upload') == 'stash') {
        pb_backupbuddy::set_greedy_script_limits(true);
        /*
        echo '<pre>';
        print_r( $_POST );
        echo '</pre>';
        */
        $requestcore_file = dirname(dirname(dirname(__FILE__))) . '/lib/requestcore/requestcore.class.php';
        require_once $requestcore_file;
        $link = pb_backupbuddy::_POST('link');
        $destination_file = dirname(dirname(dirname(dirname(__FILE__)))) . '/' . basename(pb_backupbuddy::_POST('link'));
        $destination_file = substr($destination_file, 0, stripos($destination_file, '.zip') + 4);
        $_GET['file'] = basename($destination_file);
        $request = new RequestCore($link);
        $request->set_write_file($destination_file);
        echo '<div id="pb_importbuddy_working" style="padding: 20px;">Downloading backup from Stash to `' . $destination_file . '`...<br><br><img src="' . pb_backupbuddy::plugin_url() . '/images/loading_large.gif" title="Working... Please wait as this may take a moment..."><br><br></div>';
        pb_backupbuddy::flush();
        $response = $request->send_request(false);
        if ($response !== true) {
            pb_backupbuddy::alert('Error #8548459598. Unable to download file from Stash. You may manually download it and upload to the server via FTP.');
        } else {
            // No error.
            if (!file_exists($destination_file)) {
                pb_backupbuddy::alert('Error #34845745878. Stash returned a success but the backup file was not found locally. Check this server\'s directory write permissions. You may manually download it and upload to the server via FTP.');
            }
        }
        echo '<script type="text/javascript">jQuery("#pb_importbuddy_working").hide();</script>';
    }
}
Пример #2
0
 /**
  *	self::status()
  *
  *	Logs data to a CSV file. Optional unique serial identifier.
  *	If a serial is passed then EVERYTHING will be logged to the specified serial file in addition to whatever (if anything) is logged to main status file.
  *	Always logs to main status file based on logging settings whether serial is passed or not.
  *
  *	@see self::get_status().
  *
  *	@param	string	$type		Valid types: error, warning, details, message
  *	@param	string	$text		Text message to log.
  *	@param	string	$serial		Optional. Optional unique identifier for this plugin's message. Status messages are unique per plugin so this adds an additional unique layer for retrieval.
  *								If self::$_status_serial has been set by set_status_serial() then it will override if $serial is blank.
  *	@return	null
  */
 public static function status($type, $message, $serial = '', $js_mode = false)
 {
     global $pb_backupbuddy_js_status;
     if (defined('PB_IMPORTBUDDY') || isset($pb_backupbuddy_js_status) && $pb_backupbuddy_js_status === true) {
         $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" . $type . "\t" . str_replace(chr(9), '   ', $message);
         $status = str_replace('\\', '/', $status);
         echo '<script type="text/javascript">pb_status_append("' . str_replace("\n", '\\n', str_replace('"', '&quot;', $status)) . '");</script>';
         //echo '<script type="text/javascript">pb_status_append(\'' . str_replace( '\'', '&#39;', $status ) . '\');</script>';
         /*
         USE WITH JAVASCRIPT IN PAGE:
         <script type="text/javascript">
         	function pb_status_append( status_string ) {
         		target_id = 'importbuddy_status'; // importbuddy_status or pb_backupbuddy_status
         		jQuery( '#' + target_id ).append( "\n" + status_string );
         		textareaelem = document.getElementById( target_id );
         		textareaelem.scrollTop = textareaelem.scrollHeight;
         	}
         </script>
         */
         pb_backupbuddy::flush();
         //return;
     }
     $delimiter = '|~|';
     if (self::$_status_serial != '' && $serial == '') {
         $serial = self::$_status_serial;
     }
     // Make sure we have a unique log serial for all logs for security.
     if (!isset(self::$options['log_serial']) || self::$options['log_serial'] == '') {
         self::$options['log_serial'] = self::random_string(15);
         self::save();
     }
     // Determine whether writing to main file.
     $write_main = false;
     if (self::$options['log_level'] == 0) {
         // No logging.
         $write_main = false;
     } elseif (self::$options['log_level'] == 1) {
         // Errors only.
         if ($type == 'error') {
             $write_main = true;
             self::log('[' . $serial . '] ' . $message, 'error');
         }
     } else {
         // Everything else.
         $write_main = true;
         self::log('[' . $serial . '] ' . $message, $type);
     }
     // Determine whether writing to serial file. Ignores log level.
     if ($serial != '') {
         $write_serial = true;
     } else {
         $write_serial = false;
     }
     // Return if not writing to any file.
     if ($write_main !== true && $write_serial !== true) {
         return;
     }
     // Calculate log directory.
     if (defined('PB_STANDALONE') && PB_STANDALONE === true) {
         $log_directory = ABSPATH . 'importbuddy/';
     } else {
         $log_directory = WP_CONTENT_DIR . '/uploads/pb_' . self::settings('slug') . '/';
     }
     // Prepare directory for log files. Return if unable to do so.
     if (true !== self::anti_directory_browsing($log_directory)) {
         // Unable to secure directory. Fail.
         self::alert('Unable to create / verify anti directory browsing measures for status file `' . $status_file . '`. Log not written for security.');
         return;
     }
     // Function for writing actual log CSV data. Used later.
     if (!function_exists('write_status_line')) {
         function write_status_line($file, $content_array, $delimiter)
         {
             $delimiter = '|~|';
             if (false !== ($file_handle = @fopen($file, 'a'))) {
                 // Append mode.
                 //fputcsv ( $file_handle , $content_array );
                 fwrite($file_handle, trim(implode($delimiter, $content_array)) . PHP_EOL);
                 fclose($file_handle);
             } else {
                 pb_backupbuddy::alert('Unable to open file handler for status file `' . $file . '`. Unable to write status log.');
             }
         }
     }
     $content_array = array(pb_backupbuddy::$format->localize_time(time()), sprintf("%01.2f", round(microtime(true) - self::$start_time, 2)), sprintf("%01.2f", round(memory_get_peak_usage() / 1048576, 2)), $type, str_replace(chr(9), '   ', $message));
     /********** MAIN LOG FILE **********/
     if ($write_main === true) {
         // WRITE TO MAIN LOG FILE.
         $main_file = $log_directory . 'status-' . self::$options['log_serial'] . '.txt';
         write_status_line($main_file, $content_array, $delimiter);
     }
     /********** SERIAL LOG FILE **********/
     if ($write_serial === true) {
         $serial_file = $log_directory . 'status-' . $serial . '_' . self::$options['log_serial'] . '.txt';
         write_status_line($serial_file, $content_array, $delimiter);
     }
 }
Пример #3
0
 /**
  *	status()
  *
  *	Write a status line into an existing textarea created with the status_box() function.
  *
  *	@param			$type		string		message, details, error, or warning. Currently not in use.
  *	@param			$message	string		Message to append to the status box.
  *	@return			null
  */
 function status($type, $message)
 {
     pb_backupbuddy::status($type, $message);
     $status_lines = pb_backupbuddy::get_status('ms_import', true, true, true);
     // $serial = '', $clear_retrieved = true, $erase_retrieved = true, $hide_getting_status = false
     if ($status_lines !== false) {
         // Only add lines if there is status contents.
         foreach ($status_lines as $status_line) {
             $status_line[0] = pb_backupbuddy::$format->date(pb_backupbuddy::$format->localize_time($status_line[0]));
             $status_line[1] .= 'sec';
             $status_line[2] .= 'MB';
             echo '<script type="text/javascript">jQuery( "#importbuddy_status" ).append( "\\n' . implode("\t", $status_line) . '");	textareaelem = document.getElementById( "importbuddy_status" );	textareaelem.scrollTop = textareaelem.scrollHeight;	</script>';
             pb_backupbuddy::flush();
         }
     }
     /*
     $message = htmlentities( addslashes( $message ) );
     $status = date( $this->_parent->_parent->_timestamp, time() ) . ': ' . $message;
     
     echo '<script type="text/javascript">jQuery( "#importbuddy_status" ).append( "\n' . $status . '");	textareaelem = document.getElementById( "importbuddy_status" );	textareaelem.scrollTop = textareaelem.scrollHeight;	</script>';
     pb_backupbuddy::flush();
     
     if ( $type == 'error' ) {
     	$this->log( $message, 'error' );
     } elseif ( $type == 'warning' ) {
     	$this->log( $message, 'warning' );
     } else {
     	$this->log( '[' . $type . ']' . $message, 'all' );
     }
     */
 }
Пример #4
0
    public function restore_file_restore()
    {
        $success = false;
        pb_backupbuddy::$ui->ajax_header(true, false);
        // js, no padding
        ?>
		<script type="text/javascript">
			function pb_status_append( status_string ) {
				target_id = 'pb_backupbuddy_status'; // importbuddy_status or pb_backupbuddy_status
				if( jQuery( '#' + target_id ).length == 0 ) { // No status box yet so suppress.
					return;
				}
				jQuery( '#' + target_id ).append( "\n" + status_string );
				textareaelem = document.getElementById( target_id );
				textareaelem.scrollTop = textareaelem.scrollHeight;
			}
		</script>
		<?php 
        global $pb_backupbuddy_js_status;
        $pb_backupbuddy_js_status = true;
        echo pb_backupbuddy::status_box('Restoring . . .');
        echo '<div id="pb_backupbuddy_working" style="width: 100px;"><br><center><img src="' . pb_backupbuddy::plugin_url() . '/images/working.gif" title="Working... Please wait as this may take a moment..."></center></div>';
        pb_backupbuddy::set_status_serial('restore');
        global $wp_version;
        pb_backupbuddy::status('details', 'BackupBuddy v' . pb_backupbuddy::settings('version') . ' using WordPress v' . $wp_version . ' on ' . PHP_OS . '.');
        $archive_file = pb_backupbuddy::_GET('archive');
        // archive to extract from.
        $files = pb_backupbuddy::_GET('files');
        // file to extract.
        $files_array = explode(',', $files);
        $files = array();
        foreach ($files_array as $file) {
            if (substr($file, -1) == '/') {
                // If directory then add wildcard.
                $file = $file . '*';
            }
            $files[$file] = $file;
        }
        unset($files_array);
        $serial = backupbuddy_core::get_serial_from_file($archive_file);
        // serial of archive.
        foreach ($files as $file) {
            $file = str_replace('*', '', $file);
            // Remove any wildcard.
            if (file_exists(ABSPATH . $file) && is_dir(ABSPATH . $file)) {
                if (($file_count = @scandir(ABSPATH . $file)) && count($file_count) > 2) {
                    pb_backupbuddy::status('error', __('Error #9036. The destination directory being restored already exists and is NOT empty. The directory will not be restored to prevent inadvertently losing files within the existing directory. Delete existing directory first if you wish to proceed or restore individual files.', 'it-l10n-backupbuddy') . ' Existing directory: `' . ABSPATH . $file . '`.');
                    echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
                    pb_backupbuddy::flush();
                    pb_backupbuddy::$ui->ajax_footer();
                    die;
                }
            }
        }
        require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
        $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
        // Calculate temp directory & lock it down.
        $temp_dir = get_temp_dir();
        $destination = $temp_dir . 'backupbuddy-' . $serial;
        if (!file_exists($destination) && false === mkdir($destination, 0777, true)) {
            $error = 'Error #458485945: Unable to create temporary location.';
            pb_backupbuddy::status('error', $error);
            echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
            pb_backupbuddy::flush();
            pb_backupbuddy::$ui->ajax_footer();
            die;
        }
        // If temp directory is within webroot then lock it down.
        $temp_dir = str_replace('\\', '/', $temp_dir);
        // Normalize for Windows.
        $temp_dir = rtrim($temp_dir, '/\\') . '/';
        // Enforce single trailing slash.
        if (FALSE !== stristr($temp_dir, ABSPATH)) {
            // Temp dir is within webroot.
            pb_backupbuddy::anti_directory_browsing($destination);
        }
        unset($temp_dir);
        pb_backupbuddy::status('details', 'Extracting into temporary directory "' . $destination . '".');
        pb_backupbuddy::status('details', 'Files to extract: `' . htmlentities(pb_backupbuddy::_GET('files')) . '`.');
        // Make sure temp subdirectories exist.
        /*
        foreach( $files as $file => $null ) {
        	mkdir( $destination . '/' . basename( $file ), 0777, true );
        }
        */
        pb_backupbuddy::flush();
        $extract_success = true;
        $extract_result = $zipbuddy->extract(backupbuddy_core::getBackupDirectory() . $archive_file, $destination, $files);
        if (false === $extract_result) {
            // failed.
            pb_backupbuddy::status('error', 'Error #584984458b. Unable to extract.');
            $extract_success = false;
        } else {
            // success.
            // Verify all files/directories to be extracted exist in temp destination directory. If any missing then delete everything and bail out.
            foreach ($files as &$file) {
                $file = str_replace('*', '', $file);
                // Remove any wildcard.
                if (!file_exists($destination . '/' . $file)) {
                    // Cleanup.
                    foreach ($files as $file) {
                        @trigger_error('');
                        // Clear out last error.
                        @unlink($destination . '/' . $file);
                        $last_error = error_get_last();
                        if (is_array($last_error)) {
                            pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                        }
                    }
                    pb_backupbuddy::status('error', 'Error #854783474. One or more expected files / directories missing.');
                    $extract_success = false;
                    break;
                }
            }
            unset($file);
        }
        if (true === $extract_success) {
            // Made it this far so files all exist. Move them all.
            foreach ($files as $file) {
                @trigger_error('');
                // Clear out last error.
                if (false === @rename($destination . '/' . $file, ABSPATH . $file)) {
                    $last_error = error_get_last();
                    if (is_array($last_error)) {
                        //print_r( $last_error );
                        pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                    }
                    $error = 'Error #9035. Unable to move restored file `' . $destination . '/' . $file . '` to `' . ABSPATH . $file . '`. Verify permissions on destination location & that the destination directory/file does not already exist.';
                    pb_backupbuddy::status('error', $error);
                } else {
                    $details = 'Moved `' . $destination . '/' . $file . '` to `' . ABSPATH . $file . '`.<br>';
                    pb_backupbuddy::status('details', $details);
                    $success = true;
                }
            }
        }
        // end extract succeeded.
        // Try to cleanup.
        if (file_exists($destination)) {
            if (false === pb_backupbuddy::$filesystem->unlink_recursive($destination)) {
                pb_backupbuddy::status('details', 'Unable to delete temporary holding directory `' . $destination . '`.');
            } else {
                pb_backupbuddy::status('details', 'Cleaned up temporary files.');
            }
        }
        if (true === $success) {
            pb_backupbuddy::status('message', 'Restore completed successfully.');
        }
        echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
        pb_backupbuddy::flush();
        pb_backupbuddy::$ui->ajax_footer();
        die;
    }
Пример #5
0
 /**
  *	status()
  *
  *	Write a status line into an existing textarea created with the status_box() function.
  *
  *	@param			$type		string		message, details, error, or warning. Currently not in use.
  *	@param			$message	string		Message to append to the status box.
  *	@return			null
  */
 function status($type, $message)
 {
     pb_backupbuddy::status($type, $message);
     $status_lines = pb_backupbuddy::get_status('ms_import', true, true, true);
     // $serial = '', $clear_retrieved = true, $erase_retrieved = true, $hide_getting_status = false
     if ($status_lines !== false) {
         // Only add lines if there is status contents.
         foreach ($status_lines as $status_line) {
             $status_line[0] = pb_backupbuddy::$format->date(pb_backupbuddy::$format->localize_time($status_line[0]));
             $status_line[1] .= 'sec';
             $status_line[2] .= 'MB';
             echo '<script type="text/javascript">jQuery( "#importbuddy_status" ).append( "\\n' . implode("\t", $status_line) . '");	textareaelem = document.getElementById( "importbuddy_status" );	textareaelem.scrollTop = textareaelem.scrollHeight;	</script>';
             pb_backupbuddy::flush();
         }
     }
 }
Пример #6
0
    public function deploy()
    {
        pb_backupbuddy::$ui->ajax_header();
        pb_backupbuddy::load_script('jquery');
        echo '<div id="pb_backupbuddy_working" style="width: 100px; margin-bottom: 30px;"><br><center><img src="' . pb_backupbuddy::plugin_url() . '/images/working.gif" title="Working... Please wait as this may take a moment..."></center></div>';
        ?>
		
		
		<script>
		function pb_status_append( status_string ) {
			var win = window.dialogArguments || opener || parent || top;
			win.pb_status_append( status_string );
		}
		function pb_status_undourl( undo_url ) {
			var win = window.dialogArguments || opener || parent || top;
			win.pb_status_undourl( undo_url );
		}
		
		var win = window.dialogArguments || opener || parent || top;
		win.window.scrollTo(0,0);
		</script>
		
		
		<?php 
        global $pb_backupbuddy_js_status;
        $pb_backupbuddy_js_status = true;
        pb_backupbuddy::set_status_serial('deploy');
        $step = strip_tags(pb_backupbuddy::_GET('step'));
        if (!ctype_alnum($step)) {
            die('Error #8549845: Invalid step `' . htmlentities($step) . '`.');
        }
        $stepFile = pb_backupbuddy::plugin_path() . '/controllers/pages/deploy/_' . $step . '.php';
        if (!file_exists($stepFile)) {
            pb_backupbuddy::alert('Error #3298238. Invalid deploy step `' . htmlentities(pb_backupbuddy::_GET('step')) . '` (' . $step . ').');
            die;
        }
        require $stepFile;
        echo '<br><br><br>';
        echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
        pb_backupbuddy::$ui->ajax_footer();
        pb_backupbuddy::flush();
        die;
    }
		if( jQuery( '#' + target_id ).length == 0 ) { // No status box yet so suppress.
			return;
		}
		jQuery( '#' + target_id ).append( "\n" + message );
		textareaelem = document.getElementById( target_id );
		textareaelem.scrollTop = textareaelem.scrollHeight;
	}
	
	function backupbuddy_hourpad(n) { return ("0" + n).slice(-2); }
</script>
<?php 
$success = false;
global $pb_backupbuddy_js_status;
$pb_backupbuddy_js_status = true;
echo pb_backupbuddy::status_box('Restoring . . .');
echo '<div id="pb_backupbuddy_working" style="width: 100px;"><br><center><img src="' . pb_backupbuddy::plugin_url() . '/images/working.gif" title="Working... Please wait as this may take a moment..."></center></div>';
pb_backupbuddy::set_status_serial('restore');
global $wp_version;
pb_backupbuddy::status('details', 'BackupBuddy v' . pb_backupbuddy::settings('version') . ' using WordPress v' . $wp_version . ' on ' . PHP_OS . '.');
$archive_file = pb_backupbuddy::_GET('archive');
// archive to extract from.
require pb_backupbuddy::plugin_path() . '/classes/_restoreFiles.php';
$result = backupbuddy_restore_files::restore(backupbuddy_core::getBackupDirectory() . $archive_file, $files, $finalPath = ABSPATH);
echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
pb_backupbuddy::flush();
if (false === $result) {
} else {
}
pb_backupbuddy::$ui->ajax_footer();
pb_backupbuddy::$ui->ajax_footer();
die;
Пример #8
0
 public static function restore($archive_file, $files, $finalPath, &$zipbuddy = null)
 {
     if (!current_user_can(pb_backupbuddy::$options['role_access'])) {
         die('Error #473623. Access Denied.');
     }
     $serial = backupbuddy_core::get_serial_from_file($archive_file);
     // serial of archive.
     $success = false;
     foreach ($files as $file) {
         $file = str_replace('*', '', $file);
         // Remove any wildcard.
         if (file_exists($finalPath . $file) && is_dir($finalPath . $file)) {
             if (($file_count = @scandir($finalPath . $file)) && count($file_count) > 2) {
                 pb_backupbuddy::status('error', __('Error #9036. The destination directory being restored already exists and is NOT empty. The directory will not be restored to prevent inadvertently losing files within the existing directory. Delete existing directory first if you wish to proceed or restore individual files.', 'it-l10n-backupbuddy') . ' Existing directory: `' . $finalPath . $file . '`.');
                 return false;
             }
         }
     }
     if (null === $zipbuddy) {
         require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
         $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
     }
     // Calculate temp directory & lock it down.
     $temp_dir = get_temp_dir();
     $destination = $temp_dir . 'backupbuddy-' . $serial;
     if (!file_exists($destination) && false === mkdir($destination, 0777, true)) {
         $error = 'Error #458485945: Unable to create temporary location.';
         pb_backupbuddy::status('error', $error);
         return false;
     }
     // If temp directory is within webroot then lock it down.
     $temp_dir = str_replace('\\', '/', $temp_dir);
     // Normalize for Windows.
     $temp_dir = rtrim($temp_dir, '/\\') . '/';
     // Enforce single trailing slash.
     if (FALSE !== stristr($temp_dir, ABSPATH)) {
         // Temp dir is within webroot.
         pb_backupbuddy::anti_directory_browsing($destination);
     }
     unset($temp_dir);
     pb_backupbuddy::status('details', 'Extracting into temporary directory "' . $destination . '".');
     $prettyFilesList = array();
     foreach ($files as $fileSource => $fileDestination) {
         $prettyFilesList[] = $fileSource . ' => ' . $fileDestination;
     }
     pb_backupbuddy::status('details', 'Files to extract: `' . htmlentities(implode(', ', $prettyFilesList)) . '`.');
     unset($prettyFilesList);
     pb_backupbuddy::flush();
     // Do the actual extraction.
     $extract_success = true;
     if (false === $zipbuddy->extract($archive_file, $destination, $files)) {
         pb_backupbuddy::status('error', 'Error #584984458b. Unable to extract.');
         $extract_success = false;
     }
     if (true === $extract_success) {
         // Verify all files/directories to be extracted exist in temp destination directory. If any missing then delete everything and bail out.
         foreach ($files as &$file) {
             $file = str_replace('*', '', $file);
             // Remove any wildcard.
             if (!file_exists($destination . '/' . $file)) {
                 // Cleanup.
                 foreach ($files as $file) {
                     @trigger_error('');
                     // Clear out last error.
                     @unlink($destination . '/' . $file);
                     $last_error = error_get_last();
                     if (is_array($last_error)) {
                         pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                     }
                 }
                 pb_backupbuddy::status('error', 'Error #854783474. One or more expected files / directories missing.');
                 $extract_success = false;
                 break;
             }
         }
         unset($file);
         // Made it this far so files all exist. Move them all.
         foreach ($files as $file) {
             @trigger_error('');
             // Clear out last error.
             if (false === @rename($destination . '/' . $file, $finalPath . $file)) {
                 $last_error = error_get_last();
                 if (is_array($last_error)) {
                     //print_r( $last_error );
                     pb_backupbuddy::status('error', $last_error['message'] . ' File: `' . $last_error['file'] . '`. Line: `' . $last_error['line'] . '`.');
                 }
                 $error = 'Error #9035. Unable to move restored file `' . $destination . '/' . $file . '` to `' . $finalPath . $file . '`. Verify permissions on destination location & that the destination directory/file does not already exist.';
                 pb_backupbuddy::status('error', $error);
             } else {
                 $details = 'Moved `' . $destination . '/' . $file . '` to `' . $finalPath . $file . '`.<br>';
                 pb_backupbuddy::status('details', $details);
                 $success = true;
             }
         }
     }
     // end extract success.
     // Try to cleanup.
     if (file_exists($destination)) {
         if (false === pb_backupbuddy::$filesystem->unlink_recursive($destination)) {
             pb_backupbuddy::status('details', 'Unable to delete temporary holding directory `' . $destination . '`.');
         } else {
             pb_backupbuddy::status('details', 'Cleaned up temporary files.');
         }
     }
     if (true === $success) {
         pb_backupbuddy::status('message', 'File retrieval completed successfully.');
         return true;
     } else {
         return false;
     }
 }
Пример #9
0
 private function _dump_php($output_directory, $tables)
 {
     //, $base_dump_mode, $additional_excludes ) {
     $output_file = $output_directory . 'db_1.sql';
     pb_backupbuddy::status('details', 'mysqlbuddy: Preparing to run PHP mysqldump compatibility mode.');
     if (false === ($file_handle = fopen($output_file, 'a'))) {
         pb_backupbuddy::status('error', 'Error #9018: Database file is not creatable/writable. Check your permissions for file `' . $output_file . '` in directory `' . $output_directory . '`.');
         return false;
     }
     global $wpdb;
     if (!is_object($wpdb)) {
         pb_backupbuddy::status('error', 'WordPress database object $wpdb did not exist. This should not happen.');
         error_log('WordPress database object $wpdb did not exist. This should not happen. BackupBuddy Error #8945587973.');
         return false;
     }
     // Connect if not connected for importbuddy.
     if (!mysql_ping($wpdb->dbh)) {
         mysql_connect($this->_database_host, $this->_database_user, $this->_database_pass);
         mysql_select_db($this->_database_name);
     }
     $_count = 0;
     $insert_sql = '';
     global $wpdb;
     // Used later for checking that we are still connected to DB.
     // Iterate through all the tables to backup.
     // TODO: Future ability to break up DB exporting to multiple page loads if needed. Really still need this now that we have command line dump?
     foreach ($tables as $table_key => $table) {
         $create_table = mysql_query("SHOW CREATE TABLE `{$table}`");
         if ($create_table === false) {
             pb_backupbuddy::status('error', 'Unable to access and dump database table `' . $table . '`. Table may not exist. Skipping backup of this table.');
             //pb_backupbuddy::$classes['core']->mail_error( 'Error #4537384: Unable to access and dump database table `' . $table . '`. Table may not exist. Skipping backup of this table.' );
             continue;
             // Skip this iteration as accessing this table failed.
         }
         // Table creation text.
         $create_table_array = mysql_fetch_array($create_table);
         mysql_free_result($create_table);
         // Free memory.
         $insert_sql .= str_replace("\n", '', $create_table_array[1]) . ";\n";
         // Remove internal linebreaks; only put one at end.
         unset($create_table_array);
         // Disable keys for this table.
         $insert_sql .= "/*!40000 ALTER TABLE `{$table}` DISABLE KEYS */;\n";
         // Row creation text for all rows within this table.
         $table_query = mysql_query("SELECT * FROM `{$table}`") or pb_backupbuddy::status('error', 'Error #9001: Unable to read database table `' . $table . '`. Your backup will not include data from this table (you may ignore this warning if you do not need this specific data). This is due to the following error: ' . mysql_error());
         if ($table_query === false) {
             pb_backupbuddy::status('error', 'ERROR #85449745. Unable to retrieve data from table `' . $table . '`. This table may be corrupt (try repairing the database) or too large to hold in memory (increase mysql and/or PHP memory). Check your PHP error log for further errors which may provide further information. Not continuing database dump to insure backup integrity.');
             return false;
         }
         $num_fields = mysql_num_fields($table_query);
         while ($fetch_row = mysql_fetch_array($table_query)) {
             $insert_sql .= "INSERT INTO `{$table}` VALUES(";
             for ($n = 1; $n <= $num_fields; $n++) {
                 $m = $n - 1;
                 if ($fetch_row[$m] === NULL) {
                     $insert_sql .= "NULL, ";
                 } else {
                     $insert_sql .= "'" . mysql_real_escape_string($fetch_row[$m]) . "', ";
                 }
             }
             $insert_sql = substr($insert_sql, 0, -2);
             $insert_sql .= ");\n";
             fwrite($file_handle, $insert_sql);
             $insert_sql = '';
             // Help keep HTTP alive.
             $_count++;
             if ($_count >= 400) {
                 echo ' ';
                 pb_backupbuddy::flush();
                 $_count = 0;
             }
         }
         // End foreach $tables.
         // Re-enable keys for this table.
         $insert_sql .= "/*!40000 ALTER TABLE `{$table}` ENABLE KEYS */;\n";
         // testing: mysql_close( $wpdb->dbh );
         // Verify database is still connected and working properly. Sometimes mysql runs out of memory and dies in the above foreach.
         // No point in reconnecting as we can NOT trust that our dump was succesful anymore (it most likely was not).
         if (@mysql_ping($wpdb->dbh)) {
             // Still connected to database.
             mysql_free_result($table_query);
             // Free memory.
         } else {
             // Database not connected.
             pb_backupbuddy::status('error', __('ERROR #9026: The mySQL server went away unexpectedly during database dump. This is almost always caused by mySQL running out of memory. The backup integrity can no longer be guaranteed so the backup has been halted.') . ' ' . __('Last table dumped before database server went away: ') . '`' . $table . '`.');
             return false;
         }
         // Help keep HTTP alive.
         echo ' ';
         pb_backupbuddy::status('details', 'Dumped database table `' . $table . '`.');
         pb_backupbuddy::flush();
         //unset( $tables[$table_key] );
     }
     fclose($file_handle);
     unset($file_handle);
     pb_backupbuddy::status('details', __('Finished PHP based SQL dump method.', 'it-l10n-backupbuddy'));
     return true;
 }
Пример #10
0
 public static function repairbuddy($output_file = '')
 {
     if (defined('PB_DEMO_MODE')) {
         echo 'Access denied in demo mode.';
         return;
     }
     if (!isset(pb_backupbuddy::$options)) {
         pb_backupbuddy::load();
     }
     $output = file_get_contents(pb_backupbuddy::plugin_path() . '/_repairbuddy.php');
     if (pb_backupbuddy::$options['importbuddy_pass_hash'] != '') {
         $output = preg_replace('/#PASSWORD#/', pb_backupbuddy::$options['importbuddy_pass_hash'], $output, 1);
         // Only replaces first instance.
     }
     $output = preg_replace('/#VERSION#/', pb_backupbuddy::settings('version'), $output, 1);
     // Only replaces first instance.
     if ($output_file == '') {
         // No file so output to browser.
         header('Content-Description: File Transfer');
         header('Content-Type: text/plain; name=repairbuddy.php');
         header('Content-Disposition: attachment; filename=repairbuddy.php');
         header('Expires: 0');
         header('Content-Length: ' . strlen($output));
         pb_backupbuddy::flush();
         echo $output;
         pb_backupbuddy::flush();
         // BE SURE TO die() AFTER THIS AND NOT OUTPUT TO BROWSER!
     } else {
         // Write to file.
         file_put_contents($output_file, $output);
     }
 }
Пример #11
0
 function cron_next_step($spawn_cron = true, $future_offset = 0, $next_step_title = '')
 {
     // Internal cron (optional; disabled by default).
     if ('1' == pb_backupbuddy::$options['use_internal_cron']) {
         if ($future_offset > 0) {
             // Delay requsted.
             if ($future_offset > backupbuddy_core::adjustedMaxExecutionTime()) {
                 $future_offset = 5;
                 // If huge, try 5 sec.
             }
             sleep($future_offset);
         }
         $cron_url = site_url();
         $args = array('backupbuddy_cron_action' => 'process_backup', 'backupbuddy_serial' => $this->_backup['serial'], 'backupbuddy_time' => time(), 'backupbuddy_key' => pb_backupbuddy::$options['log_serial']);
         pb_backupbuddy::status('details', 'Attempting to bypass WordPress cron and use internal cron system calling `' . $cron_url . '`. Args: `' . print_r($args, true) . '`.');
         pb_backupbuddy::flush();
         $response = wp_remote_post($cron_url, array('method' => 'POST', 'timeout' => backupbuddy_core::adjustedMaxExecutionTime(), 'redirection' => 3, 'httpversion' => '1.0', 'blocking' => false, 'headers' => array(), 'body' => $args, 'cookies' => array()));
         pb_backupbuddy::status('details', 'Cron response: `' . print_r($response, true) . '`.');
         return;
     }
     if ('1' == pb_backupbuddy::$options['skip_spawn_cron_call']) {
         pb_backupbuddy::status('details', 'Advanced option to skip call to spawn cron enabled. Setting to skip spawn_cron() call.');
         $spawn_cron = false;
     }
     pb_backupbuddy::status('details', 'Scheduling Cron for `' . $this->_backup['serial'] . '`.');
     // Need to make sure the database connection is active. Sometimes it goes away during long bouts doing other things -- sigh.
     // This is not essential so use include and not require (suppress any warning)
     @(include_once pb_backupbuddy::plugin_path() . '/lib/wpdbutils/wpdbutils.php');
     if (class_exists('pluginbuddy_wpdbutils')) {
         global $wpdb;
         $dbhelper = new pluginbuddy_wpdbutils($wpdb);
         if (!$dbhelper->kick()) {
             pb_backupbuddy::status('error', __('Database Server has gone away, unable to schedule next backup step. The backup cannot continue. This is most often caused by mysql running out of memory or timing out far too early. Please contact your host.', 'it-l10n-backupbuddy'));
             pb_backupbuddy::status('haltScript', '');
             // Halt JS on page.
             return false;
         }
     } else {
         pb_backupbuddy::status('details', __('Database Server connection status unverified.', 'it-l10n-backupbuddy'));
     }
     // Schedule event.
     $cron_time = time() + $future_offset;
     $cron_args = array($this->_backup['serial']);
     pb_backupbuddy::status('details', 'Scheduling next step to run at `' . $cron_time . '` (localized time: ' . pb_backupbuddy::$format->date(pb_backupbuddy::$format->localize_time($cron_time)) . ') with cron tag `backupbuddy_cron` to run method `process_backup` and serial arguments `' . implode(',', $cron_args) . '`.');
     $schedule_result = backupbuddy_core::schedule_single_event($cron_time, 'process_backup', $cron_args);
     if ($schedule_result === false) {
         pb_backupbuddy::status('error', 'Unable to schedule next cron step. Verify that another plugin is not preventing / conflicting.');
     } else {
         pb_backupbuddy::status('details', 'Next step scheduled.');
         pb_backupbuddy::status('startAction', 'cronPass');
         pb_backupbuddy::status('cronParams', base64_encode(json_encode(array('time' => $cron_time, 'tag' => 'backupbuddy_cron', 'method' => 'process_backup', 'args' => $cron_args))));
     }
     update_option('_transient_doing_cron', 0);
     // Prevent cron-blocking for next item.
     // Spawn cron.
     if ($spawn_cron === true) {
         pb_backupbuddy::status('details', 'Calling spawn_cron().');
         spawn_cron(time() + 150);
         // Adds > 60 seconds to get around once per minute cron running limit.
     } else {
         pb_backupbuddy::status('details', 'Not calling spawn_cron().');
     }
     $next_step_note = '';
     if ('' != $next_step_title) {
         $next_step_note = ' (' . $next_step_title . ' expected)';
     }
     pb_backupbuddy::status('details', 'About to run next step' . $next_step_note . '. If the backup does not proceed within 15 seconds then something is interfering with the WordPress CRON system such as: server loopback issues, caching plugins, or scheduling plugins. Try disabling other plugins to see if it resolves issue.  Check the Server Information page cron section to see if the next BackupBuddy step is scheduled to run. Enable "Classic" backup mode on the "Settings" page to rule out non-cron issues. Additionally you may verify no other backup processes are trying to run at the same time by verifying there is not an existing backup process listed in the cron hogging the cron process.');
     return;
 }
Пример #12
0
 /**
  *	connect()
  *
  *	Initializes a connection to the mysql database.
  *
  *	@return		boolean		True on success; else false. Success testing is very loose.
  */
 function connect_database()
 {
     // Set up database connection.
     if (false === @mysql_connect(pb_backupbuddy::$options['db_server'], pb_backupbuddy::$options['db_user'], pb_backupbuddy::$options['db_password'])) {
         pb_backupbuddy::alert('ERROR: Unable to connect to database server and/or log in. Verify the database server name, username, and password. Details: ' . mysql_error(), true, '9006');
         return false;
     }
     $database_name = mysql_real_escape_string(pb_backupbuddy::$options['db_name']);
     pb_backupbuddy::flush();
     // Select the database.
     if (false === @mysql_select_db(pb_backupbuddy::$options['db_name'])) {
         pb_backupbuddy::status('error', 'Error: Unable to connect or authenticate to database `' . pb_backupbuddy::$options['db_name'] . '`.');
         return false;
     }
     // Set up character set. Important.
     mysql_query("SET NAMES 'utf8'");
     return true;
 }
Пример #13
0
 /**
  *	self::status()
  *
  *	Logs data to a CSV file. Optional unique serial identifier.
  *	If a serial is passed then EVERYTHING will be logged to the specified serial file in addition to whatever (if anything) is logged to main status file.
  *	Always logs to main status file based on logging settings whether serial is passed or not.
  *
  *	@see self::get_status().
  *
  *	@param	string			$type		Valid types: error, warning, details, message
  *	@param	string			$text		Text message to log.
  *	@param	string|array	$serial		Optional. Optional unique identifier for this plugin's message. Status messages are unique per plugin so this adds an additional unique layer for retrieval.
  *										If self::$_status_serial has been set by set_status_serial() then it will override if $serial is blank.
  *	@return	null
  */
 public static function status($type, $message, $serials = '', $js_mode = false)
 {
     if (!class_exists('backupbuddy_core')) {
         require_once pb_backupbuddy::plugin_path() . '/classes/core.php';
     }
     if (self::$_status_serial != '' && $serials == '') {
         $serials = self::$_status_serial;
     }
     if (!is_array($serials)) {
         $serials = array($serials);
     }
     global $pb_backupbuddy_js_status;
     if (defined('PB_IMPORTBUDDY') || isset($pb_backupbuddy_js_status) && $pb_backupbuddy_js_status === true) {
         $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" . $type . "\t" . str_replace(chr(9), '   ', $message);
         $status = str_replace('\\', '/', $status);
         echo '<script type="text/javascript">pb_status_append("' . str_replace("\n", '\\n', str_replace('"', '&quot;', $status)) . '");</script>';
         pb_backupbuddy::flush();
     }
     if (defined('BACKUPBUDDY_WP_CLI') && true === BACKUPBUDDY_WP_CLI) {
         if (class_exists('WP_CLI')) {
             WP_CLI::line($type . ' - ' . $message);
         }
     }
     $delimiter = '|~|';
     // Make sure we have a unique log serial for all logs for security.
     if (!isset(self::$options['log_serial']) || self::$options['log_serial'] == '') {
         self::$options['log_serial'] = self::random_string(15);
         self::save();
     }
     foreach ($serials as $serial) {
         // Determine whether writing to main file.
         $write_main = false;
         if (self::$options['log_level'] == 0) {
             // No logging.
             $write_main = false;
         } elseif (self::$options['log_level'] == 1) {
             // Errors only.
             if ($type == 'error') {
                 $write_main = true;
                 self::log('[' . $serial . '] ' . $message, 'error');
             }
         } else {
             // Everything else.
             $write_main = true;
             self::log('[' . $serial . '] ' . $message, $type);
         }
         // Determine whether writing to serial file. Ignores log level.
         if ($serial != '') {
             $write_serial = true;
         } else {
             $write_serial = false;
         }
         // Return if not writing to any file.
         if ($write_main !== true && $write_serial !== true) {
             return;
         }
         // Calculate log directory.
         $log_directory = backupbuddy_core::getLogDirectory();
         // Also handles when within importbuddy.
         // Prepare directory for log files. Return if unable to do so.
         if (true === self::$_skiplog) {
             // bool true so skip.
             return;
         } elseif (false !== self::$_skiplog) {
             // something other than bool false so check directory before proceeding.
             if (true !== self::anti_directory_browsing($log_directory, $die_on_fail = false, $deny_all = false, $suppress_alert = true)) {
                 // Unable to secure directory. Fail.
                 self::$_skiplog = true;
                 return;
             } else {
                 self::$_skiplog = false;
             }
         }
         // Function for writing actual log CSV data. Used later.
         if (!function_exists('write_status_line')) {
             function write_status_line($file, $content_array, $delimiter)
             {
                 $delimiter = '|~|';
                 if (false !== ($file_handle = @fopen($file, 'a'))) {
                     // Append mode.
                     //fputcsv ( $file_handle , $content_array );
                     @fwrite($file_handle, trim(implode($delimiter, $content_array)) . PHP_EOL);
                     @fclose($file_handle);
                 } else {
                     //pb_backupbuddy::alert( 'Unable to open file handler for status file `' . $file . '`. Unable to write status log.' );
                 }
             }
         }
         $content_array = array(pb_backupbuddy::$format->localize_time(time()), sprintf("%01.2f", round(microtime(true) - self::$start_time, 2)), sprintf("%01.2f", round(memory_get_peak_usage() / 1048576, 2)), $type, str_replace(chr(9), '   ', $message));
         /********** MAIN LOG FILE **********/
         if ($write_main === true) {
             // WRITE TO MAIN LOG FILE.
             $main_file = $log_directory . 'status-' . self::$options['log_serial'] . '.txt';
             write_status_line($main_file, $content_array, $delimiter);
         }
         /********** SERIAL LOG FILE **********/
         if ($write_serial === true) {
             $serial_file = $log_directory . 'status-' . $serial . '_' . self::$options['log_serial'] . '.txt';
             write_status_line($serial_file, $content_array, $delimiter);
         }
     }
     // end foreach $serials.
 }
Пример #14
0
    public function rollback()
    {
        pb_backupbuddy::$ui->ajax_header();
        pb_backupbuddy::load_script('jquery');
        echo '<div id="pb_backupbuddy_working" style="width: 100px; margin-bottom: 30px;"><br><center><img src="' . pb_backupbuddy::plugin_url() . '/images/working.gif" title="Working... Please wait as this may take a moment..."></center></div>';
        ?>
		
		
		<script>
		function pb_status_append( status_string ) {
			var win = window.dialogArguments || opener || parent || top;
			win.pb_status_append( status_string );
		}
		function pb_status_undourl( undo_url ) {
			var win = window.dialogArguments || opener || parent || top;
			win.pb_status_undourl( undo_url );
		}
		
		var win = window.dialogArguments || opener || parent || top;
		win.window.scrollTo(0,0);
		</script>
		
		
		<?php 
        global $pb_backupbuddy_js_status;
        $pb_backupbuddy_js_status = true;
        pb_backupbuddy::set_status_serial('restore');
        $step = strip_tags(pb_backupbuddy::_GET('step'));
        if ('' == $step || !is_numeric($step)) {
            $step = 0;
        }
        $backupFile = strip_tags(pb_backupbuddy::_GET('archive'));
        if ('' == $backupFile) {
            pb_backupbuddy::alert('The backup file to restore from must be specified.');
            die;
        }
        $stepFile = pb_backupbuddy::plugin_path() . '/controllers/pages/rollback/_step' . $step . '.php';
        if (!file_exists($stepFile)) {
            pb_backupbuddy::alert('Error #849743. Invalid roll back step `' . htmlentities(pb_backupbuddy::_GET('step')) . '` (' . $step . ').');
            die;
        }
        require $stepFile;
        echo '<br><br><br>';
        echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
        pb_backupbuddy::$ui->ajax_footer();
        pb_backupbuddy::flush();
        die;
    }
Пример #15
0
 /**
  *	connect()
  *
  *	Initializes a connection to the mysql database.
  *
  *	@return		boolean		True on success; else false. Success testing is very loose.
  */
 function connect_database()
 {
     pb_backupbuddy::flush();
     global $wpdb;
     $wpdb = new wpdb(pb_backupbuddy::$options['db_user'], pb_backupbuddy::$options['db_password'], pb_backupbuddy::$options['db_name'], pb_backupbuddy::$options['db_server']);
     pb_backupbuddy::flush();
     return true;
 }
Пример #16
0
 public static function importbuddy($output_file = '', $importbuddy_pass_hash = '', $return_not_echo = false)
 {
     pb_backupbuddy::set_greedy_script_limits();
     // Some people run out of PHP memory.
     if ($importbuddy_pass_hash == '') {
         if (!isset(pb_backupbuddy::$options)) {
             pb_backupbuddy::load();
         }
         $importbuddy_pass_hash = pb_backupbuddy::$options['importbuddy_pass_hash'];
     }
     if ($importbuddy_pass_hash == '') {
         $message = 'Warning #9032 - You have not set an ImportBuddy password on the BackupBuddy Settings page. Once this password is set a copy of the importbuddy.php file needed to restore your backup will be included in Full backup zip files for convenience. It may manually be downloaded from the Restore / Migrate page.';
         pb_backupbuddy::status('warning', $message);
         return false;
     }
     pb_backupbuddy::status('details', 'Loading importbuddy core file into memory.');
     $output = file_get_contents(pb_backupbuddy::plugin_path() . '/_importbuddy/_importbuddy.php');
     if ($importbuddy_pass_hash != '') {
         $output = preg_replace('/#PASSWORD#/', $importbuddy_pass_hash, $output, 1);
         // Only replaces first instance.
     }
     $version_string = pb_backupbuddy::settings('version') . ' (downloaded ' . date(DATE_W3C) . ')';
     // If on DEV system (.git dir exists) then append some details on current.
     if (defined('BACKUPBUDDY_DEV') && true === BACKUPBUDDY_DEV) {
         if (@file_exists(pb_backupbuddy::plugin_path() . '/.git/logs/HEAD')) {
             $commit_log = escapeshellarg(pb_backupbuddy::plugin_path() . '/.git/logs/HEAD');
             $commit_line = str_replace('\'', '`', exec("tail -n 1 {$commit_log}"));
             $version_string .= ' <span style="font-size: 8px;">[DEV: ' . $commit_line . ']</span>';
         }
     }
     $output = preg_replace('/#VERSION#/', $version_string, $output, 1);
     // Only replaces first instance.
     // PACK IMPORTBUDDY
     $_packdata = array('_importbuddy/importbuddy' => 'importbuddy', 'classes/_migrate_database.php' => 'importbuddy/classes/_migrate_database.php', 'classes/core.php' => 'importbuddy/classes/core.php', 'classes/import.php' => 'importbuddy/classes/import.php', 'classes/restore.php' => 'importbuddy/classes/restore.php', 'classes/_restoreFiles.php' => 'importbuddy/classes/_restoreFiles.php', 'classes/remote_api.php' => 'importbuddy/classes/remote_api.php', 'js/jquery.leanModal.min.js' => 'importbuddy/js/jquery.leanModal.min.js', 'js/jquery.joyride-2.0.3.js' => 'importbuddy/js/jquery.joyride-2.0.3.js', 'js/modernizr.mq.js' => 'importbuddy/js/modernizr.mq.js', 'css/joyride.css' => 'importbuddy/css/joyride.css', 'images/working.gif' => 'importbuddy/images/working.gif', 'images/bullet_go.png' => 'importbuddy/images/bullet_go.png', 'images/favicon.png' => 'importbuddy/images/favicon.png', 'images/sort_down.png' => 'importbuddy/images/sort_down.png', 'images/icon_menu_32x32.png' => 'importbuddy/images/icon_menu_32x32.png', 'lib/dbreplace' => 'importbuddy/lib/dbreplace', 'lib/dbimport' => 'importbuddy/lib/dbimport', 'lib/commandbuddy' => 'importbuddy/lib/commandbuddy', 'lib/zipbuddy' => 'importbuddy/lib/zipbuddy', 'lib/mysqlbuddy' => 'importbuddy/lib/mysqlbuddy', 'lib/textreplacebuddy' => 'importbuddy/lib/textreplacebuddy', 'lib/cpanel' => 'importbuddy/lib/cpanel', 'pluginbuddy' => 'importbuddy/pluginbuddy', 'controllers/pages/server_info' => 'importbuddy/controllers/pages/server_info', 'controllers/pages/server_tools.php' => 'importbuddy/controllers/pages/server_tools.php', 'destinations/stash/lib/class.itx_helper.php' => 'importbuddy/classes/class.itx_helper.php', 'destinations/_s3lib/aws-sdk/lib/requestcore' => 'importbuddy/lib/requestcore');
     pb_backupbuddy::status('details', 'Loading each file into memory for writing master importbuddy file.');
     $output .= "\n<?php /*\n###PACKDATA,BEGIN\n";
     foreach ($_packdata as $pack_source => $pack_destination) {
         $pack_source = '/' . $pack_source;
         if (is_dir(pb_backupbuddy::plugin_path() . $pack_source)) {
             $files = pb_backupbuddy::$filesystem->deepglob(pb_backupbuddy::plugin_path() . $pack_source);
         } else {
             $files = array(pb_backupbuddy::plugin_path() . $pack_source);
         }
         foreach ($files as $file) {
             if (is_file($file)) {
                 $source = str_replace(pb_backupbuddy::plugin_path(), '', $file);
                 $destination = $pack_destination . substr($source, strlen($pack_source));
                 $output .= "###PACKDATA,FILE_START,{$source},{$destination}\n";
                 $output .= base64_encode(file_get_contents($file));
                 $output .= "\n";
                 $output .= "###PACKDATA,FILE_END,{$source},{$destination}\n";
             }
         }
     }
     $output .= "###PACKDATA,END\n*/";
     $output .= "\n\n\n\n\n\n\n\n\n\n";
     if (true === $return_not_echo) {
         return $output;
     }
     if ($output_file == '') {
         // No file so output to browser.
         header('Content-Description: File Transfer');
         header('Content-Type: text/plain; name=importbuddy.php');
         header('Content-Disposition: attachment; filename=importbuddy.php');
         header('Expires: 0');
         header('Content-Length: ' . strlen($output));
         pb_backupbuddy::flush();
         echo $output;
         pb_backupbuddy::flush();
         // BE SURE TO die() AFTER THIS AND NOT OUTPUT TO BROWSER!
     } else {
         // Write to file.
         pb_backupbuddy::status('details', 'Writing importbuddy master file to disk.');
         if (false === file_put_contents($output_file, $output)) {
             pb_backupbuddy::status('error', 'Error #483894: Unable to write to file `' . $output_file . '`.');
             return false;
         } else {
             return true;
         }
     }
 }
Пример #17
0
 public function start($backupFile)
 {
     $this->_before(__FUNCTION__);
     $this->_state['archive'] = $backupFile;
     $serial = backupbuddy_core::get_serial_from_file(basename($backupFile));
     $this->_state['serial'] = $serial;
     $this->_state['tempPath'] = backupbuddy_core::getTempDirectory() . $this->_state['type'] . '_' . $this->_state['serial'] . '/';
     unset($backupFile);
     unset($serial);
     // Get zip meta information.
     $customTitle = 'Backup Details';
     pb_backupbuddy::status('details', 'Attempting to retrieve zip meta data from comment.');
     if (false !== ($metaInfo = backupbuddy_core::getZipMeta($this->_state['archive']))) {
         pb_backupbuddy::status('details', 'Found zip meta data.');
     } else {
         pb_backupbuddy::status('details', 'Did not find zip meta data.');
     }
     //$this->_state['meta'] = $metaInfo;
     pb_backupbuddy::status('details', 'Loading zipbuddy.');
     require_once pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php';
     $zipbuddy = new pluginbuddy_zipbuddy(backupbuddy_core::getBackupDirectory());
     pb_backupbuddy::status('details', 'Zipbuddy loaded.');
     // Find DAT file.
     pb_backupbuddy::status('details', 'Calculating possible DAT file locations.');
     $possibleDatLocations = array();
     if (isset($metaInfo['dat_path'])) {
         $possibleDatLocations[] = $metaInfo['dat_path'][1];
         // DAT file location encoded in meta info. Should always be valid.
     }
     $possibleDatLocations[] = 'backupbuddy_dat.php';
     // DB backup.
     $possibleDatLocations[] = 'wp-content/uploads/backupbuddy_temp/' . $this->_state['serial'] . '/backupbuddy_dat.php';
     // Full backup.
     pb_backupbuddy::status('details', 'Possible DAT file locations: `' . implode(';', $possibleDatLocations) . '`.');
     $possibleDatLocations = array_unique($possibleDatLocations);
     foreach ($possibleDatLocations as $possibleDatLocation) {
         if (true === $zipbuddy->file_exists($this->_state['archive'], $possibleDatLocation, $leave_open = true)) {
             $detectedDatLocation = $possibleDatLocation;
             break;
         }
     }
     // end foreach.
     pb_backupbuddy::status('details', 'Confirmed DAT file location: `' . $detectedDatLocation . '`.');
     $this->_state['datLocation'] = $detectedDatLocation;
     unset($metaInfo);
     // No longer need anything from the meta information.
     // Load DAT file contents.
     pb_backupbuddy::status('details', 'Creating temporary file directory `' . $this->_state['tempPath'] . '`.');
     pb_backupbuddy::$filesystem->unlink_recursive($this->_state['tempPath']);
     // Remove if already exists.
     mkdir($this->_state['tempPath']);
     // Make empty directory.
     // Restore DAT file.
     pb_backupbuddy::status('details', 'Extracting DAT file.');
     $files = array($detectedDatLocation => 'backupbuddy_dat.php');
     require pb_backupbuddy::plugin_path() . '/classes/_restoreFiles.php';
     $result = backupbuddy_restore_files::restore($this->_state['archive'], $files, $this->_state['tempPath'], $zipbuddy);
     echo '<script type="text/javascript">jQuery("#pb_backupbuddy_working").hide();</script>';
     pb_backupbuddy::flush();
     if (false === $result) {
         $this->_error('Error #85484: Unable to retrieve DAT file. This is a fatal error.');
         return false;
     }
     if (false === ($datData = backupbuddy_core::get_dat_file_array($this->_state['tempPath'] . 'backupbuddy_dat.php'))) {
         $this->_error('Error #4839484: Unable to retrieve DAT file. The backup may have failed opening due to lack of memory, permissions issues, or other reason. Use ImportBuddy to restore or check the Advanced Log above for details.');
         return false;
     }
     $this->_state['dat'] = $datData;
     pb_backupbuddy::status('details', 'DAT file extracted.');
     if (site_url() != $this->_state['dat']['siteurl']) {
         $this->_error(__('Error #5849843: Site URL does not match. You cannot roll back the database if the URL has changed or for backups or another site. Use importbuddy.php to restore or migrate instead.', 'it-l10n-backupbuddy'));
         return false;
     }
     global $wpdb;
     if ($this->_state['dat']['db_prefix'] != $wpdb->prefix) {
         $this->_error(__('Error #2389394: Database prefix does not match. You cannot roll back the database if the database prefix has changed or for backups or another site. Use importbuddy.php to restore or migrate instead.', 'it-l10n-backupbuddy'));
         return false;
     }
     // Store this serial in the db for future cleanup.
     if ('rollback' == $this->_state['type']) {
         pb_backupbuddy::$options['rollback_cleanups'][$this->_state['serial']] = time();
         pb_backupbuddy::save();
         // Generate UNDO script.
         pb_backupbuddy::status('details', 'Generating undo script.');
         $this->_state['undoFile'] = 'backupbuddy_rollback_undo-' . $this->_state['serial'] . '.php';
         $undoURL = rtrim(site_url(), '/\\') . '/' . $this->_state['undoFile'];
         if (false === copy(dirname(__FILE__) . '/_rollback_undo.php', ABSPATH . $this->_state['undoFile'])) {
             $this->_error(__('Warning: Unable to create undo script in site root. You will not be able to automated undoing the rollback if something fails so BackupBuddy will not continue.', 'it-l10n-backupbuddy'));
             return false;
         }
         $this->_state['undoURL'] = $undoURL;
     }
     pb_backupbuddy::status('details', 'Finished starting function.');
     return true;
 }
Пример #18
0
 /**
  *	_migrateWpConfigGruntwork()
  *
  *	Migrates and updates the wp-config.php file contents as needed.
  *
  *	@return			true|string			True on success. On false returns the new wp-config file content.
  */
 function _migrateWpConfigGruntwork()
 {
     pb_backupbuddy::status('message', 'Starting migration of wp-config.php file...');
     pb_backupbuddy::flush();
     $configFile = ABSPATH . 'wp-config.php';
     pb_backupbuddy::status('details', 'Config file: `' . $configFile . '`.');
     if (file_exists($configFile)) {
         // Useful REGEX site: http://gskinner.com/RegExr/
         $updated_home_url = false;
         $wp_config = array();
         $lines = file($configFile);
         $patterns = array();
         $replacements = array();
         /*
         Update WP_SITEURL, WP_HOME if they exist.
         Update database DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST.
         RegExp: /define\([\s]*('|")WP_SITEURL('|"),[\s]*('|")(.)*('|")[\s]*\);/gi
         pattern: define\([\s]*('|")WP_SITEURL('|"),[\s]*('|")(.)*('|")[\s]*\);
         */
         $pattern[0] = '/define\\([\\s]*(\'|")WP_SITEURL(\'|"),[\\s]*(\'|")(.)*(\'|")[\\s]*\\);/i';
         $replace[0] = "define( 'WP_SITEURL', '" . trim($this->_state['siteurl'], '/') . "' );";
         pb_backupbuddy::status('details', 'wp-config.php: Setting WP_SITEURL (if applicable) to `' . trim($this->_state['siteurl'], '/') . '`.');
         $pattern[1] = '/define\\([\\s]*(\'|")WP_HOME(\'|"),[\\s]*(\'|")(.)*(\'|")[\\s]*\\);/i';
         $replace[1] = "define( 'WP_HOME', '" . trim($this->_state['homeurl'], '/') . "' );";
         pb_backupbuddy::status('details', 'wp-config.php: Setting WP_HOME (if applicable) to `' . trim($this->_state['homeurl'], '/') . '`.');
         $pattern[2] = '/define\\([\\s]*(\'|")DB_NAME(\'|"),[\\s]*(\'|")(.)*(\'|")[\\s]*\\);/i';
         $replace[2] = "define( 'DB_NAME', '" . $this->_state['databaseSettings']['database'] . "' );";
         $pattern[3] = '/define\\([\\s]*(\'|")DB_USER(\'|"),[\\s]*(\'|")(.)*(\'|")[\\s]*\\);/i';
         $replace[3] = "define( 'DB_USER', '" . $this->_state['databaseSettings']['username'] . "' );";
         $pattern[4] = '/define\\([\\s]*(\'|")DB_PASSWORD(\'|"),[\\s]*(\'|")(.)*(\'|")[\\s]*\\);/i';
         $replace[4] = "define( 'DB_PASSWORD', '" . $this->_preg_escape_back($this->_state['databaseSettings']['password']) . "' );";
         $pattern[5] = '/define\\([\\s]*(\'|")DB_HOST(\'|"),[\\s]*(\'|")(.)*(\'|")[\\s]*\\);/i';
         $replace[5] = "define( 'DB_HOST', '" . $this->_state['databaseSettings']['server'] . "' );";
         // If multisite, update domain.
         if (isset(pb_backupbuddy::$options['domain']) && pb_backupbuddy::$options['domain'] != '') {
             $pattern[6] = '/define\\([\\s]*(\'|")DOMAIN_CURRENT_SITE(\'|"),[\\s]*(\'|")(.)*(\'|")[\\s]*\\);/i';
             $replace[6] = "define( 'DOMAIN_CURRENT_SITE', '" . $this->_state['defaultDomain'] . "' );";
             pb_backupbuddy::status('details', 'wp-config.php: Setting DOMAIN_CURRENT_SITE (if applicable) to `' . $this->_state['databaseSettings']['defaultDomain'] . '`.');
         } else {
             pb_backupbuddy::status('details', 'wp-config.php did not update DOMAIN_CURRENT_SITE as it was blank.');
         }
         /*
         Update table prefix.
         RegExp: /\$table_prefix[\s]*=[\s]*('|")(.)*('|");/gi
         pattern: \$table_prefix[\s]*=[\s]*('|")(.)*('|");
         */
         $pattern[7] = '/\\$table_prefix[\\s]*=[\\s]*(\'|")(.)*(\'|");/i';
         $replace[7] = '$table_prefix = \'' . $this->_state['databaseSettings']['prefix'] . '\';';
         // Perform the actual replacement.
         $lines = preg_replace($pattern, $replace, $lines);
         // Check that we can write to this file.
         if (!is_writable($configFile)) {
             pb_backupbuddy::status('warning', 'Warning #28572: wp-config.php shows to be unwritable. Attempting to override permissions temporarily.');
             $oldPerms = fileperms($configFile) & 0777;
             @chmod($configFile, 0644);
             // Try to make writable.
         }
         // Write changes to config file.
         if (false === file_put_contents($configFile, $lines)) {
             pb_backupbuddy::alert('ERROR #84928: Unable to save changes to wp-config.php. Verify this file has proper write permissions. You may need to manually edit it.', true, '9020');
             return implode("\n", $lines);
         }
         // Restore prior permissions if applicable.
         if (isset($oldPerms)) {
             @chmod($configFile, $oldPerms);
         }
         unset($lines);
     } else {
         pb_backupbuddy::status('details', 'Warning: wp-config.php file not found.');
         //pb_backupbuddy::alert( 'Note: wp-config.php file not found. This is normal for a database only backup.' );
     }
     pb_backupbuddy::status('message', 'Migration of wp-config.php complete.');
     return true;
 }
Пример #19
0
 /**
  *	self::status()
  *
  *	Logs data to a CSV file. Optional unique serial identifier.
  *	If a serial is passed then EVERYTHING will be logged to the specified serial file in addition to whatever (if anything) is logged to main status file.
  *	Always logs to main status file based on logging settings whether serial is passed or not.
  *	NOTE: When full logging is on AND a serial is passed, it will be written to a _sum_ text file instead of the main log file.
  *
  *	@see self::get_status().
  *
  *	@param	string			$type		Valid types: error, warning, details, message
  *	@param	string			$text		Text message to log.
  *	@param	string			$serial		Optional. Optional unique identifier for this plugin's message. Status messages are unique per plugin so this adds an additional unique layer for retrieval.
  *										If self::$_status_serial has been set by set_status_serial() then it will override if $serial is blank.
  *	@return	null
  */
 public static function status($type, $message, $serials = '', $js_mode = false, $echoNotWrite = false)
 {
     if (!class_exists('backupbuddy_core')) {
         require_once pb_backupbuddy::plugin_path() . '/classes/core.php';
     }
     if (self::$_status_serial != '' && $serials == '') {
         $serials = self::$_status_serial;
     }
     if (defined('BACKUPBUDDY_WP_CLI') && true === BACKUPBUDDY_WP_CLI) {
         if (class_exists('WP_CLI')) {
             WP_CLI::line($type . ' - ' . $message);
         }
     }
     // Make sure we have a unique log serial for all logs for security.
     if (!isset(self::$options['log_serial']) || self::$options['log_serial'] == '') {
         self::$options['log_serial'] = self::random_string(15);
         self::save();
     }
     if (!is_array($serials)) {
         $serials = array($serials);
     }
     // Calculate log directory.
     $log_directory = backupbuddy_core::getLogDirectory();
     // Also handles when within importbuddy.
     // Prepare directory for log files. Return if unable to do so.
     if (true === self::$_skiplog) {
         // bool true so skip.
         return;
     } elseif (false !== self::$_skiplog) {
         // something other than bool false so check directory before proceeding.
         if (true !== self::anti_directory_browsing($log_directory, $die_on_fail = false, $deny_all = false, $suppress_alert = true)) {
             // Unable to secure directory. Fail.
             self::$_skiplog = true;
             return;
         } else {
             self::$_skiplog = false;
         }
     }
     foreach ($serials as $serial) {
         // ImportBuddy always write to main status log.
         if (defined('PB_IMPORTBUDDY') && PB_IMPORTBUDDY === true) {
             // IMPORTBUDDY
             $write_serial = false;
             $write_main = true;
             $main_file = $log_directory . 'status-' . self::$options['log_serial'] . '.txt';
         } else {
             // STANDALONE.
             // Determine whether writing to main extraneous log file.
             $write_main = false;
             if (self::$options['log_level'] == 0) {
                 // No logging.
                 $write_main = false;
             } elseif (self::$options['log_level'] == 1) {
                 // Errors only.
                 if ($type == 'error') {
                     $write_main = true;
                     self::log('[' . $serial . '] ' . $message, 'error');
                 }
             } else {
                 // Everything else.
                 $write_main = true;
                 self::log('[' . $serial . '] ' . $message, $type);
             }
             // Determine which normal status log files to write.
             if ($serial != '') {
                 $write_serial = true;
                 $write_main = true;
                 $main_file = $log_directory . 'status-' . $serial . '_sum_' . self::$options['log_serial'] . '.txt';
             } else {
                 $write_serial = false;
                 $write_main = false;
             }
         }
         // Function for writing actual log CSV data. Used later.
         if (!function_exists('write_status_line')) {
             function write_status_line($file, $content_array, $echoNotWrite)
             {
                 $writeData = json_encode($content_array) . PHP_EOL;
                 if (true === $echoNotWrite) {
                     // echo data instead of writing to file. used by ajax when checking status log and needing to prepend before log.
                     echo $writeData;
                 } else {
                     //$delimiter = '|~|';
                     if (false !== ($file_handle = @fopen($file, 'a'))) {
                         // Append mode.
                         //fputcsv ( $file_handle , $content_array );
                         //@fwrite( $file_handle, trim( implode( $delimiter, $content_array ) ) . PHP_EOL );
                         @fwrite($file_handle, $writeData);
                         @fclose($file_handle);
                     } else {
                         //pb_backupbuddy::alert( 'Unable to open file handler for status file `' . $file . '`. Unable to write status log.' );
                     }
                 }
             }
         }
         $content_array = array('event' => $type, 'time' => pb_backupbuddy::$format->localize_time(time()), 'u' => substr((string) microtime(), 2, 2), 'run' => sprintf("%01.2f", round(microtime(true) - self::$start_time, 2)), 'mem' => sprintf("%01.2f", round(memory_get_peak_usage() / 1048576, 2)), 'data' => str_replace(chr(9), '   ', $message));
         /********** MAIN LOG FILE or SUM FILE **********/
         if ($write_main === true) {
             // WRITE TO MAIN LOG FILE or SUM FILE.
             write_status_line($main_file, $content_array, $echoNotWrite);
         }
         /********** SERIAL LOG FILE **********/
         if ($write_serial === true) {
             $serial_file = $log_directory . 'status-' . $serial . '_' . self::$options['log_serial'] . '.txt';
             write_status_line($serial_file, $content_array, $echoNotWrite);
         }
         // Output importbuddy status log to screen.
         global $pb_backupbuddy_js_status;
         if ((defined('PB_IMPORTBUDDY') || isset($pb_backupbuddy_js_status) && $pb_backupbuddy_js_status === true) && 'true' != pb_backupbuddy::_GET('deploy')) {
             // If importbuddy, js mode, and not a deployment.
             echo '<script>pb_status_append( ' . json_encode($content_array) . ' );</script>' . "\n";
             pb_backupbuddy::flush();
         }
     }
     // end foreach $serials.
 }
Пример #20
0
 public function import($sql_file, $old_prefix, $query_start = 0, $ignore_existing = false)
 {
     $return = false;
     // Require a new table prefix.
     if ($this->_database_prefix == '') {
         pb_backupbuddy::status('error', 'ERROR 9008: A database prefix is required for importing.');
     }
     if ($query_start > 0) {
         pb_backupbuddy::status('message', 'Continuing to restore database dump starting at file location `' . $query_start . '`.');
     } else {
         pb_backupbuddy::status('message', 'Restoring database dump. This may take a moment...');
     }
     global $wpdb;
     // Check whether or not tables already exist that might collide.
     /*
     if ( $ignore_existing === false ) {
     	if ( $query_start == 0 ) { // Check number of tables already existing with this prefix. Skips this check on substeps of DB import.
     		$rows = $wpdb->get_results( "SELECT table_name FROM information_schema.tables WHERE table_name LIKE '" . backupbuddy_core::dbEscape( str_replace( '_', '\_', $this->_database_prefix ) ) . "%' AND table_schema = DATABASE()", ARRAY_A );
     		if ( count( $rows ) > 0 ) {
     			pb_backupbuddy::status( 'error', 'Error #9014: Database import halted to prevent overwriting existing WordPress data.', 'The database already contains a WordPress installation with this prefix (' . count( $rows ) . ' tables). Restore has been stopped to prevent overwriting existing data. *** Please go back and enter a new database name and/or prefix OR select the option to wipe the database prior to import from the advanced settings on the first import step. ***' );
     			return false;
     		}
     		unset( $rows );
     	}
     }
     */
     pb_backupbuddy::status('message', 'Starting database import procedure.');
     if ('-1' == $this->_maxExecutionTime) {
         pb_backupbuddy::status('details', 'Database max execution time chunking disabled based on -1 passed.');
     } else {
         pb_backupbuddy::status('details', 'mysqlbuddy: Maximum execution time for this run: ' . $this->_maxExecutionTime . ' seconds.');
     }
     pb_backupbuddy::status('details', 'mysqlbuddy: Old prefix: `' . $old_prefix . '`; New prefix: `' . $this->_database_prefix . '`.');
     pb_backupbuddy::status('details', "mysqlbuddy: Importing SQL file: `{$sql_file}`. Old prefix: `{$old_prefix}`. Query start: `{$query_start}`.");
     pb_backupbuddy::status('details', 'About to flush...');
     pb_backupbuddy::flush();
     // Attempt each method in order.
     pb_backupbuddy::status('details', 'Preparing to import using available method(s) by priority. Basing import methods off dump methods: `' . implode(',', $this->_methods) . '`');
     foreach ($this->_methods as $method) {
         if (method_exists($this, "_import_{$method}")) {
             pb_backupbuddy::status('details', 'mysqlbuddy: Attempting import method `' . $method . '`.');
             $result = call_user_func(array($this, "_import_{$method}"), $sql_file, $old_prefix, $query_start, $ignore_existing);
             if ($result === true) {
                 // Dump completed succesfully with this method.
                 pb_backupbuddy::status('details', 'mysqlbuddy: Import method `' . $method . '` completed successfully.');
                 $return = true;
                 break;
             } elseif ($result === false) {
                 // Dump failed this method. Will try compatibility fallback to next mode if able.
                 // Do nothing. Will try next mode next loop.
                 pb_backupbuddy::status('details', 'mysqlbuddy: Import method `' . $method . '` failed. Trying another compatibility mode next if able.');
             } else {
                 // Something else returned; used for resuming (integer) or a message (string).
                 pb_backupbuddy::status('details', 'mysqlbuddy: Non-boolean response (usually means resume is needed): `' . implode(',', $result) . '`');
                 return $result;
                 // Dont fallback if this happens. Usually means resume is needed to finish.
             }
         }
     }
     if ($return === true) {
         // Success.
         pb_backupbuddy::status('message', 'Database import of `' . basename($sql_file) . '` succeeded.');
         return true;
     } else {
         // Overall failure.
         pb_backupbuddy::status('error', 'Database import procedure did not complete or failed.');
         return false;
     }
 }
Пример #21
0
 public static function run_live_send()
 {
     if (true === self::$_queue_sent) {
         // Already sent. Shutdown fired again.
         return;
     }
     pb_backupbuddy::flush();
     // Send any pending data to browser.
     if (!isset(pb_backupbuddy::$options['remote_destinations'][backupbuddy_live::getLiveID()])) {
         // Live destination went away. Deleted?
         return;
     }
     $count = self::_process_dbqueue();
     if (0 == $count) {
         // Nothing needs to be sent.
         return;
     }
     self::_send_dbqueue();
 }