Пример #1
0
 /**
  * Set an OAuth token in the database by type
  * If the encryption object is set then encrypt the token before storing
  * @param \stdClass Token object to set
  * @param string $type Token type
  * @return void
  */
 public function set($token, $type)
 {
     if ($type != 'request_token' && $type != 'access_token') {
         throw new Dropbox_Exception("Expected a type of either 'request_token' or 'access_token', got '{$type}'");
     } else {
         $token = $this->encrypt($token);
         UpdraftPlus_Options::update_updraft_option($this->option_name_prefix . $type, $token);
     }
 }
Пример #2
0
 /**
  * Obtain user authorisation
  * The user will be redirected to Dropbox' web endpoint
  * @link http://tools.ietf.org/html/rfc5849#section-2.2
  * @return void
  */
 private function authorise()
 {
     // Only redirect if using CLI
     if (PHP_SAPI !== 'cli' && (!defined('DOING_CRON') || !DOING_CRON)) {
         $url = $this->getAuthoriseUrl();
         header('Location: ' . $url);
         exit;
     }
     global $updraftplus;
     $updraftplus->log('Dropbox reauthorisation needed; but we are running from cron or the CLI, so this is not possible');
     UpdraftPlus_Options::update_updraft_option("updraft_dropboxtk_request_token", '');
     $updraftplus->log(sprintf(__('You need to re-authenticate with %s, as your existing credentials are not working.', 'updraftplus'), 'Dropbox'), 'error');
     exit;
 }
Пример #3
0
 public function updraft_migrate_newdestination()
 {
     global $updraftplus;
     $ret = array();
     if (empty($_POST['key'])) {
         $ret['e'] = sprintf(__("Failure: No %s was given.", 'updraftplus'), __('key', 'updraftplus'));
     } else {
         $ud_rpc = $updraftplus->get_udrpc();
         // A bundle has these keys: key, name_indicator, url
         $decode_bundle = $ud_rpc->decode_portable_bundle($_POST['key'], 'base64_with_count');
         if (!is_array($decode_bundle) || !empty($decode_bundle['code'])) {
             $ret['e'] = __('Error:', 'updraftplus');
             if (!empty($decode_bundle['code']) && $decode_bundle['code'] == 'invalid_wrong_length') {
                 $ret['e'] .= ' ' . __('The entered key was the wrong length - please try again.', 'updraftplus');
             } elseif (!empty($decode_bundle['code']) && $decode_bundle['code'] == 'invalid_corrupt') {
                 $ret['e'] .= ' ' . __('The entered key was corrupt - please try again.', 'updraftplus') . ' (' . $decode_bundle['data'] . ')';
             } elseif (empty($decode_bundle['key']) || empty($decode_bundle['url'])) {
                 $ret['e'] .= ' ' . __('The entered key was corrupt - please try again.', 'updraftplus');
                 $ret['data'] = $decode_bundle;
             }
         } elseif (empty($decode_bundle['key']) || empty($decode_bundle['url'])) {
             $ret['e'] = __('Error:', 'updraftplus') . ' ' . __('The entered key was corrupt - please try again.', 'updraftplus');
             $ret['data'] = $decode_bundle;
         } else {
             if ($decode_bundle['url'] == trailingslashit(network_site_url())) {
                 $ret['e'] = __('Error:', 'updraftplus') . ' ' . __('The entered key does not belong to a remote site (it belongs to this one).', 'updraftplus');
             } else {
                 // Store the information
                 $remotesites = UpdraftPlus_Options::get_updraft_option('updraft_remotesites');
                 if (!is_array($remotesites)) {
                     $remotesites = array();
                 }
                 foreach ($remotesites as $k => $rsite) {
                     if (!is_array($rsite)) {
                         continue;
                     }
                     if ($rsite['url'] == $decode_bundle['url']) {
                         unset($remotesites[$k]);
                     }
                 }
                 $remotesites[] = $decode_bundle;
                 UpdraftPlus_Options::update_updraft_option('updraft_remotesites', $remotesites);
                 $ret['selector'] = $this->get_remotesites_selector($remotesites);
                 // Return the new HTML widget to the front end
                 $ret['r'] = __('The key was successfully added.', 'updraftplus') . ' ' . __('It is for sending backups to the following site: ', 'updraftplus') . htmlspecialchars($decode_bundle['url']);
             }
         }
     }
     echo json_encode($ret);
     die;
 }
 private function deleteset()
 {
     global $updraftplus;
     $backups = $updraftplus->get_backup_history();
     $timestamp = $_POST['backup_timestamp'];
     if (!isset($backups[$timestamp])) {
         $bh = $this->build_historystatus();
         return array('result' => 'error', 'message' => __('Backup set not found', 'updraftplus'), 'updraft_historystatus' => $bh['h'], 'updraft_count_backups' => $bh['c']);
     }
     // You need a nonce before you can set job data. And we certainly don't yet have one.
     $updraftplus->backup_time_nonce();
     // Set the job type before logging, as there can be different logging destinations
     $updraftplus->jobdata_set('job_type', 'delete');
     $updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms);
     if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
         $updraftplus->logfile_open($updraftplus->nonce);
         set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT);
     }
     $updraft_dir = $updraftplus->backups_dir_location();
     $backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
     $nonce = isset($backups[$timestamp]['nonce']) ? $backups[$timestamp]['nonce'] : '';
     $delete_from_service = array();
     if (isset($_POST['delete_remote']) && 1 == $_POST['delete_remote']) {
         // Locate backup set
         if (isset($backups[$timestamp]['service'])) {
             $services = is_string($backups[$timestamp]['service']) ? array($backups[$timestamp]['service']) : $backups[$timestamp]['service'];
             if (is_array($services)) {
                 foreach ($services as $service) {
                     if ($service != 'none') {
                         $delete_from_service[] = $service;
                     }
                 }
             }
         }
     }
     $files_to_delete = array();
     foreach ($backupable_entities as $key => $ent) {
         if (isset($backups[$timestamp][$key])) {
             $files_to_delete[$key] = $backups[$timestamp][$key];
         }
     }
     // Delete DB
     if (isset($backups[$timestamp]['db'])) {
         $files_to_delete['db'] = $backups[$timestamp]['db'];
     }
     // Also delete the log
     if ($nonce && !UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
         $files_to_delete['log'] = "log.{$nonce}.txt";
     }
     unset($backups[$timestamp]);
     UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backups);
     $message = '';
     $local_deleted = 0;
     $remote_deleted = 0;
     add_action('http_request_args', array($updraftplus, 'modify_http_options'));
     foreach ($files_to_delete as $key => $files) {
         # Local deletion
         if (is_string($files)) {
             $files = array($files);
         }
         foreach ($files as $file) {
             if (is_file($updraft_dir . '/' . $file)) {
                 if (@unlink($updraft_dir . '/' . $file)) {
                     $local_deleted++;
                 }
             }
         }
         if ('log' != $key && count($delete_from_service) > 0) {
             foreach ($delete_from_service as $service) {
                 if ('email' == $service) {
                     continue;
                 }
                 if (file_exists(UPDRAFTPLUS_DIR . "/methods/{$service}.php")) {
                     require_once UPDRAFTPLUS_DIR . "/methods/{$service}.php";
                 }
                 $objname = 'UpdraftPlus_BackupModule_' . $service;
                 $deleted = -1;
                 if (class_exists($objname)) {
                     # TODO: Re-use the object (i.e. prevent repeated connection setup/teardown)
                     $remote_obj = new $objname();
                     $deleted = $remote_obj->delete($files);
                 }
                 if ($deleted === -1) {
                     //echo __('Did not know how to delete from this cloud service.', 'updraftplus');
                 } elseif ($deleted !== false) {
                     $remote_deleted = $remote_deleted + count($files);
                 } else {
                     // Do nothing
                 }
             }
         }
     }
     remove_action('http_request_args', array($updraftplus, 'modify_http_options'));
     $message .= __('The backup set has been removed.', 'updraftplus') . "\n";
     $message .= sprintf(__('Local archives deleted: %d', 'updraftplus'), $local_deleted) . "\n";
     $message .= sprintf(__('Remote archives deleted: %d', 'updraftplus'), $remote_deleted) . "\n";
     $updraftplus->log('Local archives deleted: ' . $local_deleted);
     $updraftplus->log('Remote archives deleted: ' . $remote_deleted);
     if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
         restore_error_handler();
     }
     $bh = $this->build_historystatus();
     return array('result' => 'success', 'message' => $message, 'updraft_historystatus' => $bh['h'], 'updraft_count_backups' => $bh['c']);
 }
Пример #5
0
 public function bootstrap($access_token = false)
 {
     global $updraftplus;
     if (!empty($this->service) && is_object($this->service) && is_a($this->service, 'Google_Service_Drive')) {
         return $this->service;
     }
     $opts = $this->get_opts();
     if (empty($access_token)) {
         if (empty($opts['token']) || empty($opts['clientid']) || empty($opts['secret'])) {
             $updraftplus->log('Google Drive: this account is not authorised');
             $updraftplus->log('Google Drive: ' . __('Account is not authorized.', 'updraftplus'), 'error', 'googledrivenotauthed');
             return new WP_Error('not_authorized', __('Account is not authorized.', 'updraftplus'));
         }
     }
     // 		$included_paths = explode(PATH_SEPARATOR, get_include_path());
     // 		if (!in_array(UPDRAFTPLUS_DIR.'/includes', $included_paths)) {
     // 			set_include_path(UPDRAFTPLUS_DIR.'/includes'.PATH_SEPARATOR.get_include_path());
     // 		}
     $spl = spl_autoload_functions();
     if (is_array($spl)) {
         // Workaround for Google Drive CDN plugin's autoloader
         if (in_array('wpbgdc_autoloader', $spl)) {
             spl_autoload_unregister('wpbgdc_autoloader');
         }
         // http://www.wpdownloadmanager.com/download/google-drive-explorer/ - but also others, since this is the default function name used by the Google SDK
         if (in_array('google_api_php_client_autoload', $spl)) {
             spl_autoload_unregister('google_api_php_client_autoload');
         }
     }
     /*
     		if (!class_exists('Google_Config')) require_once 'Google/Config.php';
     		if (!class_exists('Google_Client')) require_once 'Google/Client.php';
     		if (!class_exists('Google_Service_Drive')) require_once 'Google/Service/Drive.php';
     		if (!class_exists('Google_Http_Request')) require_once 'Google/Http/Request.php';
     */
     if ((!class_exists('Google_Config') || !class_exists('Google_Client') || !class_exists('Google_Service_Drive') || !class_exists('Google_Http_Request')) && !function_exists('google_api_php_client_autoload_updraftplus')) {
         require_once UPDRAFTPLUS_DIR . '/includes/Google/autoload.php';
     }
     $config = new Google_Config();
     $config->setClassConfig('Google_IO_Abstract', 'request_timeout_seconds', 60);
     # In our testing, $service->about->get() fails if gzip is not disabled when using the stream wrapper
     if (!function_exists('curl_version') || !function_exists('curl_exec') || defined('UPDRAFTPLUS_GOOGLEDRIVE_DISABLEGZIP') && UPDRAFTPLUS_GOOGLEDRIVE_DISABLEGZIP) {
         $config->setClassConfig('Google_Http_Request', 'disable_gzip', true);
     }
     $client = new Google_Client($config);
     $client->setClientId($opts['clientid']);
     $client->setClientSecret($opts['secret']);
     // 			$client->setUseObjects(true);
     if (empty($access_token)) {
         $access_token = $this->access_token($opts['token'], $opts['clientid'], $opts['secret']);
     }
     // Do we have an access token?
     if (empty($access_token) || is_wp_error($access_token)) {
         $updraftplus->log('ERROR: Have not yet obtained an access token from Google (has the user authorised?)');
         $updraftplus->log(__('Have not yet obtained an access token from Google - you need to authorise or re-authorise your connection to Google Drive.', 'updraftplus'), 'error');
         return $access_token;
     }
     $client->setAccessToken(json_encode(array('access_token' => $access_token, 'refresh_token' => $opts['token'])));
     $io = $client->getIo();
     $setopts = array();
     if (is_a($io, 'Google_IO_Curl')) {
         $setopts[CURLOPT_SSL_VERIFYPEER] = UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify') ? false : true;
         if (!UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts')) {
             $setopts[CURLOPT_CAINFO] = UPDRAFTPLUS_DIR . '/includes/cacert.pem';
         }
         // Raise the timeout from the default of 15
         $setopts[CURLOPT_TIMEOUT] = 60;
         $setopts[CURLOPT_CONNECTTIMEOUT] = 15;
         if (defined('UPDRAFTPLUS_IPV4_ONLY') && UPDRAFTPLUS_IPV4_ONLY) {
             $setopts[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
         }
     } elseif (is_a($io, 'Google_IO_Stream')) {
         $setopts['timeout'] = 60;
         # We had to modify the SDK to support this
         # https://wiki.php.net/rfc/tls-peer-verification - before PHP 5.6, there is no default CA file
         if (!UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts') || version_compare(PHP_VERSION, '5.6.0', '<')) {
             $setopts['cafile'] = UPDRAFTPLUS_DIR . '/includes/cacert.pem';
         }
         if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify')) {
             $setopts['disable_verify_peer'] = true;
         }
     }
     $io->setOptions($setopts);
     $service = new Google_Service_Drive($client);
     $this->client = $client;
     $this->service = $service;
     try {
         # Get the folder name, if not previously known (this is for the legacy situation where an id, not a name, was stored)
         if (!empty($opts['parentid']) && (!is_array($opts['parentid']) || empty($opts['parentid']['name']))) {
             $rootid = $this->root_id();
             $title = '';
             $parentid = is_array($opts['parentid']) ? $opts['parentid']['id'] : $opts['parentid'];
             while (!empty($parentid) && $parentid != $rootid) {
                 $resource = $service->files->get($parentid);
                 $title = $title ? $resource->getTitle() . '/' . $title : $resource->getTitle();
                 $parents = $resource->getParents();
                 if (is_array($parents) && count($parents) > 0) {
                     $parent = array_shift($parents);
                     $parentid = is_a($parent, 'Google_Service_Drive_ParentReference') ? $parent->getId() : false;
                 } else {
                     $parentid = false;
                 }
             }
             if (!empty($title)) {
                 $opts['parentid'] = array('id' => is_array($opts['parentid']) ? $opts['parentid']['id'] : $opts['parentid'], 'name' => $title);
                 UpdraftPlus_Options::update_updraft_option('updraft_googledrive', $opts);
             }
         }
     } catch (Exception $e) {
         $updraftplus->log("Google Drive: failed to obtain name of parent folder: " . $e->getMessage() . ' (line: ' . $e->getLine() . ', file: ' . $e->getFile() . ')');
     }
     return $this->service;
 }
Пример #6
0
 private function maybe_save_backup_history_and_reschedule($backup_history)
 {
     static $last_saved_at = 0;
     if (!$last_saved_at) {
         $last_saved_at = time();
     }
     if (time() - $last_saved_at >= 10) {
         global $updraftplus;
         $updraftplus->log("Retain: saving new backup history, because at least 10 seconds have passed since the last save (sets now: " . count($backup_history) . ")");
         UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backup_history, false);
         $updraftplus->something_useful_happened();
         $last_saved_at = time();
     }
 }
