ry_include_file(''.$relative_path, 'include_once'); } } /** * Attach this updraftplus plugin as host of the UpdraftCentral libraries * (e.g. "central" folder) * * @param array $hosts List of plugins having the "central" library integrated into them * * @return array */ public function attach_updraftcentral_host($hosts) { $hosts[] = 'updraftplus'; return $hosts; } /** * Get the character set for the current database connection * * @uses WPDB::determine_charset() - exists on WP 4.6+ * * @param Object|Null $wpdb - WPDB object; if none passed, then use the global one * * @return String */ public function get_connection_charset($wpdb = null) { if (null === $wpdb) { global $wpdb; } $charset = (defined('DB_CHARSET') && DB_CHARSET) ? DB_CHARSET : 'utf8mb4'; if (method_exists($wpdb, 'determine_charset')) { $charset_collate = $wpdb->determine_charset($charset, ''); if (!empty($charset_collate['charset'])) $charset = $charset_collate['charset']; } return $charset; } /** * Runs upon the action updraftcentral_listener_pre_udrpc_action */ public function updraftcentral_listener_pre_udrpc_action() { $this->register_wp_http_option_hooks(); } /** * Runs upon the action updraftcentral_listener_post_udrpc_action */ public function updraftcentral_listener_post_udrpc_action() { $this->register_wp_http_option_hooks(false); } /** * Register our class. WP filter updraftcentral_remotecontrol_command_classes. * * @param Array $command_classes sends across the command class * * @return Array - filtered value */ public function updraftcentral_remotecontrol_command_classes($command_classes) { if (is_array($command_classes)) $command_classes['updraftplus'] = 'UpdraftCentral_UpdraftPlus_Commands'; if (is_array($command_classes)) $command_classes['updraftvault'] = 'UpdraftCentral_UpdraftVault_Commands'; return $command_classes; } /** * Load the class when required * * @param string $command_php_class Sends across the php class type */ public function updraftcentral_command_class_wanted($command_php_class) { if ('UpdraftCentral_UpdraftPlus_Commands' == $command_php_class) { updraft_try_include_file('includes/class-updraftcentral-updraftplus-commands.php', 'include_once'); } elseif ('UpdraftCentral_UpdraftVault_Commands' == $command_php_class) { updraft_try_include_file('includes/updraftvault.php', 'include_once'); } } /** * This function allows you to manually set the nonce and timestamp for the current backup job. If none are provided then it will create new ones. * * @param Boolean|string $nonce - the nonce you want to set * @param Boolean|string $timestamp - the timestamp you want to set * * @return string - returns the backup nonce that has been set */ public function backup_time_nonce($nonce = false, $timestamp = false) { $this->job_time_ms = microtime(true); if (false === $timestamp) $timestamp = time(); if (false === $nonce) $nonce = substr(md5(time().rand()), 20); $this->backup_time = $timestamp; $this->file_nonce = apply_filters('updraftplus_incremental_backup_file_nonce', $nonce); $this->nonce = $nonce; return $nonce; } /** * Get the WordPress version * * @return String - the version */ public function get_wordpress_version() { static $got_wp_version = false; if (!$got_wp_version) { global $wp_version; @include(ABSPATH.WPINC.'/version.php');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $got_wp_version = $wp_version; } return $got_wp_version; } /** * Get the UpdraftPlus version and convert it to the correct format to be used in filenames * * @return String - the file version number */ public function get_updraftplus_file_version() { if ($this->use_unminified_scripts()) return ''; $version_parts = explode('.', $this->version); $version_parts = array_slice($version_parts, 0, 3); $version = implode('.', $version_parts); return '-'.str_replace('.', '-', $version).'.min'; } /** * Opens the log file, writes a standardised header, and stores the resulting name and handle in the class variables logfile_name/logfile_handle/opened_log_time (and possibly backup_is_already_complete) * * @param String $nonce - Used in the log file name to distinguish it from other log files. Should be the job nonce. * @returns void */ public function logfile_open($nonce) { $this->logfile_name = $this->get_logfile_name($nonce); $this->backup_is_already_complete = $this->found_backup_complete_in_logfile($nonce, false); $this->logfile_handle = fopen($this->logfile_name, 'a'); $this->opened_log_time = microtime(true); $this->write_log_header(array($this, 'log')); } /** * Opens the log file, and finds if backup_is_already_complete * * @param String $nonce - Used in the log file name to distinguish it from other log files. Should be the job nonce. * @param Boolean $use_existing_result - Whether to use any existing result or not * * @return boolean - returns true if the backup is complete otherwise returns false */ public function found_backup_complete_in_logfile($nonce, $use_existing_result = true) { static $checked_files = array(); if (isset($checked_files[$nonce]) && $use_existing_result) return $checked_files[$nonce]; $logfile_name = $this->get_logfile_name($nonce); if (!file_exists($logfile_name)) return false; $backup_is_already_complete = false; $seek_to = max((filesize($logfile_name) - 340), 1); $handle = fopen($logfile_name, 'r'); if (is_resource($handle)) { // Returns 0 on success if (0 === @fseek($handle, $seek_to)) {// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $bytes_back = filesize($logfile_name) - $seek_to; // Return to the end of the file $read_recent = fread($handle, $bytes_back); // Move to end of file - ought to be redundant if ((false !== strpos($read_recent, ') The backup apparently succeeded') || false !== strpos($read_recent, ') The backup succeeded')) && false !== strpos($read_recent, 'and is now complete')) { $backup_is_already_complete = true; } } fclose($handle); } $checked_files[$nonce] = $backup_is_already_complete; return $backup_is_already_complete; } /** * Returns the logfile name for a given job * * @param String $nonce - Used in the log file name to distinguish it from other log files. Should be the job nonce. * @return string */ public function get_logfile_name($nonce) { $updraft_dir = $this->backups_dir_location(); return $updraft_dir."/log.$nonce.txt"; } /** * Writes a standardised header to the log file, using the specified logging function, which needs to be compatible with (or to be) UpdraftPlus::log() * * @param callable $logging_function */ public function write_log_header($logging_function) { global $wpdb; $updraft_dir = $this->backups_dir_location(); call_user_func($logging_function, 'Opened log file at time: '.date('r').' on '.network_site_url()); $wp_version = $this->get_wordpress_version(); $mysql_version = $wpdb->get_var('SELECT VERSION()'); if ('' == $mysql_version) $mysql_version = $wpdb->db_version(); $safe_mode = $this->detect_safe_mode(); $memory_limit = ini_get('memory_limit'); $memory_usage = round(@memory_get_usage(false)/1048576, 1);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $memory_usage2 = round(@memory_get_usage(true)/1048576, 1);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. // Attempt to raise limit to avoid false positives if (function_exists('set_time_limit')) @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $max_execution_time = (int) @ini_get("max_execution_time");// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $mp = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet"); $logline = "UpdraftPlus WordPress backup plugin (https://updraftplus.com): ".$this->version." WP: ".$wp_version." PHP: ".phpversion()." (".PHP_SAPI.", ".(function_exists('php_uname') ? @php_uname() : PHP_OS).") MySQL: $mysql_version (max packet size=$mp) WPLANG: ".get_locale()." Server: ".$_SERVER["SERVER_SOFTWARE"]." safe_mode: $safe_mode max_execution_time: $max_execution_time memory_limit: $memory_limit (used: {$memory_usage}M | {$memory_usage2}M) multisite: ".(is_multisite() ? (is_subdomain_install() ? 'Y (sub-domain)' : 'Y (sub-folder)') : 'N')." openssl: ".(defined('OPENSSL_VERSION_TEXT') ? OPENSSL_VERSION_TEXT : 'N')." mcrypt: ".(function_exists('mcrypt_encrypt') ? 'Y' : 'N')." LANG: ".getenv('LANG')." ZipArchive::addFile: ";// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. // method_exists causes some faulty PHP installations to segfault, leading to support requests if (version_compare(phpversion(), '5.2.0', '>=') && extension_loaded('zip')) { $logline .= 'Y'; } else { $logline .= (class_exists('ZipArchive') && method_exists('ZipArchive', 'addFile')) ? "Y" : "N"; } if (0 === $this->current_resumption) { $memlim = $this->memory_check_current(); if ($memlim<65 && $memlim>0) { $this->log(sprintf(__('The amount of memory (RAM) allowed for PHP is very low (%s Mb) - you should increase it to avoid failures due to insufficient memory (consult your web hosting company for more help)', 'updraftplus'), round($memlim, 1)), 'warning', 'lowram'); } if ($max_execution_time>0 && $max_execution_time<20) { call_user_func($logging_function, sprintf(__('The amount of time allowed for WordPress plugins to run is very low (%s seconds) - you should increase it to avoid backup failures due to time-outs (consult your web hosting company for more help - it is the max_execution_time PHP setting; the recommended value is %s seconds or more)', 'updraftplus'), $max_execution_time, 90), 'warning', 'lowmaxexecutiontime'); } } call_user_func($logging_function, $logline); $hosting_bytes_free = $this->get_hosting_disk_quota_free(); if (is_array($hosting_bytes_free)) { $perc = round(100*$hosting_bytes_free[1]/(max($hosting_bytes_free[2], 1)), 1); $quota_free = ' / '.sprintf('Free disk space in account: %s (%s used)', round($hosting_bytes_free[3]/1048576, 1)." MB", "$perc %"); if ($hosting_bytes_free[3] < 1048576*50) { $quota_free_mb = round($hosting_bytes_free[3]/1048576, 1); call_user_func($logging_function, sprintf(__('Your free space in your hosting account is very low - only %s Mb remain', 'updraftplus'), $quota_free_mb), 'warning', 'lowaccountspace'.$quota_free_mb); } } else { $quota_free = ''; } $disk_free_space = function_exists('disk_free_space') ? @disk_free_space($updraft_dir) : false;// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. // == rather than === here is deliberate; support experience shows that a result of (int)0 is not reliable. i.e. 0 can be returned when the real result should be false. if (false == $disk_free_space) { call_user_func($logging_function, "Free space on disk containing Updraft's temporary directory: Unknown".$quota_free); } else { call_user_func($logging_function, "Free space on disk containing Updraft's temporary directory: ".round($disk_free_space/1048576, 1)." MB".$quota_free); $disk_free_mb = round($disk_free_space/1048576, 1); if ($disk_free_space < 50*1048576) call_user_func($logging_function, sprintf(__('Your free disk space is very low - only %s Mb remain', 'updraftplus'), round($disk_free_space/1048576, 1)), 'warning', 'lowdiskspace'.$disk_free_mb); } } /** * This function will read the next chunk from the log file and return it's contents and last read byte position * * @param String $nonce - the UpdraftPlus file nonce * * @return array - an empty array if there is no log file or an array with log file contents and last read byte position */ public function get_last_log_chunk($nonce) { $this->logfile_name = $this->get_logfile_name($nonce); if (file_exists($this->logfile_name)) { $contents = ''; $seek_to = max(0, $this->jobdata_get('clone_first_byte', 0)); $first_byte = $seek_to; $handle = fopen($this->logfile_name, 'r'); if (is_resource($handle)) { // Returns 0 on success if (0 === @fseek($handle, $seek_to)) {// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. while (strlen($contents) < 1048576 && ($buffer = fgets($handle, 262144)) !== false) { $contents .= $buffer; $seek_to += 262144; } $this->jobdata_set('clone_first_byte', $seek_to); } fclose($handle); } return array('log_contents' => $contents, 'first_byte' => $first_byte); } return array(); } /** * * Verifies that the indicated amount of memory is available * * @param Integer $how_many_bytes_needed - how many bytes need to be available * * @return Boolean - whether the needed number of bytes is available */ public function verify_free_memory($how_many_bytes_needed) { // This returns in MB $memory_limit = $this->memory_check_current(); if (!is_numeric($memory_limit)) return false; $memory_limit = $memory_limit * 1048576; $memory_usage = round(@memory_get_usage(false), 1);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $memory_usage2 = round(@memory_get_usage(true), 1);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. if ($memory_limit - $memory_usage > $how_many_bytes_needed && $memory_limit - $memory_usage2 > $how_many_bytes_needed) return true; return false; } /** * Logs the given line, adding (relative) time stamp and newline * Note these subtleties of log handling: * - Messages at level 'error' are not logged to file - it is assumed that a separate call to log() at another level will take place. This is because at level 'error', messages are translated; whereas the log file is for developers who may not know the translated language. Messages at level 'error' are for the user. * - Messages at level 'error' do not persist through the job (they are only saved with save_backup_to_history(), and never restored from there - so only the final save_backup_to_history() errors * persist); we presume that either a) they will be cleared on the next attempt, or b) they will occur again on the final attempt (at which point they will go to the user). But... * - messages at level 'warning' persist. These are conditions that are unlikely to be cleared, not-fatal, but the user should be informed about. The $uniq_id field (which should not be numeric) can then be used for warnings that should only be logged once * $skip_dblog = true is suitable when there's a risk of excessive logging, and the information is not important for the user to see in the browser on the settings page * The uniq_id field is also used with PHP event detection - it is set then to 'php_event' - which is useful for anything hooking the action to detect * * @param string $line the log line * @param string $level the log level: notice, warning, error. If suffixed with a hyphen and a destination, then the default destination is changed too. * @param boolean $uniq_id each of these will only be logged once * @param boolean $skip_dblog if true, then do not write to the database * @return null */ public function log($line, $level = 'notice', $uniq_id = false, $skip_dblog = false) { $destination = 'default'; if (preg_match('/^([a-z]+)-([a-z]+)$/', $level, $matches)) { $level = $matches[1]; $destination = $matches[2]; } if ('error' == $level || 'warning' == $level) { if ('error' == $level && 0 == $this->error_count()) $this->log('An error condition has occurred for the first time during this job'); if ($uniq_id) { $this->errors[$uniq_id] = array('level' => $level, 'message' => $line); } else { $this->errors[] = array('level' => $level, 'message' => $line); } // Errors are logged separately if ('error' == $level) return; // It's a warning $warnings = $this->jobdata_get('warnings'); if (!is_array($warnings)) $warnings = array(); if ($uniq_id) { $warnings[$uniq_id] = $line; } else { $warnings[] = $line; } $this->jobdata_set('warnings', $warnings); } if (false === ($line = apply_filters('updraftplus_logline', $line, $this->nonce, $level, $uniq_id, $destination))) return; if ($this->logfile_handle) { // Record log file times relative to the backup start, if possible $rtime = (!empty($this->job_time_ms)) ? microtime(true)-$this->job_time_ms : microtime(true)-$this->opened_log_time; fwrite($this->logfile_handle, sprintf("%08.03f", round($rtime, 3))." (".$this->current_resumption.") ".(('notice' != $level) ? '['.ucfirst($level).'] ' : '').$line."\n"); } switch ($this->jobdata_get('job_type')) { case 'download': // Download messages are keyed on the job (since they could be running several), and type // The values of the POST array were checked before $findex = empty($_POST['findex']) ? 0 : $_POST['findex']; if (!empty($_POST['timestamp']) && !empty($_POST['type'])) $this->jobdata_set('dlmessage_'.$_POST['timestamp'].'_'.$_POST['type'].'_'.$findex, $line); break; case 'restore': // if ('debug' != $level) echo $line."\n"; break; default: if (!$skip_dblog && 'debug' != $level) UpdraftPlus_Options::update_updraft_option('updraft_lastmessage', $line." (".date_i18n('M d H:i:s').")", false); break; } if (defined('UPDRAFTPLUS_CONSOLELOG') && UPDRAFTPLUS_CONSOLELOG) echo $line."\n"; if (defined('UPDRAFTPLUS_BROWSERLOG') && UPDRAFTPLUS_BROWSERLOG) echo htmlentities($line)."
\n"; } /** * Remove any logged warnings with the specified identifier. (The use case for this is that you can warn of something that may be about to happen (with a probably crash if it does), and then remove the warning if it did not happen). * * @see self::log() * * @param String $uniq_id - the identifier, previously passed to self::log() */ public function log_remove_warning($uniq_id) { $warnings = $this->jobdata_get('warnings'); if (!is_array($warnings)) $warnings = array(); // Avoid an unnecessary database write if nothing changed if (isset($warnings[$uniq_id])) { unset($warnings[$uniq_id]); $this->jobdata_set('warnings', $warnings); } unset($this->errors[$uniq_id]); } /** * Indicate whether or not a warning is logged with a specific identifier * * @see self::log() * * @param String $uniq_id - the identifier, previously passed to self::log() * * @return Boolean */ public function warning_exists($uniq_id) { $warnings = $this->jobdata_get('warnings'); return !empty($warnings[$uniq_id]); } /** * For efficiency, you can also feed false or a string into this function * * @param Boolean|String|WP_Error $err - the errors * @param Boolean $echo - whether to echo() the error(s) * @param Boolean $logerror - whether to pass errors to UpdraftPlus::log() * @return Boolean - returns false for convenience */ public function log_wp_error($err, $echo = false, $logerror = false) { if (false === $err) return false; if (is_string($err)) { $this->log("Error message: $err"); if ($echo) $this->log(sprintf(__('Error: %s', 'updraftplus'), $err), 'notice-warning'); if ($logerror) $this->log($err, 'error'); return false; } foreach ($err->get_error_messages() as $msg) { $this->log("Error message: $msg"); if ($echo) $this->log(sprintf(__('Error: %s', 'updraftplus'), $msg), 'notice-warning'); if ($logerror) $this->log($msg, 'error'); } $codes = $err->get_error_codes(); if (is_array($codes)) { foreach ($codes as $code) { $data = $err->get_error_data($code); if (!empty($data)) { $ll = (is_string($data)) ? $data : serialize($data); $this->log("Error data (".$code."): ".$ll); } } } // Returns false so that callers can return with false more efficiently if they wish return false; } /** * This function will construct the restore information log line using the passed in parameters and then log the line using $this->log(); * * @param array $restore_information - an array of restore information * * @return void */ public function log_restore_update($restore_information) { $this->log("RINFO:".json_encode($restore_information), 'notice-progress'); } /** * Outputs data to the browser. * Will also fill the buffer on nginx systems after a specified amount of time. * * @param String $line The text to output * @return void */ public function output_to_browser($line) { echo $line; if (false === stripos($_SERVER['SERVER_SOFTWARE'], 'nginx')) return; static $strcount = 0; static $time = 0; $buffer_size = 65536; // The default NGINX config uses a buffer size of 32 or 64k, depending on the system. So we use 64K. if (0 == $time) $time = time(); $strcount += strlen($line); if ((time() - $time) >= 8) { // if the string count is > the buffer size, we reset, as it's likely the string was already sent. if ($strcount > $buffer_size) { $time = time(); $strcount = $strcount - $buffer_size; return; } echo str_repeat(" ", ($buffer_size-$strcount)); // reset values $time = time(); $strcount = 0; } } /** * Get the maximum packet size on the WPDB MySQL connection, in bytes, after (optionally) attempting to raise it to 32MB if it appeared to be lower. * A default value equal to 1MB is returned if the true value could not be found - it has been found reasonable to assume that at least this is available. * * @param Boolean $first_raise * @param Boolean $log_it * * @return Integer */ public function max_packet_size($first_raise = true, $log_it = true) { global $wpdb; $mp = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet"); // Default to 1MB $mp = (is_numeric($mp) && $mp > 0) ? $mp : 1048576; // 32MB if ($first_raise && $mp < 33554432) { $save = $wpdb->show_errors(false); $req = @$wpdb->query("SET GLOBAL max_allowed_packet=33554432");// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the method. $wpdb->show_errors($save); if (!$req) $this->log("Tried to raise max_allowed_packet from ".round($mp/1048576, 1)." MB to 32 MB, but failed (".$wpdb->last_error.", ".serialize($req).")"); $mp = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet"); // Default to 1MB $mp = (is_numeric($mp) && $mp > 0) ? $mp : 1048576; } if ($log_it) $this->log("Max packet size: ".round($mp/1048576, 1)." MB"); return $mp; } /** * Q. Why is this abstracted into a separate function? A. To allow poedit and other parsers to pick up the need to translate strings passed to it (and not pick up all of those passed to log()). * 1st argument = the line to be logged (obligatory) * Further arguments = parameters for sprintf() * * @return null */ public function log_e() { $args = func_get_args(); // Get first argument $pre_line = array_shift($args); // Log it whilst still in English if (is_wp_error($pre_line)) { $this->log_wp_error($pre_line); } else { // Now run (v)sprintf on it, using any remaining arguments. vsprintf = sprintf but takes an array instead of individual arguments $this->log(vsprintf($pre_line, $args)); // This is slightly hackish, in that we have no way to use a different level or destination. In that case, the caller should instead call log() twice with different parameters, instead of using this convenience function. $this->log(vsprintf($pre_line, $args), 'notice-restore'); } } /** * This function is used by cloud methods file_put_contents($updraft_dir.'/binziptest/subdir1/subdir2/test2.html', 'UpdraftPlus is a really great backup and restoration plugin for WordPress.'); $exec = $potzip; if (defined('UPDRAFTPLUS_BINZIP_OPTS') && UPDRAFTPLUS_BINZIP_OPTS) $exec .= ' '.UPDRAFTPLUS_BINZIP_OPTS; $exec .= " -v -@ binziptest/test.zip"; $all_ok = true; $descriptorspec = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w') ); $handle = proc_open($exec, $descriptorspec, $pipes, $updraft_dir); if (is_resource($handle)) { if (!fwrite($pipes[0], "binziptest/subdir1/subdir2/test2.html\n")) { @fclose($pipes[0]);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @fclose($pipes[1]);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @fclose($pipes[2]);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $all_ok = false; } else { fclose($pipes[0]); while (!feof($pipes[1])) { $w = fgets($pipes[1]); if ($w && $log_it) $this->log("Output: ".trim($w)); } fclose($pipes[1]); while (!feof($pipes[2])) { $last_error = fgets($pipes[2]); if (!empty($last_error) && $log_it) $this->log("Stderr output: ".trim($w)); } fclose($pipes[2]); $ret = function_exists('proc_close') ? proc_close($handle) : -1; if (0 != $ret) { if ($log_it) $this->log("Binary zip: error (code: $ret)"); $all_ok = false; } } } else { if ($log_it) $this->log("Error: proc_open failed"); $all_ok = false; } } // Do we now actually have a working zip? Need to test the created object using PclZip // If it passes, then remove dirs and then return $potzip; $found_first = false; $found_second = false; if ($all_ok && file_exists($updraft_dir.'/binziptest/test.zip')) { if (function_exists('gzopen')) { if (!class_exists('PclZip')) include_once(ABSPATH.'/wp-admin/includes/class-pclzip.php'); $zip = new PclZip($updraft_dir.'/binziptest/test.zip'); if (($list = $zip->listContent()) != 0) { foreach ($list as $obj) { if ($obj['filename'] && !empty($obj['stored_filename']) && 'binziptest/subdir1/subdir2/test.html' == $obj['stored_filename'] && 131 == $obj['size']) $found_first=true; if ($obj['filename'] && !empty($obj['stored_filename']) && 'binziptest/subdir1/subdir2/test2.html' == $obj['stored_filename'] && 138 == $obj['size']) $found_second=true; } } } else { // PclZip will die() if gzopen is not found // Obviously, this is a kludge - we assume it's working. We could, of course, just return false - but since we already know now that PclZip can't work, that only leaves ZipArchive $this->log("gzopen function not found; PclZip cannot be invoked; will assume that binary zip works if we have a non-zero file"); if (filesize($updraft_dir.'/binziptest/test.zip') > 0) { $found_first = true; $found_second = true; } } } $this->remove_binzip_test_files($updraft_dir); if ($found_first && $found_second) { if ($log_it) $this->log("Working binary zip found: $potzip"); if ($cacheit) $this->jobdata_set('binzip', $potzip); return $potzip; } } $this->remove_binzip_test_files($updraft_dir); } if ($cacheit) $this->jobdata_set('binzip', false); return false; } /** * Remove potentially existing test files after binzip testing * * @param String $updraft_dir - directory to find the files in */ private function remove_binzip_test_files($updraft_dir) { @unlink($updraft_dir.'/binziptest/subdir1/subdir2/test.html');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @unlink($updraft_dir.'/binziptest/subdir1/subdir2/test2.html');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @rmdir($updraft_dir.'/binziptest/subdir1/subdir2');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @rmdir($updraft_dir.'/binziptest/subdir1');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @unlink($updraft_dir.'/binziptest/test.zip');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @rmdir($updraft_dir.'/binziptest');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. } public function option_filter_get($which) { global $wpdb; $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $which)); // Has to be get_row instead of get_var because of funkiness with 0, false, null values return (is_object($row)) ? $row->option_value : false; } /** * Indicate which checksums to take for backup files. Abstracted for extensibilty and future changes. * * @returns array - a list of hashing algorithms, as understood by PHP's hash() function */ public function which_checksums() { return apply_filters('updraftplus_which_checksums', array('sha1', 'sha256')); } /** * Pretty printing of the raw backup information * * @param String $description * @param Array $history * @param String $entity * @param Array $checksums * @param Array $jobdata * @param Boolean $smaller * @return String */ public function printfile($description, $history, $entity, $checksums, $jobdata, $smaller = false) { if (empty($history[$entity])) return; // PHP 7.2+ throws a warning if you try to count() a string $how_many = is_string($history[$entity]) ? 1 : count($history[$entity]); if ($smaller) { $pfiles = "".$description." (".sprintf(__('files: %s', 'updraftplus'), $how_many).")
\n"; } else { $pfiles = "

".$description." (".sprintf(__('files: %s', 'updraftplus'), $how_many).")

\n\n"; } $is_incremental = (!empty($jobdata) && !empty($jobdata['job_type']) && 'incremental' == $jobdata['job_type'] && 'db' != substr($entity, 0, 2)) ? true : false; if ($is_incremental) { $backup_timestamp = $jobdata['backup_time']; $backup_history = UpdraftPlus_Backup_History::get_history($backup_timestamp); $pfiles .= "
"; foreach ($backup_history['incremental_sets'] as $timestamp => $backup) { if (isset($backup[$entity])) { $pfiles .= "
".get_date_from_gmt(gmdate('Y-m-d H:i:s', (int) $timestamp), 'M d, Y G:i')."\n
\n"; foreach ($backup[$entity] as $ind => $file) { $pfiles .= "
".$this->get_entity_row($file, $history, $entity, $checksums, $jobdata, $ind)."\n
\n"; } } } $pfiles .= "
\n"; } else { $pfiles .= "\n"; } return $pfiles; } /** * This function will use the passed in information to prepare a pretty string describing the backup from the raw backup history * * @param String $file - the backup file * @param Array $history - the backup history * @param String $entity - the backup entity * @param Array $checksums - checksums for the backup file * @param Array $jobdata - the jobdata for this backup * @param Integer $ind - the index of the file * * @return String - returns the entity output string */ public function get_entity_row($file, $history, $entity, $checksums, $jobdata, $ind) { $op = htmlspecialchars($file); $skey = $entity.((0 == $ind) ? '' : $ind).'-size'; $op = apply_filters('updraft_report_downloadable_file_link', $op, $entity, $ind, $jobdata); $op .= "\n"; $meta = ''; if ('db' == substr($entity, 0, 2) && 'db' != $entity) { $dind = substr($entity, 2); if (is_array($jobdata) && !empty($jobdata['backup_database']) && is_array($jobdata['backup_database']) && !empty($jobdata['backup_database'][$dind]) && is_array($jobdata['backup_database'][$dind]['dbinfo']) && !empty($jobdata['backup_database'][$dind]['dbinfo']['host'])) { $dbinfo = $jobdata['backup_database'][$dind]['dbinfo']; $meta .= sprintf(__('External database (%s)', 'updraftplus'), $dbinfo['user'].'@'.$dbinfo['host'].'/'.$dbinfo['name'])."
"; } } if (isset($history[$skey])) $meta .= sprintf(__('Size: %s MB', 'updraftplus'), round($history[$skey]/1048576, 1)); $ckey = $entity.$ind; foreach ($checksums as $ck) { $ck_plain = false; if (isset($history['checksums'][$ck][$ckey])) { $meta .= (($meta) ? ', ' : '').sprintf(__('%s checksum: %s', 'updraftplus'), strtoupper($ck), $history['checksums'][$ck][$ckey]); $ck_plain = true; } if (isset($history['checksums'][$ck][$ckey.'.crypt'])) { if ($ck_plain) $meta .= ' '.__('(when decrypted)'); $meta .= (($meta) ? ', ' : '').sprintf(__('%s checksum: %s', 'updraftplus'), strtoupper($ck), $history['checksums'][$ck][$ckey.'.crypt']); } } $fileinfo = apply_filters("updraftplus_fileinfo_$entity", array(), $ind); if (is_array($fileinfo) && !empty($fileinfo)) { if (isset($fileinfo['html'])) { $meta .= $fileinfo['html']; } } // if ($meta) $meta = " ($meta)"; if ($meta) $meta = "
$meta"; return $op.$meta; } /** * This important function returns a list of file entities that can potentially be backed up (subject to users settings), and optionally further meta-data about them * * @param boolean $include_others * @param boolean $full_info * @return array */ public function get_backupable_file_entities($include_others = true, $full_info = false) { $wp_upload_dir = $this->wp_upload_dir(); if ($full_info) { $arr = array( 'plugins' => array('path' => untrailingslashit(WP_PLUGIN_DIR), 'description' => __('Plugins', 'updraftplus'), 'singular_description' => __('Plugin', 'updraftplus')), 'themes' => array('path' => WP_CONTENT_DIR.'/themes', 'description' => __('Themes', 'updraftplus'), 'singular_description' => __('Theme', 'updraftplus')), 'uploads' => array('path' => untrailingslashit($wp_upload_dir['basedir']), 'description' => __('Uploads', 'updraftplus')) ); } else { $arr = array( 'plugins' => untrailingslashit(WP_PLUGIN_DIR), 'themes' => WP_CONTENT_DIR.'/themes', 'uploads' => untrailingslashit($wp_upload_dir['basedir']) ); } $arr = apply_filters('updraft_backupable_file_entities', $arr, $full_info); // We then add 'others' on to the end if ($include_others) { if ($full_info) { $arr['others'] = array('path' => WP_CONTENT_DIR, 'description' => __('Others', 'updraftplus')); } else { $arr['others'] = WP_CONTENT_DIR; } } // Entries that should be added after 'others' $arr = apply_filters('updraft_backupable_file_entities_final', $arr, $full_info); return $arr; } public function php_error_to_logline($errno, $errstr, $errfile, $errline) { switch ($errno) { case 1: $e_type = 'E_ERROR'; break; case 2: $e_type = 'E_WARNING'; break; case 4: $e_type = 'E_PARSE'; break; case 8: $e_type = 'E_NOTICE'; break; case 16: $e_type = 'E_CORE_ERROR'; break; case 32: $e_type = 'E_CORE_WARNING'; break; case 64: $e_type = 'E_COMPILE_ERROR'; break; case 128: $e_type = 'E_COMPILE_WARNING'; break; case 256: $e_type = 'E_USER_ERROR'; break; case 512: $e_type = 'E_USER_WARNING'; break; case 1024: $e_type = 'E_USER_NOTICE'; break; case 2048: $e_type = 'E_STRICT'; break; case 4096: $e_type = 'E_RECOVERABLE_ERROR'; break; case 8192: $e_type = 'E_DEPRECATED'; break; case 16384: $e_type = 'E_USER_DEPRECATED'; break; case 30719: $e_type = 'E_ALL'; break; default: $e_type = "E_UNKNOWN ($errno)"; break; } if (false !== stripos($errstr, 'table which is not valid in this version of Gravity Forms')) return false; if (!is_string($errstr)) $errstr = serialize($errstr); if (0 === strpos($errfile, ABSPATH)) $errfile = substr($errfile, strlen(ABSPATH)); if ('E_DEPRECATED' == $e_type && !empty($this->no_deprecation_warnings)) { return false; } return "PHP event: code $e_type: $errstr (line $errline, $errfile)"; } public function php_error($errno, $errstr, $errfile, $errline) { if (0 == error_reporting()) return true; $logline = $this->php_error_to_logline($errno, $errstr, $errfile, $errline); if (false !== $logline) $this->log($logline, 'notice', 'php_event'); // Pass it up the chain return $this->error_reporting_stop_when_logged; } /** * Proceed with a backup; before calling this, at least all the initial job data must be set up * * @param Integer $resumption_no - which resumption this is; from 0 upwards * @param String $bnonce - the backup job identifier */ public function backup_resume($resumption_no, $bnonce) { // Theoretically (N.B. has been seen in the real world), the WP scheduler might call us more than once within the same context (e.g. an incremental run followed by a main backup resumption), leaving us with incorrect internal state if we don't reset. static $last_bnonce = null; if ($last_bnonce) $this->jobdata_reset(); $last_bnonce = $bnonce; set_error_handler(array($this, 'php_error'), E_ALL & ~E_STRICT); $this->current_resumption = $resumption_no; if (function_exists('set_time_limit')) @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. if (function_exists('ignore_user_abort')) @ignore_user_abort(true);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $runs_started = array(); $time_now = microtime(true); UpdraftPlus_Backup_History::always_get_from_db(); // Restore state $resumption_extralog = ''; $prev_resumption = $resumption_no - 1; $last_successful_resumption = -1; $job_type = 'backup'; if (0 == $resumption_no) { $label = $this->jobdata_get('label'); if ($label) $resumption_extralog = apply_filters('updraftplus_autobackup_extralog', ", label=$label"); } else { $this->nonce = $bnonce; $file_nonce = $this->jobdata_get('file_nonce'); $this->file_nonce = $file_nonce ? $file_nonce : $bnonce; $this->backup_time = $this->jobdata_get('backup_time'); $this->job_time_ms = $this->jobdata_get('job_time_ms'); // Get the warnings before opening the log file, as opening the log file may generate new ones (which then leads to $this->errors having duplicate entries when they are copied over below) $warnings = $this->jobdata_get('warnings'); $this->logfile_open($this->file_nonce); if (!$this->get_backup_job_semaphore_lock($this->nonce, $resumption_no)) { $this->log('Failed to get backup job lock; possible overlapping resumptions - will abort this instance'); die; } // Import existing warnings. The purpose of this is so that when save_backup_to_history() is called, it has a complete set - because job data expires quickly, whilst the warnings of the last backup run need to persist if (is_array($warnings)) { foreach ($warnings as $warning) { $this->errors[] = array('level' => 'warning', 'message' => $warning); } } $runs_started = $this->jobdata_get('runs_started'); if (!is_array($runs_started)) $runs_started =array(); $time_passed = $this->jobdata_get('run_times'); if (!is_array($time_passed)) $time_passed = array(); foreach ($time_passed as $run => $passed) { if (isset($runs_started[$run]) && $runs_started[$run] + $time_passed[$run] + 30 > $time_now) { // We don't want to increase the resumption if WP has started two copies of the same resumption off if ($run && $run == $resumption_no) { $increase_resumption = false; $this->log("It looks like WordPress's scheduler has started multiple instances of this resumption"); } else { $increase_resumption = true; } UpdraftPlus_Job_Scheduler::terminate_due_to_activity('check-in', round($time_now, 1), round($runs_started[$run] + $time_passed[$run], 1), $increase_resumption); } } $useful_checkins = $this->jobdata_get('useful_checkins', array()); if (!empty($useful_checkins)) { $last_successful_resumption = min(max($useful_checkins), $prev_resumption); } if (isset($time_passed[$prev_resumption])) { // N.B. A check-in occurred; we haven't yet tested if it was useful $resumption_extralog = ", previous check-in=".round($time_passed[$prev_resumption], 2)."s"; } // This is just a simple test to catch restorations of old backup sets where the backup includes a resumption of the backup job if ($time_now - $this->backup_time > 172800 && true == apply_filters('updraftplus_check_obsolete_backup', true, $time_now, $this)) { // We have seen cases where the get_site_option() call that self::get_jobdata() relies on returns nothing, even though the data was there in the database. This appears to be sometimes reproducible for the people who get it, but stops being reproducible if they change their backup times - which suggests that they're having failures at times of extreme load. We can attempt to detect this case, and reschedule, instead of aborting. if (empty($this->backup_time) && empty($this->backup_is_already_complete) && !empty($this->logfile_name) && is_readable($this->logfile_name)) { $first_log_bit = file_get_contents($this->logfile_name, false, null, 0, 250); if (preg_match('/\(0\) Opened log file at time: (.*) on /', $first_log_bit, $matches)) { $first_opened = strtotime($matches[1]); // The value of 1000 seconds here is somewhat arbitrary; but allows for the problem to occur in ~ the first 15 minutes. In practice, the problem is extremely rare; if this does not catch it, we can tweak the algorithm. if (time() - $first_opened < 1000) { $this->log("This backup task (".$this->nonce.") failed to load its job data (possible database server malfunction), but has only recently started: scheduling a fresh resumption in order to try again, and then ending this resumption ($time_now, ".$this->backup_time.") (existing jobdata keys: ".implode(', ', array_keys($this->jobdata)).")"); UpdraftPlus_Job_Scheduler::reschedule(120); die; } } } // If we are doing a local upload then we do not want to abort the backup as it's possible they are uploading a backup that is older than two days if (empty($this->jobdata['local_upload'])) { $this->log("This backup task (" . $this->nonce . ") is either complete or began over 2 days ago: ending ($time_now, " . $this->backup_time . ") (existing jobdata keys: " . implode(', ', array_keys($this->jobdata)) . ")"); die; } } } $this->last_successful_resumption = $last_successful_resumption; $runs_started[$resumption_no] = $time_now; if (!empty($this->backup_time)) $this->jobdata_set('runs_started', $runs_started); // Schedule again, to run in 5 minutes again, in case we again fail // The actual interval can be increased (for future resumptions) by other code, if it detects apparent overlapping $resume_interval = max((int) $this->jobdata_get('resume_interval'), 100); $btime = $this->backup_time; $job_type = $this->jobdata_get('job_type'); do_action('updraftplus_resume_backup_'.$job_type); $updraft_dir = $this->backups_dir_location(); $time_ago = time()-$btime; $this->log("Backup run: resumption=$resumption_no, nonce=$bnonce, file_nonce=".$this->file_nonce." begun at=$btime ({$time_ago}s ago), job type=$job_type".$resumption_extralog); // This works round a bizarre bug seen in one WP install, where delete_transient and wp_clear_scheduled_hook both took no effect, and upon 'resumption' the entire backup would repeat. // Argh. In fact, this has limited effect, as apparently (at least on another install seen), the saving of the updated transient via jobdata_set() also took no effect. Still, it does not hurt. if ($resumption_no >= 1 && 'finished' == $this->jobdata_get('jobstatus')) { $this->log('Terminate: This backup job is already finished (1).'); die; } elseif ('clouduploading' != $this->jobdata_get('jobstatus') && 'backup' == $job_type && !empty($this->backup_is_already_complete)) { $this->jobdata_set('jobstatus', 'finished'); $this->log('Terminate: This backup job is already finished (2).'); die; } if ($resumption_no > 0 && isset($runs_started[$prev_resumption])) { $our_expected_start = $runs_started[$prev_resumption] + $resume_interval; // If the previous run increased the resumption time, then it is timed from the end of the previous run, not the start if (isset($time_passed[$prev_resumption]) && $time_passed[$prev_resumption] > 0) $our_expected_start += $time_passed[$prev_resumption]; $our_expected_start = apply_filters('updraftplus_expected_start', $our_expected_start, $job_type); // More than 12 minutes late? if ($time_now > $our_expected_start + 720) { $this->log('Long time past since expected resumption time: approx expected='.round($our_expected_start, 1).", now=".round($time_now, 1).", diff=".round($time_now-$our_expected_start, 1)); $this->log(__('Your website is visited infrequently and UpdraftPlus is not getting the resources it hoped for; please read this page:', 'updraftplus').' https://updraftplus.com/faqs/why-am-i-getting-warnings-about-my-site-not-having-enough-visitors/', 'warning', 'infrequentvisits'); } } $this->jobdata_set('current_resumption', $resumption_no); $first_run = apply_filters('updraftplus_filerun_firstrun', 0); // April 2022: a similar situation is handled further down, but takes longer to kick in; so extra check has been added (a case where the first runtime under cli was > 4 hours was followed by running under cgi-fci with only 20 minute resumption times; it's better to detect this early) if ($resumption_no == $first_run + 1 && $resume_interval >= 600 && '' != PHP_SAPI) { $last_sapi = $this->jobdata_get('last_sapi'); if ('' != $last_sapi && PHP_SAPI != $last_sapi) { $resume_interval = $this->get_initial_resume_interval(); $this->log(sprintf("Run environment has changed (%s -> %s) - resetting resumption interval to %d", $last_sapi, PHP_SAPI, $resume_interval)); $this->jobdata_set('last_sapi', PHP_SAPI); } // We don't want to be in permanent conflict with the overlap detector } elseif ($resumption_no >= $first_run + 8 && $resumption_no < $first_run + 15 && $resume_interval >= 300) { // $time_passed is set earlier list($max_time, $timings_string, $run_times_known) = UpdraftPlus_Manipulation_Functions::max_time_passed($time_passed, $resumption_no - 1, $first_run); // Do this on resumption 8, or the first time that we have 6 data points. This is only done once to prevent any potential for back-and-forth. if (($first_run + 8 == $resumption_no && $run_times_known >= 6) || (6 == $run_times_known && !empty($time_passed[$prev_resumption]))) { $this->log("Time passed on previous resumptions: $timings_string (known: $run_times_known, max: $max_time)"); // Remember that 30 seconds is used as the 'perhaps something is still running' detection threshold, and that 45 seconds is used as the 'the next resumption is approaching - reschedule!' interval if ($resume_interval > $max_time + 52) { $resume_interval = round($max_time + 52); $this->log("Based on the available data, we are bringing the resumption interval down to: $resume_interval seconds"); $this->jobdata_set('resume_interval', $resume_interval); } } elseif (isset($time_passed[$prev_resumption]) && $time_theres nothing more that needs to be done, otherwise we need to tweak some more jobdata to skip to the upload stage and use the specified clone backup if (isset($options['clone_backup']) && 'current' == $options['clone_backup']) return $jobdata; global $updraftplus_admin; add_filter('updraftplus_get_backup_file_basename_from_time', array($updraftplus_admin, 'upload_local_backup_name'), 10, 3); $backup_history = UpdraftPlus_Backup_History::get_history(); $backup = $backup_history[$options['use_timestamp']]; $jobstatus_key = array_search('jobstatus', $jobdata) + 1; $backup_time_key = array_search('backup_time', $jobdata) + 1; $backup_files_key = array_search('backup_files', $jobdata) + 1; $db_backups = $jobdata[$backup_database_key]; $db_backup_info = $this->update_database_jobdata($db_backups, $backup); $skip_entities = array('more', 'wpcore'); $file_backups = $this->update_files_jobdata($backup, $skip_entities); $jobdata[$jobstatus_key] = 'clouduploading'; $jobdata[$backup_time_key] = $options['use_timestamp']; $jobdata[$backup_files_key] = 'finished'; $jobdata[] = 'backup_files_array'; $jobdata[] = $file_backups; $jobdata[] = 'blog_name'; $jobdata[] = $db_backup_info['blog_name']; $jobdata[$backup_database_key] = $db_backup_info['db_backups']; $jobdata[] = 'local_upload'; $jobdata[] = true; return $jobdata; } /** * This function will update the database backup jobdata and set each entity to finished or encrypted to prevent that entity from being backed up again. This will also return the blog name that the database backup belongs to, just in case it's from another site. * * @param array $db_backups - the database backup jobdata * @param array $backup - the backup history for this backup * * @return array - an array that contains the updated database backup jobdata and the blog name */ public function update_database_jobdata($db_backups, $backup) { $backup_database_info = array( 'blog_name' => '', 'db_backups' => $db_backups ); if (!is_array($db_backups)) return $backup_database_info; /* We need to tweak the database array here by setting each database entity to finished or encrypted if it's an encrypted archive. I also grab the backups blog name here ready to be used later, just in case this backup set is from another site. */ foreach ($db_backups as $key => $db_info) { $status = 'finished'; $db_index = ('wp' == $key) ? '' : $key; if (isset($backup['db'.$db_index])) { $db_backup_name = $backup['db'.$db_index]; if (preg_match('/^backup_([\-0-9]{15})_(.*)_([0-9a-f]{12})-[\-a-z]+([0-9]+)?+(\.(zip|gz|gz\.crypt))?$/i', $db_backup_name, $matches)) { $backup_database_info['blog_name'] = $matches[2]; } if (UpdraftPlus_Encryption::is_file_encrypted($db_backup_name)) $status = 'encrypted'; if (is_array($db_info) && isset($db_info['status'])) { $db_backups[$key]['status'] = $status; } else { $db_backups[$key] = $status; } } else { unset($db_backups[$key]); } } $backup_database_info['db_backups'] = $db_backups; return $backup_database_info; } /** * This function will update the files backup jobdata by constructing the backup entities and their sizes from the backup * * @param array $backup - the backup array * @param array $skip_entities - an array of entities to skip * * @return array - the files backup array */ public function update_files_jobdata($backup, $skip_entities = array()) { $file_backups = array(); $backupable_entities = $this->get_backupable_file_entities(true); // We need to construct the expected files array here, this gets added to the jobdata much later in the backup process but we need this before we start foreach ($backupable_entities as $entity => $path) { if (in_array($entity, $skip_entities)) continue; if (isset($backup[$entity])) $file_backups[$entity] = $backup[$entity]; if (isset($backup[$entity . '-size'])) $file_backups[$entity . '-size'] = $backup[$entity . '-size']; } return $file_backups; } /** * Start a files backup (used by WP cron) */ public function backup_files() { // Note that the "false" for database gets over-ridden automatically if they turn out to have the same schedules $this->boot_backup(true, false); } /** * Start a database backup (used by WP cron) */ public function backup_database() { // Note that nothing will happen if the file backup had the same schedule $this->boot_backup(false, true); } /** * Start a files + database backup (used by users manually in WP cron, and 'Backup Now') * * @param array $options * @return Boolean|Void - as for UpdraftPlus::boot_backup() */ public function backup_all($options) { $skip_cloud = empty($options['nocloud']) ? false : true; return $this->boot_backup(1, 1, false, false, $skip_cloud ? 'none' : false, $options); } /** * Start a files backup * * @param array $options * @return Boolean|Void - as for UpdraftPlus::boot_backup() */ public function backupnow_files($options) { $skip_cloud = empty($options['nocloud']) ? false : true; return $this->boot_backup(1, 0, false, false, $skip_cloud ? 'none' : false, $options); } /** * Start a files backup * * @param array $options * @return Boolean|Void - as for UpdraftPlus::boot_backup() */ public function backupnow_database($options) { $skip_cloud = empty($options['nocloud']) ? false : true; return $this->boot_backup(0, 1, false, false, ($skip_cloud) ? 'none' : false, $options); } /** * This function will try and get a lock for the backup, it will return false if it fails to get a lock. * * @param Boolean $backup_files - boolean to indicate if we want a lock for files * @param Boolean $backup_database - boolean to indicate if we want a lock for the database * * @return boolean - boolean to indicate if we got a lock or not */ public function get_semaphore_lock($backup_files, $backup_database) { $semaphore = ($backup_files ? 'f' : '') . ($backup_database ? 'd' : ''); if (!class_exists('UpdraftPlus_Semaphore')) updraft_try_include_file('includes/class-semaphore.php', 'include_once'); UpdraftPlus_Semaphore::ensure_semaphore_exists($semaphore); // Are we doing an action called by the WP scheduler? If so, we want to check when that last happened; the point being that the dodgy WP scheduler, when overloaded, can call the event multiple times - and sometimes, it evades the semaphore because it calls a second run after the first has finished, or > 3 minutes (our semaphore lock time) later // doing_action() was added in WP 3.9 // wp_cron() can be called from the 'init' action if (function_exists('doing_action') && (doing_action('init') || (defined('DOING_CRON') && DOING_CRON)) && (doing_action('updraft_backup_database') || doing_action('updraft_backup'))) {// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $last_scheduled_action_called_at = get_option("updraft_last_scheduled_$semaphore"); // 11 minutes - so, we're assuming that they haven't custom-modified their schedules to run scheduled backups more often than that. If they have, they need also to use the filter to over-ride this check. $seconds_ago = time() - $last_scheduled_action_called_at; if ($last_scheduled_action_called_at && $seconds_ago < 660 && apply_filters('updraft_check_repeated_scheduled_backups', true)) { $this->log(sprintf('Scheduled backup aborted - another backup of this type was apparently invoked by the WordPress scheduler only %d seconds ago - the WordPress scheduler invoking events multiple times usually indicates a very overloaded server (or other plugins that mis-use the scheduler)', $seconds_ago)); return false; } } update_option("updraft_last_scheduled_$semaphore", time()); $this->semaphore = UpdraftPlus_Semaphore::factory(); $this->semaphore->lock_name = $semaphore; $semaphore_log_message = 'Requesting semaphore lock ('.$semaphore.')'; if (!empty($last_scheduled_action_called_at)) { $semaphore_log_message .= " (apparently via scheduler: last_scheduled_action_called_at=$last_scheduled_action_called_at, seconds_ago=$seconds_ago)"; } else { $semaphore_log_message .= " (apparently not via scheduler)"; } $this->log($semaphore_log_message); if (!$this->semaphore->lock()) { $this->log('Failed to gain semaphore lock ('.$semaphore.') - another backup of this type is apparently already active - aborting (if this is wrong - i.e. if the other backup crashed without removing the lock, then another can be started after 3 minutes)'); return false; } return true; } /** * This function will try and get a lock for the backup job, it will return false if it fails to get a lock. * * @param String $job_nonce - the backup job nonce * @param Integer $resumption_no - the current resumption * * @return boolean - boolean to indicate if we got a lock or not */ public function get_backup_job_semaphore_lock($job_nonce, $resumption_no) { $semaphore = $job_nonce; if (!class_exists('Updraft_Semaphore_3_0')) updraft_try_include_file('includes/class-updraft-semaphore.php', 'include_once'); if (empty($this->backup_semaphore)) { $this->backup_semaphore = new Updraft_Semaphore_3_0($semaphore, 30, array($this)); } if (1 <= $resumption_no) { $this->log('Requesting backup semaphore lock ('.$semaphore.')'); if (!$this->backup_semaphore->lock()) { $this->log('Failed to gain semaphore lock ('.$semaphore.') - another resumption for this job is apparently already active'); return false; } } return true; } /** * This function will check to see if any of the known backups are still running and return true otherwise returns false. * * @return boolean|string - returns false if no backup is running or a error code if there is a backup running */ public function is_backup_running() { $backup_history = UpdraftPlus_Backup_History::get_history(); foreach ($backup_history as $backup) { $nonce = $backup['nonce']; // Check the job is not still running. $jobdata = $this->jobdata_getarray($nonce); if (!empty($jobdata) && 'finished' != $jobdata['jobstatus']) { // Check that there is not a resumption scheduled if (wp_next_scheduled('updraft_backup_resume')) return "job_resumption_scheduled"; $time_passed = $jobdata['run_times']; // No runtime found so return if (!is_array($time_passed)) return "job_scheduled_{$nonce}_no_run_times"; // Runtime has been found so make sure last activity is over an hour $time_passed = end($time_passed); if (strtotime($time_passed) <= time() - (3600)) continue; return "job_scheduled_{$nonce}_run_time_activity"; } } return false; } /** * This function is a filter function which will return the nonce for the incremental backup set we want to add to * * @param String $nonce - the backup nonce we want to filter * * @return string - the backup nonce */ public function incremental_backup_file_nonce($nonce) { if (apply_filters('updraftplus_incremental_addon_installed', false) && !empty($this->file_nonce)) return $this->file_nonce; return $nonce; } /** * Get the initial resumption interval, in seconds * * @return Integer */ private function get_initial_resume_interval() { // Allow the resume interval to be more than 300 if last time we know we went beyond that - but never more than 600 if (defined('UPDRAFTPLUS_INITIAL_RESUME_INTERVAL') && is_numeric(UPDRAFTPLUS_INITIAL_RESUME_INTERVAL)) { $resume_interval = UPDRAFTPLUS_INITIAL_RESUME_INTERVAL; } else { $resume_interval = (int) min(max(300, get_site_transient('updraft_initial_resume_interval')), 600); } // We delete it because we only want to know about behaviour found during the very last backup run (so, if you move servers then old data is not retained) delete_site_transient('updraft_initial_resume_interval'); return $resume_interval; } /** * This procedure initiates a backup run * $backup_files/$backup_database: true/false = yes/no (over-write allowed); 1/0 = yes/no (force) * * @param Boolean|Integer $backup_files * @param Boolean|Integer $backup_database * @param Boolean|Array $restrict_files_to_override * @param Boolean $one_shot * @param Boolean|Array|String $service * @param Array $options * * @return Boolean|Void - false indicates definite failure; true indicates a job was started and ran through as far as possible on this resumption. Note that you should not expect this method to return at all, depending on how long the backup takes, and available PHP run time, etc. In case of failure, currently there may or may not be information logged, and it may or may not be logged at the 'error' level. If more precise feedback is needed, then this can be improved. Void is currently used if no backup was started because none was needed. */ public function boot_backup($backup_files, $backup_database, $restrict_files_to_override = false, $one_shot = false, $service = false, $options = array()) { if (function_exists('ignore_user_abort')) @ignore_user_abort(true);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. if (function_exists('set_time_limit')) @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $is_scheduled_backup = is_bool($backup_files) || is_bool($backup_database); $hosting_company = $this->get_hosting_info(); if (!empty($options['incremental']) && in_array('only_one_incremental_per_day', $this->is_hosting_backup_limit_reached())) { $this->log(__("You have reached the daily limit for the number of incremental backups you can create at this time.", 'updraftplus').' '.__(' Your hosting provider only allows you to take one incremental backup per day.', 'updraftplus').' '.sprintf(__('Please contact your hosting company (%s) if you require further support.', 'updraftplus'), $hosting_company['name'])); return false; } elseif (empty($options['incremental']) && in_array('only_one_backup_per_month', $this->is_hosting_backup_limit_reached())) { $this->log(__('You have reached the monthly limit for the number of backups you can create at this time.', 'updraftplus').' '.__('Your hosting provider only allows you to take one backup per month.', 'updraftplus').' '.sprintf(__('Please contact your hosting company (%s) if you require further support.', 'updraftplus'), $hosting_company['name'])); return false; } if (false === $restrict_files_to_override && isset($options['restrict_files_to_override'])) $restrict_files_to_override = $options['restrict_files_to_override']; // Generate backup information $use_nonce = empty($options['use_nonce']) ? false : $options['use_nonce']; $use_timestamp = empty($options['use_timestamp']) ? false : $options['use_timestamp']; $this->backup_time_nonce($use_nonce, $use_timestamp); // The current_resumption is consulted within logfile_open() $this->current_resumption = 0; $this->logfile_open($this->file_nonce); if (!is_file($this->logfile_name)) { $this->log('Failed to open log file ('.$this->logfile_name.') - you need to check your UpdraftPlus settings (your chosen directory for creating files in is not writable, or you ran out of disk space). Backup aborted.'); $this->log(__('Could not create files in the backup directory. Backup aborted - check your UpdraftPlus settings.', 'updraftplus'), 'error'); return false; } // Some house-cleaning UpdraftPlus_Filesystem_Functions::clean_temporary_files(); // Log some information that may be helpful $this->log("Tasks: Backup files: $backup_files (schedule: ".UpdraftPlus_Options::get_updraft_option('updraft_interval', 'unset').") Backup DB: $backup_database (schedule: ".UpdraftPlus_Options::get_updraft_option('updraft_interval_database', 'unset').")"); // The is_bool() check here is confirming that we're allowed to adjust the parameters if (false === $one_shot && is_bool($backup_database)) { // If the files and database schedules are the same, and if this the file one, then we rope in database too. // On the other hand, if the schedules were the same and this was the database run, then there is nothing to do. $files_schedule = UpdraftPlus_Options::get_updraft_option('updraft_interval'); $db_schedule = UpdraftPlus_Options::get_updraft_option('updraft_interval_database'); $sched_log_extra = ''; if ('manual' != $files_schedule && false !== $files_schedule) { if ($files_schedule == $db_schedule || UpdraftPlus_Options::get_updraft_option('updraft_interval_database', 'xyz') == 'xyz') { $sched_log_extra = 'Combining jobs from identical schedules. '; $backup_database = (true == $backup_files) ? true : false; } elseif ($files_schedule && $db_schedule && $files_schedule != $db_schedule) { // This stored value is the earliest of the two apparently-close jobs $combine_around = empty($this->combine_jobs_around) ? false : $this->combine_jobs_around; if (preg_match('/^(cancel:)?(\d+)$/', $combine_around, $matches)) { $combine_around = $matches[2]; // Re-save the option, since otherwise it will have been reset and not be accessible to the 'other' run UpdraftPlus_Options::update_updraft_option('updraft_combine_jobs_around', 'cancel:'.$this->combine_jobs_around); $margin = (defined('UPDRAFTPLUS_COMBINE_MARGIN') && is_numeric(UPDRAFTPLUS_COMBINE_MARGIN)) ? UPDRAFTPLUS_COMBINE_MARGIN : 600; $time_now = time(); // The margin is doubled, to cope with the lack of predictability in WP's cron system if ($time_now >= $combine_around && $time_now <= $combine_around + 2*$margin) { $sched_log_extra = 'Combining jobs from co-inciding events. '; if ('cancel:' == $matches[1]) { $backup_database = false; $backup_files = false; } else { // We want them both to happen on whichever run is first (since, afterwards, the updraft_combine_jobs_around option will have been removed when the event is rescheduled). $backup_database = true; $backup_files = true; } } } } } $this->log("Processed schedules. {$sched_log_extra}Tasks now: Backup files: $backup_files Backup DB: $backup_database"); } if (false == apply_filters('updraftplus_boot_backup', true, $backup_files, $backup_database, $one_shot)) { $this->log("Backup aborted (via filter)"); return false; } $enabled_storage_objects_and_ids = array(); // All scheduled backups will go through this condition (and some others may too) // This section sets up default options, filters services/instances, and populates $options['remote_storage_instances'] if (!is_string($service) && !is_array($service)) { $all_services = !empty($options['remote_storage_instances']) ? array_keys($options['remote_storage_instances']) : UpdraftPlus_Options::get_updraft_option('updraft_service'); if (is_string($all_services)) $all_services = (array) $all_services; $enabled_storage_objects_and_ids = UpdraftPlus_Storage_Methods_Interface::get_enabled_storage_objects_and_ids($all_services); $legacy_storage_instances = array(); if (!isset($options['remote_storage_instances'])) { $remote_storage_instances = array(); foreach ($enabled_storage_objects_and_ids as $method_id => $method_info) { if ($method_info['object']->supports_feature('multi_options')) { foreach ($method_info['instance_settings'] as $instance_id => $instance_settings) { // We already know the instance is enabled, as we only selected those. We just want to give add-ons an opportunity to filter it. if (!apply_filters('updraft_boot_backup_remote_storage_instance_include', true, $instance_settings, $method_id, $instance_id, $is_scheduled_backup)) continue; if (!isset($remote_storage_instances[$method_id])) $remote_storage_instances[$method_id] = array(); $remote_storage_instances[$method_id][] = $instance_id; } } else { $legacy_storage_instances[] = $method_id; } } $options['remote_storage_instances'] = $remote_storage_instances; } $service = array_merge(array_keys($options['remote_storage_instances']), $legacy_storage_instances); } $service = $this->just_one($service); $service = $this->get_canonical_service_list($service); if (!empty($options['extradata']) && !empty($options['extradata']['services']) && preg_match('#remotesend/(\d+)#', $options['extradata']['services'])) { $service[] = 'remotesend'; } $canonised_storage_objects_and_ids = array_merge(array_flip($service), $enabled_storage_objects_and_ids); $option_cache = array(); foreach ($canonised_storage_objects_and_ids as $method_id => $method_info) { // Explained at updraftplus/-/merge_requests/1302#note_206636 if (!is_array($method_info)) $canonised_storage_objects_and_ids[$method_id] = $method_info = array(); if (!isset($method_info['object']) || !is_object($method_info['object'])) { updraft_try_include_file('methods/'.$method_id.'.php', 'include_once'); $cclass = 'UpdraftPlus_BackupModule_'.$method_id; if (class_exists($cclass)) { $method_info['object'] = $canonised_storage_objects_and_ids[$method_id]['object'] = new $cclass; } else { error_log("UpdraftPlus: backup class does not exist: $cclass"); } } if (isset($method_info['object']) && is_object($method_info['object']) && is_callable(array($method_info['object'], 'get_credentials'))) { $opts = $method_info['object']->get_credentials(); if (is_array($opts)) { foreach ($opts as $opt) $option_cache[$opt] = UpdraftPlus_Options::get_updraft_option($opt); } } } $option_cache = apply_filters('updraftplus_job_option_cache', $option_cache); // If nothing to be done, then just finish if (!$backup_files && !$backup_database) { $ret = $this->backup_finish(false, false); // Don't keep useless log files if (!UpdraftPlus_Options::get_updraft_option('updraft_debug_mode') && !empty($this->logfile_name) && file_exists($this->logfile_name)) { unlink($this->logfile_name); } // Currently backup_finish() appears to have a void return. We don't want to return false, as that indicates failure. But neither was it really a success. Void seems fine for now, given that nothing is currently using it. return $ret; } if (!$this->get_semaphore_lock($backup_files, $backup_database)) { // get_semaphore_lock() already does some of its own logging (though not currently (Nov 2019) at 'error' level) return false; } $resume_interval = $this->get_initial_resume_interval(); $job_file_entities = array(); if ($backup_files) { $possible_backups = $this->get_backupable_file_entities(true); foreach ($possible_backups as $youwhat => $whichdir) { if ((false === $restrict_files_to_override && UpdraftPlus_Options::get_updraft_option("updraft_include_$youwhat", apply_filters("updraftplus_defaultoption_include_$youwhat", true))) || (is_array($restrict_files_to_override) && in_array($youwhat, $restrict_files_to_override))) { // The 0 indicates the zip file index $job_file_entities[$youwhat] = array( 'index' => 0 ); } } } $followups_allowed = (((!$one_shot && defined('DOING_CRON') && DOING_CRON)) || (defined('UPDRAFTPLUS_FOLLOWUPS_ALLOWED') && UPDRAFTPLUS_FOLLOWUPS_ALLOWED)); $split_every = max((int) UpdraftPlus_Options::get_updraft_option('updraft_split_every', 400), UPDRAFTPLUS_SPLIT_MIN); $initial_jobdata = array( 'resume_interval', $resume_interval, 'job_type', 'backup', 'jobstatus', 'begun', 'backup_time', $this->backup_time, 'job_time_ms', $this->job_time_ms, 'service', $service, 'split_every', $split_every, 'maxzipbatch', 26214400, // 25MB 'job_file_entities', $job_file_entities, 'option_cache', $option_cache, 'uploaded_lastreset', 9, 'one_shot', $one_shot, 'followsups_allowed', $followups_allowed, 'last_sapi', PHP_SAPI, ); if ($one_shot) update_site_option('updraft_oneshotnonce', $this->nonce); if ($this->file_nonce && $this->file_nonce != $this->nonce) array_push($initial_jobdata, 'file_nonce', $this->file_nonce); // 'autobackup' == $options['extradata'] might be set from another plugin so keeping here to keep support if (!empty($options['extradata']) && (!empty($options['extradata']['autobackup']) || 'autobackup' === $options['extradata'])) array_push($initial_jobdata, 'is_autobackup', true); // Save what *should* be done, to make it resumable from this point on if ($backup_database) { $dbs = apply_filters('updraft_backup_databases', array('wp' => 'begun')); if (is_array($dbs)) { foreach ($dbs as $key => $db) { if ('wp' != $key && (!is_array($db) || empty($db['dbinfo']) || !is_array($db['dbinfo']) || empty($db['dbinfo']['host']))) unset($dbs[$key]); } } } else { $dbs = 'no'; } array_push($initial_jobdata, 'backup_database', $dbs); array_push($initial_jobdata, 'backup_files', (($backup_files) ? 'begun' : 'no')); if (is_array($options) && !empty($options['label'])) array_push($initial_jobdata, 'label', $options['label']); if (!empty($options['always_keep'])) array_push($initial_jobdata, 'always_keep', true); if (!empty($options['remote_storage_instances'])) array_push($initial_jobdata, 'remote_storage_instances', $options['remote_storage_instances']); try { // Use of jobdata_set_multi saves around 200ms call_user_func_array(array($this, 'jobdata_set_multi'), apply_filters('updraftplus_initial_jobdata', $initial_jobdata, $options, $split_every)); } catch (Exception $e) { $this->log("Exception when calling jobdata_set_multi: ".$e->getMessage().' ('.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')'); return false; } // Everything is set up; now go $this->backup_resume(0, $this->nonce); if ($one_shot) delete_site_option('updraft_oneshotnonce'); return true; } /** * The purpose of this function is to abstract away historical discrepancies in service lists, by returning in a single, logical form (in particular, no 'none' or '' entries, and always an array) * * @param Array|String|Boolean|Null $services - a list of services to canonicalize, or a string indicating a single service. If null is parsed, then the saved settings will be read. * * @return Array - an array of service names. All service names will be non-empty strings, and 'none' will not feature. If there are no services, then the array will be empty. */ public function get_canonical_service_list($services = null) { if (null === $services) $services = UpdraftPlus_Options::get_updraft_option('updraft_service'); $services = (array) $services; foreach ($services as $key => $service) { if ('' === $service || 'none' === $service || false === $service) unset($services[$key]); } return $services; } /** * Perform the tasks necessary when a backup has run through all the available steps. N.B. This does not imply that the were all successful or that the backup is finished. * * @param Boolean $do_cleanup - if (and only if) this is set will resumptions be unscheduled * @param Boolean $allow_email - if this is false, then no email will be sent * @param Boolean $force_abort - set to indicate that the user is manually aborting the backup */ public function backup_finish($do_cleanup, $allow_email, $force_abort = false) { if (!empty($this->semaphore)) $this->semaphore->unlock(); if (!empty($this->backup_semaphore)) $this->backup_semaphore->release(); $this->restore_composer_autoloaders(); $delete_jobdata = false; $clone_job = $this->jobdata_get('clone_job'); if (!empty($clone_job)) { $clone_id = $this->jobdata_get('clone_id'); $secret_token = $this->jobdata_get('secret_token'); } // The valid use of $do_cleanup is to indicate if in fact anything exists to clean up (if no job really started, then there may be nothing) // In fact, leaving the hook to run (if debug is set) is harmless, as the resume job should only do tasks that were left unfinished, which at this stage is none. if (0 == $this->error_count() || $force_abort) { if ($do_cleanup) { $cancel_event = $this->current_resumption + 1; $this->log("There were no errors in the uploads, so the 'resume' event ($cancel_event) is being unscheduled"); // This apparently-worthless setting of metadata before deleting it is for the benefit of a WP install seen where wp_clear_scheduled_hook() and delete_transient() apparently did nothing (probably a faulty cache) $this->jobdata_set('jobstatus', 'finished'); wp_clear_scheduled_hook('updraft_backup_resume', array($cancel_event, $this->nonce)); // This should be unnecessary - even if it does resume, all should be detected as finished; but I saw one very strange case where it restarted, and repeated everything; so, this will help wp_clear_scheduled_hook('updraft_backup_resume', array($cancel_event+1, $this->nonce)); wp_clear_scheduled_hook('updraft_backup_resume', array($cancel_event+2, $this->nonce)); wp_clear_scheduled_hook('updraft_backup_resume', array($cancel_event+3, $this->nonce)); wp_clear_scheduled_hook('updraft_backup_resume', array($cancel_event+4, $this->nonce)); $delete_jobdata = true; } } else { if ($this->newresumption_scheduled) { if ($this->current_resumption + 1 != $this->jobdata_get('fail_on_resume')) { $this->log("There were errors in the uploads, so the 'resume' event is remaining scheduled"); $this->jobdata_set('jobstatus', 'resumingforerrors'); } } // If there were no errors before moving to the upload stage, on the first run, then bring the resumption back very close. Since this is only attempted on the first run, it is really only an efficiency thing for a quicker finish if there was an unexpected networking event. We don't want to do it straight away every time, as it may be that the cloud service is down - and might be up in 5 minutes time. This was added after seeing a case where resumption 0 got to run for 10 hours... and the resumption 7 that should have picked up the uploading of 1 archive that failed never occurred. if (isset($this->error_count_before_cloud_backup) && 0 === $this->error_count_before_cloud_backup) { if (0 == $this->current_resumption) { UpdraftPlus_Job_Scheduler::reschedule(60); } else { // Added 27/Feb/2016 - though the cloud service seems to be down, we still don't want to wait too long $resume_interval = $this->jobdata_get('resume_interval'); // 15 minutes + 2 for each resumption (a modest back-off) $max_interval = 900 + $this->current_resumption * 120; if ($resume_interval > $max_interval) { UpdraftPlus_Job_Scheduler::reschedule($max_interval); } } } } // Send the results email if appropriate, which means: // - The caller allowed it (which is not the case in an 'empty' run) // - And: An email address was set (which must be so in email mode) // And one of: // - Debug mode // - There were no errors (which means we completed and so this is the final run - time for the final report) // - It was the tenth resumption; everything failed $send_an_email = false; // Save the jobdata's state for the reporting - because it might get changed (e.g. incremental backup is scheduled) $jobdata_as_was = $this->jobdata; // Make sure that the final status is shown if ($force_abort) { $send_an_email = true; $final_message = __('The backup was aborted by the user', 'updraftplus'); if (!empty($clone_job)) $this->get_updraftplus_clone()->clone_failed_delete(array('clone_id' => $clone_id, 'secret_token' => $secret_token, 'reason' => 'The backup was aborted by the user')); } elseif (0 == $this->error_count()) { $send_an_email = true; $service = $this->jobdata_get('service'); $remote_sent = (!empty($service) && ((is_array($service) && in_array('remotesend', $service)) || 'remotesend' === $service)) ? true : false; if (0 == $this->error_count('warning')) { $final_message = __('The backup apparently succeeded and is now complete', 'updraftplus'); // Ensure it is logged in English. Not hugely important; but helps with a tiny number of really broken setups in which the options cacheing is broken if ('The backup apparently succeeded and is now complete' != $final_message) { $this->log('The backup apparently succeeded and is now complete'); } } else { $final_message = __('The backup apparently succeeded (with warnings) and is now complete', 'updraftplus'); if ('The backup apparently succeeded (with warnings) and is now complete' != $final_message) { $this->log('The backup apparently succeeded (with warnings) and is now complete'); } } if ($remote_sent && !$force_abort) { $final_message .= empty($clone_job) ? '. '.__('To complete your migration/clone, you should now log in to the remote site and restore the backup set.', 'updraftplus') : '. '.__('Your clone will now deploy this data to re-create your site.', 'updraftplus'); } if ($do_cleanup) $delete_jobdata = apply_filters('updraftplus_backup_complete', $delete_jobdata); } elseif (false == $this->newresumption_scheduled || $this->current_resumption + 1 == $this->jobdata_get('fail_on_resume')) { if ($this->current_resumption + 1 == $this->jobdata_get('fail_on_resume')) { $this->log("The resumption is being cancelled, as it was only scheduled to enable error reporting, which can be performed now"); wp_clear_scheduled_hook('updraft_backup_resume', array($this->current_resumption + 1, $this->nonce)); } $send_an_email = true; $final_message = __('The backup attempt has finished, apparently unsuccessfully', 'updraftplus'); if (!empty($clone_job)) $this->get_updraftplus_clone()->clone_failed_delete(array('clone_id' => $clone_id, 'secret_token' => $secret_token, 'reason' => 'The backup attempt has finished, apparently unsuccessfully')); } else { // There are errors, but a resumption will be attempted $final_message = __('The backup has not finished; a resumption is scheduled', 'updraftplus'); } if (0 == $this->error_count()) { // delete manifest files $updraft_dir = $this->backups_dir_location(); $backup_files_array = $this->jobdata_get('backup_files_array', array()); if (!empty($backup_files_array)) { foreach ($backup_files_array as $entity => $files) { if ('-size' === substr($entity, -5, 5) || !is_array($files)) continue; foreach ($files as $file) { $fullpath = $updraft_dir.'/'.$file; if (file_exists($fullpath.'.list.tmp')) { $this->log("Deleting zip manifest ({$file}.list.tmp)"); unlink($fullpath.'.list.tmp'); } } } } } // Now over-ride the decision to send an email, if needed if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) { $send_an_email = true; $this->log("An email has been scheduled for this job, because we are in debug mode"); } $email = UpdraftPlus_Options::get_updraft_option('updraft_email'); // If there's no email address, or the set was empty, that is the final over-ride: don't send if (!$allow_email) { $send_an_email = false; $this->log("No email will be sent - this backup set was empty."); } elseif (empty($email)) { $send_an_email = false; $this->log("No email will/can be sent - the user has not configured an email address."); } if ($force_abort) $jobdata_as_was['aborted'] = true; if ($send_an_email) $this->send_results_email($final_message, $jobdata_as_was); // Make sure this is the final message logged (so it remains on the dashboard) $this->log($final_message); @fclose($this->logfile_handle);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $this->logfile_handle = null; // This is left until last for the benefit of the front-end UI, which then gets maximum chance to display the 'finished' status if ($delete_jobdata) delete_site_option('updraft_jobdata_'.$this->nonce); } /** * The jobdata is passed in instead of fetched, because the live jobdata may now differ from that which should be reported on (e.g. an incremental run was subsequently scheduled) * * @param String $final_message The final message to be sent * @param Array $jobdata Full job data */ private function send_results_email($final_message, $jobdata) { $debug_mode = UpdraftPlus_Options::get_updraft_option('updraft_debug_mode'); $sendmail_to = $this->just_one_email(UpdraftPlus_Options::get_updraft_option('updraft_email')); if (is_string($sendmail_to)) $sendmail_to = array($sendmail_to); $backup_files = $jobdata['backup_files']; $backup_db = $jobdata['backup_database']; if (is_array($backup_db)) $backup_db = $backup_db['wp']; if (is_array($backup_db)) $backup_db = $backup_db['status']; $backup_type = ('backup' == $jobdata['job_type']) ? __('Full backup', 'updraftplus') : __('Incremental', 'updraftplus'); $was_aborted = !empty($jobdata['aborted']); if ($was_aborted) { $backup_contains = __('The backup was aborted by the user', 'updraftplus'); } elseif ('finished' == $backup_files && ('finished' == $backup_db || 'encrypted' == $backup_db)) { $backup_contains = __('Files and database', 'updraftplus')." ($backup_type)"; } elseif ('finished' == $backup_files) { $backup_contains = ('begun' == $backup_db) ? __("Files (database backup has not completed)", 'updraftplus') : __('Files only (database was not part of this particular schedule)', 'updraftplus'); $backup_contains .= " ($backup_type)"; } elseif ('finished' == $backup_db || 'encrypted' == $backup_db) { $backup_contains = ('begun' == $backup_files) ? __("Database (files backup has not completed)", 'updraftplus') : __('Database only (files were not part of this particular schedule)', 'updraftplus'); } elseif ('begun' == $backup_db || 'begun' == $backup_files) { $backup_contains = __('Incomplete', 'updraftplus'); } else { $this->log('Unknown/unexpected status: '.serialize($backup_files).'/'.serialize($backup_db)); $backup_contains = __("Unknown/unexpected error - please raise a support request", 'updraftplus'); } $append_log = ''; $attachments = array(); $error_count = 0; if ($this->error_count() > 0) { $append_log .= __('Errors encountered:', 'updraftplus')."\r\n"; $attachments[0] = $this->logfile_name; foreach ($this->errors as $err) { if (is_wp_error($err)) { foreach ($err->get_error_messages() as $msg) { $append_log .= "* ".rtrim($msg)."\r\n"; } } elseif (is_array($err) && 'error' == $err['level']) { $append_log .= "* ".rtrim($err['message'])."\r\n"; } elseif (is_string($err)) { $append_log .= "* ".rtrim($err)."\r\n"; } $error_count++; } $append_log .="\r\n"; } $warnings = (isset($jobdata['warnings'])) ? $jobdata['warnings'] : array(); if (is_array($warnings) && count($warnings) >0) { $append_log .= __('Warnings encountered:', 'updraftplus')."\r\n"; $attachments[0] = $this->logfile_name; foreach ($warnings as $err) { $append_log .= "* ".rtrim($err)."\r\n"; } $append_log .="\r\n"; } if ($debug_mode && '' != $this->logfile_name && !in_array($this->logfile_name, $attachments)) { $append_log .= "\r\n".__('The log file has been attached to this email.', 'updraftplus'); $attachments[0] = $this->logfile_name; } // We have to use the action in order to set the MIME type on the attachment - by default, WordPress just puts application/octet-stream $subject = apply_filters('updraft_report_subject', sprintf(__('Backed up: %s', 'updraftplus'), wp_specialchars_decode(get_option('blogname'), ENT_QUOTES)).' (UpdraftPlus '.$this->version.') '.get_date_from_gmt(gmdate('Y-m-d H:i:s', time()), 'Y-m-d H:i'), $error_count, count($warnings)); // The class_exists() check here is a micro-optimization to prevent a possible HTTP call whose results may be disregarded by the filter $feed = ''; if (!class_exists('UpdraftPlus_Addon_Reporting') && !defined('UPDRAFTPLUS_NOADS_B') && !defined('UPDRAFTPLUS_NONEWSFEED')) { $this->log('Fetching RSS news feed'); $rss = $this->get_updraftplus_rssfeed(); $this->log('Fetched RSS news feed; result is a: '.get_class($rss)); if (is_a($rss, 'SimplePie')) { $feed .= __('Email reports created by UpdraftPlus (free edition) bring you the latest UpdraftPlus.com news', 'updraftplus')." - ".sprintf(__('read more at %s', 'updraftplus'), 'https://updraftplus.com/news/')."\r\n\r\n"; foreach ($rss->get_items(0, 6) as $item) { $feed .= '* '; $feed .= $item->get_title(); $feed .= " (".$item->get_date('j F Y').")"; // $feed .= ' - '.$item->get_permalink(); $feed .= "\r\n"; } } $feed .= "\r\n\r\n"; } $extra_messages = apply_filters('updraftplus_report_extramessages', array()); $extra_msg = ''; if (is_array($extra_messages)) { foreach ($extra_messages as $msg) { $extra_msg .= ''.$msg['key'].': '.$msg['val']."\r\n"; } } foreach ($this->remotestorage_extrainfo as $service => $message) { if (!empty($this->backup_methods[$service])) $extra_msg .= $this->backup_methods[$service].': '.$message['plain']."\r\n"; } // Make it available to the filter $jobdata['remotestorage_extrainfo'] = $this->remotestorage_extrainfo; if (!class_exists('UpdraftPlus_Notices')) updraft_try_include_file('includes/updraftplus-notices.php', 'include_once'); global $updraftplus_notices; $ws_advert = $updraftplus_notices->do_notice(false, 'report-plain', true); $body = apply_filters('updraft_report_body', __('Backup of:', 'updraftplus').' '.site_url()."\r\n". "UpdraftPlus ".__('WordPress backup is complete', 'updraftplus').".\r\n". __('Backup contains:', 'updraftplus')." $backup_contains\r\n". __('Latest status:', 'updraftplus').' '.$final_message."\r\n". $extra_msg. "\r\n". $feed. $ws_advert."\r\n". $append_log, $final_message, $backup_contains, $this->errors, $warnings, $jobdata); $this->attachments = apply_filters('updraft_report_attachments', $attachments); $attach_size = 0; $unlink_files = array(); foreach ($this->attachments as $ind => $attach) { if ($attach == $this->logfile_name && filesize($attach) > 6*1048576) { $this->log("Log file is large (".round(filesize($attach)/1024, 1)." KB): will compress before e-mailing"); if (!$handle = fopen($attach, "r")) { $this->log("Error: Failed to open log file for reading: ".$attach); } else { if (!$whandle = gzopen($attach.'.gz', 'w')) { $this->log("Error: Failed to open log file for reading: ".$attach.".gz"); } else { while (false !== ($line = @stream_get_line($handle, 131072, "\n"))) {// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @gzwrite($whandle, $line."\n");// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. } fclose($handle); gzclose($whandle); $this->attachments[$ind] = $attach.'.gz'; $unlink_files[] = $attach.'.gz'; } } } $attach_size += filesize($this->attachments[$ind]); } foreach ($sendmail_to as $ind => $mailto) { if (false === apply_filters('updraft_report_sendto', true, $mailto, $error_count, count($warnings), $ind)) continue; foreach (explode(',', $mailto) as $sendmail_addr) { // if the address is a URL then instead of emailing it, POST it to slack if (preg_match('/^https?:\/\//i', $sendmail_addr)) { $this->log("Sending to (URL) ('$backup_contains') report (attachments: ".count($attachments).", size: ".round($attach_size/1024, 1)." KB) to: ".substr($sendmail_addr, 0, 5)."..."); $this->post_results_slack($subject, $body, trim($sendmail_addr), $this->file_nonce); } else { $this->log("Sending email ('$backup_contains') report (attachments: ".count($attachments).", size: ".round($attach_size/1024, 1)." KB) to: ".substr($sendmail_addr, 0, 5)."..."); $headers = array(); try { $headers[] = "X-UpdraftPlus-Backup-ID: ".$this->nonce; $from_email = apply_filters('updraftplus_email_from_header', $this->get_email_from_header()); $from_name = apply_filters('updraftplus_email_from_name_header', $this->get_email_from_name_header()); $use_wp_from_name_filter = '' === $from_email; // Notice that we don't use the 'wp_mail_from' filter, but only the 'From:' header to set sender name and sender email address, the reason behind it is that some SMTP plugins override the "wp_mail()" function and they do anything they want inside their own "wp_mail()" function, including not to call the php_mailer filter nor the wp_mail_from and wp_mail_from_name filters, but since the function signature remain the same as the WP one, so they may evaluate and do something with the header parameter if (!$use_wp_from_name_filter) { $headers[] = sprintf('From: %s <%s>', $from_name, $from_email); } else { add_filter('wp_mail_from_name', array($this, 'get_email_from_name_header'), 9); } add_action('wp_mail_failed', array($this, 'log_email_delivery_failure')); wp_mail(trim($sendmail_addr), $subject, $body, $headers, is_array($this->attachments) ? $this->attachments : array()); remove_action('wp_mail_failed', array($this, 'log_email_delivery_failure')); if ($use_wp_from_name_filter) remove_filter('wp_mail_from_name', array($this, 'get_email_from_name_header'), 9); } catch (Exception $e) { $this->log("Exception occurred when sending mail (".get_class($e)."): ".$e->getMessage()); } } } } foreach ($unlink_files as $file) @unlink($file);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. do_action('updraft_report_finished'); } /** * Log the email delivery failure to the log file when a PHPMailer exception is caught * * @param WP_Error $error A WP_Error object with the PHPMailer\PHPMailer\Exception message, and an array containing the mail recipient, subject, message, headers, and attachments. */ public function log_email_delivery_failure($error) { $this->log("An error occurred when sending a backup report email and/or backup file(s) via email (".$error->get_error_code()."): ".$error->get_error_message()); } /** * Check whether the provided admin_email is under the same domain with the site, and use it as a sender email to increase the chance of an email being sent successfully (if appropriate) * * @return String The admin email address if it's found to be in same domain, an empty string otherwise */ public function get_email_from_header() { $sitename = $this->get_site_name(); $admin_email = get_bloginfo('admin_email'); $admin_email_domain = preg_replace('/^[^@]+@(.+)$/', "$1", $admin_email); if (trim(strtolower($sitename)) === trim(strtolower($admin_email_domain))) { // assuming (non validating) that the email account of the admin email does exist, and the admin email is under the same domain as with the web domain and the domain exists and live as well return $admin_email; } return ''; } /** * Build sender name and use something authentic that represents the identity of the plugin and web domain * * @return String The sender name */ public function get_email_from_name_header() { return sprintf(__('UpdraftPlus on %s', 'updraftplus'), $this->get_site_name()); } /** * Post backup report to slack instead of emailing if the address is a URL * * @param string $header report title * @param string $report_body report content * @param string $webhook_url url to post report * @param string $nval backup log file nonce * @return Void */ public function post_results_slack($header, $report_body, $webhook_url, $nval) { $findcontent = __('The log file has been attached to this email.', 'updraftplus'); $report_body = str_replace($findcontent, '', $report_body); $url = admin_url(UpdraftPlus_Options::admin_page()."?page=updraftplus&action=downloadlog&updraftplus_backup_nonce=$nval"); $response = wp_remote_post($webhook_url, array( 'method' => 'POST', 'headers' => array(), 'body' => json_encode(array( 'blocks' => array( array( 'type' => 'header', 'text' => array( 'type' => 'plain_text', 'text' => $header, 'emoji' => true ), ), array( 'type' => 'section', 'text' => array( 'type' => 'mrkdwn', 'text' => $report_body ), ), array( 'type' => 'section', 'text' => array( 'type' => 'mrkdwn', 'text' => __('You can view the log by pressing the \'View log\' button.', 'updraftplus') ), 'accessory' => array( 'type' => 'button', 'text' => array( 'type' => 'plain_text', 'text' => __('View log', 'updraftplus'), 'emoji' => true ), 'value' => 'view_log_123', 'url' => $url, 'action_id' => 'button-action' ) ), ) )) )); if (!is_wp_error($response)) { $response_code = wp_remote_retrieve_response_code($response); if ($response_code < 200 || $response_code >= 300) { $this->log('HTTP POST error : '.$response_code.' - '.wp_remote_retrieve_response_message($response)); } } else { $this->log('HTTP POST error : '.$response->get_error_code().' - '.$response->get_error_message()); } } /** * This function returns 'true' if mod_rewrite could be detected as unavailable; a 'false' result may mean it just couldn't find out the answer * * @param boolean $check_if_in_use_first * @return boolean */ public function mod_rewrite_unavailable($check_if_in_use_first = true) { if (function_exists('apache_get_modules')) { global $wp_rewrite; $mods = apache_get_modules(); if ((!$check_if_in_use_first || $wp_rewrite->using_mod_rewrite_permalinks()) && ((in_array('core', $mods) || in_array('http_core', $mods)) && !in_array('mod_rewrite', $mods))) { return true; } } return false; } /** * Count the number of alerts that have occurred at the specified level * * @param String $level - the level to count at * * @return Integer */ public function error_count($level = 'error') { $count = 0; foreach ($this->errors as $err) { if (('error' == $level && (is_string($err) || is_wp_error($err))) || (is_array($err) && $level == $err['level'])) { $count++; } } return $count; } public function list_errors() { echo ''; } /** * Save last successful backup information * * @param Array $backup_array An array of backup information */ private function save_last_backup($backup_array) { $success = ($this->error_count() == 0) ? 1 : 0; $last_backup = UpdraftPlus_Options::get_updraft_option('updraft_last_backup', array()); if (empty($last_backup)) $last_backup = array(); if ('incremental' === $this->jobdata_get('job_type')) { $last_backup['incremental_backup_time'] = $this->backup_time; // the incremental_backup_time index is used only for storing time of the incremental job type } else { $last_backup['nonincremental_backup_time'] = $this->backup_time; // otherwise the nonincremental_backup_time index is for the backup job type } $last_backup = wp_parse_args(array( 'backup_time' => $this->backup_time, // the backup_time index is used for storing either time of backup or incremental job type 'backup_array' => $backup_array, 'success' => $success, 'errors' => $this->errors, 'backup_nonce' => $this->nonce ), $last_backup); $last_backup = apply_filters('updraftplus_save_last_backup', $last_backup); UpdraftPlus_Options::update_updraft_option('updraft_last_backup', $last_backup, false); } /** * $handle must be either false or a WPDB class (or extension thereof). Other options are not yet fully supported. * * @param Resource|Boolean|Object $handle * @param Boolean $log_it - whether to log information about the check * @param Boolean $reschedule - whether to schedule a resumption if checking fails * @param Boolean $allow_bail - whether to allow the connection to fail or throw an error * @return Boolean|Integer - whether the check succeeded, or -1 for an unknown result */ public function check_db_connection($handle = false, $log_it = false, $reschedule = false, $allow_bail = false) { $type = false; if (false === $handle || is_a($handle, 'wpdb')) { $type = 'wpdb'; } elseif (is_resource($handle)) { // Expected: string(10) "mysql link" $type = get_resource_type($handle); } elseif (is_object($handle) && is_a($handle, 'mysqli')) { $type = 'mysqli'; } if (false === $type) return -1; $db_connected = -1; if ('mysql link' == $type || 'mysqli' == $type) { if ('mysql link' == $type && @mysql_ping($handle)) return true;// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved -- Needed to add this as the old ignores no longer work if ('mysqli' == $type && @mysqli_ping($handle)) return true;// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. for ($tries = 1; $tries <= 5; $tries++) { // to do, if ever needed // if ($this->db_connect(false )) return true; // sleep(1); } } elseif ('wpdb' == $type) { if (false === $handle || (is_object($handle) && 'wpdb' == get_class($handle))) { global $wpdb; $handle = $wpdb; } if (method_exists($handle, 'check_connection') && (!defined('UPDRAFTPLUS_SUPPRESS_CONNECTION_CHECKS') || !UPDRAFTPLUS_SUPPRESS_CONNECTION_CHECKS)) { if (!$handle->check_connection($allow_bail)) { if ($log_it) $this->log("The database went away, and could not be reconnected to"); // Almost certainly a no-op if ($reschedule) UpdraftPlus_Job_Scheduler::reschedule(60); $db_connected = false; } else { $db_connected = true; } } } return $db_connected; } /** * This should be called whenever a file is successfully uploaded * * @param String $file - full filepath * @param Boolean $force - mark as successfully uploaded even if not on the last service * @return Void */ public function uploaded_file($file, $force = false) { global $updraftplus_backup; $db_connected = $this->check_db_connection(false, true, true); $service = empty($updraftplus_backup->current_service) ? '' : $updraftplus_backup->current_service; $instance_id = empty($updraftplus_backup->current_instance) ? '' : $updraftplus_backup->current_instance; $shash = $service.(('' == $service) ? '' : '-').$instance_id.(('' == $instance_id) ? '' : '-').md5($file); if ($force || !empty($updraftplus_backup->last_storage_instance)) { $this->log("Recording as successfully uploaded: $file"); $new_jobdata = $this->get_uploaded_jobdata_items($file, $service, $instance_id); } else { $new_jobdata = array('uploaded_'.$shash => 'yes'); $this->log("Recording as successfully uploaded: $file (".$updraftplus_backup->current_service.", more services to follow)"); } $upload_status = $this->jobdata_get('uploading_substatus'); if (is_array($upload_status) && isset($upload_status['i'])) { $upload_status['i']++; $upload_status['p'] = 0; $new_jobdata['uploading_substatus'] = $upload_status; } $this->jobdata_set_multi($new_jobdata); // Really, we could do this immediately when we realise the DB has gone away. This is just for the probably-impossible case that a DB write really can still succeed. But, we must abort before calling delete_local(), as the removal of the local file can cause it to be recreated if the DB is out of sync with the fact that it really is already uploaded if (false === $db_connected) { UpdraftPlus_Job_Scheduler::record_still_alive(); die; } // Delete local files immediately if the option is set // Where we are only backing up locally, only the "prune" function should do deleting $service = $this->jobdata_get('service'); if (!empty($updraftplus_backup->last_storage_instance) && ('' !== $service && ((is_array($service) && count($service)>0 && (count($service) > 1 || (array('') !== $service && array('none') !== $service))) || (is_string($service) && 'none' !== $service)))) { $this->delete_local($file); } } /** * Gets the jobdata items to be added to mark a file as uploaded * * @param String $file - the file (basename) * @param String $service - service identifier * @param String $instance_id - instance identifier * * @return Array - jobdata items */ public function get_uploaded_jobdata_items($file, $service = '', $instance_id = '') { $hash = md5($file); $shash = $service.(('' == $service) ? '' : '-').$instance_id.(('' == $instance_id) ? '' : '-').md5($file); return array( 'uploaded_lastreset' => $this->current_resumption, 'uploaded_'.$hash => 'yes', 'uploaded_'.$shash =>'yes' ); } /** * Return whether a particular file has been uploaded to a particular remote service * * @param String $file - the filename (basename) * @param String $service - the service identifier; or none, to indicate all services * @param String $instance_id - the instance identifier * * @return Boolean - the result */ public function is_uploaded($file, $service = '', $instance_id = '') { $hash = $service.(('' == $service) ? '' : '-').$instance_id.(('' == $instance_id) ? '' : '-').md5($file); return ('yes' === $this->jobdata_get("uploaded_$hash")) ? true : false; } /** * This function will mark the passed in service and instance id upload as complete * * @param String $service - the service identifier * @param String $instance_id - the instance identifier * * @return void */ public function mark_upload_complete($service, $instance_id = '') { $upload_completed = $this->jobdata_get('upload_completed', array()); if (empty($instance_id)) { $upload_completed[$service] = 1; } else { if (!is_array($upload_completed[$service])) $upload_completed[$service] = array(); $upload_completed[$service][$instance_id] = 1; } $this->jobdata_set('upload_completed', $upload_completed); } /** * This function will check all the remote storage options for this job and ensure that each has completed the upload, if they have mark them as done if they have not completed then call upload_completed() for that service if it exists, otherwise mark as complete. * * @return boolean */ private function check_upload_completed() { $job_services = $this->jobdata_get('service'); $services = $this->get_canonical_service_list($job_services); $sent_to_cloud = empty($services) ? false : true; if (!$sent_to_cloud) return; $storage_objects_and_ids = UpdraftPlus_Storage_Methods_Interface::get_storage_objects_and_ids($services); foreach ($services as $service) { if ('email' == $service || 'none' == $service || !$service) continue; $remote_obj = $storage_objects_and_ids[$service]['object']; $upload_completed = $this->jobdata_get('upload_completed', array()); if (isset($upload_completed[$service]) && !is_array($upload_completed[$service])) continue; if (!empty($remote_obj) && !$remote_obj->supports_feature('multi_options')) { if (is_callable(array($remote_obj, 'upload_completed'))) { $result = $remote_obj->upload_completed(); if ($result) $this->mark_upload_complete($service); } else { $this->mark_upload_complete($service); } } elseif (!empty($storage_objects_and_ids[$service]['instance_settings'])) { foreach ($storage_objects_and_ids[$service]['instance_settings'] as $instance_id => $options) { if (isset($upload_completed[$service][$instance_id])) continue; $remote_obj->set_options($options, true, $instance_id); if (is_callable(array($remote_obj, 'upload_completed'))) { $remote_obj->upload_completed(); } else { $this->mark_upload_complete($service, $instance_id); } } } } } /** * This function will check if the passed-in file is this job's responsibility to upload. Potentially files can belong to a different job, when running an incremental backup run * * @param String $file - the name of the file * @param String $type - the file entity type (db, plugins, themes etc) * * @return boolean - whether this is a file this job should upload (at some point) */ private function is_ours_to_upload($file, $type) { if ('db' == $type) return false; $previous_backup_files_array = $this->jobdata_get('previous_backup_files_array', array()); if (isset($previous_backup_files_array[$type]) && in_array($file, $previous_backup_files_array[$type])) return false; return true; } private function delete_local($file) { $log = "Deleting local file: $file: "; if (UpdraftPlus_Options::get_updraft_option('updraft_delete_local', 1)) { $fullpath = $this->backups_dir_location().'/'.$file; // check to make sure it exists before removing if (realpath($fullpath)) { $deleted = unlink($fullpath); $this->log($log.(($deleted) ? 'OK' : 'failed')); return $deleted; } } else { $this->log($log."skipped: user has unchecked updraft_delete_local option"); } return true; } /** * For detecting another run, and aborting if one was found * * @param String $file - full file path of the file to check */ public function check_recent_modification($file) { if (file_exists($file)) { $time_mod = (int) @filemtime($file);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. $time_now = time(); if ($time_mod > 100 && ($time_now - $time_mod) < 30) { UpdraftPlus_Job_Scheduler::terminate_due_to_activity($file, $time_now, $time_mod); } } } public function get_exclude($whichone) { if ('uploads' == $whichone) { $exclude = explode(',', UpdraftPlus_Options::get_updraft_option('updraft_include_uploads_exclude', UPDRAFT_DEFAULT_UPLOADS_EXCLUDE)); } elseif ('others' == $whichone) { $exclude = explode(',', UpdraftPlus_Options::get_updraft_option('updraft_include_others_exclude', UPDRAFT_DEFAULT_OTHERS_EXCLUDE)); } else { $exclude = apply_filters('updraftplus_include_'.$whichone.'_exclude', array()); } return (empty($exclude) || !is_array($exclude)) ? array() : $exclude; } public function wp_upload_dir() { if (is_multisite()) { global $current_site; switch_to_blog($current_site->blog_id); } $wp_upload_dir = wp_upload_dir(); if (is_multisite()) restore_current_blog(); return $wp_upload_dir; } public function backup_uploads_dirlist($log_it = false) { // Create an array of directories to be skipped // Make the values into the keys $exclude = UpdraftPlus_Options::get_updraft_option('updraft_include_uploads_exclude', UPDRAFT_DEFAULT_UPLOADS_EXCLUDE); if ($log_it) $this->log("Exclusion option setting (uploads): ".$exclude); $skip = array_flip(preg_split("/,/", $exclude)); $wp_upload_dir = $this->wp_upload_dir(); $uploads_dir = $wp_upload_dir['basedir']; return $this->compile_folder_list_for_backup($uploads_dir, array(), $skip); } public function backup_others_dirlist($log_it = false) { // Create an array of directories to be skipped // Make the values into the keys $exclude = UpdraftPlus_Options::get_updraft_option('updraft_include_others_exclude', UPDRAFT_DEFAULT_OTHERS_EXCLUDE); if ($log_it) $this->log("Exclusion option setting (others): ".$exclude); $skip = array_flip(preg_split("/,/", $exclude)); $file_entities = $this->get_backupable_file_entities(false); // Keys = directory names to avoid; values = the label for that directory (used only in log files) // $avoid_these_dirs = array_flip($file_entities); $avoid_these_dirs = array(); foreach ($file_entities as $type => $dirs) { if (is_string($dirs)) { $avoid_these_dirs[$dirs] = $type; } elseif (is_array($dirs)) { foreach ($dirs as $dir) { $avoid_these_dirs[$dir] = $type; } } } return $this->compile_folder_list_for_backup(WP_CONTENT_DIR, $avoid_these_dirs, $skip); } /** * avoid_these_dirs and skip_these_dirs ultimately do the same thing; but avoid_these_dirs takes full paths whereas skip_these_dirs takes basenames; and they are logged differently (dirs in avoid_these_dirs are potentially dangerous to include; skip is just a user-level preference). They are allowed to overlap. * * @param String $backup_from_inside_dir * @param Array $avoid_these_dirs * @param Array $skip_these_dirs * * @return Array */ public function compile_folder_list_for_backup($backup_from_inside_dir, $avoid_these_dirs, $skip_these_dirs) { // Entries in $skip_these_dirs are allowed to end in *, which means "and anything else as a suffix". It's not a full shell glob, but it covers what is needed to-date. $dirlist = array(); $added = 0; $log_skipped = 0; $log_skipped_last = ''; $this->log('Looking for candidates to backup in: '.$backup_from_inside_dir); $updraft_dir = $this->backups_dir_location(); if (is_file($backup_from_inside_dir)) { array_push($dirlist, $backup_from_inside_dir); $added++; $this->log("finding files: $backup_from_inside_dir: adding to list ($added)"); } elseif ($handle = opendir($backup_from_inside_dir)) { while (false !== ($entry = readdir($handle))) { if ('.' == $entry || '..' == $entry) continue; // $candidate: full path; $entry = one-level $candidate = $backup_from_inside_dir.'/'.$entry; if (isset($avoid_these_dirs[$candidate])) { $this->log("finding files: $entry: skipping: this is the ".$avoid_these_dirs[$candidate]." directory"); } elseif ($candidate == $updraft_dir) { $this->log("finding files: $entry: skipping: this is the updraft directory"); } elseif (isset($skip_these_dirs[$entry])) { $this->log("finding files: $entry: skipping: excluded by options"); } else { $add_to_list = true; // Now deal with entries in $skip_these_dirs ending in * or starting with * foreach ($skip_these_dirs as $skip => $sind) { if ('*' == substr($skip, -1, 1) && '*' == substr($skip, 0, 1) && strlen($skip) > 2) { if (strpos($entry, substr($skip, 1, strlen($skip)-2)) !== false) { $this->log("finding files: $entry: skipping: excluded by options (glob)"); $add_to_list = false; } } elseif ('*' == substr($skip, -1, 1) && strlen($skip) > 1) { if (substr($entry, 0, strlen($skip)-1) == substr($skip, 0, strlen($skip)-1)) { $this->log("finding files: $entry: skipping: excluded by options (glob)"); $add_to_list = false; } } elseif ('*' == substr($skip, 0, 1) && strlen($skip) > 1) { if (strlen($entry) >= strlen($skip)-1 && substr($entry, (strlen($skip)-1)*-1) == substr($skip, 1)) { $this->log("finding files: $entry: skipping: excluded by options (glob)"); $add_to_list = false; } } } if ($add_to_list) { array_push($dirlist, $candidate); $added++; if ($added > 500) { if ($log_skipped >= 500) { $this->log("finding files: $entry: adding to list ($added, $log_skipped log lines skipped)"); $log_skipped = 0; $log_skipped_last = ''; } else { $log_skipped++; $log_skipped_last = $entry; } } else { $skip_dblog = (($added > 50 && 0 != $added % 100) || ($added > 2000 && 0 != $added % 500)); $this->log("finding files: $entry: adding to list ($added)", 'notice', false, $skip_dblog); } } } } @closedir($handle);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. if ($log_skipped > 0) { $this->log("finding files: $log_skipped_last: adding to list ($added, last; $log_skipped log lines skipped)"); } } else { $this->log('ERROR: Could not read the directory: '.$backup_from_inside_dir); $this->log(__('Could not read the directory', 'updraftplus').': '.$backup_from_inside_dir, 'error'); } return $dirlist; } /** * Save the backup information to the backup history during a running backup (adding information to the currently-running job) * * @param Array $backup_array - the backup history */ private function save_backup_to_history($backup_array) { if (!is_array($backup_array)) { $this->log('Could not save backup history because we have no backup array. Backup probably failed.'); $this->log(__('Could not save backup history because we have no backup array. Backup probably failed.', 'updraftplus'), 'error'); return; } $job_type = $this->jobdata_get('job_type'); $backup_array['nonce'] = $this->file_nonce; $backup_array['service'] = $this->jobdata_get('service'); $backup_array['service_instance_ids'] = array(); if ('incremental' != $job_type) $backup_array['always_keep'] = $this->jobdata_get('always_keep', false); $backup_array['files_enumerated_at'] = $this->jobdata_get('files_enumerated_at'); $remote_storage_instances = $this->jobdata_get('remote_storage_instances', array()); // N.B. Though the saved 'service' option can have various forms (especially if upgrading from (very) old versions), in the jobdata, it is always an array. $storage_objects_and_ids = UpdraftPlus_Storage_Methods_Interface::get_enabled_storage_objects_and_ids($backup_array['service'], $remote_storage_instances); // N.B. On PHP 5.5+, we'd use array_column() foreach ($storage_objects_and_ids as $method => $method_information) { if ('none' == $method || !$method || !$method_information['object']->supports_feature('multi_options')) continue; $backup_array['service_instance_ids'][$method] = array_keys($method_information['instance_settings']); } if ('incremental' != $job_type && '' != ($label = $this->jobdata_get('label', ''))) $backup_array['label'] = $label; if (!isset($backup_array['created_by_version'])) $backup_array['created_by_version'] = $this->version; $backup_array['last_saved_by_version'] = $this->version; $backup_array['is_multisite'] = is_multisite() ? true : false; $remotesend_info = $this->jobdata_get('remotesend_info'); if (is_array($remotesend_info) && !empty($remotesend_info['url'])) $backup_array['remotesend_url'] = $remotesend_info['url']; if (false != $this->jobdata_get('is_autobackup', false)) $backup_array['autobackup'] = true; if (false != ($morefiles_linked_indexes = $this->jobdata_get('morefiles_linked_indexes', false))) $backup_array['morefiles_linked_indexes'] = $morefiles_linked_indexes; if (false != ($morefiles_more_locations = $this->jobdata_get('morefiles_more_locations', false))) $backup_array['morefiles_more_locations'] = $morefiles_more_locations; UpdraftPlus_Backup_History::save_backup(apply_filters('updraftplus_save_backup_history_timestamp', $this->backup_time), $backup_array); } /** * If files + db are on different schedules but are scheduled for the same time, * then combine them $event = (object) array('hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval']); * See wp_schedule_single_event() and wp_schedule_event() in wp-includes/cron.php * * @param Object|Boolean $event - the event being scheduled * @return Object|Boolean - the filtered value */ public function schedule_event($event) { static $scheduled = array(); if (is_object($event) && ('updraft_backup' == $event->hook || 'updraft_backup_database' == $event->hook)) { // Reset the option - but make sure it is saved first so that we can used it (since this hook may be called just before our actual cron task) $this->combine_jobs_around = UpdraftPlus_Options::get_updraft_option('updraft_combine_jobs_around'); UpdraftPlus_Options::delete_updraft_option('updraft_combine_jobs_around'); $scheduled[$event->hook] = true; // This next fragment is wrong: there's only a 'second call' when saving all settings; otherwise, the WP scheduler might just be updating one event. So, there's some inefficieny as the option is wiped and set uselessly at least once when saving settings. // We only want to take action on the second call (otherwise, our information is out-of-date already) // If there is no second call, then that's fine - nothing to do // if (count($scheduled) < 2) { // return $event; // } $backup_scheduled_for = ('updraft_backup' == $event->hook) ? $event->timestamp : wp_next_scheduled('updraft_backup'); $db_scheduled_for = ('updraft_backup_database' == $event->hook) ? $event->timestamp : wp_next_scheduled('updraft_backup_database'); $diff = absint($backup_scheduled_for - $db_scheduled_for); $margin = (defined('UPDRAFTPLUS_COMBINE_MARGIN') && is_numeric(UPDRAFTPLUS_COMBINE_MARGIN)) ? UPDRAFTPLUS_COMBINE_MARGIN : 600; if ($backup_scheduled_for && $db_scheduled_for && $diff < $margin) { // We could change the event parameters; however, this would complicate other code paths (because the WP cron system uses a hash of the parameters as a key, and you must supply the exact parameters to look up events). So, we just set a marker that boot_backup() can pick up on. UpdraftPlus_Options::update_updraft_option('updraft_combine_jobs_around', min($backup_scheduled_for, $db_scheduled_for)); } } return $event; } /** * This function is both the backup scheduler and a filter callback for saving the option. It is called in the register_setting for the updraft_interval, which means when the admin settings are saved it is called. * * @param String $interval * @return String - filtered value */ public function schedule_backup($interval) { $previous_time = wp_next_scheduled('updraft_backup'); // Clear schedule so that we don't stack up scheduled backups wp_clear_scheduled_hook('updraft_backup'); if ('manual' == $interval) { // Clear increments schedule as the file schedule is manual wp_clear_scheduled_hook('updraft_backup_increments'); return 'manual'; } $previous_interval = UpdraftPlus_Options::get_updraft_option('updraft_interval'); $valid_schedules = wp_get_schedules(); if (empty($valid_schedules[$interval])) $interval = 'daily'; // Try to avoid changing the time is one was already scheduled. This is fairly conservative - we could do more, e.g. check if a backup already happened today. $default_time = ($interval == $previous_interval && $previous_time>0) ? $previous_time : $this->random_schedule_time(); $first_time = apply_filters('updraftplus_schedule_firsttime_files', $default_time); wp_schedule_event($first_time, $interval, 'updraft_backup'); return $interval; } /** * This function is both the database backup scheduler and a filter callback for saving the option. It is called in the register_setting for the updraft_interval_database, which means when the admin settings are saved it is called. * * @param String $interval * @return String - filtered value */ public function schedule_backup_database($interval) { $previous_time = wp_next_scheduled('updraft_backup_database'); // Clear schedule so that we don't stack up scheduled backups wp_clear_scheduled_hook('updraft_backup_database'); if ('manual' == $interval) return 'manual'; $previous_interval = UpdraftPlus_Options::get_updraft_option('updraft_interval_database'); $valid_schedules = wp_get_schedules(); if (empty($valid_schedules[$interval])) $interval = 'daily'; // Try to avoid changing the time is one was already scheduled. This is fairly conservative - we could do more, e.g. check if a backup already happened today. $default_time = ($interval == $previous_interval && $previous_time>0) ? $previous_time : $this->random_schedule_time(); $first_time = apply_filters('updraftplus_schedule_firsttime_db', $default_time); wp_schedule_event($first_time, $interval, 'updraft_backup_database'); return $interval; } /** * This function is both the increments backup scheduler and a filter callback for saving the option. It is called in the register_setting for the updraft_interval_increments, which means when the admin settings are saved it is called. * * @param String $interval * @return String - filtered value */ public function schedule_backup_increments($interval) { $previous_time = wp_next_scheduled('updraft_backup_increments'); // Clear schedule so that we don't stack up scheduled backups wp_clear_scheduled_hook('updraft_backup_increments'); if ('none' == $interval || empty($interval)) return 'none'; $previous_interval = UpdraftPlus_Options::get_updraft_option('updraft_interval_increments'); $valid_schedules = wp_get_schedules(); if (empty($valid_schedules[$interval])) $interval = 'daily'; // Try to avoid changing the time is one was already scheduled. This is fairly conservative - we could do more, e.g. check if a backup already happened today. $default_time = ($interval == $previous_interval && $previous_time>0) ? $previous_time : time()+120; $first_time = apply_filters('updraftplus_schedule_firsttime_increments', $default_time); wp_schedule_event($first_time, $interval, 'updraft_backup_increments'); return $interval; } /** * This function will generate a random backup schedule timestamp between the hours of 9PM and 7AM and return it * * @return string - the random timestamp */ private function random_schedule_time() { static $scheduled_timestamp = false; if ($scheduled_timestamp) return $scheduled_timestamp; $valid_hours = array(21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7); $current_hour = current_time('G'); $current_timestamp = current_time('timestamp'); if (in_array($current_hour, $valid_hours)) { $scheduled_timestamp = $current_timestamp; } else { $scheduled_timestamp = $current_timestamp + 43200; } return $scheduled_timestamp; } /** * Acts as a WordPress options filter * * @param Array $options - An array of options * @param String $option_name - The option name * * @return Array - the returned array can either be the set of updated options or a WordPress error array */ public function storage_options_filter($options, $option_name) { if ('updraft_' !== substr($option_name, 0, 8)) return $options; $method = substr($option_name, 8); $storage = UpdraftPlus_Storage_Methods_Interface::get_storage_object($method); if (!is_a($storage, 'UpdraftPlus_BackupModule') || !is_callable(array($storage, 'options_filter'))) return $options; return call_user_func(array($storage, 'options_filter'), $options); } /** * Get the location of UD's internal directory * * @param Boolean $allow_cache * @return String - the directory path. Returns without any trailing slash. */ public function backups_dir_location($allow_cache = true) { if ($allow_cache && !empty($this->backup_dir)) return $this->backup_dir; $updraft_dir = untrailingslashit(UpdraftPlus_Options::get_updraft_option('updraft_dir')); // When newly installing, if someone had (e.g.) wp-content/updraft in their database from a previous, deleted pre-1.7.18 install but had removed the updraft directory before re-installing, without this fix they'd end up with wp-content/wp-content/updraft. if (preg_match('/^wp-content\/(.*)$/', $updraft_dir, $matches) && ABSPATH.'wp-content' === WP_CONTENT_DIR) { UpdraftPlus_Options::update_updraft_option('updraft_dir', $matches[1]); $updraft_dir = WP_CONTENT_DIR.'/'.$matches[1]; } // Default if (!$updraft_dir) $updraft_dir = WP_CONTENT_DIR.'/updraft'; // Do a test for a relative path if ('/' != substr($updraft_dir, 0, 1) && "\\" != substr($updraft_dir, 0, 1) && !preg_match('/^[a-zA-Z]:/', $updraft_dir)) { // Legacy - file paths stored related to ABSPATH if (is_dir(ABSPATH.$updraft_dir) && is_file(ABSPATH.$updraft_dir.'/index.html') && is_file(ABSPATH.$updraft_dir.'/.htaccess') && !is_file(ABSPATH.$updraft_dir.'/index.php') && false !== strpos(file_get_contents(ABSPATH.$updraft_dir.'/.htaccess', false, null, 0, 20), 'deny from all')) { $updraft_dir = ABSPATH.$updraft_dir; } else { // File paths stored relative to WP_CONTENT_DIR $updraft_dir = trailingslashit(WP_CONTENT_DIR).$updraft_dir; } } // Check for the existence of the dir and prevent enumeration // index.php is for a sanity check - make sure that we're not somewhere unexpected if ((!is_dir($updraft_dir) || !is_file($updraft_dir.'/index.html') || !is_file($updraft_dir.'/.htaccess')) && !is_file($updraft_dir.'/index.php') || !is_file($updraft_dir.'/web.config')) { @mkdir($updraft_dir, 0775, true);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. @file_put_contents($updraft_dir.'/index.html', "WordPress backups by UpdraftPlus");// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. if (!is_file($updraft_dir.'/.htaccess')) @file_put_contents($updraft_dir.'/.htaccess', 'deny from all');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. if (!is_file($updraft_dir.'/web.config')) @file_put_contents($updraft_dir.'/web.config', "\n\n\n\n\n\n\n");// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. } $this->backup_dir = $updraft_dir; return $updraft_dir; } /** * This function will work out the total size of the passed in backup and return it. * * @param array $backup - an array of information about this backup set * * @return integer - the total size of the backup in bytes */ public function get_total_backup_size($backup) { $backupable_entities = $this->get_backupable_file_entities(true, true); // Add the database to the entities array ready to loop over $backupable_entities['db'] = ''; $total_size = 0; foreach ($backup as $ekey => $files) { if (!isset($backupable_entities[$ekey])) continue; if (is_string($files)) $files = array($files); foreach ($files as $findex => $file) { $size_key = (0 == $findex) ? $ekey.'-size' : $ekey.$findex.'-size'; $total_size = (false === $total_size || !isset($backup[$size_key]) || !is_numeric($backup[$size_key])) ? false : $total_size + $backup[$size_key]; } } return $total_size; } public function spool_file($fullpath, $encryption = '') { if (function_exists('set_time_limit')) @set_time_limit(900);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. if (!file_exists($fullpath) || filesize($fullpath) < 1) { _e('File not found', 'updraftplus'); return; } // Prevent any debug output // Don't enable this line - it causes 500 HTTP errors in some cases/hosts on some large files, for unknown reason // @ini_set('display_errors', '0'); if (UpdraftPlus_Encryption::is_file_encrypted($fullpath)) { if (ob_get_level()) { $flush_max = min(5, (int) ob_get_level()); for ($i=1; $i<=$flush_max; $i++) { @ob_end_clean();// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. } } header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past UpdraftPlus_Encryption::spool_crypted_file($fullpath, (string) $encryption); return; } $content_type = UpdraftPlus_Manipulation_Functions::get_mime_type_from_filename($fullpath, false); updraft_try_include_file('includes/class-partialfileservlet.php', 'include_once'); // Prevent the file being read into memory if (ob_get_level()) { $flush_max = min(5, (int) ob_get_level()); for ($i=1; $i<=$flush_max; $i++) { @ob_end_clean();// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. } } if (ob_get_level()) @ob_end_clean(); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged --Twice - see HS#6673 - someone at least needed it if (isset($_SERVER['HTTP_RANGE'])) { $range_header = trim($_SERVER['HTTP_RANGE']); } elseif (function_exists('apache_request_headers')) { foreach (apache_request_headers() as $name => $value) { if (strtoupper($name) === 'RANGE') { $range_header = trim($value); } } } if (empty($range_header)) { header("Content-Length: ".filesize($fullpath)); header("Content-type: $content_type"); header("Content-Disposition: attachment; filename=\"".basename($fullpath)."\";"); readfile($fullpath); return; } try { $range_header = UpdraftPlus_RangeHeader::createFromHeaderString($range_header); $servlet = new UpdraftPlus_PartialFileServlet($range_header); $servlet->sendFile($fullpath, $content_type); } catch (UpdraftPlus_InvalidRangeHeaderException $e) { header("HTTP/1.1 400 Bad Request"); error_log("UpdraftPlus: UpdraftPlus_InvalidRangeHeaderException: ".$e->getMessage()); } catch (UpdraftPlus_UnsatisfiableRangeException $e) { header("HTTP/1.1 416 Range Not Satisfiable"); } catch (UpdraftPlus_NonExistentFileException $e) { header("HTTP/1.1 404 Not Found"); } catch (UpdraftPlus_UnreadableFileException $e) { header("HTTP/1.1 500 Internal Server Error"); } } public function just_one_email($input, $required = false) { $x = $this->just_one($input, 'saveemails', (empty($input) && false === $required) ? '' : get_bloginfo('admin_email')); if (is_array($x)) { foreach ($x as $ind => $val) { if (empty($val)) unset($x[$ind]); } if (empty($x)) $x = ''; } return $x; } /** * Filter the values down to just one (subject to being filtered) * * @param Array|String $input - input * @param String $filter - filter suffix to use * @param Boolean|String $rinput - a 'preferred' value (unless false) if no filtering is done * * @return Array|String|Null - output, after filtering */ public function just_one($input, $filter = 'savestorage', $rinput = false) { $oinput = $input; if (false === $rinput) $rinput = is_array($input) ? array_pop($input) : $input; if (is_string($rinput) && false !== strpos($rinput, ',')) $rinput = substr($rinput, 0, strpos($rinput, ',')); return apply_filters('updraftplus_'.$filter, $rinput, $oinput); } /** * Enqueue the JavaScript and CSS for the select2 library */ public function enqueue_select2() { // De-register to defeat any plugins that may have registered incompatible versions (e.g. WooCommerce 2.5 beta1 still has the Select 2 3.5 series) wp_deregister_script('select2'); wp_deregister_style('select2'); $select2_version = $this->use_unminified_scripts() ? '4.1.0-rc.0'.'.'.time() : '4.1.0-rc.0'; $min_or_not = $this->use_unminified_scripts() ? '' : '.min'; wp_enqueue_script('select2', UPDRAFTPLUS_URL."/includes/select2/select2".$min_or_not.".js", array('jquery'), $select2_version); wp_enqueue_style('select2', UPDRAFTPLUS_URL."/includes/select2/select2".$min_or_not.".css", array(), $select2_version); } public function memory_check_current($memory_limit = false) { // Returns in megabytes if (false == $memory_limit) $memory_limit = ini_get('memory_limit'); $memory_limit = rtrim($memory_limit); $memory_unit = $memory_limit[strlen($memory_limit)-1]; if (0 == (int) $memory_unit && '0' !== $memory_unit) { $memory_limit = substr($memory_limit, 0, strlen($memory_limit)-1); } else { $memory_unit = ''; } switch ($memory_unit) { case '': $memory_limit = floor($memory_limit/1048576); break; case 'K': case 'k': $memory_limit = floor($memory_limit/1024); break; case 'G': $memory_limit = $memory_limit*1024; break; case 'M': // assumed size, no change needed break; } return $memory_limit; } public function memory_check($memory, $check_using = false) { $memory_limit = $this->memory_check_current($check_using); return ($memory_limit >= $memory) ? true : false; } /** * Get the UpdraftPlus RSS feed * * @uses fetch_feed() * * @return WP_Error|SimplePie WP_Error object on failure or SimplePie object on success */ public function get_updraftplus_rssfeed() { if (!function_exists('fetch_feed')) include(ABSPATH.WPINC.'/feed.php'); return fetch_feed('http://feeds.feedburner.com/updraftplus/'); } /** * Sets up the nonce, basic job data, opens a log file for a new restore job, and makes sure that the Updraft_Restorer class is available * * @param Boolean|string $nonce - the job nonce we want to use or false for a new one * * @return void */ public function initiate_restore_job($nonce = false) { $this->backup_time_nonce($nonce); // we reset here so that we ensure the correct jobdata gets loaded while we resume $this->jobdata_reset(); $this->jobdata_set('job_type', 'restore'); $this->jobdata_set('job_time_ms', $this->job_time_ms); $this->logfile_open($this->nonce); if (!class_exists('Updraft_Restorer')) updraft_try_include_file('restorer.php', 'include_once'); } /** * Analyse a database file and return information about it * * @param Integer $timestamp - the database time in the backup history * @param Array $res - accompanying data. The key 'updraft_encryptionphrase' will be used for decryption if relevant. * @param Boolean|String $db_file - the path to the file to analyse; if not specified (false), then it will be obtained from the backup history * @param Boolean $header_only - whether or not to stop analysis once the header ends * * @return Array - containing arrays for the resulting messages, warnings, errors and meta information */ public function analyse_db_file($timestamp, $res, $db_file = false, $header_only = false) { $mess = array(); $warn = array(); $err = array(); $info = array(); $wp_version = $this->get_wordpress_version(); global $wpdb; if (!class_exists('UpdraftPlus_Database_Utility')) updraft_try_include_file('includes/class-database-utility.php', 'include_once'); $updraft_dir = $this->backups_dir_location(); if (false === $db_file) { // This attempts to raise the maximum packet size. This can't be done within the session, only globally. Therefore, it has to be done before the session starts; in our case, during the pre-analysis. $this->max_packet_size(); $backup = UpdraftPlus_Backup_History::get_history($timestamp); if (!isset($backup['nonce']) || !isset($backup['db'])) return array($mess, $warn, $err, $info); $db_file = is_string($backup['db']) ? $updraft_dir.'/'.$backup['db'] : $updraft_dir.'/'.$backup['db'][0]; } if (!is_readable($db_file)) return array($mess, $warn, $err, $info); // Encrypted - decrypt it if (UpdraftPlus_Encryption::is_file_encrypted($db_file)) { $encryption = empty($res['updraft_encryptionphrase']) ? UpdraftPlus_Options::get_updraft_option('updraft_encryptionphrase') : $res['updraft_encryptionphrase']; if (!$encryption) { if (class_exists('UpdraftPlus_Addon_MoreDatabase')) { $err[] = sprintf(__('Error: %s', 'updraftplus'), __('Decryption failed. The database file is encrypted, but you have no encryption key entered.', 'updraftplus')); } else { $err[] = sprintf(__('Error: %s', 'updraftplus'), __('Decryption failed. The database file is encrypted.', 'updraftplus')); } return array($mess, $warn, $err, $info); } $decrypted_file = UpdraftPlus_Encryption::decrypt($db_file, $encryption); if (is_array($decrypted_file)) { $db_file = $decrypted_file['fullpath']; } else { $err[] = __('Decryption failed. The most likely cause is that you used the wrong key.', 'updraftplus'); return array($mess, $warn, $err, $info); } } // Even the empty schema when gzipped comes to 1565 bytes; a blank WP 3.6 install at 5158. But we go low, in case someone wants to share single tables. if (filesize($db_file) < 1000) { $err[] = sprintf(__('The database is too small to be a valid WordPress database (size: %s Kb).', 'updraftplus'), round(filesize($db_file)/1024, 1)); return array($mess, $warn, $err, $info); } // If the backup is not from UpdraftPlus and it's not a simple SQL file then we don't want to scan if (!empty($backup['meta_foreign']) && 'genericsql' != $backup['meta_foreign']) { $info['skipped_db_scan'] = 1; return array($mess, $warn, $err, $info); } $is_plain = ('.gz' == substr($db_file, -3, 3)) ? false : true; $dbhandle = $is_plain ? fopen($db_file, 'r') : UpdraftPlus_Filesystem_Functions::gzopen_for_read($db_file, $warn, $err); if (!is_resource($dbhandle)) { $err[] = __('Failed to open database file.', 'updraftplus'); return array($mess, $warn, $err, $info); } $info['timestamp'] = $timestamp; // Analyse the file, print the results. $line = 0; $old_siteurl = ''; $old_home = ''; $old_table_prefix = null; $old_siteinfo = array(); $gathering_siteinfo = true; $old_wp_version = ''; $old_php_version = ''; $tables_found = array(); $db_charsets_found = array(); $db_scan_timed_out = false; $php_max_input_vars_exceeded = false; // TODO: If the backup is the right size/checksum, then we could restore the $line <= 100 in the 'while' condition and not bother scanning the whole thing? Or better: sort the core tables to be first so that this usually terminates early $wanted_tables = array('terms', 'term_taxonomy', 'term_relationships', 'commentmeta', 'comments', 'links', 'options', 'postmeta', 'posts', 'users', 'usermeta'); $migration_warning = false; $processing_create = false; $processing_routine = false; $db_version = $wpdb->db_version(); // Don't set too high - we want a timely response returned to the browser // Until April 2015, this was always 90. But we've seen a few people with ~1GB databases (uncompressed), and 90s is not enough. Note that we don't bother checking here if it's compressed - having a too-large timeout when unexpected is harmless, as it won't be hit. On very large dbs, they're expecting it to take a while. // "120 or 240" is a first attempt at something more useful than just fixed at 90 - but should be sufficient (as 90 was for everyone without ~1GB databases) $default_dbscan_timeout = (filesize($db_file) < 31457280) ? 120 : 240; $dbscan_timeout = (defined('UPDRAFTPLUS_DBSCAN_TIMEOUT') && is_numeric(UPDRAFTPLUS_DBSCAN_TIMEOUT)) ? UPDRAFTPLUS_DBSCAN_TIMEOUT : $default_dbscan_timeout; if (function_exists('set_time_limit')) @set_time_limit($dbscan_timeout);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Silenced to suppress errors that may arise because of the function. // We limit the time that we spend scanning the file for character sets $db_charset_collate_scan_timeout = (defined('UPDRAFTPLUS_DB_CHARSET_COLLATE_SCAN_TIMEOUT') && is_numeric(UPDRAFTPLUS_DB_CHARSET_COLLATE_SCAN_TIMEOUT)) ? UPDRAFTPLUS_DB_CHARSET_COLLATE_SCAN_TIMEOUT : 10; $charset_scan_start_time = microtime(true); $db_supported_character_sets = (array) $GLOBALS['wpdb']->get_results('SHOW CHARACTER SET', OBJECT_K); $db_supported_collations = (array) $GLOBALS['wpdb']->get_results('SHOW COLLATION', OBJECT_K); $db_charsets_found = array(); $db_collates_found = array(); $db_supported_charset_related_to_unsupported_collation = false; $db_supported_charsets_related_to_unsupported_collations = array(); while ((($is_plain && !feof($dbhandle)) || (!$is_plain && !gzeof($dbhandle))) && ($line<100 || (!$header_only && count($wanted_tables)>0) || ((microtime(true) - $charset_scan_start_time) < $db_charset_collate_scan_timeout && !empty($db_supported_character_sets)))) { $line++; // Up to 1MB $buffer = $is_plain ? rtrim(fgets($dbhandle, 1048576)) : rtrim(gzgets($dbhandle, 1048576)); // Comments are what we are interested in if (substr($buffer, 0, 1) == '#') { $processing_create = false; $processing_routine = false; if ('' == $old_siteurl && preg_match('/^\# Backup of: (http(.*))$/', $buffer, $matches)) { $old_siteurl = untrailingslashit($matches[1]); $mess[] = __('Backup of:', 'updraftplus').' '.htmlspecialchars($old_siteurl).((!empty($old_wp_version)) ? ' '.sprintf(__('(version: %s)', 'updraftplus'), $old_wp_version) : ''); // Check for should-be migration if (untrailingslashit(site_url()) != $old_siteurl) { if (!$migration_warning) { $migration_warning = true; $info['migration'] = true; // && !class_exists('UpdraftPlus_Addons_Migrator') if (UpdraftPlus_Manipulation_Functions::normalise_url($old_siteurl) == UpdraftPlus_Manipulation_Functions::normalise_url(site_url())) { // Same site migration with only http/https difference $info['same_url'] = false; $info['url_scheme_change'] = true; $old_siteurl_parsed = parse_url($old_siteurl); $actual_siteurl_parsed = parse_url(site_url()); if ((stripos($old_siteurl_parsed['host'], 'www.') === 0 && stripos($actual_siteurl_parsed['host'], 'www.') !== 0) || (stripos($old_siteurl_parsed['host'], 'www.') !== 0 && stripos($actual_siteurl_parsed['host'], 'www.') === 0)) { $powarn = sprintf(__('The website address in the backup set (%s) is slightly different from that of the site now (%s). This is not expected to be a problem for restoring the site, as long as visits to the former address still reach the site.', 'updraftplus'), $old_siteurl, site_url()).' '; } else { $powarn = ''; } if (('https' == $old_siteurl_parsed['scheme'] && 'http' == $actual_siteurl_parsed['scheme']) || ('http' == $old_siteurl_parsed['scheme'] && 'https' == $actual_siteurl_parsed['scheme'])) { $powarn .= sprintf(__('This backup set is of this site, but at the time of the backup you were using %s, whereas the site now uses %s.', 'updraftplus'), $old_siteurl_parsed['scheme'], $actual_siteurl_parsed['scheme']); if ('https' == $old_siteurl_parsed['scheme']) { $powarn .= ' '.apply_filters('updraftplus_https_to_http_additional_warning', sprintf(__('This restoration will work if you still have an SSL certificate (i.e. can use https) to access the site. Otherwise, you will want to use %s to search/replace the site address so that the site can be visited without https.', 'updraftplus'), ''.__('the migrator add-on', 'updraftplus').'')); } else { $powarn .= ' '.apply_filters('updraftplus_http_to_https_additional_warning', sprintf(__('As long as your web hosting allows http (i.e. non-SSL access) or will forward requests to https (which is almost always the case), this is no problem. If that is not yet set up, then you should set it up, or use %s so that the non-https links are automatically replaced.', 'updraftplus'), apply_filters('updraftplus_migrator_addon_link', ''.__('the migrator add-on', 'updraftplus').''))); } } else { $powarn .= apply_filters('updraftplus_dbscan_urlchange_www_append_warning', ''); } $warn[] = $powarn; } else { // For completely different site migration $info['same_url'] = false; $info['url_scheme_change'] = false; $warn[] = apply_filters('updraftplus_dbscan_urlchange', ''.sprintf(__('This backup set is from a different site (%s) - this is not a restoration, but a migration. You need the Migrator add-on in order to make this work.', 'updraftplus'), htmlspecialchars($old_siteurl.' / '.untrailingslashit(site_url()))).'', $old_siteurl, $res); } if (!class_exists('UpdraftPlus_Addons_Migrator')) { $warn[] .= ''.__('You can search and replace your database (for migrating a website to a new location/URL) with the Migrator add-on - follow this link for more information', 'updraftplus').''; } } if ($this->mod_rewrite_unavailable(false)) { $warn[] = sprintf(__('You are using the %s webserver, but do not seem to have the %s module loaded.', 'updraftplus'), 'Apache', 'mod_rewrite').' '.sprintf(__('You should enable %s to make any pretty permalinks (e.g. %s) work', 'updraftplus'), 'mod_rewrite', 'http://example.com/my-page/'); } } else { // For exactly same URL site restoration $info['same_url'] = true; $info['url_scheme_change'] = false; } } elseif ('' == $old_home && preg_match('/^\# Home URL: (http(.*))$/', $buffer, $matches)) { $old_home = untrailingslashit($matches[1]); // Check for should-be migration if (!$migration_warning && UpdraftPlus_Manipulation_Functions::normalise_url(home_url()) != UpdraftPlus_Manipulation_Functions::normalise_url($old_home)) { $migration_warning = true; $powarn = apply_filters('updraftplus_dbscan_urlchange', ''.sprintf(__('This backup set is from a different site (%s) - this is not a restoration, but a migration. You need the Migrator add-on in order to make this work.', 'updraftplus'), htmlspecialchars($old_home.' / '.home_url())).'', $old_home, $res); if (!empty($powarn)) $warn[] = $powarn; } } elseif (!isset($info['created_by_version']) && preg_match('/^\# Created by UpdraftPlus version ([\d\.]+)/', $buffer, $matches)) { $info['created_by_version'] = trim($matches[1]); } elseif ('' == $old_wp_version && preg_match('/^\# WordPress Version: ([0-9]+(\.[0-9]+)+)(-[-a-z0-9]+,)?(.*)$/', $buffer, $matches)) { $old_wp_version = $matches[1]; if (!empty($matches[3])) $old_wp_version .= substr($matches[3], 0, strlen($matches[3])-1); if (version_compare($old_wp_version, $wp_version, '>')) { // $mess[] = sprintf(__('%s version: %s', 'updraftplus'), 'WordPress', $old_wp_version); $warn[] = sprintf(__('You are importing from a newer version of WordPress (%s) into an older one (%s). There are no guarantees that WordPress can handle this.', 'updraftplus'), $old_wp_version, $wp_version); } if (preg_match('/running on PHP ([0-9]+\.[0-9]+)(\s|\.)/', $matches[4], $nmatches) && preg_match('/^([0-9]+\.[0-9]+)(\s|\.)/', PHP_VERSION, $cmatches)) { $old_php_version = $nmatches[1]; $current_php_version = $cmatches[1]; if (version_compare($old_php_version, $current_php_version, '>')) { // $mess[] = sprintf(__('%s version: %s', 'updraftplus'), 'WordPress', $old_wp_version); $warn[] = sprintf(__('The site in this backup was running on a webserver with version %s of %s. ', 'updraftplus'), $old_php_version, 'PHP').' '.sprintf(__('This is significantly newer than the server which you are now restoring onto (version %s).', 'updraftplus'), PHP_VERSION).' '.sprintf(__('You should only proceed if you cannot update the current server and are confident (or willing to risk) that your plugins/themes/etc. are compatible with the older %s version.', 'updraftplus'), 'PHP').' '.sprintf(__('Any support requests to do with %s should be raised with your web hosting company.', 'updraftplus'), 'PHP'); } elseif (version_compare($old_php_version, $current_php_version, '<')) { $warn[] = sprintf(__('The site in this backup was running on a webserver with version %s of %s. ', 'updraftplus'), $old_php_version, 'PHP').' '.sprintf(__('This is older than the server which you are now restoring onto (version %s).', 'updraftplus'), PHP_VERSION).' '.sprintf(__('You should only proceed if you have checked and are confident (or willing to risk) that your plugins/themes/etc. are compatible with the new %s version.', 'updraftplus'), 'PHP').' '.sprintf(__('Any support requests to do with %s should be raised with your web hosting company.', 'updraftplus'), 'PHP'); } } } elseif (null === $old_table_prefix && (preg_match('/^\# Table prefix: ?(\S*)$/', $buffer, $matches) || preg_match('/^-- Table prefix: ?(\S*)$/i', $buffer, $matches))) { $old_table_prefix = $matches[1]; // echo ''.__('Old table prefix:', 'updraftplus').'<