public static function change_path($file) { $opts = UpdraftPlus_Options::get_updraft_option('updraft_dropbox'); $folder = empty($opts['folder']) ? '' : $opts['folder']; $dropbox_folder = trailingslashit($folder); return $dropbox_folder == '/' || $dropbox_folder == './' ? $file : $dropbox_folder . $file; }
public function get_service($opts, $useservercerts = false, $disablesslverify = null) { $user = $opts['user']; $apikey = $opts['apikey']; $authurl = $opts['authurl']; $region = !empty($opts['region']) ? $opts['region'] : null; require_once UPDRAFTPLUS_DIR . '/vendor/autoload.php'; global $updraftplus; # The new authentication APIs don't match the values we were storing before $new_authurl = 'https://lon.auth.api.rackspacecloud.com' == $authurl || 'uk' == $authurl ? Rackspace::UK_IDENTITY_ENDPOINT : Rackspace::US_IDENTITY_ENDPOINT; if (null === $disablesslverify) { $disablesslverify = UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify'); } if (empty($user) || empty($apikey)) { throw new Exception(__('Authorisation failed (check your credentials)', 'updraftplus')); } $updraftplus->log("Cloud Files authentication URL: " . $new_authurl); $client = new Rackspace($new_authurl, array('username' => $user, 'apiKey' => $apikey)); $this->client = $client; if ($disablesslverify) { $client->setSslVerification(false); } else { if ($useservercerts) { $client->setConfig(array($client::SSL_CERT_AUTHORITY, 'system')); } else { $client->setSslVerification(UPDRAFTPLUS_DIR . '/includes/cacert.pem', true, 2); } } return $client->objectStoreService('cloudFiles', $region); }
/** * 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; }
/** * Get an OAuth token from the database * If the encryption object is set then decrypt the token before returning * @param string $type Token type to retrieve * @return array|bool */ public function get($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 { if (false !== ($gettoken = UpdraftPlus_Options::get_updraft_option($this->option_name_prefix . $type))) { $token = $this->decrypt($gettoken); return $token; } return false; } }
public function get_service($opts, $useservercerts = false, $disablesslverify = null) { # 'tenant', 'user', 'password', 'authurl', 'path', (optional) 'region' extract($opts); if (null === $disablesslverify) { $disablesslverify = UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify'); } if (empty($user) || empty($password) || empty($authurl)) { throw new Exception(__('Authorisation failed (check your credentials)', 'updraftplus')); } require_once UPDRAFTPLUS_DIR . '/oc/autoload.php'; global $updraftplus; $updraftplus->log("OpenStack authentication URL: " . $authurl); $client = new OpenStack($authurl, array('username' => $user, 'password' => $password, 'tenantName' => $tenant)); $this->client = $client; if ($disablesslverify) { $client->setSslVerification(false); } else { if ($useservercerts) { $client->setConfig(array($client::SSL_CERT_AUTHORITY => false)); } else { $client->setSslVerification(UPDRAFTPLUS_DIR . '/includes/cacert.pem', true, 2); } } $client->authenticate(); if (empty($region)) { $catalog = $client->getCatalog(); if (!empty($catalog)) { $items = $catalog->getItems(); if (is_array($items)) { foreach ($items as $item) { $name = $item->getName(); $type = $item->getType(); if ('swift' != $name || 'object-store' != $type) { continue; } $eps = $item->getEndpoints(); if (!is_array($eps)) { continue; } foreach ($eps as $ep) { if (is_object($ep) && !empty($ep->region)) { $region = $ep->region; } } } } } } $this->region = $region; return $client->objectStoreService('swift', $region); }
function backup($backup_array) { global $updraftplus; $updraft_dir = $updraftplus->backups_dir_location() . '/'; foreach ($backup_array as $type => $file) { $fullpath = $updraft_dir . $file; foreach (explode(',', UpdraftPlus_Options::get_updraft_option('updraft_email')) as $sendmail_addr) { wp_mail(trim($sendmail_addr), __("WordPress Backup", 'updraftplus') . " " . date('Y-m-d H:i', $updraftplus->backup_time), __("Backup is of:", 'updraftplus') . " " . $type . ". " . __('Be wary; email backups may fail because of file size limitations on mail servers.', 'updraftplus'), null, array($fullpath)); } $updraftplus->uploaded_file($file); } $updraftplus->prune_retained_backups("email", null, null); }
public function backup($backup_array) { global $updraftplus, $updraftplus_backup; $updraft_dir = trailingslashit($updraftplus->backups_dir_location()); $email = $updraftplus->just_one_email(UpdraftPlus_Options::get_updraft_option('updraft_email'), true); if (!is_array($email)) { $email = array($email); } foreach ($backup_array as $type => $file) { $descrip_type = preg_match('/^(.*)\\d+$/', $type, $matches) ? $matches[1] : $type; $fullpath = $updraft_dir . $file; if (file_exists($fullpath) && filesize($fullpath) > UPDRAFTPLUS_WARN_EMAIL_SIZE) { $size_in_mb_of_big_file = round(filesize($fullpath) / 1048576, 1); $toobig_hash = md5($file); $updraftplus->log($file . ': ' . sprintf(__('This backup archive is %s Mb in size - the attempt to send this via email is likely to fail (few email servers allow attachments of this size). If so, you should switch to using a different remote storage method.', 'updraftplus'), $size_in_mb_of_big_file), 'warning', 'toobigforemail_' . $toobig_hash); } $any_attempted = false; $any_sent = false; foreach ($email as $ind => $addr) { if (!apply_filters('updraftplus_email_wholebackup', true, $addr, $ind, $type)) { continue; } foreach (explode(',', $addr) as $sendmail_addr) { $send_short = strlen($sendmail_addr) > 5 ? substr($sendmail_addr, 0, 5) . '...' : $sendmail_addr; $updraftplus->log("{$file}: email to: {$send_short}"); $any_attempted = true; $subject = __("WordPress Backup", 'updraftplus') . ': ' . get_bloginfo('name') . ' (UpdraftPlus ' . $updraftplus->version . ') ' . get_date_from_gmt(gmdate('Y-m-d H:i:s', $updraftplus->backup_time), 'Y-m-d H:i'); $sent = wp_mail(trim($sendmail_addr), $subject, sprintf(__("Backup is of: %s.", 'updraftplus'), site_url() . ' (' . $descrip_type . ')'), null, array($fullpath)); if ($sent) { $any_sent = true; } } } if ($any_sent) { if (isset($toobig_hash)) { $updraftplus->log_removewarning('toobigforemail_' . $toobig_hash); // Don't leave it still set for the next archive unset($toobig_hash); } $updraftplus->uploaded_file($file); } elseif ($any_attempted) { $updraftplus->log('Mails were not sent successfully'); $updraftplus->log(__('The attempt to send the backup via email failed (probably the backup was too large for this method)', 'updraftplus'), 'error'); } else { $updraftplus->log('No email addresses were configured to send to'); } } return null; }
private function get_opts() { $this->opts = UpdraftPlus_Options::get_updraft_option('updraft_adminlocking'); if (!is_array($this->opts)) { $this->opts = array(); } if (!isset($this->opts['password'])) { $this->opts['password'] = ''; } if (!isset($this->opts['session_length'])) { $this->opts['session_length'] = 3600; } if (!isset($this->opts['support_url'])) { $this->opts['support_url'] = ''; } }
public function getBackupsData() { $backup_list = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); if (empty($backup_list)) { return; } $backups = array(); foreach ($backup_list as $timestamp => $backups_info) { $time_mm = strtotime("-{$this->last_months} month"); // If date more than 1 month - skip it if (date('Y-m-d', $timestamp) < date('Y-m-d', $time_mm)) { continue; } $this->backups_size = 0; $this->backup_files = array(); $destinations = array(); if (is_array($backups_info)) { if ($this->viewTypes && is_array($this->viewTypes)) { foreach ($this->viewTypes as $type) { $this->_addBackupElement($backups_info, $type); } } if (isset($backups_info['service']) && !empty($backups_info['service'])) { if (is_array($backups_info['service'])) { foreach ($backups_info['service'] as $service) { if ($service == 'none') { $service = 'local'; } $destinations[] = $service; } } else { if ($backups_info['service'] == 'none') { $backups_info['service'] = 'local'; } $destinations[] = $backups_info['service']; } } if (isset($this->backup_files) && is_array($this->backup_files) && !empty($this->backup_files)) { $backups[date('Y-m-d', $timestamp)][] = array('timestamp' => $timestamp, 'file' => $this->backup_files, 'dest' => $destinations, 'source' => null, 'size' => $this->backups_size, 'links' => array()); } } } return $backups; }
public function backup($backup_array) { global $updraftplus, $updraftplus_backup; $updraft_dir = trailingslashit($updraftplus->backups_dir_location()); $email = $updraftplus->just_one_email(UpdraftPlus_Options::get_updraft_option('updraft_email'), true); if (!is_array($email)) { $email = array($email); } foreach ($backup_array as $type => $file) { $descrip_type = preg_match('/^(.*)\\d+$/', $type, $matches) ? $matches[1] : $type; $fullpath = $updraft_dir . $file; #if (file_exists($fullpath) && filesize($fullpath) > ... $any_attempted = false; $any_sent = false; foreach ($email as $ind => $addr) { if (!apply_filters('updraftplus_email_wholebackup', true, $addr, $ind, $type)) { continue; } foreach (explode(',', $addr) as $sendmail_addr) { $send_short = strlen($sendmail_addr) > 5 ? substr($sendmail_addr, 0, 5) . '...' : $sendmail_addr; $updraftplus->log("{$file}: email to: {$send_short}"); $any_attempted = true; $subject = __("WordPress Backup", 'updraftplus') . ': ' . get_bloginfo('name') . ' (UpdraftPlus ' . $updraftplus->version . ') ' . get_date_from_gmt(gmdate('Y-m-d H:i:s', $updraftplus->backup_time), 'Y-m-d H:i'); $sent = wp_mail(trim($sendmail_addr), $subject, sprintf(__("Backup is of: %s.", 'updraftplus'), site_url() . ' (' . $descrip_type . ')'), null, array($fullpath)); if ($sent) { $any_sent = true; } } } if ($any_sent) { $updraftplus->uploaded_file($file); } elseif ($any_attempted) { $updraftplus->log('Mails were not sent successfully'); $updraftplus->log(__('The attempt to send the backup via email failed (probably the backup was too large for this method)', 'updraftplus'), 'error'); } else { $updraftplus->log('No email addresses were configured to send to'); } } return null; }
<?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');
<?php // https://www.dropbox.com/developers/apply?cont=/developers/apps if (!defined('UPDRAFTPLUS_DIR')) { die('No direct access allowed.'); } # Converted to job_options: yes # Converted to array options: yes # Migrate options to new-style storage - May 2014 # appkey, secret, folder, updraft_dropboxtk_request_token, updraft_dropboxtk_access_token if (!is_array(UpdraftPlus_Options::get_updraft_option('updraft_dropbox'))) { $opts = array('appkey' => UpdraftPlus_Options::get_updraft_option('updraft_dropbox_appkey'), 'secret' => UpdraftPlus_Options::get_updraft_option('updraft_dropbox_secret'), 'folder' => UpdraftPlus_Options::get_updraft_option('updraft_dropbox_folder'), 'tk_request_token' => UpdraftPlus_Options::get_updraft_option('updraft_dropboxtk_request_token'), 'tk_access_token' => UpdraftPlus_Options::get_updraft_option('updraft_dropboxtk_access_token')); UpdraftPlus_Options::update_updraft_option('updraft_dropbox', $opts); UpdraftPlus_Options::delete_updraft_option('updraft_dropbox_appkey'); UpdraftPlus_Options::delete_updraft_option('updraft_dropbox_secret'); UpdraftPlus_Options::delete_updraft_option('updraft_dropbox_folder'); UpdraftPlus_Options::delete_updraft_option('updraft_dropboxtk_request_token'); UpdraftPlus_Options::delete_updraft_option('updraft_dropboxtk_access_token'); } class UpdraftPlus_BackupModule_dropbox { private $current_file_hash; private $current_file_size; private $dropbox_object; public function chunked_callback($offset, $uploadid, $fullpath = false) { global $updraftplus; // Update upload ID $updraftplus->jobdata_set('updraf_dbid_' . $this->current_file_hash, $uploadid); $updraftplus->jobdata_set('updraf_dbof_' . $this->current_file_hash, $offset); $this->upload_tick = time();
public static function config_print_engine($key, $whoweare_short, $whoweare_long, $console_descrip, $console_url, $img_html = '', $include_endpoint_chooser = false) { ?> <tr class="updraftplusmethod <?php echo $key; ?> "> <td></td> <td><?php echo $img_html; ?> <p><em><?php printf(__('%s is a great choice, because UpdraftPlus supports chunked uploads - no matter how big your site is, UpdraftPlus can upload it a little at a time, and not get thwarted by timeouts.', 'updraftplus'), $whoweare_long); ?> </em></p> <?php if ('s3generic' == $key) { _e('Examples of S3-compatible storage providers:') . ' '; echo '<a href="http://www.cloudian.com/">Cloudian</a>, '; echo '<a href="http://cloud.google.com/storage">Google Cloud Storage</a>, '; echo '<a href="https://www.mh.connectria.com/rp/order/cloud_storage_index">Connectria</a>, '; echo '<a href="http://www.constant.com/cloud/storage/">Constant</a>, '; echo '<a href="http://www.eucalyptus.com/eucalyptus-cloud/iaas">Eucalyptus</a>, '; echo '<a href="http://cloud.nifty.com/storage/">Nifty</a>, '; echo '<a href="http://www.ntt.com/cloudn/data/storage.html">Cloudn</a>'; echo '' . __('... and many more!', 'updraftplus') . '<br>'; } ?> </td> </tr> <tr class="updraftplusmethod <?php echo $key; ?> "> <th></th> <td> <?php global $updraftplus_admin; if (!class_exists('SimpleXMLElement')) { $updraftplus_admin->show_double_warning('<strong>' . __('Warning', 'updraftplus') . ':</strong> ' . sprintf(__('Your web server\'s PHP installation does not included a required module (%s). Please contact your web hosting provider\'s support.', 'updraftplus'), 'SimpleXMLElement') . ' ' . sprintf(__("UpdraftPlus's %s module <strong>requires</strong> %s. Please do not file any support requests; there is no alternative.", 'updraftplus'), $whoweare_long, 'SimpleXMLElement'), $key); } $updraftplus_admin->curl_check($whoweare_long, true, $key); ?> </td> </tr> <tr class="updraftplusmethod <?php echo $key; ?> "> <th></th> <td> <p><?php if ($console_url) { echo sprintf(__('Get your access key and secret key <a href="%s">from your %s console</a>, then pick a (globally unique - all %s users) bucket name (letters and numbers) (and optionally a path) to use for storage. This bucket will be created for you if it does not already exist.', 'updraftplus'), $console_url, $console_descrip, $whoweare_long); } ?> <a href="http://updraftplus.com/faqs/i-get-ssl-certificate-errors-when-backing-up-andor-restoring/"><?php _e('If you see errors about SSL certificates, then please go here for help.', 'updraftplus'); ?> </a></p> </td></tr> <?php if ($include_endpoint_chooser) { ?> <tr class="updraftplusmethod <?php echo $key; ?> "> <th><?php echo sprintf(__('%s end-point', 'updraftplus'), $whoweare_short); ?> :</th> <td><input type="text" style="width: 292px" id="updraft_<?php echo $key; ?> _endpoint" name="updraft_<?php echo $key; ?> _endpoint" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_' . $key . '_endpoint')); ?> " /></td> </tr> <?php } else { ?> <input type="hidden" id="updraft_<?php echo $key; ?> _endpoint" name="updraft_<?php echo $key; ?> _endpoint" value=""> <?php } ?> <tr class="updraftplusmethod <?php echo $key; ?> "> <th><?php echo sprintf(__('%s access key', 'updraftplus'), $whoweare_short); ?> :</th> <td><input type="text" autocomplete="off" style="width: 292px" id="updraft_<?php echo $key; ?> _apikey" name="updraft_<?php echo $key; ?> _login" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_' . $key . '_login')); ?> " /></td> </tr> <tr class="updraftplusmethod <?php echo $key; ?> "> <th><?php echo sprintf(__('%s secret key', 'updraftplus'), $whoweare_short); ?> :</th> <td><input type="<?php echo apply_filters('updraftplus_admin_secret_field_type', 'text'); ?> " autocomplete="off" style="width: 292px" id="updraft_<?php echo $key; ?> _apisecret" name="updraft_<?php echo $key; ?> _pass" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_' . $key . '_pass')); ?> " /></td> </tr> <tr class="updraftplusmethod <?php echo $key; ?> "> <th><?php echo sprintf(__('%s location', 'updraftplus'), $whoweare_short); ?> :</th> <td><?php echo $key; ?> ://<input title="<?php echo htmlspecialchars(__('Enter only a bucket name or a bucket and path. Examples: mybucket, mybucket/mypath', 'updraftplus')); ?> " type="text" style="width: 292px" name="updraft_<?php echo $key; ?> _remote_path" id="updraft_<?php echo $key; ?> _path" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_' . $key . '_remote_path')); ?> " /></td> </tr> <tr class="updraftplusmethod <?php echo $key; ?> "> <th></th> <td><p><button id="updraft-<?php echo $key; ?> -test" type="button" class="button-primary" style="font-size:18px !important"><?php echo sprintf(__('Test %s Settings', 'updraftplus'), $whoweare_short); ?> </button></p></td> </tr> <?php }
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; }
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; }
public function backup_wpcore_dirlist($whichdir, $logit = false) { // Need to properly analyse the plugins, themes, uploads, content paths in order to strip them out (they may have various non-default manual values) global $updraftplus; if (false !== ($wpcore_dirlist = apply_filters('updraftplus_dirlist_wpcore_override', false, $whichdir))) { return $wpcore_dirlist; } $possible_backups = $updraftplus->get_backupable_file_entities(false); # We don't want to exclude the very thing we are backing up unset($possible_backups['wpcore']); # We do want to exclude everything in wp-content $possible_backups['wp-content'] = WP_CONTENT_DIR; foreach ($possible_backups as $key => $dir) { if (is_array($dir)) { foreach ($dir as $ind => $rdir) { if (!empty($rdir)) { $possible_backups_dirs[$rdir] = $key . $ind; } } } else { if (!empty($dir)) { $possible_backups_dirs[$dir] = $key; } } } # Create an array of directories to be skipped $exclude = UpdraftPlus_Options::get_updraft_option('updraft_include_wpcore_exclude', ''); if ($logit) { $updraftplus->log("Exclusion option setting (wpcore): " . $exclude); } # Make the values into the keys $wpcore_skip = array_flip(preg_split("/,/", $exclude)); $wpcore_skip['wp_content'] = 0; // Removing the slash is important (though ought to be redundant by here); otherwise path matching does not work $wpcore_dirlist = $updraftplus->compile_folder_list_for_backup(untrailingslashit($whichdir), $possible_backups_dirs, $wpcore_skip); // This is not required to be a perfect test. The point is to make sure we do get WP core. // Not using this approach for now. // if (true == apply_filters('updraftplus_backup_wpcore_dirlist_strict', false)) { // $wpcore_valid = array('wp-admin', 'wp-includes', 'index.php', 'xmlrpc.php'); // foreach ($wpcore_dirlist as $dir) { // // } // } return $wpcore_dirlist; }
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; }
private function restore_backup($timestamp) { @set_time_limit(900); global $wp_filesystem, $updraftplus; $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); if (!is_array($backup_history[$timestamp])) { echo '<p>' . __('This backup does not exist in the backup history - restoration aborted. Timestamp:', 'updraftplus') . " {$timestamp}</p><br/>"; return new WP_Error('does_not_exist', __('Backup does not exist in the backup history', 'updraftplus')); } // request_filesystem_credentials passes on fields just via hidden name/value pairs. // Build array of parameters to be passed via this $extra_fields = array(); if (isset($_POST['updraft_restore']) && is_array($_POST['updraft_restore'])) { foreach ($_POST['updraft_restore'] as $entity) { $_POST['updraft_restore_' . $entity] = 1; $extra_fields[] = 'updraft_restore_' . $entity; } } // Now make sure that updraft_restorer_ option fields get passed along to request_filesystem_credentials foreach ($_POST as $key => $value) { if (0 === strpos($key, 'updraft_restorer_')) { $extra_fields[] = $key; } } $credentials = request_filesystem_credentials(UpdraftPlus_Options::admin_page() . "?page=updraftplus&action=updraft_restore&backup_timestamp={$timestamp}", '', false, false, $extra_fields); WP_Filesystem($credentials); if ($wp_filesystem->errors->get_error_code()) { echo '<p><em><a href="http://updraftplus.com/faqs/asked-ftp-details-upon-restorationmigration-updates/">' . __('Why am I seeing this?', 'updraftplus') . '</a></em></p>'; foreach ($wp_filesystem->errors->get_error_messages() as $message) { show_message($message); } exit; } # Set up logging $updraftplus->backup_time_nonce(); $updraftplus->jobdata_set('job_type', 'restore'); $updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms); $updraftplus->logfile_open($updraftplus->nonce); # Provide download link for the log file #echo '<p><a target="_new" href="?action=downloadlog&page=updraftplus&updraftplus_backup_nonce='.htmlspecialchars($updraftplus->nonce).'">'.__('Follow this link to download the log file for this restoration.', 'updraftplus').'</a></p>'; # TODO: Automatic purging of old log files # TODO: Provide option to auto-email the log file //if we make it this far then WP_Filesystem has been instantiated and is functional (tested with ftpext, what about suPHP and other situations where direct may work?) echo '<h1>' . __('UpdraftPlus Restoration: Progress', 'updraftplus') . '</h1><div id="updraft-restore-progress">'; $this->show_admin_warning('<a target="_new" href="?action=downloadlog&page=updraftplus&updraftplus_backup_nonce=' . htmlspecialchars($updraftplus->nonce) . '">' . __('Follow this link to download the log file for this restoration (needed for any support requests).', 'updraftplus') . '</a>'); $updraft_dir = trailingslashit($updraftplus->backups_dir_location()); $foreign_known = apply_filters('updraftplus_accept_archivename', array()); $service = isset($backup_history[$timestamp]['service']) ? $backup_history[$timestamp]['service'] : false; if (!is_array($service)) { $service = array($service); } // Now, need to turn any updraft_restore_<entity> fields (that came from a potential WP_Filesystem form) back into parts of the _POST array (which we want to use) if (empty($_POST['updraft_restore']) || !is_array($_POST['updraft_restore'])) { $_POST['updraft_restore'] = array(); } $backup_set = $backup_history[$timestamp]; $entities_to_restore = array(); foreach ($_POST['updraft_restore'] as $entity) { if (empty($backup_set['meta_foreign'])) { $entities_to_restore[$entity] = $entity; } else { if ('db' == $entity && !empty($foreign_known[$backup_set['meta_foreign']]) && !empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) { $entities_to_restore[$entity] = 'db'; } else { $entities_to_restore[$entity] = 'wpcore'; } } } foreach ($_POST as $key => $value) { if (0 === strpos($key, 'updraft_restore_')) { $nkey = substr($key, 16); if (!isset($entities_to_restore[$nkey])) { $_POST['updraft_restore'][] = $nkey; if (empty($backup_set['meta_foreign'])) { $entities_to_restore[$nkey] = $nkey; } else { if ('db' == $entity && !empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) { $entities_to_restore[$nkey] = 'db'; } else { $entities_to_restore[$nkey] = 'wpcore'; } } } } } if (0 == count($_POST['updraft_restore'])) { echo '<p>' . __('ABORT: Could not find the information on which entities to restore.', 'updraftplus') . '</p>'; echo '<p>' . __('If making a request for support, please include this information:', 'updraftplus') . ' ' . count($_POST) . ' : ' . htmlspecialchars(serialize($_POST)) . '</p>'; return new WP_Error('missing_info', 'Backup information not found'); } $updraftplus->log("Restore job started. Entities to restore: " . implode(', ', array_flip($entities_to_restore))); $this->entities_to_restore = $entities_to_restore; set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT); /* $_POST['updraft_restore'] is typically something like: array( 0=>'db', 1=>'plugins', 2=>'themes'), etc. i.e. array ( 'db', 'plugins', themes') */ $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); uksort($backup_set, array($this, 'sort_restoration_entities')); // We use a single object for each entity, because we want to store information about the backup set require_once UPDRAFTPLUS_DIR . '/restorer.php'; global $updraftplus_restorer; $updraftplus_restorer = new Updraft_Restorer(new Updraft_Restorer_Skin(), $backup_set); $second_loop = array(); echo "<h2>" . __('Final checks', 'updraftplus') . '</h2>'; if (empty($backup_set['meta_foreign'])) { $entities_to_download = $entities_to_restore; } else { if (!empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) { $entities_to_download = array(); if (in_array('db', $entities_to_restore)) { $entities_to_download['db'] = 1; } if (count($entities_to_restore) > 1 || !in_array('db', $entities_to_restore)) { $entities_to_download['wpcore'] = 1; } } else { $entities_to_download = array('wpcore' => 1); } } // First loop: make sure that files are present + readable; and populate array for second loop foreach ($backup_set as $type => $files) { // All restorable entities must be given explicitly, as we can store other arbitrary data in the history array if (!isset($backupable_entities[$type]) && 'db' != $type) { continue; } if (isset($backupable_entities[$type]['restorable']) && $backupable_entities[$type]['restorable'] == false) { continue; } if (!isset($entities_to_download[$type])) { continue; } if ('wpcore' == $type && is_multisite() && 0 === $updraftplus_restorer->ud_backup_is_multisite) { echo "<p>{$type}: <strong>"; echo __('Skipping restoration of WordPress core when importing a single site into a multisite installation. If you had anything necessary in your WordPress directory then you will need to re-add it manually from the zip file.', 'updraftplus'); #TODO #$updraftplus->log_e('Skipping restoration of WordPress core when importing a single site into a multisite installation. If you had anything necessary in your WordPress directory then you will need to re-add it manually from the zip file.'); echo "</strong></p>"; continue; } if (is_string($files)) { $files = array($files); } foreach ($files as $ind => $file) { $fullpath = $updraft_dir . $file; echo sprintf(__("Looking for %s archive: file name: %s", 'updraftplus'), $type, htmlspecialchars($file)) . "<br>"; add_action('http_request_args', array($updraftplus, 'modify_http_options')); foreach ($service as $serv) { if (!is_readable($fullpath)) { $sd = empty($updraftplus->backup_methods[$serv]) ? $serv : $updraftplus->backup_methods[$serv]; echo __("File is not locally present - needs retrieving from remote storage", 'updraftplus') . " ({$sd})"; $this->download_file($file, $serv); echo ": "; if (!is_readable($fullpath)) { echo __("Error", 'updraftplus'); } else { echo __("OK", 'updraftplus'); } echo '<br>'; } } remove_action('http_request_args', array($updraftplus, 'modify_http_options')); $index = $ind == 0 ? '' : $ind; // If a file size is stored in the backup data, then verify correctness of the local file if (isset($backup_history[$timestamp][$type . $index . '-size'])) { $fs = $backup_history[$timestamp][$type . $index . '-size']; echo __("Archive is expected to be size:", 'updraftplus') . " " . round($fs / 1024, 1) . " Kb: "; $as = @filesize($fullpath); if ($as == $fs) { echo __('OK', 'updraftplus') . '<br>'; } else { echo "<strong>" . __('Error:', 'updraftplus') . "</strong> " . __('file is size:', 'updraftplus') . " " . round($as / 1024) . " ({$fs}, {$as})<br>"; } } else { echo __("The backup records do not contain information about the proper size of this file.", 'updraftplus') . "<br>"; } if (!is_readable($fullpath)) { echo __('Could not find one of the files for restoration', 'updraftplus') . " ({$file})<br>"; $updraftplus->log("{$file}: " . __('Could not find one of the files for restoration', 'updraftplus'), 'error'); echo '</div>'; restore_error_handler(); return false; } } if (empty($updraftplus_restorer->ud_foreign)) { $types = array($type); } else { if ('db' != $type || empty($foreign_known[$updraftplus_restorer->ud_foreign]['separatedb'])) { $types = array('wpcore'); } else { $types = array('db'); } } foreach ($types as $check_type) { $info = isset($backupable_entities[$check_type]) ? $backupable_entities[$check_type] : array(); $val = $updraftplus_restorer->pre_restore_backup($files, $check_type, $info); if (is_wp_error($val)) { $updraftplus->log_wp_error($val); foreach ($val->get_error_messages() as $msg) { echo '<strong>' . __('Error:', 'updraftplus') . '</strong> ' . htmlspecialchars($msg) . '<br>'; } foreach ($val->get_error_codes() as $code) { if ('already_exists' == $code) { $this->print_delete_old_dirs_form(false); } } echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return $val; } elseif (false === $val) { echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return false; } } foreach ($entities_to_restore as $entity => $via) { if ($via == $type) { $second_loop[$entity] = $files; } } } $updraftplus_restorer->delete = UpdraftPlus_Options::get_updraft_option('updraft_delete_local') ? true : false; if ('none' === $service || 'email' === $service || empty($service) || is_array($service) && 1 == count($service) && (in_array('none', $service) || in_array('', $service) || in_array('email', $service)) || !empty($updraftplus_restorer->ud_foreign)) { if ($updraftplus_restorer->delete) { $updraftplus->log_e('Will not delete any archives after unpacking them, because there was no cloud storage for this backup'); } $updraftplus_restorer->delete = false; } if (!empty($updraftplus_restorer->ud_foreign)) { $updraftplus->log("Foreign backup; created by: " . $updraftplus_restorer->ud_foreign); } // Second loop: now actually do the restoration uksort($second_loop, array($this, 'sort_restoration_entities')); foreach ($second_loop as $type => $files) { # Types: uploads, themes, plugins, others, db $info = isset($backupable_entities[$type]) ? $backupable_entities[$type] : array(); echo 'db' == $type ? "<h2>" . __('Database', 'updraftplus') . "</h2>" : "<h2>" . $info['description'] . "</h2>"; $updraftplus->log("Entity: " . $type); if (is_string($files)) { $files = array($files); } foreach ($files as $fkey => $file) { $last_one = 1 == count($second_loop) && 1 == count($files); $val = $updraftplus_restorer->restore_backup($file, $type, $info, $last_one); if (is_wp_error($val)) { $updraftplus->log_e($val); foreach ($val->get_error_messages() as $msg) { echo '<strong>' . __('Error message', 'updraftplus') . ':</strong> ' . htmlspecialchars($msg) . '<br>'; } $codes = $val->get_error_codes(); if (is_array($codes)) { foreach ($codes as $code) { $data = $val->get_error_data($code); if (!empty($data)) { $pdata = is_string($data) ? $data : serialize($data); echo '<strong>' . __('Error data:', 'updraftplus') . '</strong> ' . htmlspecialchars($pdata) . '<br>'; if (false !== strpos($pdata, 'PCLZIP_ERR_BAD_FORMAT (-10)')) { echo '<a href="http://updraftplus.com/faqs/error-message-pclzip_err_bad_format-10-invalid-archive-structure-mean/"><strong>' . __('Please consult this FAQ for help on what to do about it.', 'updraftplus') . '</strong></a><br>'; } } } } echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return $val; } elseif (false === $val) { echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return false; } unset($files[$fkey]); } unset($second_loop[$type]); } foreach (array('template', 'stylesheet', 'template_root', 'stylesheet_root') as $opt) { add_filter('pre_option_' . $opt, array($this, 'option_filter_' . $opt)); } # Clear any cached pages after the restore $updraftplus_restorer->clear_cache(); if (!function_exists('validate_current_theme')) { require_once ABSPATH . WPINC . '/themes'; } # Have seen a case where the current theme in the DB began with a capital, but not on disk - and this breaks migrating from Windows to a case-sensitive system $template = get_option('template'); if (!empty($template) && $template != WP_DEFAULT_THEME && $template != strtolower($template)) { $theme_root = get_theme_root($template); $theme_root2 = get_theme_root(strtolower($template)); if (!file_exists("{$theme_root}/{$template}/style.css") && file_exists("{$theme_root}/" . strtolower($template) . "/style.css")) { $updraftplus->log_e("Theme directory (%s) not found, but lower-case version exists; updating database option accordingly", $template); update_option('template', strtolower($template)); } } if (!validate_current_theme()) { global $updraftplus; echo '<strong>'; $updraftplus->log_e("The current theme was not found; to prevent this stopping the site from loading, your theme has been reverted to the default theme"); echo '</strong>'; } #foreach (array('template', 'stylesheet', 'template_root', 'stylesheet_root') as $opt) { # remove_filter('pre_option_'.$opt, array($this, 'option_filter_'.$opt)); #} echo '</div>'; //close the updraft_restore_progress div restore_error_handler(); return true; }
public function analyse_db_file($timestamp, $res, $db_file = false, $header_only = false) { $mess = array(); $warn = array(); $err = array(); $info = array(); global $wp_version; include ABSPATH . WPINC . '/version.php'; $updraft_dir = $this->backups_dir_location(); if (false === $db_file) { # This attempts to raise the maximum packet size. This can't be done within the session, only globally. Therefore, it has to be done before the session starts; in our case, during the pre-analysis. $this->get_max_packet_size(); $backup = $this->get_backup_history($timestamp); if (!isset($backup['nonce']) || !isset($backup['db'])) { return array($mess, $warn, $err, $info); } $db_file = is_string($backup['db']) ? $updraft_dir . '/' . $backup['db'] : $updraft_dir . '/' . $backup['db'][0]; } if (!is_readable($db_file)) { return array($mess, $warn, $err, $info); } // Encrypted - decrypt it if ($this->is_db_encrypted($db_file)) { $encryption = empty($res['updraft_encryptionphrase']) ? UpdraftPlus_Options::get_updraft_option('updraft_encryptionphrase') : $res['updraft_encryptionphrase']; if (!$encryption) { if (class_exists('UpdraftPlus_Addon_MoreDatabase')) { $err[] = sprintf(__('Error: %s', 'updraftplus'), __('Decryption failed. The database file is encrypted, but you have no encryption key entered.', 'updraftplus')); } else { $err[] = sprintf(__('Error: %s', 'updraftplus'), __('Decryption failed. The database file is encrypted.', 'updraftplus')); } return array($mess, $warn, $err, $info); } $ciphertext = $this->decrypt($db_file, $encryption); if ($ciphertext) { $new_db_file = $updraft_dir . '/' . basename($db_file, '.crypt'); if (!file_put_contents($new_db_file, $ciphertext)) { $err[] = __('Failed to write out the decrypted database to the filesystem.', 'updraftplus'); return array($mess, $warn, $err, $info); } $db_file = $new_db_file; } else { $err[] = __('Decryption failed. The most likely cause is that you used the wrong key.', 'updraftplus'); return array($mess, $warn, $err, $info); } } # Even the empty schema when gzipped comes to 1565 bytes; a blank WP 3.6 install at 5158. But we go low, in case someone wants to share single tables. if (filesize($db_file) < 1000) { $err[] = sprintf(__('The database is too small to be a valid WordPress database (size: %s Kb).', 'updraftplus'), round(filesize($db_file) / 1024, 1)); return array($mess, $warn, $err, $info); } $is_plain = '.gz' == substr($db_file, -3, 3) ? false : true; $dbhandle = $is_plain ? fopen($db_file, 'r') : $this->gzopen_for_read($db_file, $warn, $err); if (!is_resource($dbhandle)) { $err[] = __('Failed to open database file.', 'updraftplus'); return array($mess, $warn, $err, $info); } # Analyse the file, print the results. $line = 0; $old_siteurl = ''; $old_home = ''; $old_table_prefix = ''; $old_siteinfo = array(); $gathering_siteinfo = true; $old_wp_version = ''; $old_php_version = ''; $tables_found = array(); // TODO: If the backup is the right size/checksum, then we could restore the $line <= 100 in the 'while' condition and not bother scanning the whole thing? Or better: sort the core tables to be first so that this usually terminates early $wanted_tables = array('terms', 'term_taxonomy', 'term_relationships', 'commentmeta', 'comments', 'links', 'options', 'postmeta', 'posts', 'users', 'usermeta'); $migration_warning = false; // Don't set too high - we want a timely response returned to the browser // Until April 2015, this was always 90. But we've seen a few people with ~1Gb databases (uncompressed), and 90s is not enough. Note that we don't bother checking here if it's compressed - having a too-large timeout when unexpected is harmless, as it won't be hit. On very large dbs, they're expecting it to take a while. // "120 or 240" is a first attempt at something more useful than just fixed at 90 - but should be sufficient (as 90 was for everyone without ~1Gb databases) $default_dbscan_timeout = filesize($db_file) < 31457280 ? 120 : 240; $dbscan_timeout = defined('UPDRAFTPLUS_DBSCAN_TIMEOUT') && is_numeric(UPDRAFTPLUS_DBSCAN_TIMEOUT) ? UPDRAFTPLUS_DBSCAN_TIMEOUT : $default_dbscan_timeout; @set_time_limit($dbscan_timeout); while (($is_plain && !feof($dbhandle) || !$is_plain && !gzeof($dbhandle)) && ($line < 100 || !$header_only && count($wanted_tables) > 0)) { $line++; // Up to 1Mb $buffer = $is_plain ? rtrim(fgets($dbhandle, 1048576)) : rtrim(gzgets($dbhandle, 1048576)); // Comments are what we are interested in if (substr($buffer, 0, 1) == '#') { if ('' == $old_siteurl && preg_match('/^\\# Backup of: (http(.*))$/', $buffer, $matches)) { $old_siteurl = untrailingslashit($matches[1]); $mess[] = __('Backup of:', 'updraftplus') . ' ' . htmlspecialchars($old_siteurl) . (!empty($old_wp_version) ? ' ' . sprintf(__('(version: %s)', 'updraftplus'), $old_wp_version) : ''); // Check for should-be migration if (!$migration_warning && $old_siteurl != untrailingslashit(site_url())) { $migration_warning = true; $powarn = apply_filters('updraftplus_dbscan_urlchange', sprintf(__('Warning: %s', 'updraftplus'), '<a href="https://updraftplus.com/shop/migrator/">' . __('This backup set is from a different site - this is not a restoration, but a migration. You need the Migrator add-on in order to make this work.', 'updraftplus') . '</a>'), $old_siteurl, $res); if (!empty($powarn)) { $warn[] = $powarn; } } } elseif ('' == $old_home && preg_match('/^\\# Home URL: (http(.*))$/', $buffer, $matches)) { $old_home = untrailingslashit($matches[1]); // Check for should-be migration if (!$migration_warning && $old_home != home_url()) { $migration_warning = true; $powarn = apply_filters('updraftplus_dbscan_urlchange', sprintf(__('Warning: %s', 'updraftplus'), '<a href="https://updraftplus.com/shop/migrator/">' . __('This backup set is from a different site - this is not a restoration, but a migration. You need the Migrator add-on in order to make this work.', 'updraftplus') . '</a>'), $old_home, $res); if (!empty($powarn)) { $warn[] = $powarn; } } } elseif ('' == $old_wp_version && preg_match('/^\\# WordPress Version: ([0-9]+(\\.[0-9]+)+)(-[-a-z0-9]+,)?(.*)$/', $buffer, $matches)) { $old_wp_version = $matches[1]; if (!empty($matches[3])) { $old_wp_version .= substr($matches[3], 0, strlen($matches[3]) - 1); } if (version_compare($old_wp_version, $wp_version, '>')) { //$mess[] = sprintf(__('%s version: %s', 'updraftplus'), 'WordPress', $old_wp_version); $warn[] = sprintf(__('You are importing from a newer version of WordPress (%s) into an older one (%s). There are no guarantees that WordPress can handle this.', 'updraftplus'), $old_wp_version, $wp_version); } if (preg_match('/running on PHP ([0-9]+\\.[0-9]+)(\\s|\\.)/', $matches[4], $nmatches) && preg_match('/^([0-9]+\\.[0-9]+)(\\s|\\.)/', PHP_VERSION, $cmatches)) { $old_php_version = $nmatches[1]; $current_php_version = $cmatches[1]; if (version_compare($old_php_version, $current_php_version, '>')) { //$mess[] = sprintf(__('%s version: %s', 'updraftplus'), 'WordPress', $old_wp_version); $warn[] = sprintf(__('The site in this backup was running on a webserver with version %s of %s. ', 'updraftplus'), $old_php_version, 'PHP') . ' ' . sprintf(__('This is significantly newer than the server which you are now restoring onto (version %s).', 'updraftplus'), PHP_VERSION) . ' ' . sprintf(__('You should only proceed if you cannot update the current server and are confident (or willing to risk) that your plugins/themes/etc. are compatible with the older %s version.', 'updraftplus'), 'PHP') . ' ' . sprintf(__('Any support requests to do with %s should be raised with your web hosting company.', 'updraftplus'), 'PHP'); } } } elseif ('' == $old_table_prefix && (preg_match('/^\\# Table prefix: (\\S+)$/', $buffer, $matches) || preg_match('/^-- Table prefix: (\\S+)$/i', $buffer, $matches))) { $old_table_prefix = $matches[1]; // echo '<strong>'.__('Old table prefix:', 'updraftplus').'</strong> '.htmlspecialchars($old_table_prefix).'<br>'; } elseif (empty($info['label']) && preg_match('/^\\# Label: (.*)$/', $buffer, $matches)) { $info['label'] = $matches[1]; $mess[] = __('Backup label:', 'updraftplus') . ' ' . htmlspecialchars($info['label']); } elseif ($gathering_siteinfo && preg_match('/^\\# Site info: (\\S+)$/', $buffer, $matches)) { if ('end' == $matches[1]) { $gathering_siteinfo = false; // Sanity checks if (isset($old_siteinfo['multisite']) && !$old_siteinfo['multisite'] && is_multisite()) { // Just need to check that you're crazy if (!defined('UPDRAFTPLUS_EXPERIMENTAL_IMPORTINTOMULTISITE') || UPDRAFTPLUS_EXPERIMENTAL_IMPORTINTOMULTISITE != true) { $err[] = sprintf(__('Error: %s', 'updraftplus'), __('You are running on WordPress multisite - but your backup is not of a multisite site.', 'updraftplus')); return array($mess, $warn, $err, $info); } // Got the needed code? if (!class_exists('UpdraftPlusAddOn_MultiSite') || !class_exists('UpdraftPlus_Addons_Migrator')) { $err[] = sprintf(__('Error: %s', 'updraftplus'), __('To import an ordinary WordPress site into a multisite installation requires both the multisite and migrator add-ons.', 'updraftplus')); return array($mess, $warn, $err, $info); } } elseif (isset($old_siteinfo['multisite']) && $old_siteinfo['multisite'] && !is_multisite()) { $warn[] = __('Warning:', 'updraftplus') . ' ' . __('Your backup is of a WordPress multisite install; but this site is not. Only the first site of the network will be accessible.', 'updraftplus') . ' <a href="http://codex.wordpress.org/Create_A_Network">' . __('If you want to restore a multisite backup, you should first set up your WordPress installation as a multisite.', 'updraftplus') . '</a>'; } } elseif (preg_match('/^([^=]+)=(.*)$/', $matches[1], $kvmatches)) { $key = $kvmatches[1]; $val = $kvmatches[2]; if ('multisite' == $key && $val) { $mess[] = '<strong>' . __('Site information:', 'updraftplus') . '</strong>' . ' is a WordPress Network'; } $old_siteinfo[$key] = $val; } } } elseif (preg_match('/^\\s*create table \\`?([^\\`\\(]*)\\`?\\s*\\(/i', $buffer, $matches)) { $table = $matches[1]; $tables_found[] = $table; if ($old_table_prefix) { // Remove prefix $table = $this->str_replace_once($old_table_prefix, '', $table); if (in_array($table, $wanted_tables)) { $wanted_tables = array_diff($wanted_tables, array($table)); } } } } if ($is_plain) { @fclose($dbhandle); } else { @gzclose($dbhandle); } /* $blog_tables = "CREATE TABLE $wpdb->terms ( CREATE TABLE $wpdb->term_taxonomy ( CREATE TABLE $wpdb->term_relationships ( CREATE TABLE $wpdb->commentmeta ( CREATE TABLE $wpdb->comments ( CREATE TABLE $wpdb->links ( CREATE TABLE $wpdb->options ( CREATE TABLE $wpdb->postmeta ( CREATE TABLE $wpdb->posts ( $users_single_table = "CREATE TABLE $wpdb->users ( $users_multi_table = "CREATE TABLE $wpdb->users ( $usermeta_table = "CREATE TABLE $wpdb->usermeta ( $ms_global_tables = "CREATE TABLE $wpdb->blogs ( CREATE TABLE $wpdb->blog_versions ( CREATE TABLE $wpdb->registration_log ( CREATE TABLE $wpdb->site ( CREATE TABLE $wpdb->sitemeta ( CREATE TABLE $wpdb->signups ( */ $missing_tables = array(); if ($old_table_prefix) { if (!$header_only) { foreach ($wanted_tables as $table) { if (!in_array($old_table_prefix . $table, $tables_found)) { $missing_tables[] = $table; } } if (count($missing_tables) > 0) { $warn[] = sprintf(__('This database backup is missing core WordPress tables: %s', 'updraftplus'), implode(', ', $missing_tables)); } } } else { if (empty($backup['meta_foreign'])) { $warn[] = __('UpdraftPlus was unable to find the table prefix when scanning the database backup.', 'updraftplus'); } } return array($mess, $warn, $err, $info); }
function unpack_package($package, $delete_package = true) { global $wp_filesystem, $updraftplus; $updraft_dir = $updraftplus->backups_dir_location(); // If not database, then it is a zip - unpack in the usual way #if (!preg_match('/db\.gz(\.crypt)?$/i', $package)) return parent::unpack_package($updraft_dir.'/'.$package, $delete_package); if (!preg_match('/db\\.gz(\\.crypt)?$/i', $package)) { return $this->unpack_package_zip($updraft_dir . '/' . $package, $delete_package); } $backup_dir = $wp_filesystem->find_folder($updraft_dir); // Unpack a database. The general shape of the following is copied from class-wp-upgrader.php @set_time_limit(1800); $this->skin->feedback('unpack_package'); $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/'; @$wp_filesystem->mkdir($upgrade_folder, octdec($this->calculate_additive_chmod_oct(FS_CHMOD_DIR, 0775))); //Clean up contents of upgrade directory beforehand. $upgrade_files = $wp_filesystem->dirlist($upgrade_folder); if (!empty($upgrade_files)) { foreach ($upgrade_files as $file) { $wp_filesystem->delete($upgrade_folder . $file['name'], true); } } //We need a working directory $working_dir = $upgrade_folder . basename($package, '.crypt'); # $working_dir_localpath = WP_CONTENT_DIR.'/upgrade/'. basename($package, '.crypt'); // Clean up working directory if ($wp_filesystem->is_dir($working_dir)) { $wp_filesystem->delete($working_dir, true); } if (!$wp_filesystem->mkdir($working_dir, octdec($this->calculate_additive_chmod_oct(FS_CHMOD_DIR, 0775)))) { return new WP_Error('mkdir_failed', __('Failed to create a temporary directory', 'updraftplus') . ' (' . $working_dir . ')'); } // Unpack package to working directory if ($updraftplus->is_db_encrypted($package)) { $this->skin->feedback('decrypt_database'); $encryption = UpdraftPlus_Options::get_updraft_option('updraft_encryptionphrase'); if (!$encryption) { return new WP_Error('no_encryption_key', __('Decryption failed. The database file is encrypted, but you have no encryption key entered.', 'updraftplus')); } $plaintext = $updraftplus->decrypt(false, $encryption, $wp_filesystem->get_contents($backup_dir . $package)); if ($plaintext) { $this->skin->feedback('decrypted_database'); if (!$wp_filesystem->put_contents($working_dir . '/backup.db.gz', $plaintext)) { return new WP_Error('write_failed', __('Failed to write out the decrypted database to the filesystem', 'updraftplus')); } } else { return new WP_Error('decryption_failed', __('Decryption failed. The most likely cause is that you used the wrong key.', 'updraftplus')); } } else { if (!$wp_filesystem->copy($backup_dir . $package, $working_dir . '/backup.db.gz')) { if ($wp_filesystem->errors->get_error_code()) { foreach ($wp_filesystem->errors->get_error_messages() as $message) { show_message($message); } } return new WP_Error('copy_failed', $this->strings['copy_failed']); } } // Once extracted, delete the package if required (non-recursive, is a file) if ($delete_package) { $wp_filesystem->delete($backup_dir . $package, false, true); } return $working_dir; }
/** * Execute an API call * @todo Improve error handling * @param string $method The HTTP method * @param string $url The API endpoint * @param string $call The API method to call * @param array $additional Additional parameters * @return string|object stdClass */ public function fetch($method, $url, $call, array $additional = array()) { // Get the signed request URL $request = $this->getSignedRequest($method, $url, $call, $additional); // Initialise and execute a cURL request $handle = curl_init($request['url']); // Get the default options array $options = $this->defaultOptions; if (!UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts')) { $options[CURLOPT_CAINFO] = UPDRAFTPLUS_DIR . '/includes/cacert.pem'; } if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify')) { $options[CURLOPT_SSL_VERIFYPEER] = false; } else { $options[CURLOPT_SSL_VERIFYPEER] = true; } if ($method == 'GET' && $this->outFile) { // GET $options[CURLOPT_RETURNTRANSFER] = false; $options[CURLOPT_HEADER] = false; $options[CURLOPT_FILE] = $this->outFile; $options[CURLOPT_BINARYTRANSFER] = true; if (isset($additional['headers'])) { $options[CURLOPT_HTTPHEADER] = $additional['headers']; } $this->outFile = null; } elseif ($method == 'POST') { // POST $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = $request['postfields']; } elseif ($method == 'PUT' && $this->inFile) { // PUT $options[CURLOPT_PUT] = true; $options[CURLOPT_INFILE] = $this->inFile; // @todo Update so the data is not loaded into memory to get its size $options[CURLOPT_INFILESIZE] = strlen(stream_get_contents($this->inFile)); fseek($this->inFile, 0); $this->inFile = null; } // Set the cURL options at once curl_setopt_array($handle, $options); // Execute, get any error and close $response = curl_exec($handle); $error = curl_error($handle); curl_close($handle); //Check if a cURL error has occured if ($response === false) { throw new Dropbox_CurlException($error); } else { // Parse the response if it is a string if (is_string($response)) { $response = $this->parse($response); } // Set the last response $this->lastResponse = $response; // The API doesn't return an error message for the 304 status code... // 304's are only returned when the path supplied during metadata calls has not been modified if ($response['code'] == 304) { $response['body'] = new \stdClass(); $response['body']->error = 'The folder contents have not changed'; } // Check if an error occurred and throw an Exception if (!empty($response['body']->error)) { // Dropbox returns error messages inconsistently... if ($response['body']->error instanceof \stdClass) { $array = array_values((array) $response['body']->error); $message = $array[0]; } else { $message = $response['body']->error; } // Throw an Exception with the appropriate with the appropriate message and code switch ($response['code']) { case 304: throw new Dropbox_NotModifiedException($message, 304); case 400: throw new Dropbox_BadRequestException($message, 400); case 404: throw new Dropbox_NotFoundException($message, 404); case 406: throw new Dropbox_NotAcceptableException($message, 406); case 415: throw new Dropbox_UnsupportedMediaTypeException($message, 415); default: throw new Dropbox_Exception($message, $response['code']); } } return $response; } }
private function list_our_keys($our_keys = false) { if (false === $our_keys) { $our_keys = UpdraftPlus_Options::get_updraft_option('updraft_migrator_localkeys'); } if (empty($our_keys)) { return '<em>' . __('No keys to allow remote sites to connect have yet been created.', 'updraftplus') . '</em>'; } $ret = ''; $first_one = true; foreach ($our_keys as $k => $key) { if (!is_array($key)) { continue; } if ($first_one) { $first_one = false; $ret .= '<p><strong>' . __('Existing keys', 'updraftplus') . '</strong><br>'; } $ret .= htmlspecialchars($key['name']); $ret .= ' - <a href="#" class="updraft_migrate_local_key_delete" data-keyid="' . esc_attr($k) . '">' . __('Delete', 'updraftplus') . '</a>'; $ret .= '<br>'; } if ($ret) { $ret .= '</p>'; } return $ret; }
<?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];
function get_config() { return array('login' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_login'), 'pass' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_pass'), 'remote_path' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_remote_path'), 'whoweare' => 'S3', 'whoweare_long' => __('S3 (Compatible)', 'updraftplus'), 'key' => 's3generic', 'endpoint' => UpdraftPlus_Options::get_updraft_option('updraft_s3generic_endpoint')); }
public function encrypt_file($file) { global $updraftplus; $encryption = UpdraftPlus_Options::get_updraft_option('updraft_encryptionphrase'); if (strlen($encryption) > 0) { $updraftplus->log("Attempting to encrypt backup file"); $result = apply_filters('updraft_encrypt_file', null, $file, $encryption, $this->whichdb, $this->whichdb_suffix); if (null === $result) { // $updraftplus->log(sprintf(__("As previously warned (see: %s), encryption is no longer a feature of the free edition of UpdraftPlus", 'updraftplus'), 'https://updraftplus.com/next-updraftplus-release-ready-testing/ + https://updraftplus.com/shop/updraftplus-premium/'), 'warning', 'needpremiumforcrypt'); // UpdraftPlus_Options::update_updraft_option('updraft_encryptionphrase', ''); return basename($file); } return $result; } else { return basename($file); } }
public static function config_print() { ?> <tr class="updraftplusmethod ftp"> <td></td> <td><p><em><?php printf(__('%s is a great choice, because UpdraftPlus supports chunked uploads - no matter how big your site is, UpdraftPlus can upload it a little at a time, and not get thwarted by timeouts.', 'updraftplus'), 'FTP'); ?> </em></p></td> </tr> <tr class="updraftplusmethod ftp"> <th></th> <td><em><?php echo apply_filters('updraft_sftp_ftps_notice', '<strong>' . htmlspecialchars(__('Only non-encrypted FTP is supported by regular UpdraftPlus.')) . '</strong> <a href="http://updraftplus.com/shop/sftp/">' . __('If you want encryption (e.g. you are storing sensitive business data), then an add-on is available.', 'updraftplus')) . '</a>'; ?> </em></td> </tr> <tr class="updraftplusmethod ftp"> <th><?php _e('FTP Server', 'updraftplus'); ?> :</th> <td><input type="text" size="40" id="updraft_server_address" name="updraft_server_address" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_server_address')); ?> " /></td> </tr> <tr class="updraftplusmethod ftp"> <th><?php _e('FTP Login', 'updraftplus'); ?> :</th> <td><input type="text" size="40" id="updraft_ftp_login" name="updraft_ftp_login" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_ftp_login')); ?> " /></td> </tr> <tr class="updraftplusmethod ftp"> <th><?php _e('FTP Password', 'updraftplus'); ?> :</th> <td><input type="<?php echo apply_filters('updraftplus_admin_secret_field_type', 'text'); ?> " size="40" id="updraft_ftp_pass" name="updraft_ftp_pass" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_ftp_pass')); ?> " /></td> </tr> <tr class="updraftplusmethod ftp"> <th><?php _e('Remote Path', 'updraftplus'); ?> :</th> <td><input type="text" size="64" id="updraft_ftp_remote_path" name="updraft_ftp_remote_path" value="<?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_ftp_remote_path')); ?> " /> <em><?php _e('Needs to already exist', 'updraftplus'); ?> </em></td> </tr> <tr class="updraftplusmethod ftp"> <th></th> <td><p><button id="updraft-ftp-test" type="button" class="button-primary" style="font-size:18px !important"><?php echo sprintf(__('Test %s Settings', 'updraftplus'), 'FTP'); ?> </button></p></td> </tr> <?php }
<?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() {
public function connect() { // Implicit SSL - not handled via PHP's native ftp_ functions, so we use curl instead if ($this->port == 990 || defined('UPDRAFTPLUS_FTP_USECURL') && UPDRAFTPLUS_FTP_USECURL) { if ($this->ssl == false) { $this->port = 21; } else { $this->curl_handle = curl_init(); if (!$this->curl_handle) { $this->port = 21; } else { $options = array(CURLOPT_USERPWD => $this->username . ':' . $this->password, CURLOPT_PORT => $this->port, CURLOPT_CONNECTTIMEOUT => 20, CURLOPT_FTP_CREATE_MISSING_DIRS => true); $options[CURLOPT_FTP_SSL] = CURLFTPSSL_TRY; //CURLFTPSSL_ALL, // require SSL For both control and data connections if (990 == $this->port) { $options[CURLOPT_FTPSSLAUTH] = CURLFTPAUTH_SSL; // CURLFTPAUTH_DEFAULT, // let cURL choose the FTP authentication method (either SSL or TLS) } else { $options[CURLOPT_FTPSSLAUTH] = CURLFTPAUTH_DEFAULT; // let cURL choose the FTP authentication method (either SSL or TLS) } // Prints to STDERR by default - noisy if (defined('WP_DEBUG') && WP_DEBUG == true && UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) { $options[CURLOPT_VERBOSE] = true; } if ($this->disable_verify) { $options[CURLOPT_SSL_VERIFYPEER] = false; $options[CURLOPT_SSL_VERIFYHOST] = 0; } else { $options[CURLOPT_SSL_VERIFYPEER] = true; } if (!$this->use_server_certs) { $options[CURLOPT_CAINFO] = UPDRAFTPLUS_DIR . '/includes/cacert.pem'; } if ($this->passive != true) { $options[CURLOPT_FTPPORT] = '-'; } foreach ($options as $option_name => $option_value) { if (!curl_setopt($this->curl_handle, $option_name, $option_value)) { // throw new Exception( sprintf( 'Could not set cURL option: %s', $option_name ) ); global $updraftplus; if (is_a($updraftplus, 'UpdraftPlus')) { $updraftplus->log("Curl exception: will revert to normal FTP"); } $this->port = 21; $this->curl_handle = false; } } } // All done - leave if ($this->curl_handle) { $this->login_type = 'encrypted (implicit, port 990)'; return true; } } } $time_start = time(); if (function_exists('ftp_ssl_connect') && $this->ssl !== false) { $this->conn_id = ftp_ssl_connect($this->host, $this->port, 15); $attempting_ssl = true; } if ($this->conn_id) { $this->login_type = 'encrypted'; $this->ssl = true; } else { $this->conn_id = ftp_connect($this->host, $this->port, 15); } if ($this->conn_id) { $result = ftp_login($this->conn_id, $this->username, $this->password); } if (!empty($result)) { ftp_set_option($this->conn_id, FTP_TIMEOUT_SEC, $this->timeout); ftp_pasv($this->conn_id, $this->passive); $this->system_type = ftp_systype($this->conn_id); return true; } elseif (!empty($attempting_ssl)) { global $updraftplus_admin; if (isset($updraftplus_admin->logged) && is_array($updraftplus_admin->logged)) { # Clear the previous PHP messages, so that we only show the user messages from the method that worked (or from both if both fail) $save_array = $updraftplus_admin->logged; $updraftplus_admin->logged = array(); #trigger_error(__('Encrypted login failed; trying non-encrypted', 'updraftplus'), E_USER_NOTICE); } $this->ssl = false; $this->login_type = 'non-encrypted'; $time_start = time(); $this->conn_id = ftp_connect($this->host, $this->port, 15); if ($this->conn_id) { $result = ftp_login($this->conn_id, $this->username, $this->password); } if (!empty($result)) { ftp_set_option($this->conn_id, FTP_TIMEOUT_SEC, $this->timeout); ftp_pasv($this->conn_id, $this->passive); $this->system_type = ftp_systype($this->conn_id); return true; } else { # Add back the previous PHP messages if (isset($save_array)) { $updraftplus_admin->logged = array_merge($save_array, $updraftplus_admin->logged); } } } # If we got here, then we failed if (time() - $time_start > 14) { global $updraftplus_admin; if (isset($updraftplus_admin->logged) && is_array($updraftplus_admin->logged)) { $updraftplus_admin->logged[] = sprintf(__('The %s connection timed out; if you entered the server correctly, then this is usually caused by a firewall blocking the connection - you should check with your web hosting company.', 'updraftplus'), 'FTP'); } else { global $updraftplus; $updraftplus->log(sprintf(__('The %s connection timed out; if you entered the server correctly, then this is usually caused by a firewall blocking the connection - you should check with your web hosting company.', 'updraftplus'), 'FTP'), 'error'); } } return false; }
private function save_configuration_bundle() { $this->configuration_bundle = array(); // Some items must always be saved + restored; others only on a migration // Remember, if modifying this, that a restoration can include restoring a destroyed site from a backup onto a fresh WP install on the same URL. So, it is not necessarily desirable to retain the current settings and drop the ones in the backup. $keys_to_save = array('updraft_remotesites', 'updraft_migrator_localkeys'); if ($this->old_siteurl != $this->our_siteurl) { global $updraftplus; $keys_to_save = array_merge($keys_to_save, $updraftplus->get_settings_keys()); $keys_to_save[] = 'updraft_backup_history'; } foreach ($keys_to_save as $key) { $this->configuration_bundle[$key] = UpdraftPlus_Options::get_updraft_option($key); } }
public function download($file) { global $updraftplus; $config = $this->get_config(); $whoweare = $config['whoweare']; $s3 = $this->getS3($config['accesskey'], $config['secretkey'], UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts'), UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify'), UpdraftPlus_Options::get_updraft_option('updraft_ssl_nossl')); if (is_wp_error($s3)) { return $updraftplus->log_wp_error($s3, false, true); } $bucket_name = untrailingslashit($config['path']); $bucket_path = ""; if (preg_match("#^([^/]+)/(.*)\$#", $bucket_name, $bmatches)) { $bucket_name = $bmatches[1]; $bucket_path = $bmatches[2] . "/"; } $region = $config['key'] == 'dreamobjects' || $config['key'] == 's3generic' ? 'n/a' : @$s3->getBucketLocation($bucket_name); if (empty($region) && 's3' == $config['key']) { # Final thing to attempt - see if it was just the location request that failed $s3 = $this->use_dns_bucket_name($s3, $bucket_name); if (false !== ($gb = @$s3->getBucket($bucket_name, null, null, 1))) { $keep_going = true; } } if (!empty($region) || !empty($keep_going)) { $this->set_region($s3, $region); $fullpath = $updraftplus->backups_dir_location() . '/' . $file; if (!$s3->getObject($bucket_name, $bucket_path . $file, $fullpath, true)) { $updraftplus->log("{$whoweare} Error: Failed to download {$file}. Check your permissions and credentials."); $updraftplus->log(sprintf(__('%s Error: Failed to download %s. Check your permissions and credentials.', 'updraftplus'), $whoweare, $file), 'error'); return false; } } else { $updraftplus->log("{$whoweare} Error: Failed to access bucket {$bucket_name}. Check your permissions and credentials."); $updraftplus->log(sprintf(__('%s Error: Failed to access bucket %s. Check your permissions and credentials.', 'updraftplus'), $whoweare, $bucket_name), 'error'); return false; } return true; }