Пример #7
0
 public function backups_dir_location()
 {
     if (!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_backup_dir = WP_CONTENT_DIR . '/updraft';
     $updraft_dir = $updraft_dir ? $updraft_dir : $default_backup_dir;
     // 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);
         @file_put_contents($updraft_dir . '/index.html', "<html><body><a href=\"https://updraftplus.com\">WordPress backups by UpdraftPlus</a></body></html>");
         if (!is_file($updraft_dir . '/.htaccess')) {
             @file_put_contents($updraft_dir . '/.htaccess', 'deny from all');
         }
         if (!is_file($updraft_dir . '/web.config')) {
             @file_put_contents($updraft_dir . '/web.config', "<configuration>\n<system.webServer>\n<authorization>\n<deny users=\"*\" />\n</authorization>\n</system.webServer>\n</configuration>\n");
         }
     }
     $this->backup_dir = $updraft_dir;
     return $updraft_dir;
 }
Пример #8
0
 public function admin_action_upgrade_theme()
 {
     if (!current_user_can('update_themes')) {
         return;
     }
     $theme = isset($_REQUEST['theme']) ? urldecode($_REQUEST['theme']) : '';
     check_admin_referer('upgrade-theme_' . $theme);
     $title = __('Update Theme');
     $parent_file = 'themes.php';
     $submenu_file = 'themes.php';
     require_once ABSPATH . 'wp-admin/admin-header.php';
     # Did the user get the opportunity to indicate whether they wanted a backup?
     if (!isset($_POST['updraft_autobackup_answer'])) {
         $this->auto_backup_form_and_die();
     }
     # Do not use bools here - conflicts with get_option() with a non-default value
     $autobackup = isset($_POST['updraft_autobackup']) && $_POST['updraft_autobackup'] == 'yes' ? 1 : 0;
     if (!empty($_POST['updraft_autobackup_setdefault']) && 'yes' == $_POST['updraft_autobackup_setdefault']) {
         UpdraftPlus_Options::update_updraft_option('updraft_autobackup_default', $autobackup);
     }
     if ($autobackup) {
         echo '<div class="wrap"><h2>' . __('Automatic Backup', 'updraftplus') . '</h2>';
         $this->autobackup_go('themes', true);
         echo '</div>';
     }
     # Now, the backup is (if chosen) done... but the upgrade may not directly proceed. If WP needed filesystem credentials, then it may put up an intermediate screen, which we need to insert a field in to prevent an endless circle
     add_filter('request_filesystem_credentials', array($this, 'request_filesystem_credentials'));
 }
Пример #9
0
 public function show_authed_admin_warning()
 {
     global $updraftplus_admin, $updraftplus;
     $dropbox = $this->bootstrap();
     if (false === $dropbox) {
         return false;
     }
     try {
         $accountInfo = $dropbox->accountInfo();
     } catch (Exception $e) {
         $accountinfo_err = sprintf(__("%s error: %s", 'updraftplus'), 'Dropbox', $e->getMessage()) . ' (' . $e->getCode() . ')';
     }
     $message = "<strong>" . __('Success:', 'updraftplus') . '</strong> ' . sprintf(__('you have authenticated your %s account', 'updraftplus'), 'Dropbox');
     # We log, because otherwise people get confused by the most recent log message of 'Parameter not found: oauth_token' and raise support requests
     $updraftplus->log(__('Success:', 'updraftplus') . ' ' . sprintf(__('you have authenticated your %s account', 'updraftplus'), 'Dropbox'));
     if (empty($accountInfo['code']) || "200" != $accountInfo['code']) {
         $message .= " (" . __('though part of the returned information was not as expected - your mileage may vary', 'updraftplus') . ")" . $accountInfo['code'];
         if (!empty($accountinfo_err)) {
             $message .= "<br>" . htmlspecialchars($accountinfo_err);
         }
     } else {
         $body = $accountInfo['body'];
         $message .= ". <br>" . sprintf(__('Your %s account name: %s', 'updraftplus'), 'Dropbox', htmlspecialchars($body->display_name));
         $opts = $this->get_opts();
         $opts['ownername'] = '';
         if (!empty($body->display_name)) {
             $opts['ownername'] = $body->display_name;
         }
         UpdraftPlus_Options::update_updraft_option('updraft_dropbox', $opts);
         try {
             $quota_info = $body->quota_info;
             $total_quota = max($quota_info->quota, 1);
             $normal_quota = $quota_info->normal;
             $shared_quota = $quota_info->shared;
             $available_quota = $total_quota - ($normal_quota + $shared_quota);
             $used_perc = round(($normal_quota + $shared_quota) * 100 / $total_quota, 1);
             $message .= ' <br>' . sprintf(__('Your %s quota usage: %s %% used, %s available', 'updraftplus'), 'Dropbox', $used_perc, round($available_quota / 1048576, 1) . ' Mb');
         } catch (Exception $e) {
         }
     }
     $updraftplus_admin->show_admin_warning($message);
 }
Пример #10
0
 /**
  * Delete the request and access tokens currently stored in the database
  * @return bool
  */
 public function delete()
 {
     $opts = UpdraftPlus_Options::get_updraft_option($this->option_array);
     $opts[$this->option_name_prefix . 'request_token'] = '';
     $opts[$this->option_name_prefix . 'access_token'] = '';
     UpdraftPlus_Options::update_updraft_option($this->option_array, $opts);
     return true;
 }
Пример #11
0
<?php

if (!defined('UPDRAFTPLUS_DIR')) {
    die('No direct access allowed.');
}
require_once UPDRAFTPLUS_DIR . '/methods/s3.php';
# Migrate options to new-style storage - Jan 2014
if (!is_array(UpdraftPlus_Options::get_updraft_option('updraft_dreamobjects')) && '' != UpdraftPlus_Options::get_updraft_option('updraft_dreamobjects_login', '')) {
    $opts = array('accesskey' => UpdraftPlus_Options::get_updraft_option('updraft_dreamobjects_login'), 'secretkey' => UpdraftPlus_Options::get_updraft_option('updraft_dreamobjects_pass'), 'path' => UpdraftPlus_Options::get_updraft_option('updraft_dreamobjects_remote_path'));
    UpdraftPlus_Options::update_updraft_option('updraft_dreamobjects', $opts);
    UpdraftPlus_Options::delete_updraft_option('updraft_dreamobjects_login');
    UpdraftPlus_Options::delete_updraft_option('updraft_dreamobjects_pass');
    UpdraftPlus_Options::delete_updraft_option('updraft_dreamobjects_remote_path');
}
class UpdraftPlus_BackupModule_dreamobjects extends UpdraftPlus_BackupModule_s3
{
    protected function set_region($obj, $region, $bucket_name = '')
    {
        $config = $this->get_config();
        global $updraftplus;
        $updraftplus->log("Set endpoint: " . $config['endpoint']);
        $obj->setEndpoint($config['endpoint']);
    }
    public function get_credentials()
    {
        return array('updraft_dreamobjects');
    }
    protected function get_config()
    {
        global $updraftplus;
        $opts = $updraftplus->get_job_option('updraft_dreamobjects');
Пример #12
0
 /**
  * Delete the request and access tokens currently stored in the database
  * @return bool
  */
 public function delete()
 {
     $opts = UpdraftPlus_Options::get_updraft_option($this->option_array);
     $opts[$this->option_name_prefix . 'request_token'] = null;
     $opts[$this->option_name_prefix . 'access_token'] = null;
     unset($opts['ownername']);
     unset($opts['upgraded']);
     UpdraftPlus_Options::update_updraft_option($this->option_array, $opts);
     return true;
 }
Пример #13
0
 /**
  * Obtain user authorisation
  * The user will be redirected to Dropbox' web endpoint
  * @link http://tools.ietf.org/html/rfc5849#section-2.2
  * @return void
  */
 private function authorise()
 {
     // Only redirect if not using CLI
     if (PHP_SAPI !== 'cli' && (!defined('DOING_CRON') || !DOING_CRON) && (!defined('DOING_AJAX') || !DOING_AJAX)) {
         $url = $this->getAuthoriseUrl();
         if (!headers_sent()) {
             header('Location: ' . $url);
             exit;
         } else {
             throw new Dropbox_Exception(sprintf(__('The %s authentication could not go ahead, because something else on your site is breaking it. Try disabling your other plugins and switching to a default theme. (Specifically, you are looking for the component that sends output (most likely PHP warnings/errors) before the page begins. Turning off any debugging settings may also help).', 'updraftplus'), 'Dropbox'));
         }
         return false;
     }
     global $updraftplus;
     $updraftplus->log('Dropbox reauthorisation needed; but we are running from cron, AJAX or the CLI, so this is not possible');
     $opts = UpdraftPlus_Options::get_updraft_option("updraft_dropbox");
     $opts['tk_request_token'] = '';
     UpdraftPlus_Options::update_updraft_option("updraft_dropbox", $opts);
     throw new Dropbox_Exception(sprintf(__('You need to re-authenticate with %s, as your existing credentials are not working.', 'updraftplus'), 'Dropbox'));
     #$updraftplus->log(sprintf(__('You need to re-authenticate with %s, as your existing credentials are not working.', 'updraftplus'), 'Dropbox'), 'error');
     return false;
 }
Пример #14
0
 function rebuild_backup_history()
 {
     global $updraftplus;
     $known_files = array();
     $known_nonces = array();
     $changes = false;
     $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
     if (!is_array($backup_history)) {
         $backup_history = array();
     }
     $updraft_dir = $updraftplus->backups_dir_location();
     if (!is_dir($updraft_dir)) {
         return;
     }
     // Accumulate a list of known files
     foreach ($backup_history as $btime => $bdata) {
         $found_file = false;
         foreach ($bdata as $key => $values) {
             // Record which set this file is found in
             if (!is_array($values)) {
                 $values = array($values);
             }
             foreach ($values as $val) {
                 if (is_string($val) && preg_match('/^backup_([\\-0-9]{15})_.*_([0-9a-f]{12})-[\\-a-z]+([0-9]+(of[0-9]+)?)?+\\.(zip|gz|gz\\.crypt)$/i', $val, $matches)) {
                     $nonce = $matches[2];
                     if (isset($bdata['service']) && $bdata['service'] == 'none' && !is_file($updraft_dir . '/' . $val)) {
                         # File no longer present
                     } else {
                         $found_file = true;
                         $known_files[$val] = $nonce;
                         $known_nonces[$nonce] = $btime;
                     }
                 }
             }
         }
         if (!$found_file) {
             unset($backup_history[$btime]);
             $changes = true;
         }
     }
     if (!($handle = opendir($updraft_dir))) {
         return;
     }
     while (false !== ($entry = readdir($handle))) {
         if ($entry != "." && $entry != "..") {
             if (preg_match('/^backup_([\\-0-9]{15})_.*_([0-9a-f]{12})-([\\-a-z]+)([0-9]+(of[0-9]+)?)?\\.(zip|gz|gz\\.crypt)$/i', $entry, $matches)) {
                 $btime = strtotime($matches[1]);
                 if ($btime > 100) {
                     if (!isset($known_files[$entry])) {
                         $changes = true;
                         $nonce = $matches[2];
                         $type = $matches[3];
                         $index = empty($matches[4]) ? '0' : max((int) $matches[4] - 1, 0);
                         $itext = $index == 0 ? '' : $index;
                         // The time from the filename does not include seconds. Need to identify the seconds to get the right time
                         if (isset($known_nonces[$nonce])) {
                             $btime = $known_nonces[$nonce];
                         }
                         // No cloud backup known of this file
                         if (!isset($backup_history[$btime])) {
                             $backup_history[$btime] = array('service' => 'none');
                         }
                         $backup_history[$btime][$type][$index] = $entry;
                         $fs = @filesize($updraft_dir . '/' . $entry);
                         if (false !== $fs) {
                             $backup_history[$btime][$type . $itext . '-size'] = $fs;
                         }
                         $backup_history[$btime]['nonce'] = $nonce;
                     }
                 }
             }
         }
     }
     if ($changes) {
         UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backup_history);
     }
 }
Пример #15
0
 public function prune_retained_backups($services)
 {
     global $updraftplus, $wpdb;
     if ($updraftplus->jobdata_get('remotesend_info') != '') {
         $updraftplus->log("Prune old backups from local store: skipping, as this was a remote send operation");
         return;
     }
     if (method_exists($wpdb, 'check_connection')) {
         if (!$wpdb->check_connection(false)) {
             $updraftplus->reschedule(60);
             $updraftplus->log("It seems the database went away; scheduling a resumption and terminating for now");
             $updraftplus->record_still_alive();
             die;
         }
     }
     // If they turned off deletion on local backups, then there is nothing to do
     if (0 == UpdraftPlus_Options::get_updraft_option('updraft_delete_local') && 1 == count($services) && in_array('none', $services)) {
         $updraftplus->log("Prune old backups from local store: nothing to do, since the user disabled local deletion and we are using local backups");
         return;
     }
     $updraftplus->jobdata_set('jobstatus', 'pruning');
     // Number of backups to retain - files
     $updraft_retain = UpdraftPlus_Options::get_updraft_option('updraft_retain', 2);
     $updraft_retain = is_numeric($updraft_retain) ? $updraft_retain : 1;
     // Number of backups to retain - db
     $updraft_retain_db = UpdraftPlus_Options::get_updraft_option('updraft_retain_db', $updraft_retain);
     $updraft_retain_db = is_numeric($updraft_retain_db) ? $updraft_retain_db : 1;
     $updraftplus->log("Retain: beginning examination of existing backup sets; user setting: retain_files={$updraft_retain}, retain_db={$updraft_retain_db}");
     // Returns an array, most recent first, of backup sets
     $backup_history = $updraftplus->get_backup_history();
     $db_backups_found = 0;
     $file_backups_found = 0;
     $updraftplus->log("Number of backup sets in history: " . count($backup_history));
     $backupable_entities = $updraftplus->get_backupable_file_entities(true);
     $database_backups_found = array();
     $file_entities_backups_found = array();
     foreach ($backupable_entities as $entity => $info) {
         $file_entities_backups_found[$entity] = 0;
     }
     // The array returned by UpdraftPlus::get_backup_history() is already sorted, with most-recent first
     foreach ($backup_history as $backup_datestamp => $backup_to_examine) {
         $files_to_prune = array();
         // $backup_to_examine is an array of file names, keyed on db/plugins/themes/uploads
         // The new backup_history array is saved afterwards, so remember to unset the ones that are to be deleted
         $updraftplus->log(sprintf("Examining backup set with datestamp: %s (%s)", $backup_datestamp, gmdate('M d Y H:i:s', $backup_datestamp)));
         if (isset($backup_to_examine['native']) && false == $backup_to_examine['native']) {
             $updraftplus->log("This backup set ({$backup_datestamp}) was imported a remote location, so will not be counted or pruned. Skipping.");
             continue;
         }
         // Auto-backups are only counted or deleted once we have reached the retain limit - before that, they are skipped
         $is_autobackup = isset($backup_to_examine['autobackup']) && true == $backup_to_examine['autobackup'];
         $remote_sent = !empty($backup_to_examine['service']) && (is_array($backup_to_examine['service']) && in_array('remotesend', $backup_to_examine['service']) || 'remotesend' === $backup_to_examine['service']) ? true : false;
         # Databases
         foreach ($backup_to_examine as $key => $data) {
             if ('db' != strtolower(substr($key, 0, 2)) || '-size' == substr($key, -5, 5)) {
                 continue;
             }
             $how_many_found = empty($database_backups_found[$key]) ? 0 : $database_backups_found[$key];
             if ($is_autobackup && $how_many_found < $updraft_retain_db) {
                 $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, and we have not yet reached the retain limit, so it will not be counted or pruned. Skipping.");
                 continue;
             }
             $prune_it = false;
             if ($remote_sent) {
                 $prune_it = true;
                 $updraftplus->log("{$backup_datestamp}: {$key}: was sent to remote site; will remove from local record (only)");
             } else {
                 $database_backups_found[$key] = empty($database_backups_found[$key]) ? 1 : $database_backups_found[$key] + 1;
                 if ($database_backups_found[$key] > $updraft_retain_db) {
                     $prune_it = true;
                     $fname = is_string($data) ? $data : $data[0];
                     $updraftplus->log("{$backup_datestamp}: {$key}: this set includes a database (" . $fname . "); db count is now " . $database_backups_found[$key]);
                     $updraftplus->log("{$backup_datestamp}: {$key}: over retain limit ({$updraft_retain_db}); will delete this database");
                 }
             }
             if ($prune_it) {
                 // This should only be able to happen if you import backups with a future timestamp
                 if (!empty($backup_to_examine['nonce']) && $backup_to_examine['nonce'] == $updraftplus->nonce) {
                     $updraftplus->log("This backup set ({$backup_datestamp}) is the backup set just made, so will not be deleted.");
                 } else {
                     if (!empty($data)) {
                         foreach ($services as $service => $sd) {
                             $this->prune_file($service, $data, $sd[0], $sd[1]);
                         }
                     }
                     unset($backup_to_examine[$key]);
                     $updraftplus->record_still_alive();
                 }
             }
         }
         # Files
         foreach ($backupable_entities as $entity => $info) {
             if (!empty($backup_to_examine[$entity])) {
                 if ($is_autobackup && $file_entities_backups_found[$entity] < $updraft_retain) {
                     $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, and we have not yet reached the retain limit, so it will not be counted or pruned. Skipping.");
                     continue;
                 }
                 $prune_it = false;
                 if ($remote_sent) {
                     $prune_it = true;
                 } else {
                     $file_entities_backups_found[$entity]++;
                     if ($file_entities_backups_found[$entity] > $updraft_retain) {
                         $prune_it = true;
                     }
                 }
                 if ($prune_it) {
                     $prune_this = $backup_to_examine[$entity];
                     if (is_string($prune_this)) {
                         $prune_this = array($prune_this);
                     }
                     // This should only be able to happen if you import backups with a future timestamp
                     if (!empty($backup_to_examine['nonce']) && $backup_to_examine['nonce'] == $updraftplus->nonce) {
                         $updraftplus->log("This backup set ({$backup_datestamp}) is the backup set just made, so will not be deleted, despite being over the retain limit.");
                         continue;
                     }
                     foreach ($prune_this as $prune_file) {
                         if ($remote_sent) {
                             $updraftplus->log("{$entity}: {$backup_datestamp}: was sent to remote site; will remove from local record (only)");
                         } else {
                             $updraftplus->log("{$entity}: {$backup_datestamp}: over retain limit ({$updraft_retain}); will delete this file ({$prune_file})");
                         }
                         $files_to_prune[] = $prune_file;
                     }
                     unset($backup_to_examine[$entity]);
                 }
             }
         }
         # Actually delete the files
         foreach ($services as $service => $sd) {
             $this->prune_file($service, $files_to_prune, $sd[0], $sd[1]);
             $updraftplus->record_still_alive();
         }
         // Get new result, post-deletion; anything left in this set?
         $contains_files = 0;
         foreach ($backupable_entities as $entity => $info) {
             if (isset($backup_to_examine[$entity])) {
                 $contains_files = 1;
                 break;
             }
         }
         $contains_db = 0;
         foreach ($backup_to_examine as $key => $data) {
             if ('db' == strtolower(substr($key, 0, 2)) && '-size' != substr($key, -5, 5)) {
                 $contains_db = 1;
                 break;
             }
         }
         // Delete backup set completely if empty, o/w just remove DB
         // We search on the four keys which represent data, allowing other keys to be used to track other things
         if (!$contains_files && !$contains_db) {
             $updraftplus->log("{$backup_datestamp}: this backup set is now empty; will remove from history");
             unset($backup_history[$backup_datestamp]);
             if (isset($backup_to_examine['nonce'])) {
                 $fullpath = $this->updraft_dir . '/log.' . $backup_to_examine['nonce'] . '.txt';
                 if (is_file($fullpath)) {
                     $updraftplus->log("{$backup_datestamp}: deleting log file (log." . $backup_to_examine['nonce'] . ".txt)");
                     @unlink($fullpath);
                 } else {
                     $updraftplus->log("{$backup_datestamp}: corresponding log file not found - must have already been deleted");
                 }
             } else {
                 $updraftplus->log("{$backup_datestamp}: no nonce record found in the backup set, so cannot delete any remaining log file");
             }
         } else {
             $updraftplus->log("{$backup_datestamp}: this backup set remains non-empty ({$contains_files}/{$contains_db}); will retain in history");
             $backup_history[$backup_datestamp] = $backup_to_examine;
         }
         # Loop over backup sets
     }
     $updraftplus->log("Retain: saving new backup history (sets now: " . count($backup_history) . ") and finishing retain operation");
     UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backup_history, false);
 }
