* https://www.dropbox.com/developers/apply?cont=/developers/apps
if (!defined('UPDRAFTPLUS_DIR')) die('No direct access allowed.');
// Converted to multi-options (Feb 2017-) and previous options conversion removed: Yes
if (!class_exists('UpdraftPlus_BackupModule')) require_once(UPDRAFTPLUS_DIR.'/methods/backup-module.php');
// Fix a potential problem for users who had the short-lived 1.12.35-1.12.38 free versions (see: https://wordpress.org/support/topic/1-12-37-dropbox-auth-broken/page/2/#post-8981457)
// Can be removed after a few months
$potential_options = UpdraftPlus_Options::get_updraft_option('updraft_dropbox');
if (is_array($potential_options) && isset($potential_options['version']) && isset($potential_options['settings']) && array() === $potential_options['settings']) {
// Wipe it, which will force its re-creation in proper format
UpdraftPlus_Options::delete_updraft_option('updraft_dropbox');
class UpdraftPlus_BackupModule_dropbox extends UpdraftPlus_BackupModule {
private $current_file_hash;
private $current_file_size;
private $uploaded_offset;
* This callback is called as upload progress is made
* @param Integer $offset - the byte offset
* @param String $uploadid - identifier for the upload in progress
* @param Boolean|String $fullpath - optional full path to the file being uploaded
public function chunked_callback($offset, $uploadid, $fullpath = false) {
$storage = $this->get_storage();
$this->jobdata_set('upload_id_'.$this->current_file_hash, $uploadid);
$this->jobdata_set('upload_offset_'.$this->current_file_hash, $offset);
$time_now = microtime(true);
$time_since_last_tick = $time_now - $this->upload_tick;
$data_since_last_tick = $offset - $this->uploaded_offset;
$this->upload_tick = $time_now;
$this->uploaded_offset = $offset;
// Here we use job-wide data, because we don't expect wildly different performance for different Dropbox accounts
$chunk_size = $updraftplus->jobdata_get('dropbox_chunk_size', 1048576);
// Don't go beyond 10MB, or change the chunk size after the last segment
if ($chunk_size < 10485760 && $this->current_file_size > 0 && $offset < $this->current_file_size) {
$job_run_time = $time_now - $updraftplus->job_time_ms;
if ($time_since_last_tick < 10) {
$upload_rate = $data_since_last_tick / max($time_since_last_tick, 1);
$upload_secs = min(floor($job_run_time), 10);
if ($job_run_time < 15) $upload_secs = max(6, $job_run_time*0.6);
$new_chunk = max(min($upload_secs * $upload_rate * 0.9, 10485760), 1048576);
$new_chunk = $new_chunk - ($new_chunk % 524288);
$chunk_size = (int) $new_chunk;
$storage->setChunkSize($chunk_size);
$updraftplus->jobdata_set('dropbox_chunk_size', $chunk_size);
if ($this->current_file_size > 0) {
$percent = round(100*($offset/$this->current_file_size), 1);
$updraftplus->record_uploaded_chunk($percent, "$uploadid, $offset, ".round($chunk_size/1024, 1)." KB", $fullpath);
$this->log("Chunked Upload: $offset bytes uploaded");
// This act is done by record_uploaded_chunk, and helps prevent overlapping runs
if ($fullpath) touch($fullpath);
public function get_supported_features() {
// This options format is handled via only accessing options via $this->get_options()
return array('multi_options', 'config_templates', 'multi_storage', 'conditional_logic', 'manual_authentication');
public function get_default_options() {
* Check whether options have been set up by the user, or not
* @param Array $opts - the potential options
public function options_exist($opts) {
if (is_array($opts) && !empty($opts['tk_access_token'])) return true;
* Acts as a WordPress options filter
* @param Array $dropbox - An array of Dropbox options
* @return Array - the returned array can either be the set of updated Dropbox settings or a WordPress error array
public function options_filter($dropbox) {
// Get the current options (and possibly update them to the new format)
$opts = UpdraftPlus_Storage_Methods_Interface::update_remote_storage_options_format('dropbox');
if (is_wp_error($opts)) {
if ('recursion' !== $opts->get_error_code()) {
$msg = "(".$opts->get_error_code()."): ".$opts->get_error_message();
error_log("UpdraftPlus: $msg");
// The saved options had a problem; so, return the new ones
// If the input is not as expected, then return the current options
if (!is_array($dropbox)) return $opts;
// Remove instances that no longer exist
foreach ($opts['settings'] as $instance_id => $storage_options) {
if (!isset($dropbox['settings'][$instance_id])) unset($opts['settings'][$instance_id]);
// Dropbox has a special case where the settings could be empty so we should check for this before
if (!empty($dropbox['settings'])) {
foreach ($dropbox['settings'] as $instance_id => $storage_options) {
if (!empty($opts['settings'][$instance_id]['tk_access_token'])) {
$current_app_key = empty($opts['settings'][$instance_id]['appkey']) ? false : $opts['settings'][$instance_id]['appkey'];
$new_app_key = empty($storage_options['appkey']) ? false : $storage_options['appkey'];
// If a different app key is being used, then wipe the stored token as it cannot belong to the new app
if ($current_app_key !== $new_app_key) {
unset($opts['settings'][$instance_id]['tk_access_token']);
unset($opts['settings'][$instance_id]['ownername']);
unset($opts['settings'][$instance_id]['CSRF']);
// Now loop over the new options, and replace old options with them
foreach ($storage_options as $key => $value) {
unset($opts['settings'][$instance_id][$key]);
if (!isset($opts['settings'][$instance_id])) $opts['settings'][$instance_id] = array();
$opts['settings'][$instance_id][$key] = $value;
if (!empty($opts['settings'][$instance_id]['folder']) && preg_match('#^https?://(www.)dropbox\.com/home/Apps/UpdraftPlus(.Com)?([^/]*)/(.*)$#i', $opts['settings'][$instance_id]['folder'], $matches)) $opts['settings'][$instance_id]['folder'] = $matches[3];
// check if we have the dummy nosave option and remove it so that it doesn't get saved
if (isset($opts['settings'][$instance_id]['dummy-nosave'])) unset($opts['settings'][$instance_id]['dummy-nosave']);
public function backup($backup_array) {
$opts = $this->get_options();
if (empty($opts['tk_access_token'])) {
$this->log('You do not appear to be authenticated with Dropbox (1)');
$this->log(__('You do not appear to be authenticated with Dropbox', 'updraftplus'), 'error');
// 28 September 2017: APIv1 is gone. We'll keep the variable to make life easier if there's ever an APIv3.
if (empty($opts['tk_request_token'])) {
$this->log("begin cloud upload (using API version $use_api_ver with OAuth v2 token)");
$this->log("begin cloud upload (using API version $use_api_ver with OAuth v1 token)");
$chunk_size = $updraftplus->jobdata_get('dropbox_chunk_size', 1048576);
$dropbox = $this->bootstrap();
if (false === $dropbox) throw new Exception(__('You do not appear to be authenticated with Dropbox', 'updraftplus'));
$this->log("access gained; setting chunk size to: ".round($chunk_size/1024, 1)." KB");
$dropbox->setChunkSize($chunk_size);
$this->log('error when trying to gain access: '.$e->getMessage().' (line: '.$e->getLine().', file: '.$e->getFile().')');
$this->log(sprintf(__('error: %s (see log file for more)', 'updraftplus'), $e->getMessage()), 'error');
$updraft_dir = $updraftplus->backups_dir_location();
foreach ($backup_array as $file) {
// If we experience any failures collecting account info, then carry on anyway
Quota information is no longer provided with account information a new call to quotaInfo must be made to get this information.
$quota_info = $dropbox->quotaInfo();
// Access token expired try to refresh and then call quota info again
if ("401" == $quota_info['code']) {
$this->log('HTTP code 401 (unauthorized) code returned from Dropbox; attempting to refresh access token');
$dropbox->refreshAccessToken();
$quota_info = $dropbox->quotaInfo();
if ("200" != $quota_info['code']) {
$message = "account/info did not return HTTP 200; returned: ". $quota_info['code'];
} elseif (!isset($quota_info['body'])) {
$message = "account/info did not return the expected data";
$body = $quota_info['body'];
if (isset($body->quota_info)) {
$quota_info = $body->quota_info;
$total_quota = $quota_info->quota;
$normal_quota = $quota_info->normal;
$shared_quota = $quota_info->shared;
$available_quota = $total_quota - ($normal_quota + $shared_quota);
$message = "quota usage: normal=".round($normal_quota/1048576, 1)." MB, shared=".round($shared_quota/1048576, 1)." MB, total=".round($total_quota/1048576, 1)." MB, available=".round($available_quota/1048576, 1)." MB";
$total_quota = max($body->allocation->allocated, 1);
/* check here to see if the account is a team account and if so use the other used value
This will give us their total usage including their individual account and team account */
if (isset($body->allocation->used)) $used = $body->allocation->used;
$available_quota = $total_quota - $used;
$message = "quota usage: used=".round($used/1048576, 1)." MB, total=".round($total_quota/1048576, 1)." MB, available=".round($available_quota/1048576, 1)." MB";
$this->log("exception (".get_class($e).") occurred whilst getting account info: ".$e->getMessage());
// $this->log(sprintf(__("%s error: %s", 'updraftplus'), 'Dropbox', $e->getMessage()).' ('.$e->getCode().')', 'warning', md5($e->getMessage()));
$this->current_file_hash = $hash;
$filesize = filesize($updraft_dir.'/'.$file);
$this->current_file_size = $filesize;
$filesize = $filesize/1024;
$microtime = microtime(true);
if ('None' != ($upload_id = $this->jobdata_get('upload_id_'.$hash, 'None', 'updraf_dbid_'.$hash))) {
$offset = $this->jobdata_get('upload_offset_'.$hash, 0, 'updraf_dbof_'.$hash);
if ($offset) $this->log("This is a resumption: $offset bytes had already been uploaded");
// We don't actually abort now - there's no harm in letting it try and then fail
if (-1 != $available_quota && $available_quota < ($filesize-$offset)) {
$this->log("File upload expected to fail: file data remaining to upload ($file) size is ".($filesize-$offset)." b (overall file size; .".($filesize*1024)." b), whereas available quota is only $available_quota b");
// $this->log(sprintf(__("Account full: your %s account has only %d bytes left, but the file to be uploaded has %d bytes remaining (total size: %d bytes)",'updraftplus'),'Dropbox', $available_quota, $filesize-$offset, $filesize), 'warning');
$ufile = apply_filters('updraftplus_dropbox_modpath', $file, $this);
$this->log("Attempt to upload: $file to: $ufile");
$this->upload_tick = microtime(true);
$this->uploaded_offset = $offset;
$response = $dropbox->chunkedUpload($updraft_dir.'/'.$file, '', $ufile, true, $offset, $upload_id, array($this, 'chunked_callback'));
if (empty($response['code']) || "200" != $response['code']) {
$this->log('Unexpected HTTP code returned from Dropbox: '.$response['code']." (".serialize($response).")");
if ($response['code'] >= 400) {
if (401 == $response['code']) {
$this->log('HTTP code 401 returned from Dropbox, refreshing access token');
$dropbox->refreshAccessToken();
$this->log(sprintf(__('error: failed to upload file to %s (see log file for more)', 'updraftplus'), $file), 'error');
$this->log(__('did not return the expected response - check your log file for more details', 'updraftplus'), 'warning');
$this->log("chunked upload exception (".get_class($e)."): ".$e->getMessage().' (line: '.$e->getLine().', file: '.$e->getFile().')');
if (preg_match("/Submitted input out of alignment: got \[(\d+)\] expected \[(\d+)\]/i", $e->getMessage(), $matches)) {
// Try the indicated offset
$dropbox_wanted = (int) $matches[2];
$this->log("not yet aligned: tried=$we_tried, wanted=$dropbox_wanted; will attempt recovery");
$this->uploaded_offset = $dropbox_wanted;
$upload_id = $this->jobdata_get('upload_id_'.$hash, 'None', 'updraf_dbid_'.$hash);
$dropbox->chunkedUpload($updraft_dir.'/'.$file, '', $ufile, true, $dropbox_wanted, $upload_id, array($this, 'chunked_callback'));
if (preg_match('/Upload with upload_id .* already completed/', $msg)) {
$this->log('returned an error, but apparently indicating previous success: '.$msg);
$this->log($msg.' (line: '.$e->getLine().', file: '.$e->getFile().')');
$this->log(sprintf(__('failed to upload file to %s (see log file for more)', 'updraftplus'), $ufile), 'error');
if (strpos($msg, 'select/poll returned error') !== false && $this->upload_tick > 0 && time() - $this->upload_tick > 800) {
UpdraftPlus_Job_Scheduler::reschedule(60);
$this->log("Select/poll returned after a long time: scheduling a resumption and terminating for now");
UpdraftPlus_Job_Scheduler::record_still_alive();
if (preg_match('/Upload with upload_id .* already completed/', $msg)) {
$this->log('returned an error, but apparently indicating previous success: '.$msg);
$this->log(sprintf(__('failed to upload file to %s (see log file for more)', 'updraftplus'), $ufile), 'error');
if (strpos($msg, 'select/poll returned error') !== false && $this->upload_tick > 0 && time() - $this->upload_tick > 800) {
UpdraftPlus_Job_Scheduler::reschedule(60);
$this->log("Select/poll returned after a long time: scheduling a resumption and terminating for now");
UpdraftPlus_Job_Scheduler::record_still_alive();
$updraftplus->uploaded_file($file);
$microtime_elapsed = microtime(true)-$microtime;
$speedps = ($microtime_elapsed > 0) ? $filesize/$microtime_elapsed : 0;
$speed = sprintf("%.2d", $filesize)." KB in ".sprintf("%.2d", $microtime_elapsed)."s (".sprintf("%.2d", $speedps)." KB/s)";
$this->log("File upload success (".$file."): $speed");
$this->jobdata_delete('upload_id_'.$hash, 'updraf_dbid_'.$hash);
$this->jobdata_delete('upload_offset_'.$hash, 'updraf_dbof_'.$hash);
* This method gets a list of files from the remote stoage that match the string passed in and returns an array of backups
* @param String $match a substring to require (tested via strpos() !== false)
public function listfiles($match = 'backup_') {
$opts = $this->get_options();
if (empty($opts['tk_access_token'])) return new WP_Error('no_settings', __('No settings were found', 'updraftplus').' (dropbox)');
$dropbox = $this->bootstrap();
$this->log('access error: '.$e->getMessage().' (line: '.$e->getLine().', file: '.$e->getFile().')');
return new WP_Error('access_error', $e->getMessage());
$searchpath = '/'.untrailingslashit(apply_filters('updraftplus_dropbox_modpath', '', $this));
/* Some users could have a large amount of backups, the max search is 1000 entries we should continue to search until there are no more entries to bring back. */
$search = $dropbox->search($match, $searchpath, 1000, $cursor);
if (empty($search['code']) || 200 != $search['code']) return new WP_Error('response_error', sprintf(__('%s returned an unexpected HTTP response: %s', 'updraftplus'), 'Dropbox', $search['code']), $search['body']);
if (empty($search['body'])) return array();
if (isset($search['body']->matches) && is_array($search['body']->matches)) {
$matches = array_merge($matches, $search['body']->matches);
} elseif (is_array($search['body'])) {
$matches = $search['body'];
if (isset($search['body']->has_more) && true == $search['body']->has_more && isset($search['body']->cursor)) {
$cursor = $search['body']->cursor;
$this->log($e->getMessage().' (line: '.$e->getLine().', file: '.$e->getFile().')');
// The most likely cause of a search_error is specifying a non-existent path, which should just result in an empty result set.
// return new WP_Error('search_error', $e->getMessage());
foreach ($matches as $item) {
if (!is_object($item)) continue;
if (isset($item->metadata)) $item = $item->metadata; // 2/files/search_v2 has a slightly different output structure compared to 2/files/search model
if ((!isset($item->size) || $item->size > 0) && 'folder' != $item->{'.tag'} && !empty($item->path_display) && 0 === strpos($item->path_display, $searchpath)) {
$path = substr($item->path_display, strlen($searchpath));
if ('/' == substr($path, 0, 1)) $path = substr($path, 1);
// Ones in subfolders are not wanted
if (false !== strpos($path, '/')) continue;
$result = array('name' => $path);
if (!empty($item->size)) $result['size'] = $item->size;
* Identification of Dropbox app
private function defaults() {
return apply_filters('updraftplus_dropbox_defaults', array('Z3Q3ZmkwbnplNHA0Zzlx', 'bTY0bm9iNmY4eWhjODRt'));
* Delete files from the service using the Dropbox API
* @param Array $files - array of filenames to delete
* @param Array $data - unused here
* @param Array $sizeinfo - unused here
* @return Boolean|String - either a boolean true or an error code string
public function delete($files, $data = null, $sizeinfo = array()) {// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- $data and $sizeinfo unused
if (is_string($files)) $files = array($files);
$opts = $this->get_options();
if (empty($opts['tk_access_token'])) {
$this->log('You do not appear to be authenticated with Dropbox (3)');
$this->log(sprintf(__('You do not appear to be authenticated with %s (whilst deleting)', 'updraftplus'), 'Dropbox'), 'warning');
return 'authentication_fail';
$dropbox = $this->bootstrap();
$this->log($e->getMessage().' (line: '.$e->getLine().', file: '.$e->getFile().')');
$this->log(sprintf(__('Failed to access %s when deleting (see log file for more)', 'updraftplus'), 'Dropbox'), 'warning');
return 'service_unavailable';
if (false === $dropbox) return false;
foreach ($files as $file) {
$ufile = apply_filters('updraftplus_dropbox_modpath', $file, $this);
$this->log("request deletion: $ufile");