Пример #16
0
 function save_backup_history($backup_array)
 {
     if (is_array($backup_array)) {
         $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
         $backup_history = is_array($backup_history) ? $backup_history : array();
         $backup_array['nonce'] = $this->nonce;
         $backup_array['service'] = $this->jobdata_get('service');
         $backup_history[$this->backup_time] = $backup_array;
         UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backup_history);
     } else {
         $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');
     }
 }
Пример #17
0
 public function updraft_ajax_handler()
 {
     global $updraftplus;
     $nonce = empty($_REQUEST['nonce']) ? "" : $_REQUEST['nonce'];
     if (!wp_verify_nonce($nonce, 'updraftplus-credentialtest-nonce') || empty($_REQUEST['subaction'])) {
         die('Security check');
     }
     // Mitigation in case the nonce leaked to an unauthorised user
     if (isset($_REQUEST['subaction']) && 'dismissautobackup' == $_REQUEST['subaction']) {
         if (!current_user_can('update_plugins') && !current_user_can('update_themes')) {
             return;
         }
     } elseif (isset($_REQUEST['subaction']) && ('dismissexpiry' == $_REQUEST['subaction'] || 'dismissdashnotice' == $_REQUEST['subaction'])) {
         if (!current_user_can('update_plugins')) {
             return;
         }
     } else {
         if (!UpdraftPlus_Options::user_can_manage()) {
             return;
         }
     }
     // Some of this checks that _REQUEST['subaction'] is set, which is redundant (done already in the nonce check)
     if (isset($_REQUEST['subaction']) && 'lastlog' == $_REQUEST['subaction']) {
         echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', '(' . __('Nothing yet logged', 'updraftplus') . ')'));
     } elseif ('forcescheduledresumption' == $_REQUEST['subaction'] && !empty($_REQUEST['resumption']) && !empty($_REQUEST['job_id']) && is_numeric($_REQUEST['resumption'])) {
         // Casting $resumption to int is absolutely necessary, as the WP cron system uses a hashed serialisation of the parameters for identifying jobs. Different type => different hash => does not match
         $resumption = (int) $_REQUEST['resumption'];
         $job_id = $_REQUEST['job_id'];
         $get_cron = $this->get_cron($job_id);
         if (!is_array($get_cron)) {
             echo json_encode(array('r' => false));
         } else {
             $updraftplus->log("Forcing resumption: job id={$job_id}, resumption={$resumption}");
             $time = $get_cron[0];
             // 				wp_unschedule_event($time, 'updraft_backup_resume', array($resumption, $job_id));
             wp_clear_scheduled_hook('updraft_backup_resume', array($resumption, $job_id));
             $updraftplus->close_browser_connection(json_encode(array('r' => true)));
             $updraftplus->jobdata_set_from_array($get_cron[1]);
             $updraftplus->backup_resume($resumption, $job_id);
         }
     } elseif (isset($_GET['subaction']) && 'activejobs_list' == $_GET['subaction']) {
         $download_status = array();
         if (!empty($_GET['downloaders'])) {
             foreach (explode(':', $_GET['downloaders']) as $downloader) {
                 # prefix, timestamp, entity, index
                 if (preg_match('/^([^,]+),(\\d+),([-a-z]+|db[0-9]+),(\\d+)$/', $downloader, $matches)) {
                     $findex = empty($matches[4]) ? '0' : $matches[4];
                     $updraftplus->nonce = dechex($matches[2]) . $findex . substr(md5($matches[3]), 0, 3);
                     $updraftplus->jobdata_reset();
                     $status = $this->download_status($matches[2], $matches[3], $matches[4]);
                     if (is_array($status)) {
                         $status['base'] = $matches[1];
                         $status['timestamp'] = $matches[2];
                         $status['what'] = $matches[3];
                         $status['findex'] = $findex;
                         $download_status[] = $status;
                     }
                 }
             }
         }
         if (!empty($_GET['oneshot'])) {
             $job_id = get_site_option('updraft_oneshotnonce', false);
             // print_active_job() for one-shot jobs that aren't in cron
             $active_jobs = false === $job_id ? '' : $this->print_active_job($job_id, true);
         } elseif (!empty($_GET['thisjobonly'])) {
             // print_active_jobs() is for resumable jobs where we want the cron info to be included in the output
             $active_jobs = $this->print_active_jobs($_GET['thisjobonly']);
         } else {
             $active_jobs = $this->print_active_jobs();
         }
         $logupdate_array = array();
         if (!empty($_REQUEST['log_fetch'])) {
             if (isset($_REQUEST['log_nonce'])) {
                 $log_nonce = $_REQUEST['log_nonce'];
                 $log_pointer = isset($_REQUEST['log_pointer']) ? absint($_REQUEST['log_pointer']) : 0;
                 $logupdate_array = $this->fetch_log($log_nonce, $log_pointer);
             }
         }
         echo json_encode(array('l' => htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', '(' . __('Nothing yet logged', 'updraftplus') . ')')), 'j' => $active_jobs, 'ds' => $download_status, 'u' => $logupdate_array));
     } elseif (isset($_REQUEST['subaction']) && 'remotecontrol_createkey' == $_REQUEST['subaction']) {
         // Use the site URL - this means that if the site URL changes, communication ends; which is the case anyway
         $name_hash = md5(site_url());
         // 32 characters
         $created = $updraftplus->create_remote_control_key($name_hash);
         echo json_encode($created);
         die;
     } elseif (isset($_REQUEST['subaction']) && 'callwpaction' == $_REQUEST['subaction'] && !empty($_REQUEST['wpaction'])) {
         ob_start();
         $res = '<em>Request received: </em>';
         if (preg_match('/^([^:]+)+:(.*)$/', stripslashes($_REQUEST['wpaction']), $matches)) {
             $action = $matches[1];
             if (null === ($args = json_decode($matches[2], true))) {
                 $res .= "The parameters (should be JSON) could not be decoded";
                 $action = false;
             } else {
                 $res .= "Will despatch action: " . htmlspecialchars($action) . ", parameters: " . htmlspecialchars(implode(',', $args));
             }
         } else {
             $action = $_REQUEST['wpaction'];
             $res .= "Will despatch action: " . htmlspecialchars($action) . ", no parameters";
         }
         echo json_encode(array('r' => $res));
         $ret = ob_get_clean();
         ob_end_clean();
         $updraftplus->close_browser_connection($ret);
         if (!empty($action)) {
             if (!empty($args)) {
                 do_action_ref_array($action, $args);
             } else {
                 do_action($action);
             }
         }
         die;
     } elseif (isset($_REQUEST['subaction']) && 'whichdownloadsneeded' == $_REQUEST['subaction'] && is_array($_REQUEST['downloads']) && isset($_REQUEST['timestamp']) && is_numeric($_REQUEST['timestamp'])) {
         // The purpose of this is to look at the list of indicated downloads, and indicate which are not already fully downloaded. i.e. Which need further action.
         $send_back = array();
         $backup = $updraftplus->get_backup_history($_REQUEST['timestamp']);
         $updraft_dir = $updraftplus->backups_dir_location();
         $backupable_entities = $updraftplus->get_backupable_file_entities();
         if (empty($backup)) {
             echo json_encode(array('result' => 'asyouwere'));
         } else {
             foreach ($_REQUEST['downloads'] as $i => $download) {
                 if (is_array($download) && 2 == count($download) && isset($download[0]) && isset($download[1])) {
                     $entity = $download[0];
                     if (('db' == $entity || isset($backupable_entities[$entity])) && isset($backup[$entity])) {
                         $indexes = explode(',', $download[1]);
                         $retain_string = '';
                         foreach ($indexes as $index) {
                             $retain = true;
                             // default
                             $findex = 0 == $index ? '' : (string) $index;
                             $files = $backup[$entity];
                             if (!is_array($files)) {
                                 $files = array($files);
                             }
                             $size_key = $entity . $findex . '-size';
                             if (isset($files[$index]) && isset($backup[$size_key])) {
                                 $file = $updraft_dir . '/' . $files[$index];
                                 if (file_exists($file) && filesize($file) >= $backup[$size_key]) {
                                     $retain = false;
                                 }
                             }
                             if ($retain) {
                                 $retain_string .= '' === $retain_string ? $index : ',' . $index;
                                 $send_back[$i][0] = $entity;
                                 $send_back[$i][1] = $retain_string;
                             }
                         }
                     } else {
                         $send_back[$i][0] = $entity;
                         $send_back[$i][1] = $download[$i][1];
                     }
                 } else {
                     // Format not understood. Just send it back as-is.
                     $send_back[$i] = $download[$i];
                 }
             }
             // Finally, renumber the keys (to usual PHP style - 0, 1, ...). Otherwise, in order to preserve the indexes, json_encode() will create an object instead of an array in the case where $send_back only has one element (and is indexed with an index > 0)
             $send_back = array_values($send_back);
             echo json_encode(array('downloads' => $send_back));
         }
     } elseif (isset($_REQUEST['subaction']) && 'httpget' == $_REQUEST['subaction']) {
         if (empty($_REQUEST['uri'])) {
             echo json_encode(array('r' => ''));
             die;
         }
         $uri = $_REQUEST['uri'];
         if (!empty($_REQUEST['curl'])) {
             if (!function_exists('curl_exec')) {
                 echo json_encode(array('e' => 'No Curl installed'));
                 die;
             }
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $uri);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($ch, CURLOPT_FAILONERROR, true);
             curl_setopt($ch, CURLOPT_HEADER, true);
             curl_setopt($ch, CURLOPT_VERBOSE, true);
             curl_setopt($ch, CURLOPT_STDERR, $output = fopen('php://temp', "w+"));
             $response = curl_exec($ch);
             $error = curl_error($ch);
             $getinfo = curl_getinfo($ch);
             curl_close($ch);
             $resp = array();
             if (false === $response) {
                 $resp['e'] = htmlspecialchars($error);
                 # json_encode(array('e' => htmlspecialchars($error)));
             }
             $resp['r'] = empty($response) ? '' : htmlspecialchars(substr($response, 0, 2048));
             rewind($output);
             $verb = stream_get_contents($output);
             if (!empty($verb)) {
                 $resp['r'] = htmlspecialchars($verb) . "\n\n" . $resp['r'];
             }
             echo json_encode($resp);
             // 				echo json_encode(array('r' => htmlspecialchars(substr($response, 0, 2048))));
         } else {
             $response = wp_remote_get($uri, array('timeout' => 10));
             if (is_wp_error($response)) {
                 echo json_encode(array('e' => htmlspecialchars($response->get_error_message())));
                 die;
             }
             echo json_encode(array('r' => $response['response']['code'] . ': ' . htmlspecialchars(substr($response['body'], 0, 2048))));
         }
         die;
     } elseif (isset($_REQUEST['subaction']) && 'dismissautobackup' == $_REQUEST['subaction']) {
         UpdraftPlus_Options::update_updraft_option('updraftplus_dismissedautobackup', time() + 84 * 86400);
     } elseif (isset($_REQUEST['subaction']) && 'set_autobackup_default' == $_REQUEST['subaction']) {
         // This option when set should have integers, not bools
         $default = empty($_REQUEST['default']) ? 0 : 1;
         UpdraftPlus_Options::update_updraft_option('updraft_autobackup_default', $default);
     } elseif (isset($_REQUEST['subaction']) && 'dismissexpiry' == $_REQUEST['subaction']) {
         UpdraftPlus_Options::update_updraft_option('updraftplus_dismissedexpiry', time() + 14 * 86400);
     } elseif (isset($_REQUEST['subaction']) && 'dismissdashnotice' == $_REQUEST['subaction']) {
         UpdraftPlus_Options::update_updraft_option('updraftplus_dismisseddashnotice', time() + 366 * 86400);
     } elseif (isset($_REQUEST['subaction']) && 'poplog' == $_REQUEST['subaction']) {
         echo json_encode($this->fetch_log($_REQUEST['backup_nonce']));
     } elseif (isset($_REQUEST['subaction']) && 'restore_alldownloaded' == $_REQUEST['subaction'] && isset($_REQUEST['restoreopts']) && isset($_REQUEST['timestamp'])) {
         $backups = $updraftplus->get_backup_history();
         $updraft_dir = $updraftplus->backups_dir_location();
         $timestamp = (int) $_REQUEST['timestamp'];
         if (!isset($backups[$timestamp])) {
             echo json_encode(array('m' => '', 'w' => '', 'e' => __('No such backup set exists', 'updraftplus')));
             die;
         }
         $mess = array();
         parse_str($_REQUEST['restoreopts'], $res);
         if (isset($res['updraft_restore'])) {
             set_error_handler(array($this, 'get_php_errors'), E_ALL & ~E_STRICT);
             $elements = array_flip($res['updraft_restore']);
             $warn = array();
             $err = array();
             @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
             $max_execution_time = (int) @ini_get('max_execution_time');
             if ($max_execution_time > 0 && $max_execution_time < 61) {
                 $warn[] = sprintf(__('The PHP setup on this webserver allows only %s seconds for PHP to run, and does not allow this limit to be raised. If you have a lot of data to import, and if the restore operation times out, then you will need to ask your web hosting company for ways to raise this limit (or attempt the restoration piece-by-piece).', 'updraftplus'), $max_execution_time);
             }
             if (isset($backups[$timestamp]['native']) && false == $backups[$timestamp]['native']) {
                 $warn[] = __('This backup set was not known by UpdraftPlus to be created by the current WordPress installation, but was either found in remote storage, or was sent from a remote site.', 'updraftplus') . ' ' . __('You should make sure that this really is a backup set intended for use on this website, before you restore (rather than a backup set of an unrelated website).', 'updraftplus');
             }
             if (isset($elements['db'])) {
                 // Analyse the header of the database file + display results
                 list($mess2, $warn2, $err2, $info) = $updraftplus->analyse_db_file($timestamp, $res);
                 $mess = array_merge($mess, $mess2);
                 $warn = array_merge($warn, $warn2);
                 $err = array_merge($err, $err2);
                 foreach ($backups[$timestamp] as $bid => $bval) {
                     if ('db' != $bid && 'db' == substr($bid, 0, 2) && '-size' != substr($bid, -5, 5)) {
                         $warn[] = __('Only the WordPress database can be restored; you will need to deal with the external database manually.', 'updraftplus');
                         break;
                     }
                 }
             }
             $backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
             $backupable_plus_db = $backupable_entities;
             $backupable_plus_db['db'] = array('path' => 'path-unused', 'description' => __('Database', 'updraftplus'));
             if (!empty($backups[$timestamp]['meta_foreign'])) {
                 $foreign_known = apply_filters('updraftplus_accept_archivename', array());
                 if (!is_array($foreign_known) || empty($foreign_known[$backups[$timestamp]['meta_foreign']])) {
                     $err[] = sprintf(__('Backup created by unknown source (%s) - cannot be restored.', 'updraftplus'), $backups[$timestamp]['meta_foreign']);
                 } else {
                     // For some reason, on PHP 5.5 passing by reference in a single array stopped working with apply_filters_ref_array (though not with do_action_ref_array).
                     $backupable_plus_db = apply_filters_ref_array("updraftplus_importforeign_backupable_plus_db", array($backupable_plus_db, array($foreign_known[$backups[$timestamp]['meta_foreign']], &$mess, &$warn, &$err)));
                 }
             }
             foreach ($backupable_plus_db as $type => $entity_info) {
                 if (!isset($elements[$type])) {
                     continue;
                 }
                 $whatwegot = $backups[$timestamp][$type];
                 if (is_string($whatwegot)) {
                     $whatwegot = array($whatwegot);
                 }
                 $expected_index = 0;
                 $missing = '';
                 ksort($whatwegot);
                 $outof = false;
                 foreach ($whatwegot as $index => $file) {
                     if (preg_match('/\\d+of(\\d+)\\.zip/', $file, $omatch)) {
                         $outof = max($matches[1], 1);
                     }
                     if ($index != $expected_index) {
                         $missing .= $missing == '' ? 1 + $expected_index : "," . (1 + $expected_index);
                     }
                     if (!file_exists($updraft_dir . '/' . $file)) {
                         $err[] = sprintf(__('File not found (you need to upload it): %s', 'updraftplus'), $updraft_dir . '/' . $file);
                     } elseif (filesize($updraft_dir . '/' . $file) == 0) {
                         $err[] = sprintf(__('File was found, but is zero-sized (you need to re-upload it): %s', 'updraftplus'), $file);
                     } else {
                         $itext = 0 == $index ? '' : $index;
                         if (!empty($backups[$timestamp][$type . $itext . '-size']) && $backups[$timestamp][$type . $itext . '-size'] != filesize($updraft_dir . '/' . $file)) {
                             if (empty($warn['doublecompressfixed'])) {
                                 $warn[] = sprintf(__('File (%s) was found, but has a different size (%s) from what was expected (%s) - it may be corrupt.', 'updraftplus'), $file, filesize($updraft_dir . '/' . $file), $backups[$timestamp][$type . $itext . '-size']);
                             }
                         }
                         do_action_ref_array("updraftplus_checkzip_{$type}", array($updraft_dir . '/' . $file, &$mess, &$warn, &$err));
                     }
                     $expected_index++;
                 }
                 do_action_ref_array("updraftplus_checkzip_end_{$type}", array(&$mess, &$warn, &$err));
                 // Detect missing archives where they are missing from the end of the set
                 if ($outof > 0 && $expected_index < $outof) {
                     for ($j = $expected_index; $j < $outof; $j++) {
                         $missing .= $missing == '' ? 1 + $j : "," . (1 + $j);
                     }
                 }
                 if ('' != $missing) {
                     $warn[] = sprintf(__("This multi-archive backup set appears to have the following archives missing: %s", 'updraftplus'), $missing . ' (' . $entity_info['description'] . ')');
                 }
             }
             if (0 == count($err) && 0 == count($warn)) {
                 $mess_first = __('The backup archive files have been successfully processed. Now press Restore again to proceed.', 'updraftplus');
             } elseif (0 == count($err)) {
                 $mess_first = __('The backup archive files have been processed, but with some warnings. If all is well, then now press Restore again to proceed. Otherwise, cancel and correct any problems first.', 'updraftplus');
             } else {
                 $mess_first = __('The backup archive files have been processed, but with some errors. You will need to cancel and correct any problems before retrying.', 'updraftplus');
             }
             if (count($this->logged) > 0) {
                 foreach ($this->logged as $lwarn) {
                     $warn[] = $lwarn;
                 }
             }
             restore_error_handler();
             // Get the info if it hasn't already come from the DB scan
             if (!isset($info) || !is_array($info)) {
                 $info = array();
             }
             // Not all chracters can be json-encoded, and we don't need this potentially-arbitrary user-supplied info.
             unset($info['label']);
             if (!isset($info['created_by_version']) && !empty($backups[$timestamp]['created_by_version'])) {
                 $info['created_by_version'] = $backups[$timestamp]['created_by_version'];
             }
             if (!isset($info['multisite']) && !empty($backups[$timestamp]['multisite'])) {
                 $info['multisite'] = $backups[$timestamp]['multisite'];
             }
             echo json_encode(array('m' => '<p>' . $mess_first . '</p>' . implode('<br>', $mess), 'w' => implode('<br>', $warn), 'e' => implode('<br>', $err), 'i' => json_encode($info)));
         }
     } elseif ('vault_connect' == $_REQUEST['subaction'] && isset($_REQUEST['email']) && isset($_REQUEST['pass']) || 'vault_disconnect' == $_REQUEST['subaction'] || 'vault_recountquota' == $_REQUEST['subaction']) {
         require_once UPDRAFTPLUS_DIR . '/methods/updraftvault.php';
         $vault = new UpdraftPlus_BackupModule_updraftvault();
         call_user_func(array($vault, 'ajax_' . $_REQUEST['subaction']));
     } elseif (isset($_POST['backup_timestamp']) && 'deleteset' == $_REQUEST['subaction']) {
         $backups = $updraftplus->get_backup_history();
         $timestamps = (string) $_POST['backup_timestamp'];
         $timestamps = explode(',', $timestamps);
         $delete_remote = empty($_POST['delete_remote']) ? false : true;
         // You need a nonce before you can set job data. And we certainly don't yet have one.
         $updraftplus->backup_time_nonce();
         // Set the job type before logging, as there can be different logging destinations
         $updraftplus->jobdata_set('job_type', 'delete');
         $updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms);
         if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
             $updraftplus->logfile_open($updraftplus->nonce);
             set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT);
         }
         $updraft_dir = $updraftplus->backups_dir_location();
         $backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
         $local_deleted = 0;
         $remote_deleted = 0;
         $sets_removed = 0;
         foreach ($timestamps as $i => $timestamp) {
             if (!isset($backups[$timestamp])) {
                 echo json_encode(array('result' => 'error', 'message' => __('Backup set not found', 'updraftplus')));
                 die;
             }
             $nonce = isset($backups[$timestamp]['nonce']) ? $backups[$timestamp]['nonce'] : '';
             $delete_from_service = array();
             if ($delete_remote) {
                 // Locate backup set
                 if (isset($backups[$timestamp]['service'])) {
                     $services = is_string($backups[$timestamp]['service']) ? array($backups[$timestamp]['service']) : $backups[$timestamp]['service'];
                     if (is_array($services)) {
                         foreach ($services as $service) {
                             if ($service && $service != 'none' && $service != 'email') {
                                 $delete_from_service[] = $service;
                             }
                         }
                     }
                 }
             }
             $files_to_delete = array();
             foreach ($backupable_entities as $key => $ent) {
                 if (isset($backups[$timestamp][$key])) {
                     $files_to_delete[$key] = $backups[$timestamp][$key];
                 }
             }
             // Delete DB
             if (isset($backups[$timestamp]['db'])) {
                 $files_to_delete['db'] = $backups[$timestamp]['db'];
             }
             // Also delete the log
             if ($nonce && !UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
                 $files_to_delete['log'] = "log.{$nonce}.txt";
             }
             unset($backups[$timestamp]);
             $sets_removed++;
             UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backups);
             add_action('http_request_args', array($updraftplus, 'modify_http_options'));
             foreach ($files_to_delete as $key => $files) {
                 # Local deletion
                 if (is_string($files)) {
                     $files = array($files);
                 }
                 foreach ($files as $file) {
                     if (is_file($updraft_dir . '/' . $file)) {
                         if (@unlink($updraft_dir . '/' . $file)) {
                             $local_deleted++;
                         }
                     }
                 }
                 if ('log' != $key && count($delete_from_service) > 0) {
                     foreach ($delete_from_service as $service) {
                         if ('email' == $service) {
                             continue;
                         }
                         if (file_exists(UPDRAFTPLUS_DIR . "/methods/{$service}.php")) {
                             require_once UPDRAFTPLUS_DIR . "/methods/{$service}.php";
                         }
                         $objname = "UpdraftPlus_BackupModule_" . $service;
                         $deleted = -1;
                         if (class_exists($objname)) {
                             # TODO: Re-use the object (i.e. prevent repeated connection setup/teardown)
                             $remote_obj = new $objname();
                             $deleted = $remote_obj->delete($files);
                         }
                         if ($deleted === -1) {
                             //echo __('Did not know how to delete from this cloud service.', 'updraftplus');
                         } elseif ($deleted !== false) {
                             $remote_deleted = $remote_deleted + count($files);
                         } else {
                             // Do nothing
                         }
                     }
                 }
             }
             remove_action('http_request_args', array($updraftplus, 'modify_http_options'));
         }
         $message = sprintf(__('Backup sets removed: %d', 'updraftplus'), $sets_removed) . "\n";
         $message .= sprintf(__('Local archives deleted: %d', 'updraftplus'), $local_deleted) . "\n";
         $message .= sprintf(__('Remote archives deleted: %d', 'updraftplus'), $remote_deleted) . "\n";
         $updraftplus->log("Local archives deleted: " . $local_deleted);
         $updraftplus->log("Remote archives deleted: " . $remote_deleted);
         print json_encode(array('result' => 'success', 'message' => $message));
         if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
             restore_error_handler();
         }
     } elseif ('rawbackuphistory' == $_REQUEST['subaction']) {
         echo '<h3 id="ud-debuginfo-rawbackups">' . __('Known backups (raw)', 'updraftplus') . '</h3><pre>';
         var_dump($updraftplus->get_backup_history());
         echo '</pre>';
         echo '<h3 id="ud-debuginfo-files">Files</h3><pre>';
         $updraft_dir = $updraftplus->backups_dir_location();
         $raw_output = array();
         $d = dir($updraft_dir);
         while (false !== ($entry = $d->read())) {
             $fp = $updraft_dir . '/' . $entry;
             $mtime = filemtime($fp);
             if (is_dir($fp)) {
                 $size = '       d';
             } elseif (is_link($fp)) {
                 $size = '       l';
             } elseif (is_file($fp)) {
                 $size = sprintf("%8.1f", round(filesize($fp) / 1024, 1)) . ' ' . gmdate('r', $mtime);
             } else {
                 $size = '       ?';
             }
             if (preg_match('/^log\\.(.*)\\.txt$/', $entry, $lmatch)) {
                 $entry = '<a target="_top" href="?action=downloadlog&page=updraftplus&updraftplus_backup_nonce=' . htmlspecialchars($lmatch[1]) . '">' . $entry . '</a>';
             }
             $raw_output[$mtime] = empty($raw_output[$mtime]) ? sprintf("%s %s\n", $size, $entry) : $raw_output[$mtime] . sprintf("%s %s\n", $size, $entry);
         }
         @$d->close();
         krsort($raw_output, SORT_NUMERIC);
         foreach ($raw_output as $line) {
             echo $line;
         }
         echo '</pre>';
         echo '<h3 id="ud-debuginfo-options">' . __('Options (raw)', 'updraftplus') . '</h3>';
         $opts = $updraftplus->get_settings_keys();
         asort($opts);
         // <tr><th>'.__('Key','updraftplus').'</th><th>'.__('Value','updraftplus').'</th></tr>
         echo '<table><thead></thead><tbody>';
         foreach ($opts as $opt) {
             echo '<tr><td>' . htmlspecialchars($opt) . '</td><td>' . htmlspecialchars(print_r(UpdraftPlus_Options::get_updraft_option($opt), true)) . '</td>';
         }
         echo '</tbody></table>';
         do_action('updraftplus_showrawinfo');
     } elseif ('countbackups' == $_REQUEST['subaction']) {
         $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
         $backup_history = is_array($backup_history) ? $backup_history : array();
         #echo sprintf(__('%d set(s) available', 'updraftplus'), count($backup_history));
         echo __('Existing Backups', 'updraftplus') . ' (' . count($backup_history) . ')';
     } elseif ('ping' == $_REQUEST['subaction']) {
         // The purpose of this is to detect brokenness caused by extra line feeds in plugins/themes - before it breaks other AJAX operations and leads to support requests
         echo 'pong';
     } elseif ('checkoverduecrons' == $_REQUEST['subaction']) {
         $how_many_overdue = $this->howmany_overdue_crons();
         if ($how_many_overdue >= 4) {
             echo json_encode(array('m' => $this->show_admin_warning_overdue_crons($how_many_overdue)));
         }
     } elseif ('delete_old_dirs' == $_REQUEST['subaction']) {
         $this->delete_old_dirs_go(false);
     } elseif ('phpinfo' == $_REQUEST['subaction']) {
         phpinfo(INFO_ALL ^ (INFO_CREDITS | INFO_LICENSE));
         echo '<h3 id="ud-debuginfo-constants">' . __('Constants', 'updraftplus') . '</h3>';
         $opts = @get_defined_constants();
         ksort($opts);
         // <tr><th>'.__('Key','updraftplus').'</th><th>'.__('Value','updraftplus').'</th></tr>
         echo '<table><thead></thead><tbody>';
         foreach ($opts as $key => $opt) {
             echo '<tr><td>' . htmlspecialchars($key) . '</td><td>' . htmlspecialchars(print_r($opt, true)) . '</td>';
         }
         echo '</tbody></table>';
     } elseif ('doaction' == $_REQUEST['subaction'] && !empty($_REQUEST['subsubaction']) && 'updraft_' == substr($_REQUEST['subsubaction'], 0, 8)) {
         do_action($_REQUEST['subsubaction']);
     } elseif ('backupnow' == $_REQUEST['subaction']) {
         $backupnow_nocloud = empty($_REQUEST['backupnow_nocloud']) ? false : true;
         $event = !empty($_REQUEST['backupnow_nofiles']) ? 'updraft_backupnow_backup_database' : (!empty($_REQUEST['backupnow_nodb']) ? 'updraft_backupnow_backup' : 'updraft_backupnow_backup_all');
         // The call to backup_time_nonce() allows us to know the nonce in advance, and return it
         $nonce = $updraftplus->backup_time_nonce();
         $msg = json_encode(array('nonce' => $nonce, 'm' => '<strong>' . __('Start backup', 'updraftplus') . ':</strong> ' . htmlspecialchars(__('OK. You should soon see activity in the "Last log message" field below.', 'updraftplus'))));
         $updraftplus->close_browser_connection($msg);
         $options = array('nocloud' => $backupnow_nocloud, 'use_nonce' => $nonce);
         if (!empty($_REQUEST['onlythisfileentity']) && is_string($_REQUEST['onlythisfileentity'])) {
             // Something to see in the 'last log' field when it first appears, before the backup actually starts
             $updraftplus->log(__('Start backup', 'updraftplus'));
             $options['restrict_files_to_override'] = explode(',', $_REQUEST['onlythisfileentity']);
         }
         if (!empty($_REQUEST['extradata'])) {
             $options['extradata'] = $_REQUEST['extradata'];
         }
         do_action($event, apply_filters('updraft_backupnow_options', $options));
         # Old-style: schedule an event in 5 seconds time. This has the advantage of testing out the scheduler, and alerting the user if it doesn't work... but has the disadvantage of not working in that case.
         # I don't think the </div>s should be here - in case this is ever re-activated
         // 			if (wp_schedule_single_event(time()+5, $event, array($backupnow_nocloud)) === false) {
         // 				$updraftplus->log("A backup run failed to schedule");
         // 				echo __("Failed.", 'updraftplus')."</div>";
         // 			} else {
         // 				echo htmlspecialchars(__('OK. You should soon see activity in the "Last log message" field below.','updraftplus'))." <a href=\"https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/\"><br>".__('Nothing happening? Follow this link for help.','updraftplus')."</a></div>";
         // 				$updraftplus->log("A backup run has been scheduled");
         // 			}
     } elseif (isset($_GET['subaction']) && 'lastbackup' == $_GET['subaction']) {
         echo $this->last_backup_html();
     } elseif (isset($_GET['subaction']) && 'activejobs_delete' == $_GET['subaction'] && isset($_GET['jobid'])) {
         $cron = get_option('cron');
         $found_it = 0;
         foreach ($cron as $time => $job) {
             if (isset($job['updraft_backup_resume'])) {
                 foreach ($job['updraft_backup_resume'] as $hook => $info) {
                     if (isset($info['args'][1]) && $info['args'][1] == $_GET['jobid']) {
                         $args = $cron[$time]['updraft_backup_resume'][$hook]['args'];
                         wp_unschedule_event($time, 'updraft_backup_resume', $args);
                         if (!$found_it) {
                             echo json_encode(array('ok' => 'Y', 'm' => __('Job deleted', 'updraftplus')));
                         }
                         $found_it = 1;
                     }
                 }
             }
         }
         if (!$found_it) {
             echo json_encode(array('ok' => 'N', 'm' => __('Could not find that job - perhaps it has already finished?', 'updraftplus')));
         }
     } elseif (isset($_GET['subaction']) && 'diskspaceused' == $_GET['subaction'] && isset($_GET['entity'])) {
         if ('updraft' == $_GET['entity']) {
             echo $this->recursive_directory_size($updraftplus->backups_dir_location());
         } else {
             $backupable_entities = $updraftplus->get_backupable_file_entities(true, false);
             if ('all' == $_GET['entity']) {
                 $total_size = 0;
                 foreach ($backupable_entities as $entity => $data) {
                     # Might be an array
                     $basedir = $backupable_entities[$entity];
                     $dirs = apply_filters('updraftplus_dirlist_' . $entity, $basedir);
                     $size = $this->recursive_directory_size($dirs, $updraftplus->get_exclude($entity), $basedir, 'numeric');
                     if (is_numeric($size) && $size > 0) {
                         $total_size += $size;
                     }
                 }
                 echo $this->convert_numeric_size_to_text($total_size);
             } elseif (!empty($backupable_entities[$_GET['entity']])) {
                 # Might be an array
                 $basedir = $backupable_entities[$_GET['entity']];
                 $dirs = apply_filters('updraftplus_dirlist_' . $_GET['entity'], $basedir);
                 echo $this->recursive_directory_size($dirs, $updraftplus->get_exclude($_GET['entity']), $basedir);
             } else {
                 _e('Error', 'updraftplus');
             }
         }
     } elseif (isset($_GET['subaction']) && 'historystatus' == $_GET['subaction']) {
         $remotescan = isset($_GET['remotescan']) && $_GET['remotescan'] == 1;
         $rescan = $remotescan || isset($_GET['rescan']) && $_GET['rescan'] == 1;
         if ($rescan) {
             $messages = $updraftplus->rebuild_backup_history($remotescan);
         }
         $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
         $backup_history = is_array($backup_history) ? $backup_history : array();
         $output = $this->existing_backup_table($backup_history);
         if (!empty($messages) && is_array($messages)) {
             $noutput = '<div style="margin-left: 100px; margin-top: 10px;"><ul style="list-style: disc inside;">';
             foreach ($messages as $msg) {
                 $noutput .= '<li>' . ($msg['desc'] ? $msg['desc'] . ': ' : '') . '<em>' . $msg['message'] . '</em></li>';
             }
             $noutput .= '</ul></div>';
             $output = $noutput . $output;
         }
         // 			echo @json_encode(array('n' => sprintf(__('%d set(s) available', 'updraftplus'), count($backup_history)), 't' => $output));
         echo @json_encode(array('n' => sprintf(__('Existing Backups', 'updraftplus') . ' (%d)', count($backup_history)), 't' => $output, 'cksum' => md5($output)));
         // Legacy code
         // 		} elseif (isset($_GET['subaction']) && 'downloadstatus' == $_GET['subaction'] && isset($_GET['timestamp']) && isset($_GET['type'])) {
         //
         // 			$findex = (isset($_GET['findex'])) ? $_GET['findex'] : '0';
         // 			if (empty($findex)) $findex = '0';
         // 			$updraftplus->nonce = $_GET['timestamp'];
         //
         // 			echo json_encode($this->download_status($_GET['timestamp'], $_GET['type'], $findex));
         //
     } elseif (isset($_POST['subaction']) && $_POST['subaction'] == 'credentials_test') {
         $method = preg_match("/^[a-z0-9]+\$/", $_POST['method']) ? $_POST['method'] : "";
         require_once UPDRAFTPLUS_DIR . "/methods/{$method}.php";
         $objname = "UpdraftPlus_BackupModule_{$method}";
         $this->logged = array();
         # TODO: Add action for WP HTTP SSL stuff
         set_error_handler(array($this, 'get_php_errors'), E_ALL & ~E_STRICT);
         if (method_exists($objname, "credentials_test")) {
             $obj = new $objname();
             $obj->credentials_test();
         }
         if (count($this->logged) > 0) {
             echo "\n\n" . __('Messages:', 'updraftplus') . "\n";
             foreach ($this->logged as $err) {
                 echo "* {$err}\n";
             }
         }
         restore_error_handler();
     }
     die;
 }
Пример #18
0
 private function vault_connect($email, $password)
 {
     // Username and password set up?
     if (empty($email) || empty($password)) {
         return new WP_Error('blank_details', __('You need to supply both an email address and a password', 'updraftplus'));
     }
     global $updraftplus;
     // Use SSL to prevent snooping
     $result = wp_remote_post($this->vault_mothership . '/?udm_action=vault_connect', array('timeout' => 20, 'body' => array('e' => $email, 'p' => base64_encode($password), 'sid' => $updraftplus->siteid(), 'su' => base64_encode(home_url()))));
     if (is_wp_error($result) || false === $result) {
         return $result;
     }
     $response = json_decode($result['body'], true);
     if (!is_array($response) || !isset($response['mothership']) || !isset($response['loggedin'])) {
         if (preg_match('/has banned your IP address \\(([\\.:0-9a-f]+)\\)/', $result['body'], $matches)) {
             return new WP_Error('banned_ip', sprintf(__("UpdraftPlus.com has responded with 'Access Denied'.", 'updraftplus') . '<br>' . __("It appears that your web server's IP Address (%s) is blocked.", 'updraftplus') . ' ' . __('This most likely means that you share a webserver with a hacked website that has been used in previous attacks.', 'updraftplus') . '<br> <a href="https://updraftplus.com/unblock-ip-address/" target="_blank">' . __('To remove the block, please go here.', 'updraftplus') . '</a> ', $matches[1]));
         } else {
             return new WP_Error('unknown_response', sprintf(__('UpdraftPlus.Com returned a response which we could not understand (data: %s)', 'updraftplus'), $result['body']));
         }
     }
     switch ($response['loggedin']) {
         case 'connected':
             if (!empty($response['token'])) {
                 // Store it
                 $vault_settings = UpdraftPlus_Options::get_updraft_option('updraft_updraftvault');
                 if (!is_array($vault_settings)) {
                     $vault_settings = array();
                 }
                 $vault_settings['email'] = $email;
                 $vault_settings['token'] = (string) $response['token'];
                 $vault_settings['quota'] = -1;
                 unset($vault_settings['last_config']);
                 if (isset($response['quota'])) {
                     $vault_settings['quota'] = $response['quota'];
                 }
                 UpdraftPlus_Options::update_updraft_option('updraft_updraftvault', $vault_settings);
                 if (!empty($response['config']) && is_array($response['config']) && !empty($response['config']['accesskey'])) {
                     $this->vault_set_config($response['config']);
                 }
             } elseif (isset($response['quota']) && !$response['quota']) {
                 return new WP_Error('no_quota', __('You do not currently have any UpdraftPlus Vault quota', 'updraftplus'));
             } else {
                 return new WP_Error('unknown_response', __('UpdraftPlus.Com returned a response, but we could not understand it', 'updraftplus'));
             }
             break;
         case 'authfailed':
             if (!empty($response['authproblem'])) {
                 if ('invalidpassword' == $response['authproblem']) {
                     $authfail_error = new WP_Error('authfailed', __('Your email address was valid, but your password was not recognised by UpdraftPlus.Com.', 'updraftplus') . ' <a href="https://updraftplus.com/my-account/lost-password/">' . __('If you have forgotten your password, then go here to change your password on updraftplus.com.', 'updraftplus') . '</a>');
                     return $authfail_error;
                 } elseif ('invaliduser' == $response['authproblem']) {
                     return new WP_Error('authfailed', __('You entered an email address that was not recognised by UpdraftPlus.Com', 'updraftplus'));
                 }
             }
             return new WP_Error('authfailed', __('Your email address and password were not recognised by UpdraftPlus.Com', 'updraftplus'));
             break;
         default:
             return new WP_Error('unknown_response', __('UpdraftPlus.Com returned a response, but we could not understand it', 'updraftplus'));
             break;
     }
     return true;
 }
Пример #19
0
<?php

if (!defined('UPDRAFTPLUS_DIR')) {
    die('No direct access allowed.');
}
# Converted to array options: yes
# Converted to job_options: yes
# Migrate options to new-style storage - May 2014
if (!is_array(UpdraftPlus_Options::get_updraft_option('updraft_ftp')) && '' != UpdraftPlus_Options::get_updraft_option('updraft_server_address', '')) {
    $opts = array('user' => UpdraftPlus_Options::get_updraft_option('updraft_ftp_login'), 'pass' => UpdraftPlus_Options::get_updraft_option('updraft_ftp_pass'), 'host' => UpdraftPlus_Options::get_updraft_option('updraft_server_address'), 'path' => UpdraftPlus_Options::get_updraft_option('updraft_ftp_remote_path'), 'passive' => true);
    UpdraftPlus_Options::update_updraft_option('updraft_ftp', $opts);
    UpdraftPlus_Options::delete_updraft_option('updraft_server_address');
    UpdraftPlus_Options::delete_updraft_option('updraft_ftp_pass');
    UpdraftPlus_Options::delete_updraft_option('updraft_ftp_remote_path');
    UpdraftPlus_Options::delete_updraft_option('updraft_ftp_login');
}
class UpdraftPlus_BackupModule_ftp
{
    // Get FTP object with parameters set
    private function getFTP($server, $user, $pass, $disable_ssl = false, $disable_verify = true, $use_server_certs = false, $passive = true)
    {
        if ('' == trim($server) || '' == trim($user) || '' == trim($pass)) {
            return new WP_Error('no_settings', sprintf(__('No %s settings were found', 'updraftplus'), 'FTP'));
        }
        if (!class_exists('UpdraftPlus_ftp_wrapper')) {
            require_once UPDRAFTPLUS_DIR . '/includes/ftp.class.php';
        }
        $port = 21;
        if (preg_match('/^(.*):(\\d+)$/', $server, $matches)) {
            $server = $matches[1];
            $port = $matches[2];
Пример #20
0
 private function auth_request()
 {
     # &updraftcopycomparms=, because copy.com is dumb and always appends '?param=value' regardless of the supplied format...
     # i.e. we get sent back to somewhere like:
     # options-general.php?action=updraftmethod-copycom-auth&updraftcopycomparms=?oauth_token=(etc)&oauth_verifier=(etc)
     $callback_url = UpdraftPlus_Options::admin_page_url() . '?action=updraftmethod-copycom-auth&updraftcopycomparms=';
     $get_request = $this->storage->get('oauth/request?scope=' . $this->get_copycom_perms() . '&oauth_callback=' . urlencode($callback_url));
     if (!is_string($get_request)) {
         throw new Exception('Unexpected HTTP result returned (' . serialize($get_request) . ')');
     }
     parse_str($get_request, $result);
     # Also, there's oauth_callback_confirmed - not sure it's any use (it should be 'true')
     if (empty($result['oauth_token']) || empty($result['oauth_token_secret'])) {
         throw new Exception('Unexpected HTTP result returned (' . serialize($get_request) . ')');
     }
     # We will need this. But don't set token yet, as that is taken to indicate that all is finished
     $this->options['tokensecret'] = $result['oauth_token_secret'];
     UpdraftPlus_Options::update_updraft_option('updraft_copycom', $this->options);
     # Next: request an authorize screen
     #$auth_request = $this->storage->get('applications/authorize');
     # N.B. It's www.copy.com - not the api_url in the storage
     $authurl = 'https://www.copy.com/applications/authorize?oauth_token=' . urlencode($result['oauth_token']);
     # = wp_remote_get($this->storage->api_url.'?oauth_token='.urlencode($result['oauth_token']));
     #if (is_wp_error($auth_request))  { global $updraftplus; return $updraftplus->log_wp_error($auth_request, false, true); }
     if (!headers_sent()) {
         header('Location: ' . $authurl);
         exit;
     } else {
         throw new Exception(sprintf(__('The %s authentication could not go ahead, because something else on your site is breaking it. Try disabling your other plugins and switching to a default theme. (Specifically, you are looking for the component that sends output (most likely PHP warnings/errors) before the page begins. Turning off any debugging settings may also help).', 'updraftplus'), 'Copy.Com'));
     }
 }
Пример #21
0
 public function rebuild_backup_history($remotescan = false)
 {
     # TODO: Make compatible with incremental naming scheme
     global $updraftplus;
     $messages = array();
     $gmt_offset = get_option('gmt_offset');
     # Array of nonces keyed by filename
     $known_files = array();
     # Array of backup times keyed by nonce
     $known_nonces = array();
     $changes = false;
     $backupable_entities = $updraftplus->get_backupable_file_entities(true, false);
     $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
     if (!is_array($backup_history)) {
         $backup_history = array();
     }
     $updraft_dir = $updraftplus->backups_dir_location();
     if (!is_dir($updraft_dir)) {
         return;
     }
     $accept = apply_filters('updraftplus_accept_archivename', array());
     if (!is_array($accept)) {
         $accept = array();
     }
     // Process what is known from the database backup history; this means populating $known_files and $known_nonces
     foreach ($backup_history as $btime => $bdata) {
         $found_file = false;
         foreach ($bdata as $key => $values) {
             if ('db' != $key && !isset($backupable_entities[$key])) {
                 continue;
             }
             // Record which set this file is found in
             if (!is_array($values)) {
                 $values = array($values);
             }
             foreach ($values as $val) {
                 if (!is_string($val)) {
                     continue;
                 }
                 if (preg_match('/^backup_([\\-0-9]{15})_.*_([0-9a-f]{12})-[\\-a-z]+([0-9]+)?+(\\.(zip|gz|gz\\.crypt))?$/i', $val, $matches)) {
                     $nonce = $matches[2];
                     if (isset($bdata['service']) && ($bdata['service'] === 'none' || is_array($bdata['service']) && array('none') === $bdata['service']) && !is_file($updraft_dir . '/' . $val)) {
                         # File without remote storage is no longer present
                     } else {
                         $found_file = true;
                         $known_files[$val] = $nonce;
                         $known_nonces[$nonce] = empty($known_nonces[$nonce]) || $known_nonces[$nonce] < 100 ? $btime : min($btime, $known_nonces[$nonce]);
                     }
                 } else {
                     $accepted = false;
                     foreach ($accept as $fkey => $acc) {
                         if (preg_match('/' . $acc['pattern'] . '/i', $val)) {
                             $accepted = $fkey;
                         }
                     }
                     if (!empty($accepted) && false != ($btime = apply_filters('updraftplus_foreign_gettime', false, $fkey, $val)) && $btime > 0) {
                         $found_file = true;
                         # Generate a nonce; this needs to be deterministic and based on the filename only
                         $nonce = substr(md5($val), 0, 12);
                         $known_files[$val] = $nonce;
                         $known_nonces[$nonce] = empty($known_nonces[$nonce]) || $known_nonces[$nonce] < 100 ? $btime : min($btime, $known_nonces[$nonce]);
                     }
                 }
             }
         }
         if (!$found_file) {
             # File recorded as being without remote storage is no longer present - though it may in fact exist in remote storage, and this will be picked up later
             unset($backup_history[$btime]);
             $changes = true;
         }
     }
     $remotefiles = array();
     $remotesizes = array();
     # Scan remote storage and get back lists of files and their sizes
     # TODO: Make compatible with incremental naming
     if ($remotescan) {
         add_action('http_request_args', array($updraftplus, 'modify_http_options'));
         foreach ($updraftplus->backup_methods as $method => $desc) {
             require_once UPDRAFTPLUS_DIR . '/methods/' . $method . '.php';
             $objname = 'UpdraftPlus_BackupModule_' . $method;
             $obj = new $objname();
             if (!method_exists($obj, 'listfiles')) {
                 continue;
             }
             $files = $obj->listfiles('backup_');
             if (is_array($files)) {
                 foreach ($files as $entry) {
                     $n = $entry['name'];
                     if (!preg_match('/^backup_([\\-0-9]{15})_.*_([0-9a-f]{12})-([\\-a-z]+)([0-9]+)?(\\.(zip|gz|gz\\.crypt))?$/i', $n, $matches)) {
                         continue;
                     }
                     if (isset($remotefiles[$n])) {
                         $remotefiles[$n][] = $method;
                     } else {
                         $remotefiles[$n] = array($method);
                     }
                     if (!empty($entry['size'])) {
                         if (empty($remotesizes[$n]) || $remotesizes[$n] < $entry['size']) {
                             $remotesizes[$n] = $entry['size'];
                         }
                     }
                 }
             } elseif (is_wp_error($files)) {
                 foreach ($files->get_error_codes() as $code) {
                     if ('no_settings' == $code || 'no_addon' == $code || 'insufficient_php' == $code) {
                         continue;
                     }
                     $messages[] = array('method' => $method, 'desc' => $desc, 'code' => $code, 'message' => $files->get_error_message($code));
                 }
             }
         }
         remove_action('http_request_args', array($updraftplus, 'modify_http_options'));
     }
     if (!($handle = opendir($updraft_dir))) {
         return;
     }
     // See if there are any more files in the local directory than the ones already known about
     while (false !== ($entry = readdir($handle))) {
         $accepted_foreign = false;
         $potmessage = false;
         if ('.' == $entry || '..' == $entry) {
             continue;
         }
         # TODO: Make compatible with Incremental naming
         if (preg_match('/^backup_([\\-0-9]{15})_.*_([0-9a-f]{12})-([\\-a-z]+)([0-9]+)?(\\.(zip|gz|gz\\.crypt))?$/i', $entry, $matches)) {
             // Interpret the time as one from the blog's local timezone, rather than as UTC
             # $matches[1] is YYYY-MM-DD-HHmm, to be interpreted as being the local timezone
             $btime2 = strtotime($matches[1]);
             $btime = !empty($gmt_offset) ? $btime2 - $gmt_offset * 3600 : $btime2;
             $nonce = $matches[2];
             $type = $matches[3];
             if ('db' == $type) {
                 $type .= !empty($matches[4]) ? $matches[4] : '';
                 $index = 0;
             } else {
                 $index = empty($matches[4]) ? '0' : max((int) $matches[4] - 1, 0);
             }
             $itext = $index == 0 ? '' : $index;
         } elseif (false != ($accepted_foreign = apply_filters('updraftplus_accept_foreign', false, $entry)) && false !== ($btime = apply_filters('updraftplus_foreign_gettime', false, $accepted_foreign, $entry))) {
             $nonce = substr(md5($entry), 0, 12);
             $type = preg_match('/\\.sql(\\.(bz2|gz))?$/i', $entry) || preg_match('/-database-([-0-9]+)\\.zip$/i', $entry) ? 'db' : 'wpcore';
             $index = '0';
             $itext = '';
             $potmessage = array('code' => 'foundforeign_' . md5($entry), 'desc' => $entry, 'method' => '', 'message' => sprintf(__('Backup created by: %s.', 'updraftplus'), $accept[$accepted_foreign]['desc']));
         } elseif ('.zip' == strtolower(substr($entry, -4, 4)) || preg_match('/\\.sql(\\.(bz2|gz))?$/i', $entry)) {
             $potmessage = array('code' => 'possibleforeign_' . md5($entry), 'desc' => $entry, 'method' => '', 'message' => __('This file does not appear to be an UpdraftPlus backup archive (such files are .zip or .gz files which have a name like: backup_(time)_(site name)_(code)_(type).(zip|gz)).', 'updraftplus') . ' <a href="http://updraftplus.com/shop/updraftplus-premium/">' . __('If this is a backup created by a different backup plugin, then UpdraftPlus Premium may be able to help you.', 'updraftplus') . '</a>');
             $messages[$potmessage['code']] = $potmessage;
             continue;
         } else {
             continue;
         }
         // The time from the filename does not include seconds. Need to identify the seconds to get the right time
         if (isset($known_nonces[$nonce])) {
             $btime_exact = $known_nonces[$nonce];
             # TODO: If the btime we had was more than 60 seconds earlier, then this must be an increment - we then need to change the $backup_history array accordingly. We can pad the '60 second' test, as there's no option to run an increment more frequently than every 4 hours (though someone could run one manually from the CLI)
             if ($btime > 100 && $btime_exact - $btime > 60 && !empty($backup_history[$btime_exact])) {
                 # TODO: This needs testing
                 # The code below assumes that $backup_history[$btime] is presently empty
                 # Re-key array, indicating the newly-found time to be the start of the backup set
                 $backup_history[$btime] = $backup_history[$btime_exact];
                 unset($backup_history[$btime_exact]);
                 $btime_exact = $btime;
             }
             $btime = $btime_exact;
         }
         if ($btime <= 100) {
             continue;
         }
         $fs = @filesize($updraft_dir . '/' . $entry);
         if (!isset($known_files[$entry])) {
             $changes = true;
             if (is_array($potmessage)) {
                 $messages[$potmessage['code']] = $potmessage;
             }
             if ('db' == $type && !$accepted_foreign) {
                 list($mess, $warn, $err, $info) = $this->analyse_db_file(false, array(), $updraft_dir . '/' . $entry, true);
                 if (!empty($info['label'])) {
                     $backup_history[$btime]['label'] = $info['label'];
                 }
             }
         }
         # TODO: Code below here has not been reviewed or adjusted for compatibility with incremental backups
         # Make sure we have the right list of services
         $current_services = !empty($backup_history[$btime]) && !empty($backup_history[$btime]['service']) ? $backup_history[$btime]['service'] : array();
         if (is_string($current_services)) {
             $current_services = array($current_services);
         }
         if (!is_array($current_services)) {
             $current_services = array();
         }
         if (!empty($remotefiles[$entry])) {
             if (0 == count(array_diff($current_services, $remotefiles[$entry]))) {
                 $backup_history[$btime]['service'] = $remotefiles[$entry];
                 $changes = true;
             }
             # Get the right size (our local copy may be too small)
             foreach ($remotefiles[$entry] as $rem) {
                 if (!empty($rem['size']) && $rem['size'] > $fs) {
                     $fs = $rem['size'];
                     $changes = true;
                 }
             }
             # Remove from $remotefiles, so that we can later see what was left over
             unset($remotefiles[$entry]);
         } else {
             # Not known remotely
             if (!empty($backup_history[$btime])) {
                 if (empty($backup_history[$btime]['service']) || 'none' !== $backup_history[$btime]['service'] && '' !== $backup_history[$btime]['service'] && array('none') !== $backup_history[$btime]['service']) {
                     $backup_history[$btime]['service'] = 'none';
                     $changes = true;
                 }
             } else {
                 $backup_history[$btime]['service'] = 'none';
                 $changes = true;
             }
         }
         $backup_history[$btime][$type][$index] = $entry;
         if ($fs > 0) {
             $backup_history[$btime][$type . $itext . '-size'] = $fs;
         }
         $backup_history[$btime]['nonce'] = $nonce;
         if (!empty($accepted_foreign)) {
             $backup_history[$btime]['meta_foreign'] = $accepted_foreign;
         }
     }
     # Any found in remote storage that we did not previously know about?
     # Compare $remotefiles with $known_files / $known_nonces, and adjust $backup_history
     if (count($remotefiles) > 0) {
         # $backup_history[$btime]['nonce'] = $nonce
         foreach ($remotefiles as $file => $services) {
             if (!preg_match('/^backup_([\\-0-9]{15})_.*_([0-9a-f]{12})-([\\-a-z]+)([0-9]+)?(\\.(zip|gz|gz\\.crypt))?$/i', $file, $matches)) {
                 continue;
             }
             $nonce = $matches[2];
             $type = $matches[3];
             if ('db' == $type) {
                 $index = 0;
                 $type .= empty($matches[4]) ? $matches[4] : '';
             } else {
                 $index = empty($matches[4]) ? '0' : max((int) $matches[4] - 1, 0);
             }
             $itext = $index == 0 ? '' : $index;
             $btime2 = strtotime($matches[1]);
             $btime = !empty($gmt_offset) ? $btime2 - $gmt_offset * 3600 : $btime2;
             if (isset($known_nonces[$nonce])) {
                 $btime = $known_nonces[$nonce];
             }
             if ($btime <= 100) {
                 continue;
             }
             # Remember that at this point, we already know that the file is not known about locally
             if (isset($backup_history[$btime])) {
                 if (!isset($backup_history[$btime]['service']) || (is_array($backup_history[$btime]['service']) && $backup_history[$btime]['service'] !== $services || is_string($backup_history[$btime]['service']) && (1 != count($services) || $services[0] !== $backup_history[$btime]['service']))) {
                     $changes = true;
                     $backup_history[$btime]['service'] = $services;
                     $backup_history[$btime]['nonce'] = $nonce;
                 }
                 if (!isset($backup_history[$btime][$type][$index])) {
                     $changes = true;
                     $backup_history[$btime][$type][$index] = $file;
                     $backup_history[$btime]['nonce'] = $nonce;
                     if (!empty($remotesizes[$file])) {
                         $backup_history[$btime][$type . $itext . '-size'] = $remotesizes[$file];
                     }
                 }
             } else {
                 $changes = true;
                 $backup_history[$btime]['service'] = $services;
                 $backup_history[$btime][$type][$index] = $file;
                 $backup_history[$btime]['nonce'] = $nonce;
                 if (!empty($remotesizes[$file])) {
                     $backup_history[$btime][$type . $itext . '-size'] = $remotesizes[$file];
                 }
                 $backup_history[$btime]['native'] = false;
                 $messages['nonnative'] = array('message' => __('One or more backups has been added from scanning remote storage; note that these backups will not be automatically deleted through the "retain" settings; if/when you wish to delete them then you must do so manually.', 'updraftplus'), 'code' => 'nonnative', 'desc' => '', 'method' => '');
             }
         }
     }
     if ($changes) {
         UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backup_history);
     }
     return $messages;
 }
Пример #22
0
 public function prune_retained_backups($services)
 {
     global $updraftplus, $wpdb;
     if ($updraftplus->jobdata_get('remotesend_info') != '') {
         $updraftplus->log("Prune old backups from local store: skipping, as this was a remote send operation");
         return;
     }
     if (method_exists($wpdb, 'check_connection')) {
         if (!$wpdb->check_connection(false)) {
             $updraftplus->reschedule(60);
             $updraftplus->log("It seems the database went away; scheduling a resumption and terminating for now");
             $updraftplus->record_still_alive();
             die;
         }
     }
     // If they turned off deletion on local backups, then there is nothing to do
     if (0 == UpdraftPlus_Options::get_updraft_option('updraft_delete_local') && 1 == count($services) && in_array('none', $services)) {
         $updraftplus->log("Prune old backups from local store: nothing to do, since the user disabled local deletion and we are using local backups");
         return;
     }
     // 		$updraftplus->jobdata_set('jobstatus', 'pruning');
     // 		$updraftplus->jobdata_set('prune', 'begun');
     call_user_func_array(array($updraftplus, 'jobdata_set_multi'), array('jobstatus', 'pruning', 'prune', 'begun'));
     // Number of backups to retain - files
     $updraft_retain = UpdraftPlus_Options::get_updraft_option('updraft_retain', 2);
     $updraft_retain = is_numeric($updraft_retain) ? $updraft_retain : 1;
     // Number of backups to retain - db
     $updraft_retain_db = UpdraftPlus_Options::get_updraft_option('updraft_retain_db', $updraft_retain);
     $updraft_retain_db = is_numeric($updraft_retain_db) ? $updraft_retain_db : 1;
     $updraftplus->log("Retain: beginning examination of existing backup sets; user setting: retain_files={$updraft_retain}, retain_db={$updraft_retain_db}");
     // Returns an array, most recent first, of backup sets
     $backup_history = $updraftplus->get_backup_history();
     $db_backups_found = 0;
     $file_backups_found = 0;
     $updraftplus->log("Number of backup sets in history: " . count($backup_history));
     $backupable_entities = $updraftplus->get_backupable_file_entities(true);
     $database_backups_found = array();
     $file_entities_backups_found = array();
     foreach ($backupable_entities as $entity => $info) {
         $file_entities_backups_found[$entity] = 0;
     }
     // The array returned by UpdraftPlus::get_backup_history() is already sorted, with most-recent first
     foreach ($backup_history as $backup_datestamp => $backup_to_examine) {
         $files_to_prune = array();
         // $backup_to_examine is an array of file names, keyed on db/plugins/themes/uploads
         // The new backup_history array is saved afterwards, so remember to unset the ones that are to be deleted
         $updraftplus->log(sprintf("Examining backup set with datestamp: %s (%s)", $backup_datestamp, gmdate('M d Y H:i:s', $backup_datestamp)));
         if (isset($backup_to_examine['native']) && false == $backup_to_examine['native']) {
             $updraftplus->log("This backup set ({$backup_datestamp}) was imported from a remote location, so will not be counted or pruned. Skipping.");
             continue;
         }
         // Auto-backups are only counted or deleted once we have reached the retain limit - before that, they are skipped
         $is_autobackup = isset($backup_to_examine['autobackup']) && true == $backup_to_examine['autobackup'];
         $remote_sent = !empty($backup_to_examine['service']) && (is_array($backup_to_examine['service']) && in_array('remotesend', $backup_to_examine['service']) || 'remotesend' === $backup_to_examine['service']) ? true : false;
         $any_deleted_via_filter_yet = false;
         # Databases
         foreach ($backup_to_examine as $key => $data) {
             if ('db' != strtolower(substr($key, 0, 2)) || '-size' == substr($key, -5, 5)) {
                 continue;
             }
             if (empty($database_backups_found[$key])) {
                 $database_backups_found[$key] = 0;
             }
             if (!empty($backup_to_examine['nonce']) && $backup_to_examine['nonce'] == $updraftplus->nonce) {
                 $updraftplus->log("This backup set ({$backup_datestamp}) is the backup set just made, so will not be deleted.");
                 $database_backups_found[$key]++;
                 continue;
             }
             if ($is_autobackup) {
                 if ($any_deleted_via_filter_yet) {
                     $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, but we have previously deleted a backup due to a limit, so it will be pruned (but not counted towards numerical limits).");
                     $prune_it = true;
                 } elseif ($database_backups_found[$key] < $updraft_retain_db) {
                     $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, and we have not yet reached any retain limits, so it will not be counted or pruned. Skipping.");
                     continue;
                 } else {
                     $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, and we have already reached retain limits, so it will be pruned.");
                     $prune_it = true;
                 }
             } else {
                 $prune_it = false;
             }
             if ($remote_sent) {
                 $prune_it = true;
                 $updraftplus->log("{$backup_datestamp}: {$key}: was sent to remote site; will remove from local record (only)");
             }
             // All non-auto backups must be run through this filter (in date order) regardless of the current state of $prune_it - so that filters are able to track state.
             $prune_it_before_filter = $prune_it;
             if (!$is_autobackup) {
                 $prune_it = apply_filters('updraftplus_prune_or_not', $prune_it, 'db', $backup_datestamp, $database_backups_found[$key], $key, $data, $updraft_retain_db);
             }
             // Apply the final retention limit list (do not increase the 'retained' counter before seeing if the backup is being pruned for some other reason)
             if (!$prune_it && !$is_autobackup) {
                 if ($database_backups_found[$key] + 1 > $updraft_retain_db) {
                     $prune_it = true;
                     $fname = is_string($data) ? $data : $data[0];
                     $updraftplus->log("{$backup_datestamp}: {$key}: this set includes a database (" . $fname . "); db count is now " . $database_backups_found[$key]);
                     $updraftplus->log("{$backup_datestamp}: {$key}: over retain limit ({$updraft_retain_db}); will delete this database");
                 }
             }
             if ($prune_it) {
                 if (!$prune_it_before_filter) {
                     $any_deleted_via_filter_yet = true;
                 }
                 if (!empty($data)) {
                     $size_key = $key . '-size';
                     $size = isset($backup_to_examine[$size_key]) ? $backup_to_examine[$size_key] : null;
                     foreach ($services as $service => $sd) {
                         $this->prune_file($service, $data, $sd[0], $sd[1], array($size));
                     }
                 }
                 unset($backup_to_examine[$key]);
                 $updraftplus->record_still_alive();
             } elseif (!$is_autobackup) {
                 $database_backups_found[$key]++;
             }
         }
         $any_deleted_via_filter_yet = false;
         $file_sizes = array();
         # Files
         foreach ($backupable_entities as $entity => $info) {
             if (!empty($backup_to_examine[$entity])) {
                 // This should only be able to happen if you import backups with a future timestamp
                 if (!empty($backup_to_examine['nonce']) && $backup_to_examine['nonce'] == $updraftplus->nonce) {
                     $updraftplus->log("This backup set ({$backup_datestamp}) is the backup set just made, so will not be deleted, despite being over the retain limit.");
                     $file_entities_backups_found[$entity]++;
                     continue;
                 }
                 if ($is_autobackup) {
                     if ($any_deleted_via_filter_yet) {
                         $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, but we have previously deleted a backup due to a limit, so it will be pruned (but not counted towards numerical limits).");
                         $prune_it = true;
                     } elseif ($file_entities_backups_found[$entity] < $updraft_retain) {
                         $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, and we have not yet reached any retain limits, so it will not be counted or pruned. Skipping.");
                         continue;
                     } else {
                         $updraftplus->log("This backup set ({$backup_datestamp}) was an automatic backup, and we have already reached retain limits, so it will be pruned.");
                         $prune_it = true;
                     }
                 } else {
                     $prune_it = false;
                 }
                 if ($remote_sent) {
                     $prune_it = true;
                 }
                 // All non-auto backups must be run through this filter (in date order) regardless of the current state of $prune_it - so that filters are able to track state.
                 $prune_it_before_filter = $prune_it;
                 if (!$is_autobackup) {
                     $prune_it = apply_filters('updraftplus_prune_or_not', $prune_it, 'files', $backup_datestamp, $file_entities_backups_found[$entity], $entity, $data, $updraft_retain);
                 }
                 // The "more than maximum to keep?" counter should not be increased until we actually know that the set is being kept. Before verison 1.11.22, we checked this before running the filter, which resulted in the counter being increased for sets that got pruned via the filter (i.e. not kept) - and too many backups were thus deleted
                 if (!$prune_it && !$is_autobackup) {
                     if ($file_entities_backups_found[$entity] >= $updraft_retain) {
                         $updraftplus->log("{$entity}: {$backup_datestamp}: over retain limit ({$updraft_retain}); will delete this file entity");
                         $prune_it = true;
                     }
                 }
                 if ($prune_it) {
                     if (!$prune_it_before_filter) {
                         $any_deleted_via_filter_yet = true;
                     }
                     $prune_this = $backup_to_examine[$entity];
                     if (is_string($prune_this)) {
                         $prune_this = array($prune_this);
                     }
                     foreach ($prune_this as $k => $prune_file) {
                         if ($remote_sent) {
                             $updraftplus->log("{$entity}: {$backup_datestamp}: was sent to remote site; will remove from local record (only)");
                         }
                         $size_key = 0 == $k ? $entity . '-size' : $entity . $k . '-size';
                         $size = isset($backup_to_examine[$size_key]) ? $backup_to_examine[$size_key] : null;
                         $files_to_prune[] = $prune_file;
                         $file_sizes[] = $size;
                     }
                     unset($backup_to_examine[$entity]);
                 } elseif (!$is_autobackup) {
                     $file_entities_backups_found[$entity]++;
                 }
             }
         }
         // Sending an empty array is not itself a problem - except that the remote storage method may not check that before setting up a connection, which can waste time: especially if this is done every time around the loop.
         if (!empty($files_to_prune)) {
             # Actually delete the files
             foreach ($services as $service => $sd) {
                 $this->prune_file($service, $files_to_prune, $sd[0], $sd[1], $file_sizes);
                 $updraftplus->record_still_alive();
             }
         }
         // Get new result, post-deletion; anything left in this set?
         $contains_files = 0;
         foreach ($backupable_entities as $entity => $info) {
             if (isset($backup_to_examine[$entity])) {
                 $contains_files = 1;
                 break;
             }
         }
         $contains_db = 0;
         foreach ($backup_to_examine as $key => $data) {
             if ('db' == strtolower(substr($key, 0, 2)) && '-size' != substr($key, -5, 5)) {
                 $contains_db = 1;
                 break;
             }
         }
         // Delete backup set completely if empty, o/w just remove DB
         // We search on the four keys which represent data, allowing other keys to be used to track other things
         if (!$contains_files && !$contains_db) {
             $updraftplus->log("{$backup_datestamp}: this backup set is now empty; will remove from history");
             unset($backup_history[$backup_datestamp]);
             if (isset($backup_to_examine['nonce'])) {
                 $fullpath = $this->updraft_dir . '/log.' . $backup_to_examine['nonce'] . '.txt';
                 if (is_file($fullpath)) {
                     $updraftplus->log("{$backup_datestamp}: deleting log file (log." . $backup_to_examine['nonce'] . ".txt)");
                     @unlink($fullpath);
                 } else {
                     $updraftplus->log("{$backup_datestamp}: corresponding log file not found - must have already been deleted");
                 }
             } else {
                 $updraftplus->log("{$backup_datestamp}: no nonce record found in the backup set, so cannot delete any remaining log file");
             }
         } else {
             $updraftplus->log("{$backup_datestamp}: this backup set remains non-empty ({$contains_files}/{$contains_db}); will retain in history");
             $backup_history[$backup_datestamp] = $backup_to_examine;
         }
         # Loop over backup sets
     }
     $updraftplus->log("Retain: saving new backup history (sets now: " . count($backup_history) . ") and finishing retain operation");
     UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backup_history, false);
     $updraftplus->jobdata_set('prune', 'finished');
 }
Пример #23
0
 public function save_settings($settings)
 {
     global $updraftplus;
     // Make sure that settings filters are registered
     UpdraftPlus_Options::admin_init();
     $return_array = array('saved' => true, 'changed' => array());
     $add_to_post_keys = array('updraft_interval', 'updraft_interval_database', 'updraft_starttime_files', 'updraft_starttime_db', 'updraft_startday_files', 'updraft_startday_db');
     //If database and files are on same schedule, override the db day/time settings
     if (isset($settings['updraft_interval_database']) && isset($settings['updraft_interval_database']) && $settings['updraft_interval_database'] == $settings['updraft_interval'] && isset($settings['updraft_starttime_files'])) {
         $settings['updraft_starttime_db'] = $settings['updraft_starttime_files'];
         $settings['updraft_startday_db'] = $settings['updraft_startday_files'];
     }
     foreach ($add_to_post_keys as $key) {
         // For add-ons that look at $_POST to find saved settings, add the relevant keys to $_POST so that they find them there
         if (isset($settings[$key])) {
             $_POST[$key] = $settings[$key];
         }
     }
     // Wipe the extra retention rules, as they are not saved correctly if the last one is deleted
     UpdraftPlus_Options::update_updraft_option('updraft_retain_extrarules', array());
     UpdraftPlus_Options::update_updraft_option('updraft_email', array());
     UpdraftPlus_Options::update_updraft_option('updraft_report_warningsonly', array());
     UpdraftPlus_Options::update_updraft_option('updraft_report_wholebackup', array());
     UpdraftPlus_Options::update_updraft_option('updraft_extradbs', array());
     UpdraftPlus_Options::update_updraft_option('updraft_include_more_path', array());
     $relevant_keys = $updraftplus->get_settings_keys();
     if (method_exists('UpdraftPlus_Options', 'mass_options_update')) {
         $settings = UpdraftPlus_Options::mass_options_update($settings);
         $mass_updated = true;
     }
     foreach ($settings as $key => $value) {
         // 			$exclude_keys = array('option_page', 'action', '_wpnonce', '_wp_http_referer');
         // 			if (!in_array($key, $exclude_keys)) {
         if (in_array($key, $relevant_keys)) {
             if ($key == "updraft_service" && is_array($value)) {
                 foreach ($value as $subkey => $subvalue) {
                     if ($subvalue == '0') {
                         unset($value[$subkey]);
                     }
                 }
             }
             $updated = empty($mass_updated) ? UpdraftPlus_Options::update_updraft_option($key, $value) : true;
             // Add information on what has changed to array to loop through to update links etc.
             if ($updated) {
                 $return_array['changed'][$key] = $value;
             } elseif (empty($mass_updated) && $key == 'updraft_interval') {
                 //To schedule a database when the interval is not changed.
                 $updraftplus->schedule_backup($value);
             } elseif (empty($mass_updated) && $key == 'updraft_interval_database') {
                 $updraftplus->schedule_backup_database($value);
             }
         } else {
             // When last active, it was catching: option_page, action, _wpnonce, _wp_http_referer, updraft_s3_endpoint, updraft_dreamobjects_endpoint. The latter two are empty; probably don't need to be in the page at all.
             //error_log("Non-UD key when saving from POSTed data: ".$key);
         }
     }
     // Checking for various possible messages
     $updraft_dir = $updraftplus->backups_dir_location(false);
     $really_is_writable = $updraftplus->really_is_writable($updraft_dir);
     $dir_info = $this->really_writable_message($really_is_writable, $updraft_dir);
     $button_title = esc_attr(__('This button is disabled because your backup directory is not writable (see the settings).', 'updraftplus'));
     $return_array['backup_now_message'] = $this->backup_now_remote_message();
     $return_array['backup_dir'] = array('writable' => $really_is_writable, 'message' => $dir_info, 'button_title' => $button_title);
     //Because of the single AJAX call, we need to remove the existing UD messages from the 'all_admin_notices' action
     remove_all_actions('all_admin_notices');
     //Moving from 2 to 1 ajax call
     ob_start();
     $service = UpdraftPlus_Options::get_updraft_option('updraft_service');
     $this->setup_all_admin_notices_global($service);
     $this->setup_all_admin_notices_udonly($service);
     do_action('all_admin_notices');
     if (!$really_is_writable) {
         //Check if writable
         $this->show_admin_warning_unwritable();
     }
     if ($return_array['saved'] == true) {
         //
         $this->show_admin_warning(__('Your settings have been saved.', 'updraftplus'), 'updated fade');
     }
     $messages_output = ob_get_contents();
     ob_clean();
     // Backup schedule output
     $this->next_scheduled_backups_output();
     $scheduled_output = ob_get_clean();
     $return_array['messages'] = $messages_output;
     $return_array['scheduled'] = $scheduled_output;
     return $return_array;
 }
Пример #24
0
 private function create_remote_control_key($index = false, $extra_info = array(), $post_it = false)
 {
     global $updraftplus;
     $our_keys = UpdraftPlus_Options::get_updraft_option('updraft_central_localkeys');
     if (!is_array($our_keys)) {
         $our_keys = array();
     }
     if (false === $index) {
         if (empty($our_keys)) {
             $index = 0;
         } else {
             $index = max(array_keys($our_keys)) + 1;
         }
     }
     $name_hash = $index;
     if (isset($our_keys[$name_hash])) {
         unset($our_keys[$name_hash]);
     }
     $indicator_name = $this->indicator_name_from_index($name_hash);
     $ud_rpc = $updraftplus->get_udrpc($indicator_name);
     $send_to_updraftpluscom = false;
     if ('__updraftpluscom' == $post_it) {
         $send_to_updraftpluscom = true;
         $post_it = defined('UPDRAFTPLUS_OVERRIDE_UDCOM_DESTINATION') ? UPDRAFTPLUS_OVERRIDE_UDCOM_DESTINATION : 'https://updraftplus.com/?updraftcentral_action=receive_key';
         $post_it_description = 'UpdraftPlus.Com';
     } else {
         $post_it_description = $post_it;
     }
     // Normally, key generation takes seconds, even on a slow machine. However, some Windows machines appear to have a setup in which it takes a minute or more. And then, if you're on a double-localhost setup on slow hardware - even worse. It doesn't hurt to just raise the maximum execution time.
     @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
     $key_size = empty($extra_info['key_size']) || !is_numeric($extra_info['key_size']) || $extra_info['key_size'] < 512 ? 2048 : (int) $extra_info['key_size'];
     // 		unset($extra_info['key_size']);
     if (is_object($ud_rpc) && $ud_rpc->generate_new_keypair($key_size)) {
         if ($post_it && empty($extra_info['mothership_firewalled'])) {
             $p_url = parse_url($post_it);
             if (is_array($p_url) && !empty($p_url['user'])) {
                 $http_username = $p_url['user'];
                 $http_password = empty($p_url['pass']) ? '' : $p_url['pass'];
                 $post_it = $p_url['scheme'] . '://' . $p_url['host'];
                 if (!empty($p_url['port'])) {
                     $post_it .= ':' . $p_url['port'];
                 }
                 $post_it .= $p_url['path'];
                 if (!empty($p_url['query'])) {
                     $post_it .= '?' . $p_url['query'];
                 }
             }
             $post_options = array('timeout' => 90, 'body' => array('updraftcentral_action' => 'receive_key', 'key' => $ud_rpc->get_key_remote()));
             if (!empty($http_username)) {
                 $post_options['headers'] = array('Authorization' => 'Basic ' . base64_encode($http_username . ':' . $http_password));
             }
             // This option allows the key to be sent to the other side via a known-secure channel (e.g. http over SSL), rather than potentially allowing it to travel over an unencrypted channel (e.g. http back to the user's browser). As such, if specified, it is compulsory for it to work.
             $sent_key = wp_remote_post($post_it, $post_options);
             if (is_wp_error($sent_key) || empty($sent_key)) {
                 $err_msg = sprintf(__('A key was created, but the attempt to register it with %s was unsuccessful - please try again later.', 'updraftplus'), (string) $post_it_description);
                 if (is_wp_error($sent_key)) {
                     $err_msg .= ' ' . $sent_key->get_error_message() . ' (' . $sent_key->get_error_code() . ')';
                 }
                 return array('r' => $err_msg);
             }
             $response = json_decode(wp_remote_retrieve_body($sent_key), true);
             if (!is_array($response) || !isset($response['key_id']) || !isset($response['key_public'])) {
                 return array('r' => sprintf(__('A key was created, but the attempt to register it with %s was unsuccessful - please try again later.', 'updraftplus'), (string) $post_it_description), 'raw' => wp_remote_retrieve_body($sent_key));
             }
             $key_hash = hash('sha256', $ud_rpc->get_key_remote());
             $local_bundle = $ud_rpc->get_portable_bundle('base64_with_count', $extra_info, array('key' => array('key_hash' => $key_hash, 'key_id' => $response['key_id'])));
         } elseif ($post_it) {
             // Don't send; instead, include in the bundle info that the mothership is firewalled; this will then tell the mothership to try the reverse connection instead
             if (is_array($extra_info)) {
                 $extra_info['mothership_firewalled_callback_url'] = wp_nonce_url(admin_url('admin-ajax.php'), 'updraftcentral_receivepublickey');
                 $extra_info['updraft_key_index'] = $index;
             }
             $local_bundle = $ud_rpc->get_portable_bundle('base64_with_count', $extra_info, array('key' => $ud_rpc->get_key_remote()));
         }
         if (isset($extra_info['name'])) {
             $name = (string) $extra_info['name'];
             unset($extra_info['name']);
         } else {
             $name = 'UpdraftCentral Remote Control';
         }
         $our_keys[$name_hash] = array('name' => $name, 'key' => $ud_rpc->get_key_local(), 'extra_info' => $extra_info, 'created' => time());
         // Store the other side's public key
         if (!empty($response) && is_array($response) && !empty($response['key_public'])) {
             $our_keys[$name_hash]['publickey_remote'] = $response['key_public'];
         }
         UpdraftPlus_Options::update_updraft_option('updraft_central_localkeys', $our_keys);
         return array('bundle' => $local_bundle, 'r' => __('Key created successfully.', 'updraftplus') . ' ' . __('You must copy and paste this key now - it cannot be shown again.', 'updraftplus'));
     }
     return false;
 }
Пример #25
0
 public function admin_init()
 {
     if (empty($_POST['updraft_unlockadmin_session_length']) && empty($_POST['updraft_unlockadmin_password']) || empty($_POST['nonce'])) {
         return;
     }
     if (!wp_verify_nonce($_POST['nonce'], 'updraftplus-unlockadmin-nonce')) {
         return;
     }
     $user = wp_get_current_user();
     if (!is_a($user, 'WP_User')) {
         return;
     }
     $this->get_opts();
     if (!empty($_POST['updraft_unlockadmin_session_length']) && isset($_POST['updraft_unlockadmin_oldpassword']) && $_POST['updraft_unlockadmin_oldpassword'] == $this->opts['password']) {
         $this->old_password = $this->opts['password'];
         $this->opts['password'] = $_POST['updraft_unlockadmin_password'];
         $this->opts['support_url'] = $_POST['updraft_unlockadmin_support_url'];
         $this->opts['session_length'] = (int) $_POST['updraft_unlockadmin_session_length'];
         UpdraftPlus_Options::update_updraft_option('updraft_adminlocking', $this->opts);
         $this->password_length = strlen($this->opts['password']);
         add_action('all_admin_notices', array($this, 'show_admin_warning_passwordset'));
     }
     // Note: this code also fires when the user sets a new password (because we don't want to immediately lock them)
     $password = $this->opts['password'];
     if ($password === (string) $_POST['updraft_unlockadmin_password']) {
         $session_length = (int) $this->opts['session_length'];
         if ($session_length < 1) {
             $session_length = 86400;
         }
         // The cookie relies on the user ID, password and session time. So, someone stealing the cookie can't use it forever. They need the password to generate valid cookies.
         $time_now = time();
         $expire = $time_now + $session_length;
         $cookie_session_began = $time_now - $time_now % $session_length;
         $correct_hash = hash('sha256', $user->ID . '-' . $password . '-' . $cookie_session_began);
         $secure = apply_filters('secure_auth_cookie', is_ssl(), $user->ID);
         setcookie('updraft_unlockadmin', $cookie_session_began . ':' . $correct_hash, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
         $this->correct_password_supplied = true;
     } else {
         $this->correct_password_supplied = false;
     }
 }
Пример #26
0
 public function get_setting_and_check_default_setting_save()
 {
     # Do not use bools here - conflicts with get_option() with a non-default value
     $autobackup = isset($_REQUEST['updraft_autobackup']) && $_REQUEST['updraft_autobackup'] == 'yes' ? 1 : 0;
     if (!empty($_REQUEST['updraft_autobackup_setdefault']) && 'yes' == $_REQUEST['updraft_autobackup_setdefault']) {
         UpdraftPlus_Options::update_updraft_option('updraft_autobackup_default', $autobackup);
     }
     return $autobackup;
 }
Пример #27
0
<?php

if (!defined('UPDRAFTPLUS_DIR')) {
    die('No direct access allowed.');
}
require_once UPDRAFTPLUS_DIR . '/methods/s3.php';
# Migrate options to new-style storage - Jan 2014
if (!is_array(UpdraftPlus_Options::get_updraft_option('updraft_s3generic')) && '' != UpdraftPlus_Options::get_updraft_option('updraft_s3generic_login', '')) {
    $opts = array('accesskey' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_login'), 'secretkey' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_pass'), 'path' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_remote_path'), 'endpoint' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_endpoint'));
    UpdraftPlus_Options::update_updraft_option('updraft_s3generic', $opts);
    UpdraftPlus_Options::delete_updraft_option('updraft_s3generic_login');
    UpdraftPlus_Options::delete_updraft_option('updraft_s3generic_pass');
    UpdraftPlus_Options::delete_updraft_option('updraft_s3generic_remote_path');
    UpdraftPlus_Options::delete_updraft_option('updraft_s3generic_endpoint');
}
class UpdraftPlus_BackupModule_s3generic extends UpdraftPlus_BackupModule_s3
{
    protected function set_region($obj, $region = '')
    {
        $config = $this->get_config();
        $endpoint = $region != '' && $region != 'n/a' ? $region : $config['endpoint'];
        global $updraftplus;
        $updraftplus->log("Set endpoint: {$endpoint}");
        $obj->setEndpoint($endpoint);
    }
    public function get_credentials()
    {
        return array('updraft_s3generic');
    }
    function get_config()
    {
Пример #28
0
 public function show_authed_admin_success()
 {
     global $updraftplus_admin;
     $opts = $this->get_opts();
     if (empty($opts['tmp_access_token'])) {
         return;
     }
     $tmp_opts = $opts;
     $tmp_opts['token'] = $opts['tmp_access_token'];
     $message = '';
     try {
         $service = $this->bootstrap($tmp_opts);
         if (false != $this->client && !is_wp_error($this->client)) {
             $oauth2 = new Google_Service_Oauth2($this->client);
         }
         if (false != $oauth2 && !empty($oauth2->userinfo)) {
             $userinfo = $oauth2->userinfo->get();
             $username = $userinfo->name;
             $opts['ownername'] = $username;
         }
     } catch (Exception $e) {
         if (is_a($e, 'Google_Service_Exception')) {
             $errs = $e->getErrors();
             $message .= __('However, subsequent access attempts failed:', 'updraftplus');
             if (is_array($errs)) {
                 $message .= '<ul style="list-style: disc inside;">';
                 foreach ($errs as $err) {
                     $message .= '<li>';
                     if (!empty($err['reason'])) {
                         $message .= '<strong>' . htmlspecialchars($err['reason']) . ':</strong> ';
                     }
                     if (!empty($err['message'])) {
                         $message .= htmlspecialchars($err['message']);
                     } else {
                         $message .= htmlspecialchars(serialize($err));
                     }
                     $message .= '</li>';
                 }
                 $message .= '</ul>';
             } else {
                 $message .= htmlspecialchars(serialize($errs));
             }
         }
     }
     $updraftplus_admin->show_admin_warning(__('Success', 'updraftplus') . ': ' . sprintf(__('you have authenticated your %s account.', 'updraftplus'), __('Google Cloud', 'updraftplus')) . ' ' . (!empty($username) ? sprintf(__('Name: %s.', 'updraftplus'), $username) . ' ' : '') . $message);
     unset($opts['tmp_access_token']);
     UpdraftPlus_Options::update_updraft_option('updraft_googlecloud', $opts);
 }
Пример #29
0
 private function restore_configuration_bundle($table)
 {
     global $updraftplus;
     $updraftplus->log("Restoring prior UD configuration (table: {$table}; keys: " . count($this->configuration_bundle) . ")");
     foreach ($this->configuration_bundle as $key => $value) {
         UpdraftPlus_Options::delete_updraft_option($key, $value);
         UpdraftPlus_Options::update_updraft_option($key, $value);
     }
 }
Пример #30
0
 function delete($files)
 {
     global $updraftplus;
     if (is_string($files)) {
         $files = array($files);
     }
     if (!$this->is_gdocs($this->gdocs)) {
         // Do we have an access token?
         if (!($access_token = $this->access_token(UpdraftPlus_Options::get_updraft_option('updraft_googledrive_token'), UpdraftPlus_Options::get_updraft_option('updraft_googledrive_clientid'), UpdraftPlus_Options::get_updraft_option('updraft_googledrive_secret')))) {
             $updraftplus->log('ERROR: Have not yet obtained an access token from Google (has the user authorised?)');
             $updraftplus->log(__('Have not yet obtained an access token from Google - you need to authorise or re-authorise your connection to Google Drive.', 'updraftplus'), 'error');
             return false;
         }
         // Make sure $this->gdocs is a UpdraftPlus_GDocs object, or give an error
         if (is_wp_error($e = $this->need_gdocs($access_token))) {
             return false;
         }
     }
     $ids = UpdraftPlus_Options::get_updraft_option('updraft_file_ids', array());
     $ret = true;
     foreach ($files as $file) {
         if (!isset($ids[$file])) {
             $updraftplus->log("{$file}: Could not delete: could not find a record of the Google Drive file ID for this file");
             $ret = false;
             continue;
         }
         $del == $this->gdocs->delete_resource($ids[$file]);
         if (is_wp_error($del)) {
             foreach ($del->get_error_messages() as $msg) {
                 $updraftplus->log("{$file}: Deletion failed: {$msg}");
             }
             $ret = false;
             continue;
         } else {
             $updraftplus->log("{$file}: Deletion successful");
             unset($ids[$file]);
             UpdraftPlus_Options::update_updraft_option('updraft_file_ids', $ids);
         }
     }
     return $ret;
 }