PluginProbe
UpdraftPlus: WP Backup & Migration Plugin / 1.0.6
UpdraftPlus: WP Backup & Migration Plugin v1.0.6
1.26.7 1.26.6 1.26.5 1.26.4 1.26.3 1.9.19 1.9.25 1.9.26 1.9.30 1.9.31 1.9.32 1.9.4 1.9.40 1.9.41 1.9.42 1.9.43 1.9.44 1.9.45 1.9.46 1.9.5 1.9.50 1.9.51 1.9.60 1.9.62 1.9.63 All 371 releases
updraftplus / updraftplus.php

updraftplus.php in UpdraftPlus: WP Backup & Migration Plugin 1.0.6, at updraftplus.php

2,418 lines 103.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Plugin Name: UpdraftPlus - Backup/Restore
4 Plugin URI: http://wordpress.org/extend/plugins/updraftplus
5 Description: Uploads, themes, plugins, and your DB can be automatically backed up to Amazon S3, Google Drive, FTP, or emailed, on separate schedules.
6 Author: David Anderson.
7 Version: 1.0.6
8 Donate link: http://david.dw-perspective.org.uk/donate
9 License: GPLv3 or later
10 Author URI: http://wordshell.net
11 */
12
13 /*
14 TODO (some of these items mine, some from original Updraft awaiting review):
15 //Add DropBox and Microsoft Skydrive support
16 //Backup record should include *where* the backup was placed, so that we don't attempt to delete old ones from the wrong place? (Or would that be unexpected to users to have things from elsewhere deleted?)
17 //improve error reporting. s3 and dir backup have decent reporting now, but not sure i know what to do from here
18 //list backups that aren't tracked (helps with double backup problem)
19 //investigate $php_errormsg further
20 //pretty up return messages in admin area
21 //check s3/ftp download
22
23 //Rip out the "last backup" bit, and/or put in a display of the last log
24
25 Encrypt filesystem, if memory allows (and have option for abort if not); split up into multiple zips when needed
26 // Does not delete old custom directories upon a restore?
27 */
28
29 /* Portions copyright 2010 Paul Kehrer
30 Portions copyright 2011-12 David Anderson
31 Other portions copyright as indicated authors in the relevant files
32 Particular thanks to Sorin Iclanzan, author of the "Backup" plugin, from which much Google Drive code was taken under the GPLv3+
33
34 This program is free software; you can redistribute it and/or modify
35 it under the terms of the GNU General Public License as published by
36 the Free Software Foundation; either version 3 of the License, or
37 (at your option) any later version.
38
39 This program is distributed in the hope that it will be useful,
40 but WITHOUT ANY WARRANTY; without even the implied warranty of
41 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 GNU General Public License for more details.
43
44 You should have received a copy of the GNU General Public License
45 along with this program; if not, write to the Free Software
46 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
47 */
48 // TODO: Note this might *lower* the limit - should check first.
49
50 @set_time_limit(900); //15 minutes max. i'm not sure how long a really big site could take to back up?
51
52 $updraft = new UpdraftPlus();
53
54 if(!$updraft->memory_check(192)) {
55 # TODO: Better solution is to split the backup set into manageable chunks based on this limit
56 @ini_set('memory_limit', '192M'); //up the memory limit for large backup files... should split the backup set into manageable chunks based on the limit
57 }
58
59 define('UPDRAFT_DEFAULT_OTHERS_EXCLUDE','upgrade,cache,updraft,index.php');
60
61 class UpdraftPlus {
62
63 var $version = '1.0.6';
64
65 var $dbhandle;
66 var $errors = array();
67 var $nonce;
68 var $logfile_name = "";
69 var $logfile_handle = false;
70 var $backup_time;
71 var $gdocs;
72 var $gdocs_access_token;
73
74 function __construct() {
75 // Initialisation actions
76 # Create admin page
77 add_action('admin_menu', array($this,'add_admin_pages'));
78 add_action('admin_init', array($this,'admin_init'));
79 add_action('updraft_backup', array($this,'backup_files'));
80 add_action('updraft_backup_database', array($this,'backup_database'));
81 # backup_all is used by the manual "Backup Now" button
82 add_action('updraft_backup_all', array($this,'backup_all'));
83 # this is our runs-after-backup event, whose purpose is to see if it succeeded or failed, and resume/mom-up etc.
84 add_action('updraft_backup_resume', array($this,'backup_resume'));
85 add_action('wp_ajax_updraft_download_backup', array($this, 'updraft_download_backup'));
86 # http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules
87 add_filter('cron_schedules', array($this,'modify_cron_schedules'));
88 add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
89 add_action('init', array($this, 'googledrive_backup_auth'));
90 }
91
92 // Handle Google OAuth 2.0 - ?page=updraftplus&action=auth
93 function googledrive_backup_auth() {
94 if ( is_admin() && isset( $_GET['page'] ) && $_GET['page'] == 'updraftplus' && isset( $_GET['action'] ) && $_GET['action'] == 'auth' ) {
95 if ( isset( $_GET['state'] ) ) {
96 if ( $_GET['state'] == 'token' )
97 $this->gdrive_auth_token();
98 elseif ( $_GET['state'] == 'revoke' )
99 $this->gdrive_auth_revoke();
100 } elseif (isset($_GET['updraftplus_googleauth'])) {
101 $this->gdrive_auth_request();
102 }
103 }
104 }
105
106 /**
107 * Acquire single-use authorization code from Google OAuth 2.0
108 */
109 function gdrive_auth_request() {
110 $params = array(
111 'response_type' => 'code',
112 'client_id' => get_option('updraft_googledrive_clientid'),
113 'redirect_uri' => admin_url('options-general.php?page=updraftplus&action=auth'),
114 'scope' => 'https://www.googleapis.com/auth/drive.file https://docs.google.com/feeds/ https://docs.googleusercontent.com/ https://spreadsheets.google.com/feeds/',
115 'state' => 'token',
116 'access_type' => 'offline',
117 'approval_prompt' => 'auto'
118 );
119 header('Location: https://accounts.google.com/o/oauth2/auth?'.http_build_query($params));
120 }
121
122 /**
123 * Get a Google account access token using the refresh token
124 */
125 function access_token( $token, $client_id, $client_secret ) {
126 $context = array(
127 'http' => array(
128 'method' => 'POST',
129 'header' => 'Content-type: application/x-www-form-urlencoded',
130 'content' => http_build_query( array(
131 'refresh_token' => $token,
132 'client_id' => $client_id,
133 'client_secret' => $client_secret,
134 'grant_type' => 'refresh_token'
135 ) )
136 )
137 );
138 $this->log("Google Drive: requesting access token: client_id=$client_id");
139 $result = @file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create($context));
140 if($result) {
141 $result = json_decode( $result, true );
142 if ( isset( $result['access_token'] ) ) {
143 $this->log("Google Drive: successfully obtained access token");
144 return $result['access_token'];
145 } else {
146 $this->log("Google Drive error when requesting access token: response does not contain access_token");
147 return false;
148 }
149 } else {
150 $this->log("Google Drive error when requesting access token: no response");
151 return false;
152 }
153 }
154
155 function googledrive_delete_file( $file, $token) {
156 $ids = get_option('updraft_file_ids', array());
157 if (!isset($ids[$file])) {
158 $this->log("Could not delete: could not find a record of the Google Drive file ID for this file");
159 return;
160 } else {
161 $del == $this->gdocs->delete_resource($ids[$file]);
162 if (is_wp_error($del)) {
163 foreach ($del->get_error_messages() as $msg) {
164 $this->log("Deletion failed: $msg");
165 }
166 } else {
167 $this->log("Deletion successful");
168 unset($ids[$file]);
169 update_option('updraft_file_ids', $ids);
170 }
171 }
172 return;
173 }
174
175 /**
176 * Get a Google account refresh token using the code received from gdrive_auth_request
177 */
178 function gdrive_auth_token() {
179 if( isset( $_GET['code'] ) ) {
180 $context = array(
181 'http' => array(
182 'timeout' => 30,
183 'method' => 'POST',
184 'header' => 'Content-type: application/x-www-form-urlencoded',
185 'content' => http_build_query( array(
186 'code' => $_GET['code'],
187 'client_id' => get_option('updraft_googledrive_clientid'),
188 'client_secret' => get_option('updraft_googledrive_secret'),
189 'redirect_uri' => admin_url('options-general.php?page=updraftplus&action=auth'),
190 'grant_type' => 'authorization_code'
191 ) )
192 )
193 );
194 // TODO Use curl??
195 $result = @file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create($context));
196 # Oddly, sometimes fails and then trying again works...
197 /*
198 if (!$result) { sleep(1); $result = @file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create($context));}
199 if (!$result) { sleep(1); $result = @file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create($context));}
200 */
201 if($result) {
202 $result = json_decode( $result, true );
203 if ( isset( $result['refresh_token'] ) ) {
204 update_option('updraft_googledrive_token',$result['refresh_token']); // Save token
205 header('Location: '.admin_url('options-general.php?page=updraftplus&message=' . __( 'Authorization was successful.', 'updraftplus' ) ) );
206 }
207 else {
208 header('Location: '.admin_url('options-general.php?page=updraftplus&error=' . __( 'No refresh token was received!', 'updraftplus' ) ) );
209 }
210 } else {
211 header('Location: '.admin_url('options-general.php?page=updraftplus&error=' . __( 'Bad response!', 'backup' ) ) );
212 }
213 }
214 else {
215 header('Location: '.admin_url('options-general.php?page=updraftplus&error=' . __( 'Authorisation failed!', 'backup' ) ) );
216 }
217 }
218
219 /**
220 * Revoke a Google account refresh token
221 */
222 function gdrive_auth_revoke() {
223 @file_get_contents( 'https://accounts.google.com/o/oauth2/revoke?token=' . get_option('updraft_googledrive_token') );
224 update_option('updraft_googledrive_token','');
225 header( 'Location: '.admin_url( 'options-general.php?page=updraftplus&message=' . __( 'Authorization revoked.', 'backup' ) ) );
226 }
227
228 # Adds the settings link under the plugin on the plugin screen.
229 function plugin_action_links($links, $file) {
230 if ($file == plugin_basename(__FILE__)){
231 $settings_link = '<a href="'.site_url().'/wp-admin/options-general.php?page=updraftplus">'.__("Settings", "UpdraftPlus").'</a>';
232 array_unshift($links, $settings_link);
233 $settings_link = '<a href="http://david.dw-perspective.org.uk/donate">'.__("Donate","UpdraftPlus").'</a>';
234 array_unshift($links, $settings_link);
235 }
236 return $links;
237 }
238
239 function backup_time_nonce() {
240 $this->backup_time = time();
241 $this->nonce = substr(md5(time().rand()),20);
242 }
243
244 # Logs the given line, adding date stamp and newline
245 function log($line) {
246 if ($this->logfile_handle) fwrite($this->logfile_handle,date('r')." ".$line."\n");
247 }
248
249 function backup_resume($resumption_no) {
250 @ignore_user_abort(true);
251 // This is scheduled for 5 minutes after a backup job starts
252 $bnonce = get_transient('updraftplus_backup_job_nonce');
253 if (!$bnonce) return;
254 $this->nonce = $bnonce;
255 $this->logfile_open($bnonce);
256 $this->log("Resume backup ($resumption_no): begin run (will check for any remaining jobs)");
257 $btime = get_transient('updraftplus_backup_job_time');
258 if (!$btime) {
259 $this->log("Did not find stored time setting - aborting");
260 return;
261 }
262 $this->log("Resuming backup: resumption=$resumption_no, nonce=$bnonce, begun at=$btime");
263 // Schedule again, to run in 5 minutes again, in case we again fail
264 $resume_delay = 300;
265 // A different argument than before is needed otherwise the event is ignored
266 $next_resumption = $resumption_no+1;
267 if ($next_resumption < 10) {
268 wp_schedule_single_event(time()+$resume_delay, 'updraft_backup_resume' ,array($next_resumption));
269 } else {
270 $this->log("This is our tenth attempt - will not try again");
271 }
272 $this->backup_time = $btime;
273
274 // Returns an array, most recent first, of backup sets
275 $backup_history = $this->get_backup_history();
276 if (!isset($backup_history[$btime])) $this->log("Error: Could not find a record in the database of a backup with this timestamp");
277
278 $our_files=$backup_history[$btime];
279 $undone_files = array();
280 foreach ($our_files as $key => $file) {
281 $hash = md5($file);
282 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
283 if (get_transient('updraft_'.$hash) === "yes") {
284 $this->log("$file: $key: This file has been successfully uploaded in the last 3 hours");
285 } elseif (is_file($fullpath)) {
286 $this->log("$file: $key: This file has NOT been successfully uploaded in the last 3 hours: will retry");
287 $undone_files[$key] = $file;
288 } else {
289 $this->log("$file: Note: This file was not marked as successfully uploaded, but does not exist on the local filesystem");
290 $this->uploaded_file($file);
291 }
292 }
293
294 if (count($undone_files) == 0) {
295 $this->log("There were no files that needed uploading; backup job is finished");
296 return;
297 }
298
299 $this->log("Requesting backup of the files that were not successfully uploaded");
300 $this->cloud_backup($undone_files);
301 $this->cloud_backup_finish($undone_files);
302
303 $this->log("Resume backup ($resumption_no): finish run");
304
305 $this->backup_finish($next_resumption);
306
307 }
308
309 function backup_all() {
310 $this->backup(true,true);
311 }
312
313 function backup_files() {
314 # Note that the "false" for database gets over-ridden automatically if they turn out to have the same schedules
315 $this->backup(true,false);
316 }
317
318 function backup_database() {
319 # Note that nothing will happen if the file backup had the same schedule
320 $this->backup(false,true);
321 }
322
323 function logfile_open($nonce) {
324 //set log file name and open log file
325 $updraft_dir = $this->backups_dir_location();
326 $this->logfile_name = $updraft_dir. "/log.$nonce.txt";
327 // Use append mode in case it already exists
328 $this->logfile_handle = fopen($this->logfile_name, 'a');
329 }
330
331 //scheduled wp-cron events can have a race condition here if page loads are coming fast enough, but there's nothing we can do about it. TODO: I reckon there is. Store a transient based on the backup schedule. Then as the backup proceeds, check for its existence; if it has changed, then another task has begun, so abort.
332 function backup($backup_files, $backup_database) {
333
334 @ignore_user_abort(true);
335 //generate backup information
336 $this->backup_time_nonce();
337 // If we don't finish in 3 hours, then we won't finish
338 // This transient indicates the identity of the current backup job (which can be used to find the files and logfile)
339 set_transient("updraftplus_backup_job_nonce",$this->nonce,3600*3);
340 set_transient("updraftplus_backup_job_time",$this->backup_time,3600*3);
341 $this->logfile_open($this->nonce);
342
343 // Schedule the even to run later, which checks on success and can resume the backup
344 // We save the time to a variable because it is needed for un-scheduling
345 // $resume_delay = (get_option('updraft_debug_mode')) ? 60 : 300;
346 $resume_delay = 300;
347 wp_schedule_single_event(time()+$resume_delay, 'updraft_backup_resume', array(1));
348 $this->log("In case we run out of time, scheduled a resumption at: $resume_delay seconds from now");
349
350 // Log some information that may be helpful
351 global $wp_version;
352 $this->log("PHP version: ".phpversion()." WordPress version: ".$wp_version." Updraft version: ".$this->version." Backup files: $backup_files (schedule: ".get_option('updraft_interval','unset').") Backup DB: $backup_database (schedule: ".get_option('updraft_interval_database','unset').")");
353
354 # If the files and database schedules are the same, and if this the file one, then we rope in database too.
355 # On the other hand, if the schedules were the same and this was the database run, then there is nothing to do.
356 if (get_option('updraft_interval') == get_option('updraft_interval_database') || get_option('updraft_interval_database','xyz') == 'xyz' ) {
357 $backup_database = ($backup_files == true) ? true : false;
358 }
359
360 $this->log("Processed schedules. Tasks now: Backup files: $backup_files Backup DB: $backup_database");
361
362 # Possibly now nothing is to be done, except to close the log file
363 if ($backup_files || $backup_database) {
364
365 $backup_contains = "";
366
367 $backup_array = array();
368
369 //backup directories and return a numerically indexed array of file paths to the backup files
370 if ($backup_files) {
371 $this->log("Beginning backup of directories");
372 $backup_array = $this->backup_dirs();
373 $backup_contains = "Files only (no database)";
374 }
375
376 //backup DB and return string of file path
377 if ($backup_database) {
378 $this->log("Beginning backup of database");
379 $db_backup = $this->backup_db();
380 //add db path to rest of files
381 if(is_array($backup_array)) { $backup_array['db'] = $db_backup; }
382 $backup_contains = ($backup_files) ? "Files and database" : "Database only (no files)";
383 }
384
385 set_transient("updraftplus_backupcontains", $backup_contains, 3600*3);
386
387 //save this to our history so we can track backups for the retain feature
388 $this->log("Saving backup history");
389 // This is done before cloud despatch, because we want a record of what *should* be in the backup. Whether it actually makes it there or not is not yet known.
390 $this->save_backup_history($backup_array);
391
392 //cloud operations (S3,Google Drive,FTP,email,nothing)
393 //this also calls the retain (prune) feature at the end (done in this method to reuse existing cloud connections)
394 if(is_array($backup_array) && count($backup_array) >0) {
395 $this->log("Beginning dispatch of backup to remote");
396 $this->cloud_backup($backup_array);
397 }
398
399 //save the last backup info, including errors, if any
400 $this->log("Saving last backup information into WordPress db");
401 $this->save_last_backup($backup_array);
402
403 // Send the email
404 $this->cloud_backup_finish($backup_array);
405
406 }
407
408 // Close log file; delete and also delete transients if not in debug mode
409 $this->backup_finish(1);
410
411 }
412
413 function backup_finish($cancel_event) {
414
415 // In fact, leaving the hook to run (if debug is set) is harmless, as the resume job should only do tasks that were left unfinished, which at this stage is none.
416 if (empty($this->errors)) {
417 $this->log("There were no errors in the uploads, so the 'resume' event is being unscheduled");
418 wp_clear_scheduled_hook('updraft_backup_resume', array($cancel_event));
419 delete_transient("updraftplus_backup_job_nonce");
420 delete_transient("updraftplus_backup_job_time");
421 } else {
422 $this->log("There were errors in the uploads, so the 'resume' event is remaining scheduled");
423 }
424
425 @fclose($this->logfile_handle);
426
427 if (!get_option('updraft_debug_mode')) @unlink($this->logfile_name);
428
429 }
430
431 function cloud_backup_finish($backup_array) {
432
433 // Send the results email if requested
434 if(get_option('updraft_email') != "" && get_option('updraft_service') != 'email') $this->send_results_email();
435
436 }
437
438 function send_results_email() {
439
440 $sendmail_to = get_option('updraft_email');
441
442 $this->log("Sending email report to: ".$sendmail_to);
443
444 $append_log = (get_option('updraft_debug_mode') && $this->logfile_name != "") ? "\r\nLog contents:\r\n".file_get_contents($this->logfile_name) : "" ;
445
446 wp_mail($sendmail_to,'Backed up: '.get_bloginfo('name').' (UpdraftPlus '.$this->version.') '.date('Y-m-d H:i',time()),'Site: '.site_url()."\r\nUpdraftPlus WordPress backup is complete.\r\nBackup contains: ".get_transient("updraftplus_backupcontains")."\r\n\r\n".$this->wordshell_random_advert(0)."\r\n".$append_log);
447
448 }
449
450 function save_last_backup($backup_array) {
451 $success = (empty($this->errors))?1:0;
452
453 $last_backup = array('backup_time'=>$this->backup_time, 'backup_array'=>$backup_array, 'success'=>$success, 'errors'=>$this->errors);
454
455 update_option('updraft_last_backup', $last_backup);
456 }
457
458 // This should be called whenever a file is successfully uploaded
459 function uploaded_file($file, $id = false) {
460 # We take an MD5 hash because set_transient wants a name of 45 characters or less
461 $hash = md5($file);
462 $this->log("$file: $hash: recording as successfully uploaded");
463 set_transient("updraft_".$hash, "yes", 3600*4);
464 if ($id) {
465 $ids = get_option('updraft_file_ids', array() );
466 $ids[$file] = $id;
467 update_option('updraft_file_ids',$ids);
468 $this->log("Stored file<->id correlation in database ($file <-> $id)");
469 }
470 // Delete local files if the option is set
471 $this->delete_local($file);
472
473 }
474
475 function cloud_backup($backup_array) {
476 switch(get_option('updraft_service')) {
477 case 's3':
478 @set_time_limit(900);
479 $this->log("Cloud backup: S3");
480 if (count($backup_array) >0) $this->s3_backup($backup_array);
481 break;
482 case 'googledrive':
483 @set_time_limit(900);
484 $this->log("Cloud backup: Google Drive");
485 if (count($backup_array) >0) $this->googledrive_backup($backup_array);
486 break;
487 case 'ftp':
488 @set_time_limit(900);
489 $this->log("Cloud backup: FTP");
490 if (count($backup_array) >0) $this->ftp_backup($backup_array);
491 break;
492 case 'email':
493 @set_time_limit(900);
494 $this->log("Cloud backup: Email");
495 //files can easily get way too big for this...
496 foreach($backup_array as $type=>$file) {
497 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
498 wp_mail(get_option('updraft_email'),"WordPress Backup ".date('Y-m-d H:i',$this->backup_time),"Backup is of the $type. Be wary; email backups may fail because of file size limitations on mail servers.",null,array($fullpath));
499 $this->uploaded_file($file);
500 }
501 //we don't break here so it goes and executes all the default behavior below as well. this gives us retain behavior for email
502 default:
503 $this->prune_retained_backups("local");
504 break;
505 }
506 }
507
508 // Carries out retain behaviour. Pass in a valid S3 or FTP object and path if relevant.
509 function prune_retained_backups($updraft_service,$remote_object,$remote_path) {
510 $this->log("Retain: beginning examination of existing backup sets");
511 $updraft_retain = get_option('updraft_retain');
512 // Number of backups to retain
513 $retain = (isset($updraft_retain))?get_option('updraft_retain'):1;
514 $this->log("Retain: user setting: number to retain = $retain");
515 // Returns an array, most recent first, of backup sets
516 $backup_history = $this->get_backup_history();
517 $db_backups_found = 0;
518 $file_backups_found = 0;
519 $this->log("Number of backup sets in history: ".count($backup_history));
520 foreach ($backup_history as $backup_datestamp => $backup_to_examine) {
521 // $backup_to_examine is an array of file names, keyed on db/plugins/themes/uploads
522 // The new backup_history array is saved afterwards, so remember to unset the ones that are to be deleted
523 $this->log("Examining backup set with datestamp: $backup_datestamp");
524 if (isset($backup_to_examine['db'])) {
525 $db_backups_found++;
526 $this->log("$backup_datestamp: this set includes a database (".$backup_to_examine['db']."); db count is now $db_backups_found");
527 if ($db_backups_found > $retain) {
528 $this->log("$backup_datestamp: over retain limit; will delete this database");
529 $file = $backup_to_examine['db'];
530 $this->log("$backup_datestamp: Delete this file: $file");
531 if ($file != '') {
532 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
533 @unlink($fullpath); //delete it if it's locally available
534 if ($updraft_service == "s3") {
535 if (preg_match("#^([^/]+)/(.*)$#",$remote_path,$bmatches)) {
536 $s3_bucket=$bmatches[1];
537 $s3_uri = $bmatches[2]."/".$file;
538 } else {
539 $s3_bucket = $remote_path;
540 $s3_uri = $file;
541 }
542 $this->log("$backup_datestamp: Delete remote: bucket=$s3_bucket, URI=$s3_uri");
543 # Here we brought in the function deleteObject in order to get more direct access to any error
544 $rest = new S3Request('DELETE', $s3_bucket, $s3_uri);
545 $rest = $rest->getResponse();
546 if ($rest->error === false && $rest->code !== 204) {
547 $this->log("S3 Error: Expected HTTP response 204; got: ".$rest->code);
548 $this->error("S3 Error: Unexpected HTTP response code ".$rest->code." (expected 204)");
549 } elseif ($rest->error !== false) {
550 $this->log("S3 Error: ".$rest->error['code'].": ".$rest->error['message']);
551 $this->error("S3 delete error: ".$rest->error['code'].": ".$rest->error['message']);
552 }
553 } elseif ($updraft_service == "ftp") {
554 $this->log("$backup_datestamp: Delete remote ftp: $remote_path/$file");
555 @$remote_object->delete($remote_path.$file);
556 } elseif ($updraft_service == "googledrive") {
557 $this->log("$backup_datestamp: Delete remote file from Google Drive: $file");
558 $this->googledrive_delete_file($file,$remote_object);
559 }
560 }
561 unset($backup_to_examine['db']);
562 }
563 }
564 if (isset($backup_to_examine['plugins']) || isset($backup_to_examine['themes']) || isset($backup_to_examine['uploads']) || isset($backup_to_examine['others'])) {
565 $file_backups_found++;
566 $this->log("$backup_datestamp: this set includes files; fileset count is now $file_backups_found");
567 if ($file_backups_found > $retain) {
568 $this->log("$backup_datestamp: over retain limit; will delete this file set");
569 $file = isset($backup_to_examine['plugins']) ? $backup_to_examine['plugins'] : "";
570 $file2 = isset($backup_to_examine['themes']) ? $backup_to_examine['themes'] : "";
571 $file3 = isset($backup_to_examine['uploads']) ? $backup_to_examine['uploads'] : "";
572 $file4 = isset($backup_to_examine['others']) ? $backup_to_examine['others'] : "";
573 foreach (array($file,$file2,$file3,$file4) as $dofile) {
574 if ($dofile) {
575 $this->log("$backup_datestamp: Delete this file: $dofile");
576 $fullpath = trailingslashit(get_option('updraft_dir')).$dofile;
577 @unlink($fullpath); //delete it if it's locally available
578 if ($updraft_service == "s3") {
579 if (preg_match("#^([^/]+)/(.*)$#",$remote_path,$bmatches)) {
580 $s3_bucket=$bmatches[1];
581 $s3_uri = $bmatches[2]."/".$dofile;
582 } else {
583 $s3_bucket = $remote_path;
584 $s3_uri = $dofile;
585 }
586 $this->log("$backup_datestamp: Delete remote: bucket=$s3_bucket, URI=$s3_uri");
587 # Here we brought in the function deleteObject in order to get more direct access to any error
588 $rest = new S3Request('DELETE', $s3_bucket, $s3_uri);
589 $rest = $rest->getResponse();
590 if ($rest->error === false && $rest->code !== 204) {
591 $this->log("S3 Error: Expected HTTP response 204; got: ".$rest->code);
592 $this->error("S3 Error: Unexpected HTTP response code ".$rest->code." (expected 204)");
593 } elseif ($rest->error !== false) {
594 $this->log("S3 Error: ".$rest->error['code'].": ".$rest->error['message']);
595 $this->error("S3 delete error: ".$rest->error['code'].": ".$rest->error['message']);
596 }
597 } elseif ($updraft_service == "ftp") {
598 $this->log("$backup_datestamp: Delete remote ftp: $remote_path/$dofile");
599 @$remote_object->delete($remote_path.$dofile);
600 } elseif ($updraft_service == "googledrive") {
601 $this->log("$backup_datestamp: Delete remote file from Google Drive: $dofile");
602 $this->googledrive_delete_file($dofile,$remote_object);
603 }
604 }
605 }
606 unset($backup_to_examine['plugins']);
607 unset($backup_to_examine['themes']);
608 unset($backup_to_examine['uploads']);
609 unset($backup_to_examine['others']);
610 }
611 }
612 // Delete backup set completely if empty, o/w just remove DB
613 if (count($backup_to_examine)==0) {
614 $this->log("$backup_datestamp: this backup set is now empty; will remove from history");
615 unset($backup_history[$backup_datestamp]);
616 } else {
617 $this->log("$backup_datestamp: this backup set remains non-empty; will retain in history");
618 $backup_history[$backup_datestamp] = $backup_to_examine;
619 }
620 }
621 $this->log("Retain: saving new backup history (sets now: ".count($backup_history).") and finishing retain operation");
622 update_option('updraft_backup_history',$backup_history);
623 }
624
625 function s3_backup($backup_array) {
626
627 if(!class_exists('S3')) require_once(dirname(__FILE__).'/includes/S3.php');
628
629 $s3 = new S3(get_option('updraft_s3_login'), get_option('updraft_s3_pass'));
630
631 $bucket_name = untrailingslashit(get_option('updraft_s3_remote_path'));
632 $bucket_path = "";
633 $orig_bucket_name = $bucket_name;
634
635 if (preg_match("#^([^/]+)/(.*)$#",$bucket_name,$bmatches)) {
636 $bucket_name = $bmatches[1];
637 $bucket_path = $bmatches[2]."/";
638 }
639
640 if (@$s3->putBucket($bucket_name, S3::ACL_PRIVATE)) {
641
642 foreach($backup_array as $file) {
643
644 // We upload in 5Mb chunks to allow more efficient resuming and hence uploading of larger files
645 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
646 $chunks = floor(filesize($fullpath) / 5242880)+1;
647 $hash = md5($file);
648
649 $this->log("S3 upload: $fullpath (chunks: $chunks) -> s3://$bucket_name/$bucket_path$file");
650
651 $filepath = $bucket_path.$file;
652
653 // This is extra code for the 1-chunk case, but less overhead (no bothering with transients)
654 if ($chunks < 2) {
655 if (!$s3->putObjectFile($fullpath, $bucket_name, $filepath)) {
656 $this->log("S3 regular upload: failed");
657 $this->error("S3 Error: Failed to upload $fullpath. Error was ".$php_errormsg);
658 } else {
659 $this->log("S3 regular upload: success");
660 $this->uploaded_file($file);
661 }
662 } else {
663
664 // Retrieve the upload ID
665 $uploadId = get_transient("updraft_${hash}_uid");
666 if (empty($uploadId)) {
667 $uploadId = $s3->initiateMultipartUpload($bucket_name, $filepath);
668 if (empty($uploadId)) {
669 $this->log("S3 upload: failed: could not get uploadId for multipart upload");
670 continue;
671 } else {
672 $this->log("S3 chunked upload: got multipart ID: $uploadId");
673 set_transient("updraft_${hash}_uid", $uploadId, 3600*3);
674 }
675 } else {
676 $this->log("S3 chunked upload: retrieved previously obtained multipart ID: $uploadId");
677 }
678
679 $successes = 0;
680 $etags = array();
681 for ($i = 1 ; $i <= $chunks; $i++) {
682 # Shorted to upd here to avoid hitting the 45-character limit
683 $etag = get_transient("upd_${hash}_e$i");
684 if (strlen($etag) > 0) {
685 $this->log("S3 chunk $i: was already completed (etag: $etag)");
686 $successes++;
687 array_push($etags, $etag);
688 } else {
689 $etag = $s3->uploadPart($bucket_name, $filepath, $uploadId, $fullpath, $i);
690 if (is_string($etag)) {
691 $this->log("S3 chunk $i: uploaded (etag: $etag)");
692 array_push($etags, $etag);
693 set_transient("upd_${hash}_e$i", $etag, 3600*3);
694 $successes++;
695 } else {
696 $this->error("S3 chunk $i: upload failed");
697 $this->log("S3 chunk $i: upload failed");
698 }
699 }
700 }
701 if ($successes >= $chunks) {
702 $this->log("S3 upload: all chunks uploaded; will now instruct S3 to re-assemble");
703 if ($s3->completeMultipartUpload ($bucket_name, $filepath, $uploadId, $etags)) {
704 $this->log("S3 upload: re-assembly succeeded");
705 $this->uploaded_file($file);
706 } else {
707 $this->log("S3 upload: re-assembly failed");
708 $this->error("S3 upload: re-assembly failed");
709 }
710 } else {
711 $this->log("S3 upload: upload was not completely successful on this run");
712 }
713 }
714 }
715 $this->prune_retained_backups('s3',$s3,$orig_bucket_name);
716 } else {
717 $this->log("S3 Error: Failed to create bucket $bucket_name. Error was ".$php_errormsg);
718 $this->error("S3 Error: Failed to create bucket $bucket_name. Error was ".$php_errormsg);
719 }
720 }
721
722 // This function taken from wordpress.org/extend/plugins/backup, by Sorin Iclanzan, under the GPLv3 or later at your choice
723 function is_gdocs( $thing ) {
724 if ( is_object( $thing ) && is_a( $thing, 'UpdraftPlus_GDocs' ) )
725 return true;
726 return false;
727 }
728
729 // This function modified from wordpress.org/extend/plugins/backup, by Sorin Iclanzan, under the GPLv3 or later at your choice
730 function need_gdocs() {
731
732 if ( ! $this->is_gdocs( $this->gdocs ) ) {
733 if ( get_option('updraft_googledrive_token') == "" || get_option('updraft_googledrive_clientid') == "" || get_option('updraft_googledrive_secret') == "" ) {
734 $this->log("GoogleDrive: this account is not authorised");
735 return new WP_Error( "not_authorized", "Account is not authorized." );
736 }
737
738 if ( is_wp_error( $this->gdocs_access_token ) ) return $access_token;
739
740 $this->gdocs = new UpdraftPlus_GDocs( $this->gdocs_access_token );
741 $this->gdocs->set_option( 'chunk_size', 1*1024*1024 ); # 1Mb; change from default of 512Kb
742 $this->gdocs->set_option( 'request_timeout', 10 ); # Change from default of 10s
743 $this->gdocs->set_option( 'max_resume_attempts', 36 ); # Doesn't look like GDocs class actually uses this anyway
744 }
745 return true;
746 }
747
748 // Returns:
749 // true = already uploaded
750 // false = failure
751 // otherwise, the file ID
752 function googledrive_upload_file( $file, $title, $parent = '') {
753
754 // Make sure $this->gdocs is a UpdraftPlus_GDocs object, or give an error
755 if ( is_wp_error( $e = $this->need_gdocs() ) ) return false;
756
757 $hash = md5($file);
758 $transkey = 'upd_'.$hash.'_gloc';
759 // This is unset upon completion, so if it is set then we are resuming
760 $possible_location = get_transient($transkey);
761
762 if ( empty( $possible_location ) ) {
763 $this->log("$file: Attempting to upload file to Google Drive.");
764 $location = $this->gdocs->prepare_upload( $file, $title, $parent );
765 } else {
766 $this->log("$file: Attempting to resume upload.");
767 $location = $this->gdocs->resume_upload( $file, $possible_location );
768 }
769
770 if ( is_wp_error( $location ) ) {
771 $this->log("GoogleDrive upload: an error occurred");
772 foreach ($location->get_error_messages() as $msg) {
773 $this->error($msg);
774 $this->log("Error details: ".$msg);
775 }
776 return false;
777 }
778
779 if (!is_string($location) && true == $location) {
780 $this->log("$file: this file is already uploaded");
781 return true;
782 }
783
784 if ( is_string( $location ) ) {
785 $res = $location;
786 $this->log("Uploading file with title ".$title);
787 $d = 0;
788 do {
789 $this->log("Google Drive upload: chunk d: $d, loc: $res");
790 $res = $this->gdocs->upload_chunk();
791 if (is_string($res)) set_transient($transkey, $res, 3600*3);
792 $p = $this->gdocs->get_upload_percentage();
793 if ( $p - $d >= 1 ) {
794 $b = intval( $p - $d );
795 // echo '<span style="width:' . $b . '%"></span>';
796 $d += $b;
797 }
798 // $this->options['backup_list'][$id]['speed'] = $this->gdocs->get_upload_speed();
799 } while ( is_string( $res ) );
800 // echo '</div>';
801
802 if ( is_wp_error( $res ) || $res !== true) {
803 $this->log( "An error occurred during GoogleDrive upload (2)" );
804 $this->error( "An error occurred during GoogleDrive upload (2)" );
805 if (is_wp_error( $res )) {
806 foreach ($res->get_error_messages() as $msg) { $this->log($msg); }
807 }
808 return false;
809 }
810
811 $this->log("The file was successfully uploaded to Google Drive in ".number_format_i18n( $this->gdocs->time_taken(), 3)." seconds at an upload speed of ".size_format( $this->gdocs->get_upload_speed() )."/s.");
812
813 delete_transient($transkey);
814 // unset( $this->options['backup_list'][$id]['location'], $this->options['backup_list'][$id]['attempt'] );
815 }
816
817 return $this->gdocs->get_file_id();
818
819 // $this->update_quota();
820 // Google's "user info" service
821 // if ( empty( $this->options['user_info'] ) ) $this->set_user_info();
822
823 }
824
825 // This function just does the formalities, and off-loads the main work to googledrive_upload_file
826 function googledrive_backup($backup_array) {
827
828 require_once(dirname(__FILE__).'/includes/class-gdocs.php');
829
830 // Do we have an access token?
831 if ( !$access_token = $this->access_token( get_option('updraft_googledrive_token'), get_option('updraft_googledrive_clientid'), get_option('updraft_googledrive_secret') )) {
832 $this->log('ERROR: Have not yet obtained an access token from Google (has the user authorised?)');
833 return new WP_Error( "no_access_token", "Have not yet obtained an access token from Google (has the user authorised?");
834 }
835
836 $this->gdocs_access_token = $access_token;
837
838 foreach ($backup_array as $file) {
839 $file_path = trailingslashit(get_option('updraft_dir')).$file;
840 $file_name = basename($file_path);
841 $this->log("$file_name: Attempting to upload to Google Drive");
842 $timer_start = microtime(true);
843 if ( $id = $this->googledrive_upload_file( $file_path, $file_name, get_option('updraft_googledrive_remotepath')) ) {
844 $this->log('OK: Archive ' . $file_name . ' uploaded to Google Drive in ' . ( round(microtime( true ) - $timer_start,2) ) . ' seconds (id: '.$id.')' );
845 $this->uploaded_file($file, $id);
846 } else {
847 $this->error("$file_name: Failed to upload to Google Drive" );
848 $this->log("ERROR: $file_name: Failed to upload to Google Drive" );
849 }
850 }
851 $this->prune_retained_backups("googledrive",$access_token,get_option('updraft_googledrive_remotepath'));
852 }
853
854 function ftp_backup($backup_array) {
855 if( !class_exists('ftp_wrapper')) {
856 require_once(dirname(__FILE__).'/includes/ftp.class.php');
857 }
858 //handle SSL and errors at some point TODO
859 $ftp = new ftp_wrapper(get_option('updraft_server_address'),get_option('updraft_ftp_login'),get_option('updraft_ftp_pass'));
860 $ftp->passive = true;
861 $ftp->connect();
862 //$ftp->make_dir(); we may need to recursively create dirs? TODO
863
864 $ftp_remote_path = trailingslashit(get_option('updraft_ftp_remote_path'));
865 foreach($backup_array as $file) {
866 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
867 if ($ftp->put($fullpath,$ftp_remote_path.$file,FTP_BINARY)) {
868 $this->log("ERROR: $file_name: Successfully uploaded via FTP");
869 $this->uploaded_file($file);
870 } else {
871 $this->error("$file_name: Failed to upload to FTP" );
872 $this->log("ERROR: $file_name: Failed to upload to FTP" );
873 }
874 }
875 $this->prune_retained_backups("ftp",$ftp,$ftp_remote_path);
876 }
877
878 function delete_local($file) {
879 if(get_option('updraft_delete_local')) {
880 $this->log("Deleting local file: $file");
881 //need error checking so we don't delete what isn't successfully uploaded?
882 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
883 return unlink($fullpath);
884 }
885 return true;
886 }
887
888 function backup_dirs() {
889 if(!$this->backup_time) $this->backup_time_nonce();
890 $wp_themes_dir = WP_CONTENT_DIR.'/themes';
891 $wp_upload_dir = wp_upload_dir();
892 $wp_upload_dir = $wp_upload_dir['basedir'];
893 $wp_plugins_dir = WP_PLUGIN_DIR;
894
895 if(!class_exists('PclZip')) require_once(ABSPATH.'/wp-admin/includes/class-pclzip.php');
896
897 $updraft_dir = $this->backups_dir_location();
898 if(!is_writable($updraft_dir)) $this->error('Backup directory is not writable, or does not exist.','fatal');
899
900 //get the blog name and rip out all non-alphanumeric chars other than _
901 $blog_name = str_replace(' ','_',get_bloginfo());
902 $blog_name = preg_replace('/[^A-Za-z0-9_]/','', $blog_name);
903 if(!$blog_name) $blog_name = 'non_alpha_name';
904
905 $backup_file_base = $updraft_dir.'/backup_'.date('Y-m-d-Hi',$this->backup_time).'_'.$blog_name.'_'.$this->nonce;
906
907 $backup_array = array();
908
909 # Plugins
910 @set_time_limit(900);
911 if (get_option('updraft_include_plugins', true)) {
912 $this->log("Beginning backup of plugins");
913 $full_path = $backup_file_base.'-plugins.zip';
914 $plugins = new PclZip($full_path);
915 # The paths in the zip should then begin with 'plugins', having removed WP_CONTENT_DIR from the front
916 if (!$plugins->create($wp_plugins_dir,PCLZIP_OPT_REMOVE_PATH,WP_CONTENT_DIR)) {
917 $this->error('Could not create plugins zip. Error was '.$php_errmsg,'fatal');
918 $this->log('ERROR: PclZip failure: Could not create plugins zip');
919 } else {
920 $this->log("Created plugins zip - file size is ".filesize($full_path)." bytes");
921 }
922 $backup_array['plugins'] = basename($full_path);
923 } else {
924 $this->log("No backup of plugins: excluded by user's options");
925 }
926
927 # Themes
928 @set_time_limit(900);
929 if (get_option('updraft_include_themes', true)) {
930 $this->log("Beginning backup of themes");
931 $full_path = $backup_file_base.'-themes.zip';
932 $themes = new PclZip($full_path);
933 if (!$themes->create($wp_themes_dir,PCLZIP_OPT_REMOVE_PATH,WP_CONTENT_DIR)) {
934 $this->error('Could not create themes zip. Error was '.$php_errmsg,'fatal');
935 $this->log('ERROR: PclZip failure: Could not create themes zip');
936 } else {
937 $this->log("Created themes zip - file size is ".filesize($full_path)." bytes");
938 }
939 $backup_array['themes'] = basename($full_path);
940 } else {
941 $this->log("No backup of themes: excluded by user's options");
942 }
943
944 # Uploads
945 @set_time_limit(900);
946 if (get_option('updraft_include_uploads', true)) {
947 $this->log("Beginning backup of uploads");
948 $full_path = $backup_file_base.'-uploads.zip';
949 $uploads = new PclZip($full_path);
950 if (!$uploads->create($wp_upload_dir,PCLZIP_OPT_REMOVE_PATH,WP_CONTENT_DIR)) {
951 $this->error('Could not create uploads zip. Error was '.$php_errmsg,'fatal');
952 $this->log('ERROR: PclZip failure: Could not create uploads zip');
953 } else {
954 $this->log("Created uploads zip - file size is ".filesize($full_path)." bytes");
955 }
956 $backup_array['uploads'] = basename($full_path);
957 } else {
958 $this->log("No backup of uploads: excluded by user's options");
959 }
960
961 # Others
962 @set_time_limit(900);
963 if (get_option('updraft_include_others', true)) {
964 $this->log("Beginning backup of other directories found in the content directory");
965 $full_path=$backup_file_base.'-others.zip';
966 $others = new PclZip($full_path);
967 // http://www.phpconcept.net/pclzip/user-guide/53
968 /* First parameter to create is:
969 An array of filenames or dirnames,
970 or
971 A string containing the filename or a dirname,
972 or
973 A string containing a list of filename or dirname separated by a comma.
974 */
975 // First, see what we can find. We always want to exclude these:
976 $wp_themes_dir = WP_CONTENT_DIR.'/themes';
977 $wp_upload_dir = wp_upload_dir();
978 $wp_upload_dir = $wp_upload_dir['basedir'];
979 $wp_plugins_dir = WP_PLUGIN_DIR;
980 $updraft_dir = untrailingslashit(get_option('updraft_dir'));
981
982 # Initialise
983 $other_dirlist = array();
984
985 $others_skip = preg_split("/,/",get_option('updraft_include_others_exclude',UPDRAFT_DEFAULT_OTHERS_EXCLUDE));
986 # Make the values into the keys
987 $others_skip = array_flip($others_skip);
988
989 $this->log('Looking for candidates to back up in: '.WP_CONTENT_DIR);
990 if ($handle = opendir(WP_CONTENT_DIR)) {
991 while (false !== ($entry = readdir($handle))) {
992 $candidate = WP_CONTENT_DIR.'/'.$entry;
993 if ($entry == "." || $entry == "..") { ; }
994 elseif ($candidate == $updraft_dir) { $this->log("$entry: skipping: this is the updraft directory"); }
995 elseif ($candidate == $wp_themes_dir) { $this->log("$entry: skipping: this is the themes directory"); }
996 elseif ($candidate == $wp_upload_dir) { $this->log("$entry: skipping: this is the uploads directory"); }
997 elseif ($candidate == $wp_plugins_dir) { $this->log("$entry: skipping: this is the plugins directory"); }
998 elseif (isset($others_skip[$entry])) { $this->log("$entry: skipping: excluded by options"); }
999 else { $this->log("$entry: adding to list"); array_push($other_dirlist,$candidate); }
1000 }
1001 } else {
1002 $this->log('ERROR: Could not read the content directory: '.WP_CONTENT_DIR);
1003 }
1004
1005 if (count($other_dirlist)>0) {
1006 if (!$others->create($other_dirlist,PCLZIP_OPT_REMOVE_PATH,WP_CONTENT_DIR)) {
1007 $this->error('Could not create other zip. Error was '.$php_errmsg,'fatal');
1008 $this->log('ERROR: PclZip failure: Could not create other zip');
1009 } else {
1010 $this->log("Created other directories zip - file size is ".filesize($full_path)." bytes");
1011 }
1012 $backup_array['others'] = basename($full_path);
1013 } else {
1014 $this->log("No backup of other directories: there was nothing found to back up");
1015 }
1016 } else {
1017 $this->log("No backup of other directories: excluded by user's options");
1018 }
1019 return $backup_array;
1020 }
1021
1022 function save_backup_history($backup_array) {
1023 //TODO: this stores full paths right now. should probably concatenate with ABSPATH to make it easier to move sites
1024 if(is_array($backup_array)) {
1025 $backup_history = get_option('updraft_backup_history');
1026 $backup_history = (is_array($backup_history)) ? $backup_history : array();
1027 $backup_history[$this->backup_time] = $backup_array;
1028 update_option('updraft_backup_history',$backup_history);
1029 } else {
1030 $this->error('Could not save backup history because we have no backup array. Backup probably failed.');
1031 }
1032 }
1033
1034 function get_backup_history() {
1035 //$backup_history = get_option('updraft_backup_history');
1036 //by doing a raw DB query to get the most up-to-date data from this option we slightly narrow the window for the multiple-cron race condition
1037 global $wpdb;
1038 $backup_history = @unserialize($wpdb->get_var($wpdb->prepare("SELECT option_value from $wpdb->options WHERE option_name='updraft_backup_history'")));
1039 if(is_array($backup_history)) {
1040 krsort($backup_history); //reverse sort so earliest backup is last on the array. this way we can array_pop
1041 } else {
1042 $backup_history = array();
1043 }
1044 return $backup_history;
1045 }
1046
1047
1048 /*START OF WB-DB-BACKUP BLOCK*/
1049
1050 function backup_db() {
1051
1052 $total_tables = 0;
1053
1054 global $table_prefix, $wpdb;
1055 if(!$this->backup_time) {
1056 $this->backup_time_nonce();
1057 }
1058
1059 $all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
1060 $all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
1061
1062 $updraft_dir = $this->backups_dir_location();
1063 //get the blog name and rip out all non-alphanumeric chars other than _
1064 $blog_name = str_replace(' ','_',get_bloginfo());
1065 $blog_name = preg_replace('/[^A-Za-z0-9_]/','', $blog_name);
1066 if(!$blog_name) {
1067 $blog_name = 'non_alpha_name';
1068 }
1069
1070 $backup_file_base = $updraft_dir.'/backup_'.date('Y-m-d-Hi',$this->backup_time).'_'.$blog_name.'_'.$this->nonce;
1071 if (is_writable($updraft_dir)) {
1072 if (function_exists('gzopen')) {
1073 $this->dbhandle = @gzopen($backup_file_base.'-db.gz','w');
1074 } else {
1075 $this->dbhandle = @fopen($backup_file_base.'-db.gz', 'w');
1076 }
1077 if(!$this->dbhandle) {
1078 //$this->error(__('Could not open the backup file for writing!','wp-db-backup'));
1079 }
1080 } else {
1081 //$this->error(__('The backup directory is not writable!','wp-db-backup'));
1082 }
1083
1084 //Begin new backup of MySql
1085 $this->stow("# " . __('WordPress MySQL database backup','wp-db-backup') . "\n");
1086 $this->stow("#\n");
1087 $this->stow("# " . sprintf(__('Generated: %s','wp-db-backup'),date("l j. F Y H:i T")) . "\n");
1088 $this->stow("# " . sprintf(__('Hostname: %s','wp-db-backup'),DB_HOST) . "\n");
1089 $this->stow("# " . sprintf(__('Database: %s','wp-db-backup'),$this->backquote(DB_NAME)) . "\n");
1090 $this->stow("# --------------------------------------------------------\n");
1091
1092
1093 if (defined("DB_CHARSET")) {
1094 $this->stow("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n");
1095 $this->stow("/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n");
1096 $this->stow("/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n");
1097 $this->stow("/*!40101 SET NAMES " . DB_CHARSET . " */;\n");
1098 }
1099 $this->stow("/*!40101 SET foreign_key_checks = 0 */;\n");
1100
1101 foreach ($all_tables as $table) {
1102 $total_tables++;
1103 // Increase script execution time-limit to 15 min for every table.
1104 if ( !ini_get('safe_mode') || strtolower(ini_get('safe_mode')) == "off") @set_time_limit(15*60);
1105 # === is needed, otherwise 'false' matches (i.e. prefix does not match)
1106 if ( strpos($table, $table_prefix) === 0 ) {
1107 // Create the SQL statements
1108 $this->stow("# --------------------------------------------------------\n");
1109 $this->stow("# " . sprintf(__('Table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
1110 $this->stow("# --------------------------------------------------------\n");
1111 $this->backup_table($table);
1112 } else {
1113 $this->stow("# --------------------------------------------------------\n");
1114 $this->stow("# " . sprintf(__('Skipping non-WP table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
1115 $this->stow("# --------------------------------------------------------\n");
1116 }
1117 }
1118
1119 if (defined("DB_CHARSET")) {
1120 $this->stow("/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n");
1121 $this->stow("/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n");
1122 $this->stow("/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n");
1123 }
1124
1125 $this->close($this->dbhandle);
1126
1127 if (count($this->errors)) {
1128 return false;
1129 } else {
1130 # Encrypt, if requested
1131 $encryption = get_option('updraft_encryptionphrase');
1132 if (strlen($encryption) > 0) {
1133 $this->log("Database: applying encryption");
1134 $encryption_error = 0;
1135 require_once(dirname(__FILE__).'/includes/Rijndael.php');
1136 $rijndael = new Crypt_Rijndael();
1137 $rijndael->setKey($encryption);
1138 $in_handle = @fopen($backup_file_base.'-db.gz','r');
1139 $buffer = "";
1140 while (!feof ($in_handle)) {
1141 $buffer .= fread($in_handle, 16384);
1142 }
1143 fclose ($in_handle);
1144 $out_handle = @fopen($backup_file_base.'-db.gz.crypt','w');
1145 if (!fwrite($out_handle, $rijndael->encrypt($buffer))) {$encryption_error = 1;}
1146 fclose ($out_handle);
1147 if (0 == $encryption_error) {
1148 # Delete unencrypted file
1149 @unlink($backup_file_base.'-db.gz');
1150 return basename($backup_file_base.'-db.gz.crypt');
1151 } else {
1152 $this->error("Encryption error occurred when encrypting database. Aborted.");
1153 }
1154 } else {
1155 return basename($backup_file_base.'-db.gz');
1156 }
1157 }
1158 $this->log("Total database tables backed up: $total_tables");
1159
1160 } //wp_db_backup
1161
1162 /**
1163 * Taken partially from phpMyAdmin and partially from
1164 * Alain Wolf, Zurich - Switzerland
1165 * Website: http://restkultur.ch/personal/wolf/scripts/db_backup/
1166 * Modified by Scott Merrill (http://www.skippy.net/)
1167 * to use the WordPress $wpdb object
1168 * @param string $table
1169 * @param string $segment
1170 * @return void
1171 */
1172 function backup_table($table, $segment = 'none') {
1173 global $wpdb;
1174
1175 $total_rows = 0;
1176
1177 $table_structure = $wpdb->get_results("DESCRIBE $table");
1178 if (! $table_structure) {
1179 //$this->error(__('Error getting table details','wp-db-backup') . ": $table");
1180 return false;
1181 }
1182
1183 if(($segment == 'none') || ($segment == 0)) {
1184 // Add SQL statement to drop existing table
1185 $this->stow("\n\n");
1186 $this->stow("#\n");
1187 $this->stow("# " . sprintf(__('Delete any existing table %s','wp-db-backup'),$this->backquote($table)) . "\n");
1188 $this->stow("#\n");
1189 $this->stow("\n");
1190 $this->stow("DROP TABLE IF EXISTS " . $this->backquote($table) . ";\n");
1191
1192 // Table structure
1193 // Comment in SQL-file
1194 $this->stow("\n\n");
1195 $this->stow("#\n");
1196 $this->stow("# " . sprintf(__('Table structure of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
1197 $this->stow("#\n");
1198 $this->stow("\n");
1199
1200 $create_table = $wpdb->get_results("SHOW CREATE TABLE $table", ARRAY_N);
1201 if (false === $create_table) {
1202 $err_msg = sprintf(__('Error with SHOW CREATE TABLE for %s.','wp-db-backup'), $table);
1203 //$this->error($err_msg);
1204 $this->stow("#\n# $err_msg\n#\n");
1205 }
1206 $this->stow($create_table[0][1] . ' ;');
1207
1208 if (false === $table_structure) {
1209 $err_msg = sprintf(__('Error getting table structure of %s','wp-db-backup'), $table);
1210 //$this->error($err_msg);
1211 $this->stow("#\n# $err_msg\n#\n");
1212 }
1213
1214 // Comment in SQL-file
1215 $this->stow("\n\n");
1216 $this->stow("#\n");
1217 $this->stow('# ' . sprintf(__('Data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
1218 $this->stow("#\n");
1219 }
1220
1221 if(($segment == 'none') || ($segment >= 0)) {
1222 $defs = array();
1223 $ints = array();
1224 foreach ($table_structure as $struct) {
1225 if ( (0 === strpos($struct->Type, 'tinyint')) ||
1226 (0 === strpos(strtolower($struct->Type), 'smallint')) ||
1227 (0 === strpos(strtolower($struct->Type), 'mediumint')) ||
1228 (0 === strpos(strtolower($struct->Type), 'int')) ||
1229 (0 === strpos(strtolower($struct->Type), 'bigint')) ) {
1230 $defs[strtolower($struct->Field)] = ( null === $struct->Default ) ? 'NULL' : $struct->Default;
1231 $ints[strtolower($struct->Field)] = "1";
1232 }
1233 }
1234
1235
1236 // Batch by $row_inc
1237 if ( ! defined('ROWS_PER_SEGMENT') ) {
1238 define('ROWS_PER_SEGMENT', 100);
1239 }
1240
1241 if($segment == 'none') {
1242 $row_start = 0;
1243 $row_inc = ROWS_PER_SEGMENT;
1244 } else {
1245 $row_start = $segment * ROWS_PER_SEGMENT;
1246 $row_inc = ROWS_PER_SEGMENT;
1247 }
1248 do {
1249 // don't include extra stuff, if so requested
1250 $excs = array('revisions' => 0, 'spam' => 1); //TODO, FIX THIS
1251 $where = '';
1252 if ( is_array($excs['spam'] ) && in_array($table, $excs['spam']) ) {
1253 $where = ' WHERE comment_approved != "spam"';
1254 } elseif ( is_array($excs['revisions'] ) && in_array($table, $excs['revisions']) ) {
1255 $where = ' WHERE post_type != "revision"';
1256 }
1257
1258 if ( !ini_get('safe_mode') || strtolower(ini_get('safe_mode')) == "off") @set_time_limit(15*60);
1259 $table_data = $wpdb->get_results("SELECT * FROM $table $where LIMIT {$row_start}, {$row_inc}", ARRAY_A);
1260 $entries = 'INSERT INTO ' . $this->backquote($table) . ' VALUES (';
1261 // \x08\\x09, not required
1262 $search = array("\x00", "\x0a", "\x0d", "\x1a");
1263 $replace = array('\0', '\n', '\r', '\Z');
1264 if($table_data) {
1265 foreach ($table_data as $row) {
1266 $total_rows++;
1267 $values = array();
1268 foreach ($row as $key => $value) {
1269 if ($ints[strtolower($key)]) {
1270 // make sure there are no blank spots in the insert syntax,
1271 // yet try to avoid quotation marks around integers
1272 $value = ( null === $value || '' === $value) ? $defs[strtolower($key)] : $value;
1273 $values[] = ( '' === $value ) ? "''" : $value;
1274 } else {
1275 $values[] = "'" . str_replace($search, $replace, $this->sql_addslashes($value)) . "'";
1276 }
1277 }
1278 $this->stow(" \n" . $entries . implode(', ', $values) . ');');
1279 }
1280 $row_start += $row_inc;
1281 }
1282 } while((count($table_data) > 0) and ($segment=='none'));
1283 }
1284
1285 if(($segment == 'none') || ($segment < 0)) {
1286 // Create footer/closing comment in SQL-file
1287 $this->stow("\n");
1288 $this->stow("#\n");
1289 $this->stow("# " . sprintf(__('End of data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
1290 $this->stow("# --------------------------------------------------------\n");
1291 $this->stow("\n");
1292 }
1293 $this->log("Table $table: Total rows added: $total_rows");
1294
1295 } // end backup_table()
1296
1297
1298 function stow($query_line) {
1299 if (function_exists('gzopen')) {
1300 if(! @gzwrite($this->dbhandle, $query_line)) {
1301 //$this->error(__('There was an error writing a line to the backup script:','wp-db-backup') . ' ' . $query_line . ' ' . $php_errormsg);
1302 }
1303 } else {
1304 if(false === @fwrite($this->dbhandle, $query_line)) {
1305 //$this->error(__('There was an error writing a line to the backup script:','wp-db-backup') . ' ' . $query_line . ' ' . $php_errormsg);
1306 }
1307 }
1308 }
1309
1310
1311 function close($handle) {
1312 if (function_exists('gzopen')) {
1313 gzclose($handle);
1314 } else {
1315 fclose($handle);
1316 }
1317 }
1318
1319 function error($error,$severity='') {
1320 $this->errors[] = $error;
1321 return true;
1322 }
1323
1324 /**
1325 * Add backquotes to tables and db-names in
1326 * SQL queries. Taken from phpMyAdmin.
1327 */
1328 function backquote($a_name) {
1329 if (!empty($a_name) && $a_name != '*') {
1330 if (is_array($a_name)) {
1331 $result = array();
1332 reset($a_name);
1333 while(list($key, $val) = each($a_name))
1334 $result[$key] = '`' . $val . '`';
1335 return $result;
1336 } else {
1337 return '`' . $a_name . '`';
1338 }
1339 } else {
1340 return $a_name;
1341 }
1342 }
1343
1344 /**
1345 * Better addslashes for SQL queries.
1346 * Taken from phpMyAdmin.
1347 */
1348 function sql_addslashes($a_string = '', $is_like = false) {
1349 if ($is_like) $a_string = str_replace('\\', '\\\\\\\\', $a_string);
1350 else $a_string = str_replace('\\', '\\\\', $a_string);
1351 return str_replace('\'', '\\\'', $a_string);
1352 }
1353
1354 /*END OF WP-DB-BACKUP BLOCK */
1355
1356 /*
1357 this function is both the backup scheduler and ostensibly a filter callback for saving the option.
1358 it is called in the register_setting for the updraft_interval, which means when the admin settings
1359 are saved it is called. it returns the actual result from wp_filter_nohtml_kses (a sanitization filter)
1360 so the option can be properly saved.
1361 */
1362 function schedule_backup($interval) {
1363 //clear schedule and add new so we don't stack up scheduled backups
1364 wp_clear_scheduled_hook('updraft_backup');
1365 switch($interval) {
1366 case 'daily':
1367 case 'weekly':
1368 case 'monthly':
1369 wp_schedule_event(time()+30, $interval, 'updraft_backup');
1370 break;
1371 }
1372 return wp_filter_nohtml_kses($interval);
1373 }
1374
1375 function schedule_backup_database($interval) {
1376 //clear schedule and add new so we don't stack up scheduled backups
1377 wp_clear_scheduled_hook('updraft_backup_database');
1378 switch($interval) {
1379 case 'daily':
1380 case 'weekly':
1381 case 'monthly':
1382 wp_schedule_event(time()+30, $interval, 'updraft_backup_database');
1383 break;
1384 }
1385 return wp_filter_nohtml_kses($interval);
1386 }
1387
1388 //wp-cron only has hourly, daily and twicedaily, so we need to add weekly and monthly.
1389 function modify_cron_schedules($schedules) {
1390 $schedules['weekly'] = array(
1391 'interval' => 604800,
1392 'display' => 'Once Weekly'
1393 );
1394 $schedules['monthly'] = array(
1395 'interval' => 2592000,
1396 'display' => 'Once Monthly'
1397 );
1398 return $schedules;
1399 }
1400
1401 function backups_dir_location() {
1402 $updraft_dir = untrailingslashit(get_option('updraft_dir'));
1403 $default_backup_dir = WP_CONTENT_DIR.'/updraft';
1404 //if the option isn't set, default it to /backups inside the upload dir
1405 $updraft_dir = ($updraft_dir)?$updraft_dir:$default_backup_dir;
1406 //check for the existence of the dir and an enumeration preventer.
1407 if(!is_dir($updraft_dir) || !is_file($updraft_dir.'/index.html') || !is_file($updraft_dir.'/.htaccess')) {
1408 @mkdir($updraft_dir,0777,true); //recursively create the dir with 0777 permissions. 0777 is default for php creation. not ideal, but I'll get back to this
1409 @file_put_contents($updraft_dir.'/index.html','Nothing to see here.');
1410 @file_put_contents($updraft_dir.'/.htaccess','deny from all');
1411 }
1412 return $updraft_dir;
1413 }
1414
1415 function updraft_download_backup() {
1416 $type = $_POST['type'];
1417 $timestamp = (int)$_POST['timestamp'];
1418 $backup_history = $this->get_backup_history();
1419 $file = $backup_history[$timestamp][$type];
1420 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
1421 if(!is_readable($fullpath)) {
1422 //if the file doesn't exist and they're using one of the cloud options, fetch it down from the cloud.
1423 $this->download_backup($file);
1424 }
1425 if(@is_readable($fullpath) && is_file($fullpath)) {
1426 $len = filesize($fullpath);
1427
1428 $filearr = explode('.',$file);
1429 // //we've only got zip and gz...for now
1430 $file_ext = array_pop($filearr);
1431 if($file_ext == 'zip') {
1432 header('Content-type: application/zip');
1433 } else {
1434 // This catches both when what was popped was 'crypt' (*-db.gz.crypt) and when it was 'gz' (unencrypted)
1435 header('Content-type: application/x-gzip');
1436 }
1437 header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
1438 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
1439 header("Content-Length: $len;");
1440 if ($file_ext == 'crypt') {
1441 header("Content-Disposition: attachment; filename=\"".substr($file,0,-6)."\";");
1442 } else {
1443 header("Content-Disposition: attachment; filename=\"$file\";");
1444 }
1445 ob_end_flush();
1446 if ($file_ext == 'crypt') {
1447 $encryption = get_option('updraft_encryptionphrase');
1448 if ($encryption == "") {
1449 $this->error('Decryption of database failed: the database file is encrypted, but you have no encryption key entered.');
1450 } else {
1451 require_once(dirname(__FILE__).'/includes/Rijndael.php');
1452 $rijndael = new Crypt_Rijndael();
1453 $rijndael->setKey($encryption);
1454 $in_handle = fopen($fullpath,'r');
1455 $ciphertext = "";
1456 while (!feof ($in_handle)) {
1457 $ciphertext .= fread($in_handle, 16384);
1458 }
1459 fclose ($in_handle);
1460 print $rijndael->decrypt($ciphertext);
1461 }
1462 } else {
1463 readfile($fullpath);
1464 }
1465 $this->delete_local($file);
1466 exit; //we exit immediately because otherwise admin-ajax appends an additional zero to the end for some reason I don't understand. seriously, why die('0')?
1467 } else {
1468 echo 'Download failed. File '.$fullpath.' did not exist or was unreadable. If you delete local backups then S3 or Google Drive or FTP retrieval may have failed. (Note that Google Drive downloading is not yet supported - you need to download manually if you use Google Drive).';
1469 }
1470 }
1471
1472 function download_backup($file) {
1473 switch(get_option('updraft_service')) {
1474 case 'googledrive':
1475 $this->download_googledrive_backup($file);
1476 break;
1477 case 's3':
1478 $this->download_s3_backup($file);
1479 break;
1480 case 'ftp':
1481 $this->download_ftp_backup($file);
1482 break;
1483 default:
1484 $this->error('Automatic backup restoration is only available via S3, FTP, and local. Email and downloaded backup restoration must be performed manually.');
1485 }
1486 }
1487
1488 function download_googledrive_backup($file) {
1489
1490 require_once(dirname(__FILE__).'/includes/class-gdocs.php');
1491
1492 // Do we have an access token?
1493 if ( !$access_token = $this->access_token( get_option('updraft_googledrive_token'), get_option('updraft_googledrive_clientid'), get_option('updraft_googledrive_secret') )) {
1494 $this->error('ERROR: Have not yet obtained an access token from Google (has the user authorised?)');
1495 return false;
1496 }
1497
1498 $this->gdocs_access_token = $access_token;
1499
1500 // Make sure $this->gdocs is a UpdraftPlus_GDocs object, or give an error
1501 if ( is_wp_error( $e = $this->need_gdocs() ) ) return false;
1502
1503 $ids = get_option('updraft_file_ids', array());
1504 if (!isset($ids[$file])) {
1505 $this->error("Google Drive error: $file: could not download: could not find a record of the Google Drive file ID for this file");
1506 return;
1507 } else {
1508 $content_link = $this->gdocs->get_content_link( $ids[$file], $file );
1509 if (is_wp_error($content_link)) {
1510 $this->error("Could not find $file in order to download it (id: ".$ids[$file].")");
1511 foreach ($content_link->get_error_messages() as $msg) {
1512 $this->error($msg);
1513 }
1514 return false;
1515 }
1516 // Actually download the thing
1517 $download_to = trailingslashit(get_option('updraft_dir')).$file;
1518 $this->gdocs->download_data($content_link, $download_to);
1519
1520 if (filesize($download_to) >0) {
1521 return true;
1522 } else {
1523 $this->error("Google Drive error: zero-size file was downloaded");
1524 return false;
1525 }
1526
1527 }
1528
1529 return;
1530
1531 }
1532
1533 function download_s3_backup($file) {
1534 if(!class_exists('S3')) {
1535 require_once(dirname(__FILE__).'/includes/S3.php');
1536 }
1537 $s3 = new S3(get_option('updraft_s3_login'), get_option('updraft_s3_pass'));
1538 $bucket_name = untrailingslashit(get_option('updraft_s3_remote_path'));
1539 $bucket_path = "";
1540 if (preg_match("#^([^/]+)/(.*)$#",$bucket_name,$bmatches)) {
1541 $bucket_name = $bmatches[1];
1542 $bucket_path = $bmatches[2]."/";
1543 }
1544 if (@$s3->putBucket($bucket_name, S3::ACL_PRIVATE)) {
1545 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
1546 if (!$s3->getObject($bucket_name, $bucket_path.$file, $fullpath)) {
1547 $this->error("S3 Error: Failed to download $fullpath. Error was ".$php_errormsg);
1548 }
1549 } else {
1550 $this->error("S3 Error: Failed to create bucket $bucket_name. Error was ".$php_errormsg);
1551 }
1552 }
1553
1554 function download_ftp_backup($file) {
1555 if( !class_exists('ftp_wrapper')) require_once(dirname(__FILE__).'/includes/ftp.class.php');
1556
1557 //handle SSL and errors at some point TODO
1558 $ftp = new ftp_wrapper(get_option('updraft_server_address'),get_option('updraft_ftp_login'),get_option('updraft_ftp_pass'));
1559 $ftp->passive = true;
1560 $ftp->connect();
1561 //$ftp->make_dir(); we may need to recursively create dirs? TODO
1562
1563 $ftp_remote_path = trailingslashit(get_option('updraft_ftp_remote_path'));
1564 $fullpath = trailingslashit(get_option('updraft_dir')).$file;
1565 $ftp->get($fullpath,$ftp_remote_path.$file,FTP_BINARY);
1566 }
1567
1568 function restore_backup($timestamp) {
1569 global $wp_filesystem;
1570 $backup_history = get_option('updraft_backup_history');
1571 if(!is_array($backup_history[$timestamp])) {
1572 echo '<p>This backup does not exist in the backup history - restoration aborted. Timestamp: '.$timestamp.'</p><br/>';
1573 return false;
1574 }
1575
1576 $credentials = request_filesystem_credentials("options-general.php?page=updraftplus&action=updraft_restore&backup_timestamp=$timestamp");
1577 WP_Filesystem($credentials);
1578 if ( $wp_filesystem->errors->get_error_code() ) {
1579 foreach ( $wp_filesystem->errors->get_error_messages() as $message )
1580 show_message($message);
1581 exit;
1582 }
1583
1584 //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?)
1585 echo '<span style="font-weight:bold">Restoration Progress </span><div id="updraft-restore-progress">';
1586
1587 $updraft_dir = trailingslashit(get_option('updraft_dir'));
1588 foreach($backup_history[$timestamp] as $type=>$file) {
1589 $fullpath = $updraft_dir.$file;
1590 if(!is_readable($fullpath) && $type != 'db') {
1591 $this->download_backup($file);
1592 }
1593 # Types: uploads, themes, plugins, others, db
1594 if(is_readable($fullpath) && $type != 'db') {
1595 if(!class_exists('WP_Upgrader')) {
1596 require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1597 }
1598 require_once('includes/updraft-restorer.php');
1599 $restorer = new Updraft_Restorer();
1600 $val = $restorer->restore_backup($fullpath,$type);
1601 if(is_wp_error($val)) {
1602 print_r($val);
1603 echo '</div>'; //close the updraft_restore_progress div even if we error
1604 return false;
1605 }
1606 }
1607 }
1608 echo '</div>'; //close the updraft_restore_progress div
1609 # The 'off' check is for badly configured setups - http://wordpress.org/support/topic/plugin-wp-super-cache-warning-php-safe-mode-enabled-but-safe-mode-is-off
1610 if(ini_get('safe_mode') && strtolower(ini_get('safe_mode')) != "off") {
1611 echo "<p>DB could not be restored because safe_mode is active on your server. You will need to manually restore the file via phpMyAdmin or another method.</p><br/>";
1612 return false;
1613 }
1614 return true;
1615 }
1616
1617 //deletes the -old directories that are created when a backup is restored.
1618 function delete_old_dirs() {
1619 global $wp_filesystem;
1620 $credentials = request_filesystem_credentials("options-general.php?page=updraftplus&action=updraft_delete_old_dirs");
1621 WP_Filesystem($credentials);
1622 if ( $wp_filesystem->errors->get_error_code() ) {
1623 foreach ( $wp_filesystem->errors->get_error_messages() as $message )
1624 show_message($message);
1625 exit;
1626 }
1627
1628 $to_delete = array('themes-old','plugins-old','uploads-old','others-old');
1629
1630 foreach($to_delete as $name) {
1631 //recursively delete
1632 if(!$wp_filesystem->delete(WP_CONTENT_DIR.'/'.$name, true)) {
1633 return false;
1634 }
1635 }
1636 return true;
1637 }
1638
1639 //scans the content dir to see if any -old dirs are present
1640 function scan_old_dirs() {
1641 $dirArr = scandir(WP_CONTENT_DIR);
1642 foreach($dirArr as $dir) {
1643 if(strpos($dir,'-old') !== false) {
1644 return true;
1645 }
1646 }
1647 return false;
1648 }
1649
1650
1651 function retain_range($input) {
1652 $input = (int)$input;
1653 if($input > 0 && $input < 3650) {
1654 return $input;
1655 } else {
1656 return 1;
1657 }
1658 }
1659
1660 function create_backup_dir() {
1661 global $wp_filesystem;
1662 $credentials = request_filesystem_credentials("options-general.php?page=updraftplus&action=updraft_create_backup_dir");
1663 WP_Filesystem($credentials);
1664 if ( $wp_filesystem->errors->get_error_code() ) {
1665 foreach ( $wp_filesystem->errors->get_error_messages() as $message )
1666 show_message($message);
1667 exit;
1668 }
1669
1670 $updraft_dir = untrailingslashit(get_option('updraft_dir'));
1671 $default_backup_dir = WP_CONTENT_DIR.'/updraft';
1672 $updraft_dir = ($updraft_dir)?$updraft_dir:$default_backup_dir;
1673
1674 //chmod the backup dir to 0777. ideally we'd rather chgrp it but i'm not sure if it's possible to detect the group apache is running under (or what if it's not apache...)
1675 if(!$wp_filesystem->mkdir($updraft_dir, 0777)) {
1676 return false;
1677 }
1678 return true;
1679 }
1680
1681
1682 function memory_check_current() {
1683 # Returns in megabytes
1684 $memory_limit = ini_get('memory_limit');
1685 $memory_unit = $memory_limit[strlen($memory_limit)-1];
1686 $memory_limit = substr($memory_limit,0,strlen($memory_limit)-1);
1687 switch($memory_unit) {
1688 case 'K':
1689 $memory_limit = $memory_limit/1024;
1690 break;
1691 case 'G':
1692 $memory_limit = $memory_limit*1024;
1693 break;
1694 case 'M':
1695 //assumed size, no change needed
1696 break;
1697 }
1698 return $memory_limit;
1699 }
1700
1701 function memory_check($memory) {
1702 $memory_limit = $this->memory_check_current();
1703 return ($memory_limit >= $memory)?true:false;
1704 }
1705
1706 function execution_time_check($time) {
1707 return (ini_get('max_execution_time') >= $time)?true:false;
1708 }
1709
1710 function admin_init() {
1711 if(get_option('updraft_debug_mode')) {
1712 ini_set('display_errors',1);
1713 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
1714 ini_set('track_errors',1);
1715 }
1716 wp_enqueue_script('jquery');
1717 register_setting( 'updraft-options-group', 'updraft_interval', array($this,'schedule_backup') );
1718 register_setting( 'updraft-options-group', 'updraft_interval_database', array($this,'schedule_backup_database') );
1719 register_setting( 'updraft-options-group', 'updraft_retain', array($this,'retain_range') );
1720 register_setting( 'updraft-options-group', 'updraft_encryptionphrase', 'wp_filter_nohtml_kses' );
1721 register_setting( 'updraft-options-group', 'updraft_service', 'wp_filter_nohtml_kses' );
1722 register_setting( 'updraft-options-group', 'updraft_s3_login', 'wp_filter_nohtml_kses' );
1723 register_setting( 'updraft-options-group', 'updraft_s3_pass', 'wp_filter_nohtml_kses' );
1724 register_setting( 'updraft-options-group', 'updraft_s3_remote_path', 'wp_filter_nohtml_kses' );
1725 register_setting( 'updraft-options-group', 'updraft_googledrive_clientid', 'wp_filter_nohtml_kses' );
1726 register_setting( 'updraft-options-group', 'updraft_googledrive_secret', 'wp_filter_nohtml_kses' );
1727 register_setting( 'updraft-options-group', 'updraft_googledrive_remotepath', 'wp_filter_nohtml_kses' );
1728 register_setting( 'updraft-options-group', 'updraft_ftp_login', 'wp_filter_nohtml_kses' );
1729 register_setting( 'updraft-options-group', 'updraft_ftp_pass', 'wp_filter_nohtml_kses' );
1730 register_setting( 'updraft-options-group', 'updraft_dir', 'wp_filter_nohtml_kses' );
1731 register_setting( 'updraft-options-group', 'updraft_email', 'wp_filter_nohtml_kses' );
1732 register_setting( 'updraft-options-group', 'updraft_ftp_remote_path', 'wp_filter_nohtml_kses' );
1733 register_setting( 'updraft-options-group', 'updraft_server_address', 'wp_filter_nohtml_kses' );
1734 register_setting( 'updraft-options-group', 'updraft_delete_local', 'absint' );
1735 register_setting( 'updraft-options-group', 'updraft_debug_mode', 'absint' );
1736 register_setting( 'updraft-options-group', 'updraft_include_plugins', 'absint' );
1737 register_setting( 'updraft-options-group', 'updraft_include_themes', 'absint' );
1738 register_setting( 'updraft-options-group', 'updraft_include_uploads', 'absint' );
1739 register_setting( 'updraft-options-group', 'updraft_include_others', 'absint' );
1740 register_setting( 'updraft-options-group', 'updraft_include_others_exclude', 'wp_filter_nohtml_kses' );
1741
1742 /* I see no need for this check; people can only download backups/logs if they can guess a nonce formed from a random number and if .htaccess files have no effect. The database will be encrypted. Very unlikely.
1743 if (current_user_can('manage_options')) {
1744 $updraft_dir = $this->backups_dir_location();
1745 if(strpos($updraft_dir,WP_CONTENT_DIR) !== false) {
1746 $relative_dir = str_replace(WP_CONTENT_DIR,'',$updraft_dir);
1747 $possible_updraft_url = WP_CONTENT_URL.$relative_dir;
1748 $resp = wp_remote_request($possible_updraft_url, array('timeout' => 15));
1749 if ( is_wp_error($resp) ) {
1750 add_action('admin_notices', array($this,'show_admin_warning_accessible_unknownresult') );
1751 } else {
1752 if(strpos($resp['response']['code'],'403') === false) {
1753 add_action('admin_notices', array($this,'show_admin_warning_accessible') );
1754 }
1755 }
1756 }
1757 }
1758 */
1759 if (current_user_can('manage_options') && get_option('updraft_service') == "googledrive" && get_option('updraft_googledrive_clientid') != "" && get_option('updraft_googledrive_token','xyz') == 'xyz') {
1760 add_action('admin_notices', array($this,'show_admin_warning_googledrive') );
1761 }
1762 }
1763
1764 function add_admin_pages() {
1765 add_submenu_page('options-general.php', "UpdraftPlus", "UpdraftPlus", "manage_options", "updraftplus",
1766 array($this,"settings_output"));
1767 }
1768
1769 function wordshell_random_advert($urls) {
1770 $url_start = ($urls) ? '<a href="http://wordshell.net">' : "";
1771 $url_end = ($urls) ? '</a>' : " (www.wordshell.net)";
1772 if (rand(0,1) == 0) {
1773 return "Like automating WordPress operations? Use the CLI? ${url_start}You will love WordShell${url_end} - saves time and money fast.";
1774 } else {
1775 return "${url_start}Check out WordShell${url_end} - manage WordPress from the command line - huge time-saver";
1776 }
1777 }
1778
1779 function settings_output() {
1780
1781 /*
1782 we use request here because the initial restore is triggered by a POSTed form. we then may need to obtain credentials
1783 for the WP_Filesystem. to do this WP outputs a form that we can't insert variables into (apparently). So the values are
1784 passed back in as GET parameters. REQUEST covers both GET and POST so this weird logic works.
1785 */
1786 if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'updraft_restore' && isset($_REQUEST['backup_timestamp'])) {
1787 $backup_success = $this->restore_backup($_REQUEST['backup_timestamp']);
1788 if(empty($this->errors) && $backup_success == true) {
1789 echo '<p>Restore successful!</p><br/>';
1790 echo '<b>Actions:</b> <a href="options-general.php?page=updraftplus&updraft_restore_success=true">Return to Updraft Configuration</a>.';
1791 return;
1792 } else {
1793 echo '<p>Restore failed...</p><ul>';
1794 foreach ($this->errors as $err) {
1795 echo "<li>";
1796 if (is_string($err)) { echo htmlspecialchars($err); } else {
1797 print_r($err);
1798 }
1799 echo "</li>";
1800 }
1801 echo '</ul><b>Actions:</b> <a href="options-general.php?page=updraftplus">Return to Updraft Configuration</a>.';
1802 return;
1803 }
1804 //uncomment the below once i figure out how i want the flow of a restoration to work.
1805 //echo '<b>Actions:</b> <a href="options-general.php?page=updraftplus">Return to Updraft Configuration</a>.';
1806 }
1807 $deleted_old_dirs = false;
1808 if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'updraft_delete_old_dirs') {
1809 if($this->delete_old_dirs()) {
1810 $deleted_old_dirs = true;
1811 } else {
1812 echo '<p>Old directory removal failed for some reason. You may want to do this manually.</p><br/>';
1813 }
1814 echo '<p>Old directories successfully removed.</p><br/>';
1815 echo '<b>Actions:</b> <a href="options-general.php?page=updraftplus">Return to Updraft Configuration</a>.';
1816 return;
1817 }
1818
1819 if(isset($_GET['error'])) {
1820 echo "<p><strong>ERROR:</strong> ".htmlspecialchars($_GET['error'])."</p>";
1821 }
1822 if(isset($_GET['message'])) {
1823 echo "<p><strong>Note:</strong> ".htmlspecialchars($_GET['message'])."</p>";
1824 }
1825
1826 if(isset($_GET['action']) && $_GET['action'] == 'updraft_create_backup_dir') {
1827 if(!$this->create_backup_dir()) {
1828 echo '<p>Backup directory could not be created...</p><br/>';
1829 }
1830 echo '<p>Backup directory successfully created.</p><br/>';
1831 echo '<b>Actions:</b> <a href="options-general.php?page=updraftplus">Return to Updraft Configuration</a>.';
1832 return;
1833 }
1834
1835 if(isset($_POST['action']) && $_POST['action'] == 'updraft_backup') {
1836 echo '<div class="updated fade" style="max-width: 800px; font-size:140%; padding:14px; clear:left;"><strong>Schedule backup:</strong> ';
1837 if (wp_schedule_single_event(time()+5, 'updraft_backup_all') === false) {
1838 echo "Failed.";
1839 } else {
1840 echo "OK. Now load a page from your site to make sure the schedule can trigger.";
1841 }
1842 echo '</div>';
1843 }
1844 if(isset($_POST['action']) && $_POST['action'] == 'updraft_backup_debug_all') {
1845 $this->backup(true,true);
1846 }
1847 if(isset($_POST['action']) && $_POST['action'] == 'updraft_backup_debug_db') {
1848 $this->backup_db();
1849 }
1850
1851 ?>
1852 <div class="wrap">
1853 <h1>UpdraftPlus - Backup/Restore</h1>
1854
1855 <!-- Version: <b><?php echo $this->version; ?></b><br>-->
1856 Maintained by <b>David Anderson</b> (<a href="http://david.dw-perspective.org.uk">Homepage</a> | <a href="http://wordshell.net">WordShell - WordPress command line</a> | <a href="http://david.dw-perspective.org.uk/donate">Donate</a> | <a href="http://wordpress.org/extend/plugins/updraftplus/faq/">FAQs</a> | <a href="http://profiles.wordpress.org/davidanderson/">My other WordPress plugins</a>). Version: <?php echo $this->version; ?>
1857 <br>
1858 <?php
1859 if(isset($_GET['updraft_restore_success'])) {
1860 echo "<div style=\"color:blue\">Your backup has been restored. Your old themes, uploads, and plugins directories have been retained with \"-old\" appended to their name. Remove them when you are satisfied that the backup worked properly. At this time Updraft does not automatically restore your DB. You will need to use an external tool like phpMyAdmin to perform that task.</div>";
1861 }
1862
1863 $ws_advert = $this->wordshell_random_advert(1);
1864 echo <<<ENDHERE
1865 <div class="updated fade" style="max-width: 800px; font-size:140%; padding:14px; clear:left;">${ws_advert}</div>
1866 ENDHERE;
1867
1868
1869 if($deleted_old_dirs) {
1870 echo '<div style="color:blue">Old directories successfully deleted.</div>';
1871 }
1872 if(!$this->memory_check(96)) {?>
1873 <div style="color:orange">Your PHP memory limit is too low. Updraft attempted to raise it but was unsuccessful. This plugin may not work properly with a memory limit of less than 96 Mb (though on the other hand, it has been used successfully with a 32Mb limit - your mileage may vary, but don't blame us!). Current limit is: <?php echo $this->memory_check_current(); ?> Mb</div>
1874 <?php
1875 }
1876 if(!$this->execution_time_check(300)) {?>
1877 <div style="color:orange">Your PHP max_execution_time is less than 300 seconds. This probably means you're running in safe_mode. Either disable safe_mode or modify your php.ini to set max_execution_time to a higher number. If you do not, there is a chance Updraft will be unable to complete a backup. Present limit is: <?php echo ini_get('max_execution_time'); ?> seconds.</div>
1878 <?php
1879 }
1880
1881 if($this->scan_old_dirs()) {?>
1882 <div style="color:orange">You have old directories from a previous backup. Click to delete them after you have verified that the restoration worked.</div>
1883 <form method="post" action="<?php echo remove_query_arg(array('updraft_restore_success','action')) ?>">
1884 <input type="hidden" name="action" value="updraft_delete_old_dirs" />
1885 <input type="submit" class="button-primary" value="Delete Old Dirs" onclick="return(confirm('Are you sure you want to delete the old directories? This cannot be undone.'))" />
1886 </form>
1887 <?php
1888 }
1889 if(!empty($this->errors)) {
1890 foreach($this->errors as $error) {
1891 //ignoring severity here right now
1892 echo '<div style="color:red">'.$error['error'].'</div>';
1893 }
1894 }
1895 ?>
1896
1897 <h2 style="clear:left;">Existing Schedule And Backups</h2>
1898 <table class="form-table" style="float:left; clear: both; width:475px">
1899 <tr>
1900 <?php
1901 $next_scheduled_backup = wp_next_scheduled('updraft_backup');
1902 $next_scheduled_backup = ($next_scheduled_backup) ? date('D, F j, Y H:i T',$next_scheduled_backup) : 'No backups are scheduled at this time.';
1903 $next_scheduled_backup_database = wp_next_scheduled('updraft_backup_database');
1904 if (get_option('updraft_interval_database',get_option('updraft_interval')) == get_option('updraft_interval')) {
1905 $next_scheduled_backup_database = "Will take place at the same time as the files backup.";
1906 } else {
1907 $next_scheduled_backup_database = ($next_scheduled_backup_database) ? date('D, F j, Y H:i T',$next_scheduled_backup_database) : 'No backups are scheduled at this time.';
1908 }
1909 $current_time = date('D, F j, Y H:i T',time());
1910 $updraft_last_backup = get_option('updraft_last_backup');
1911 if($updraft_last_backup) {
1912 if($updraft_last_backup['success']) {
1913 $last_backup = date('D, F j, Y H:i T',$updraft_last_backup['backup_time']);
1914 $last_backup_color = 'green';
1915 } else {
1916 $last_backup = print_r($updraft_last_backup['errors'],true);
1917 $last_backup_color = 'red';
1918 }
1919 } else {
1920 $last_backup = 'No backup has been completed.';
1921 $last_backup_color = 'blue';
1922 }
1923
1924 $updraft_dir = $this->backups_dir_location();
1925 if(is_writable($updraft_dir)) {
1926 $dir_info = '<span style="color:green">Backup directory specified is writable, which is good.</span>';
1927 $backup_disabled = "";
1928 } else {
1929 $backup_disabled = 'disabled="disabled"';
1930 $dir_info = '<span style="color:red">Backup directory specified is <b>not</b> writable, or does not exist. <span style="font-size:110%;font-weight:bold"><a href="options-general.php?page=updraftplus&action=updraft_create_backup_dir">Click here</a></span> to attempt to create the directory and set the permissions. If that is unsuccessful check the permissions on your server or change it to another directory that is writable by your web server process.</span>';
1931 }
1932 ?>
1933
1934 <th>The Time Now:</th>
1935 <td style="color:blue"><?php echo $current_time?></td>
1936 </tr>
1937 <tr>
1938 <th>Next Scheduled Files Backup:</th>
1939 <td style="color:blue"><?php echo $next_scheduled_backup?></td>
1940 </tr>
1941 <tr>
1942 <th>Next Scheduled DB Backup:</th>
1943 <td style="color:blue"><?php echo $next_scheduled_backup_database?></td>
1944 </tr>
1945 <tr>
1946 <th>Last Backup:</th>
1947 <td style="color:<?php echo $last_backup_color ?>"><?php echo $last_backup?></td>
1948 </tr>
1949 </table>
1950 <div style="float:left; width:200px; padding-top: 100px;">
1951 <form method="post" action="">
1952 <input type="hidden" name="action" value="updraft_backup" />
1953 <p><input type="submit" <?php echo $backup_disabled ?> class="button-primary" value="Backup Now!" style="padding-top:7px;padding-bottom:7px;font-size:24px !important" onclick="return(confirm('This will schedule a one-time backup. To trigger the backup immediately you may need to load a page on your site.'))" /></p>
1954 </form>
1955 <div style="position:relative">
1956 <div style="position:absolute;top:0;left:0">
1957 <?php
1958 $backup_history = get_option('updraft_backup_history');
1959 $backup_history = (is_array($backup_history))?$backup_history:array();
1960 $restore_disabled = (count($backup_history) == 0) ? 'disabled="disabled"' : "";
1961 ?>
1962 <input type="button" class="button-primary" <?php echo $restore_disabled ?> value="Restore" style="padding-top:7px;padding-bottom:7px;font-size:24px !important" onclick="jQuery('#backup-restore').fadeIn('slow');jQuery(this).parent().fadeOut('slow')" />
1963 </div>
1964 <div style="display:none;position:absolute;top:0;left:0" id="backup-restore">
1965 <form method="post" action="">
1966 <b>Choose: </b>
1967 <select name="backup_timestamp" style="display:inline">
1968 <?php
1969 foreach($backup_history as $key=>$value) {
1970 echo "<option value='$key'>".date('Y-m-d G:i',$key)."</option>\n";
1971 }
1972 ?>
1973 </select>
1974
1975 <input type="hidden" name="action" value="updraft_restore" />
1976 <input type="submit" <?php echo $restore_disabled ?> class="button-primary" value="Restore Now!" style="padding-top:7px;margin-top:5px;padding-bottom:7px;font-size:24px !important" onclick="return(confirm('Restoring from backup will replace this site\'s themes, plugins, uploads and other content directories (according to what is contained in the backup set which you select). Database restoration cannot be done through this process - you must download the database and import yourself (e.g. through PHPMyAdmin). Do you wish to continue with the restoration process?'))" />
1977 </form>
1978 </div>
1979 </div>
1980 </div>
1981 <br style="clear:both" />
1982 <table class="form-table">
1983 <tr>
1984 <th>Download Backups</th>
1985 <td><a href="#" title="Click to see available backups" onclick="jQuery('.download-backups').toggle();return false;"><?php echo count($backup_history)?> available</a></td>
1986 </tr>
1987 <tr>
1988 <td></td><td class="download-backups" style="display:none">
1989 <em>Click on a button to download the corresponding file to your computer. If you are using Opera, you should turn Turbo mode off.</em>
1990 <table>
1991 <?php
1992 foreach($backup_history as $key=>$value) {
1993 ?>
1994 <tr>
1995 <td><b><?php echo date('Y-m-d G:i',$key)?></b></td>
1996 <td>
1997 <?php if (isset($value['db'])) { ?>
1998 <form action="admin-ajax.php" method="post">
1999 <input type="hidden" name="action" value="updraft_download_backup" />
2000 <input type="hidden" name="type" value="db" />
2001 <input type="hidden" name="timestamp" value="<?php echo $key?>" />
2002 <input type="submit" value="Database" />
2003 </form>
2004 <?php } else { echo "(No database in backup)"; } ?>
2005 </td>
2006 <td>
2007 <?php if (isset($value['plugins'])) { ?>
2008 <form action="admin-ajax.php" method="post">
2009 <input type="hidden" name="action" value="updraft_download_backup" />
2010 <input type="hidden" name="type" value="plugins" />
2011 <input type="hidden" name="timestamp" value="<?php echo $key?>" />
2012 <input type="submit" value="Plugins" />
2013 </form>
2014 <?php } else { echo "(No plugins in backup)"; } ?>
2015 </td>
2016 <td>
2017 <?php if (isset($value['themes'])) { ?>
2018 <form action="admin-ajax.php" method="post">
2019 <input type="hidden" name="action" value="updraft_download_backup" />
2020 <input type="hidden" name="type" value="themes" />
2021 <input type="hidden" name="timestamp" value="<?php echo $key?>" />
2022 <input type="submit" value="Themes" />
2023 </form>
2024 <?php } else { echo "(No themes in backup)"; } ?>
2025 </td>
2026 <td>
2027 <?php if (isset($value['uploads'])) { ?>
2028 <form action="admin-ajax.php" method="post">
2029 <input type="hidden" name="action" value="updraft_download_backup" />
2030 <input type="hidden" name="type" value="uploads" />
2031 <input type="hidden" name="timestamp" value="<?php echo $key?>" />
2032 <input type="submit" value="Uploads" />
2033 </form>
2034 <?php } else { echo "(No uploads in backup)"; } ?>
2035 </td>
2036 <td>
2037 <?php if (isset($value['others'])) { ?>
2038 <form action="admin-ajax.php" method="post">
2039 <input type="hidden" name="action" value="updraft_download_backup" />
2040 <input type="hidden" name="type" value="others" />
2041 <input type="hidden" name="timestamp" value="<?php echo $key?>" />
2042 <input type="submit" value="Others" />
2043 </form>
2044 <?php } else { echo "(No others in backup)"; } ?>
2045 </td>
2046 </tr>
2047 <?php }?>
2048 </table>
2049 </td>
2050 </tr>
2051 </table>
2052 <form method="post" action="options.php">
2053 <?php settings_fields('updraft-options-group'); ?>
2054 <h2>Configure Backup Contents And Schedule</h2>
2055 <table class="form-table" style="width:850px;">
2056 <tr>
2057 <th>File Backup Intervals:</th>
2058 <td><select name="updraft_interval">
2059 <?php
2060 $intervals = array ("manual", "daily", "weekly", "monthly");
2061 foreach ($intervals as $ival) {
2062 echo "<option value=\"$ival\" ";
2063 if ($ival == get_option('updraft_interval','manual')) { echo 'selected="selected"';}
2064 echo ">".ucfirst($ival)."</option>\n";
2065 }
2066 ?>
2067 </select></td>
2068 </tr>
2069 <tr>
2070 <th>Database Backup Intervals:</th>
2071 <td><select name="updraft_interval_database">
2072 <?php
2073 $intervals = array ("manual", "daily", "weekly", "monthly");
2074 foreach ($intervals as $ival) {
2075 echo "<option value=\"$ival\" ";
2076 if ($ival == get_option('updraft_interval_database',get_option('updraft_interval'))) { echo 'selected="selected"';}
2077 echo ">".ucfirst($ival)."</option>\n";
2078 }
2079 ?>
2080 </select></td>
2081 </tr>
2082 <tr class="backup-interval-description">
2083 <td></td><td>If you would like to automatically schedule backups, choose schedules from the dropdown above. Backups will occur at the interval specified starting just after the current time. If you choose manual you must click the &quot;Backup Now!&quot; button whenever you wish a backup to occur. If the two schedules are the same, then the two backups will take place together.</td>
2084 </tr>
2085 <?php
2086 # The true (default value if non-existent) here has the effect of forcing a default of on.
2087 $include_themes = (get_option('updraft_include_themes',true)) ? 'checked="checked"' : "";
2088 $include_plugins = (get_option('updraft_include_plugins',true)) ? 'checked="checked"' : "";
2089 $include_uploads = (get_option('updraft_include_uploads',true)) ? 'checked="checked"' : "";
2090 $include_others = (get_option('updraft_include_others',true)) ? 'checked="checked"' : "";
2091 $include_others_exclude = get_option('updraft_include_others_exclude',UPDRAFT_DEFAULT_OTHERS_EXCLUDE);
2092 ?>
2093 <tr>
2094 <th>Include in Files Backup:</th>
2095 <td>
2096 <input type="checkbox" name="updraft_include_plugins" value="1" <?php echo $include_plugins; ?> /> Plugins<br>
2097 <input type="checkbox" name="updraft_include_themes" value="1" <?php echo $include_themes; ?> /> Themes<br>
2098 <input type="checkbox" name="updraft_include_uploads" value="1" <?php echo $include_uploads; ?> /> Uploads<br>
2099 <input type="checkbox" name="updraft_include_others" value="1" <?php echo $include_others; ?> /> Any other directories found inside wp-content - but exclude these directories: <input type="text" name="updraft_include_others_exclude" size="32" value="<?php echo htmlspecialchars($include_others_exclude); ?>"/><br>
2100 Include all of these, unless you are backing them up separately. Note that presently UpdraftPlus backs up these directories only - which is usually everything (except for WordPress core itself which you can download afresh from WordPress.org). But if you have made customised modifications outside of these directories, you need to back them up another way.<br>(<a href="http://wordshell.net">Use WordShell</a> for automatic backup, version control and patching).<br></td>
2101 </td>
2102 </tr>
2103 <tr>
2104 <th>Retain Backups:</th>
2105 <?php
2106 $updraft_retain = get_option('updraft_retain');
2107 $retain = ((int)$updraft_retain > 0)?get_option('updraft_retain'):1;
2108 ?>
2109 <td><input type="text" name="updraft_retain" value="<?php echo $retain ?>" style="width:50px" /></td>
2110 </tr>
2111 <tr class="email" <?php echo $email_display?>>
2112 <th>Email:</th>
2113 <td><input type="text" style="width:260px" name="updraft_email" value="<?php echo get_option('updraft_email'); ?>" /> <br>Enter an address here to have a report sent (and the whole backup, if you choose) to it.</td>
2114 </tr>
2115 <tr class="deletelocal s3 ftp email" <?php echo $display_delete_local?>>
2116 <th>Delete local backup:</th>
2117 <td><input type="checkbox" name="updraft_delete_local" value="1" <?php $delete_local = (get_option('updraft_delete_local')) ? 'checked="checked"' : "";
2118 echo $delete_local; ?> /> <br>Check this to delete the local backup file (only sensible if you have enabled a remote backup (below), otherwise you will have no backup remaining).</td>
2119 </tr>
2120
2121 <tr class="backup-retain-description">
2122 <td></td><td>By default only the most recent backup is retained. If you'd like to preserve more, specify the number here. (This many of <strong>both</strong> files and database backups will be retained.)</td>
2123 </tr>
2124 <tr>
2125 <th>Database encryption phrase:</th>
2126 <?php
2127 $updraft_encryptionphrase = get_option('updraft_encryptionphrase');
2128 ?>
2129 <td><input type="text" name="updraft_encryptionphrase" value="<?php echo $updraft_encryptionphrase ?>" style="width:132px" /></td>
2130 </tr>
2131 <tr class="backup-crypt-description">
2132 <td></td><td>If you enter a string here, it is used to encrypt backups (Rijndael). Do not lose it, or all your backups will be useless. Presently, only the database file is encrypted. This is also the key used to decrypt backups from this admin interface (so if you change it, then automatic decryption will not work until you change it back). You can also use the file example-decrypt.php from inside the UpdraftPlus plugin directory to decrypt manually.</td>
2133 </tr>
2134 </table>
2135
2136 <h2>Copying Your Backup To Remote Storage</h2>
2137
2138 <table class="form-table" style="width:850px;">
2139 <tr>
2140 <th>Remote backup:</th>
2141 <td><select name="updraft_service" id="updraft-service">
2142 <?php
2143 $debug_mode = (get_option('updraft_debug_mode')) ? 'checked="checked"' : "";
2144
2145 $display_none = 'style="display:none"';
2146 $s3 = ""; $ftp = ""; $email = ""; $googledrive="";
2147 $email_display="";
2148 $display_email_complete = "";
2149 $set = 'selected="selected"';
2150 switch(get_option('updraft_service')) {
2151 case 's3':
2152 $s3 = $set;
2153 $googledrive_display = $display_none;
2154 $ftp_display = $display_none;
2155 break;
2156 case 'googledrive':
2157 $googledrive = $set;
2158 $s3_display = $display_none;
2159 $ftp_display = $display_none;
2160 break;
2161 case 'ftp':
2162 $ftp = $set;
2163 $googledrive_display = $display_none;
2164 $s3_display = $display_none;
2165 break;
2166 case 'email':
2167 $email = $set;
2168 $ftp_display = $display_none;
2169 $s3_display = $display_none;
2170 $googledrive_display = $display_none;
2171 $display_email_complete = $display_none;
2172 break;
2173 default:
2174 $none = $set;
2175 $ftp_display = $display_none;
2176 $googledrive_display = $display_none;
2177 $s3_display = $display_none;
2178 $display_delete_local = $display_none;
2179 break;
2180 }
2181 ?>
2182 <option value="none" <?php echo $none?>>None</option>
2183 <option value="s3" <?php echo $s3?>>Amazon S3</option>
2184 <option value="googledrive" <?php echo $googledrive?>>Google Drive</option>
2185 <option value="ftp" <?php echo $ftp?>>FTP</option>
2186 <option value="email" <?php echo $email?>>E-mail</option>
2187 </select></td>
2188 </tr>
2189 <tr class="backup-service-description">
2190 <td></td><td>Choose your backup method. If choosing &quot;E-Mail&quot;, then be aware that mail servers tend to have size limits; typically around 10-20Mb; backups larger than any limits will not arrive.</td>
2191
2192 </tr>
2193
2194 <!-- Amazon S3 -->
2195 <tr class="s3" <?php echo $s3_display?>>
2196 <td></td>
2197 <td><em>Amazon S3 is a great choice, because UpdraftPlus supports chunked uploads - no matter how big your blog is, UpdraftPlus can upload it a little at a time, and not get thwarted by timeouts.</em></td>
2198 </tr>
2199 <tr class="s3" <?php echo $s3_display?>>
2200 <th>S3 access key:</th>
2201 <td><input type="text" autocomplete="off" style="width:292px" name="updraft_s3_login" value="<?php echo get_option('updraft_s3_login') ?>" /></td>
2202 </tr>
2203 <tr class="s3" <?php echo $s3_display?>>
2204 <th>S3 secret key:</th>
2205 <td><input type="text" autocomplete="off" style="width:292px" name="updraft_s3_pass" value="<?php echo get_option('updraft_s3_pass'); ?>" /></td>
2206 </tr>
2207 <tr class="s3" <?php echo $s3_display?>>
2208 <th>S3 location:</th>
2209 <td>s3://<input type="text" style="width:292px" name="updraft_s3_remote_path" value="<?php echo get_option('updraft_s3_remote_path'); ?>" /></td>
2210 </tr>
2211 <tr class="s3" <?php echo $s3_display?>>
2212 <th></th>
2213 <td><p>Get your access key and secret key from your AWS page, then pick a (globally unique) bucket name (letters and numbers) (and optionally a path) to use for storage.</p></td>
2214 </tr>
2215
2216 <!-- Google Drive -->
2217
2218 <tr class="googledrive" <?php echo $googledrive_display?>>
2219 <th>Google Drive:</th>
2220 <td>
2221 <a href="https://code.google.com/apis/console/">Follow this link to your Google API Console</a>, and there create a Client ID in the API Access section. Select 'Web Application' as the application type.</p><p>You must add <kbd><?php echo admin_url('options-general.php?page=updraftplus&action=auth'); ?></kbd> as the authorised redirect URI when asked.
2222
2223 <?php
2224 if (!class_exists('SimpleXMLElement')) { echo " <b>WARNING:</b> You do not have the SimpleXMLElement installed. Google Drive backups will <b>not</b> work until you do."; }
2225 ?>
2226
2227 </td>
2228 </tr>
2229
2230 <tr class="googledrive" <?php echo $googledrive_display?>>
2231 <th>Google Drive Client ID:</th>
2232 <td><input type="text" autocomplete="off" style="width:332px" name="updraft_googledrive_clientid" value="<?php echo get_option('updraft_googledrive_clientid') ?>" /></td>
2233 </tr>
2234 <tr class="googledrive" <?php echo $googledrive_display?>>
2235 <th>Google Drive Client Secret:</th>
2236 <td><input type="text" style="width:332px" name="updraft_googledrive_secret" value="<?php echo get_option('updraft_googledrive_secret'); ?>" /></td>
2237 </tr>
2238 <tr class="googledrive" <?php echo $googledrive_display?>>
2239 <th>Google Drive Folder ID:</th>
2240 <td><input type="text" style="width:332px" name="updraft_googledrive_remotepath" value="<?php echo get_option('updraft_googledrive_remotepath'); ?>" /> <em>(To get a folder's ID navigate to that folder in Google Drive in your web browser and copy the ID from your browser's address bar. It is the part that comes after <kbd>#folders/.</kbd> Leave empty to use your root folder)</em></td>
2241 </tr>
2242 <tr class="googledrive" <?php echo $googledrive_display?>>
2243 <th>Authenticate with Google:</th>
2244 <td><p><?php if (get_option('updraft_googledrive_token','xyz') != 'xyz') echo "<strong>(You appear to be already authenticated).</strong>"; ?> <a href="?page=updraftplus&action=auth&updraftplus_googleauth=doit"><strong>After</strong> you have saved your settings (by clicking &quot;Save Changes&quot; below), then come back here once and click this link to complete authentication with Google.</a>
2245
2246 </p>
2247 </td>
2248 </tr>
2249
2250 <tr class="ftp" <?php echo $ftp_display?>>
2251 <th><a href="#" title="Click for help!" onclick="jQuery('.ftp-description').toggle();return false;">FTP Server:</a></th>
2252 <td><input type="text" style="width:260px" name="updraft_server_address" value="<?php echo get_option('updraft_server_address'); ?>" /></td>
2253 </tr>
2254 <tr class="ftp" <?php echo $ftp_display?>>
2255 <th><a href="#" title="Click for help!" onclick="jQuery('.ftp-description').toggle();return false;">FTP Login:</a></th>
2256 <td><input type="text" autocomplete="off" name="updraft_ftp_login" value="<?php echo get_option('updraft_ftp_login') ?>" /></td>
2257 </tr>
2258 <tr class="ftp" <?php echo $ftp_display?>>
2259 <th><a href="#" title="Click for help!" onclick="jQuery('.ftp-description').toggle();return false;">FTP Password:</a></th>
2260 <td><input type="text" autocomplete="off" style="width:260px" name="updraft_ftp_pass" value="<?php echo get_option('updraft_ftp_pass'); ?>" /></td>
2261 </tr>
2262 <tr class="ftp" <?php echo $ftp_display?>>
2263 <th><a href="#" title="Click for help!" onclick="jQuery('.ftp-description').toggle();return false;">Remote Path:</a></th>
2264 <td><input type="text" style="width:260px" name="updraft_ftp_remote_path" value="<?php echo get_option('updraft_ftp_remote_path'); ?>" /></td>
2265 </tr>
2266 <tr class="ftp-description" style="display:none">
2267 <td colspan="2">An FTP remote path will look like '/home/backup/some/folder'</td>
2268 </tr>
2269 </table>
2270 <table class="form-table" style="width:850px;">
2271 <tr><td colspan="2"><h2>Advanced / Debugging Settings</h2></td></tr>
2272 <tr>
2273 <th>Backup Directory:</th>
2274 <td><input type="text" name="updraft_dir" style="width:525px" value="<?php echo $updraft_dir ?>" /></td>
2275 </tr>
2276 <tr>
2277 <td></td><td><?php echo $dir_info ?> This is where Updraft Backup/Restore will write the zip files it creates initially. This directory must be writable by your web server. Typically you'll want to have it inside your wp-content folder (this is the default). <b>Do not</b> place it inside your uploads dir, as that will cause recursion issues (backups of backups of backups of...).</td>
2278 </tr>
2279 <tr>
2280 <th>Debug mode:</th>
2281 <td><input type="checkbox" name="updraft_debug_mode" value="1" <?php echo $debug_mode; ?> /> <br>Check this for more information, if something is going wrong. Will also drop a log file in your backup directory which you can examine.</td>
2282 </tr>
2283 <tr>
2284 <td>
2285 <input type="hidden" name="action" value="update" />
2286 <input type="submit" class="button-primary" value="Save Changes" />
2287 </td>
2288 </tr>
2289 </table>
2290 </form>
2291 <?php
2292 if(get_option('updraft_debug_mode')) {
2293 ?>
2294 <div style="padding-top: 40px;">
2295 <hr>
2296 <h3>Debug Information</h3>
2297 <?php
2298 $peak_memory_usage = memory_get_peak_usage(true)/1024/1024;
2299 $memory_usage = memory_get_usage(true)/1024/1024;
2300 echo 'Peak memory usage: '.$peak_memory_usage.' MB<br/>';
2301 echo 'Current memory usage: '.$memory_usage.' MB<br/>';
2302 echo 'PHP memory limit: '.ini_get('memory_limit').' <br/>';
2303 ?>
2304 <form method="post" action="">
2305 <input type="hidden" name="action" value="updraft_backup_debug_all" />
2306 <p><input type="submit" class="button-primary" <?php echo $backup_disabled ?> value="Debug Backup" onclick="return(confirm('This will cause an immediate backup. The page will stall loading until it finishes (ie, unscheduled). Use this if you\'re trying to see peak memory usage.'))" /></p>
2307 </form>
2308 <form method="post" action="">
2309 <input type="hidden" name="action" value="updraft_backup_debug_db" />
2310 <p><input type="submit" class="button-primary" <?php echo $backup_disabled ?> value="Debug DB Backup" onclick="return(confirm('This will cause an immediate DB backup. The page will stall loading until it finishes (ie, unscheduled). The backup will remain locally despite your prefs and will not go into the backup history or up into the cloud.'))" /></p>
2311 </form>
2312 </div>
2313 <?php } ?>
2314
2315 <p><em>UpdraftPlus is based on the original Updraft by <b>Paul Kehrer</b> (<a href="http://langui.sh" target="_blank">Blog</a> | <a href="http://twitter.com/reaperhulk" target="_blank">Twitter</a> )</em></p>
2316
2317
2318 <script type="text/javascript">
2319 jQuery(document).ready(function() {
2320 jQuery('#updraft-service').change(function() {
2321 switch(jQuery(this).val()) {
2322 case 'none':
2323 jQuery('.deletelocal,.s3,.ftp,.googledrive,.s3-description,.ftp-description').fadeOut()
2324 jQuery('.email,.email-complete').fadeIn()
2325 break;
2326 case 's3':
2327 jQuery('.ftp,.ftp-description,.googledrive').fadeOut()
2328 jQuery('.s3,.deletelocal,.email,.email-complete').fadeIn()
2329 break;
2330 case 'googledrive':
2331 jQuery('.ftp,.ftp-description,.s3').fadeOut()
2332 jQuery('.googledrive,.deletelocal,.googledrive,.email,.email-complete').fadeIn()
2333 break;
2334 case 'ftp':
2335 jQuery('.googledrive,.s3,.s3-description').fadeOut()
2336 jQuery('.ftp,.deletelocal,.email,.email-complete').fadeIn()
2337 break;
2338 case 'email':
2339 jQuery('.s3,.ftp,.s3-description,.googledrive,.ftp-description,.email-complete').fadeOut()
2340 jQuery('.email,.deletelocal').fadeIn()
2341 break;
2342 }
2343 })
2344 })
2345 jQuery(window).load(function() {
2346 //this is for hiding the restore progress at the top after it is done
2347 setTimeout('jQuery("#updraft-restore-progress").toggle(1000)',3000)
2348 jQuery('#updraft-restore-progress-toggle').click(function() {
2349 jQuery('#updraft-restore-progress').toggle(500)
2350 })
2351 })
2352 </script>
2353 <?php
2354 }
2355
2356 /*array2json provided by bin-co.com under BSD license*/
2357 function array2json($arr) {
2358 if(function_exists('json_encode')) return stripslashes(json_encode($arr)); //Latest versions of PHP already have this functionality.
2359 $parts = array();
2360 $is_list = false;
2361
2362 //Find out if the given array is a numerical array
2363 $keys = array_keys($arr);
2364 $max_length = count($arr)-1;
2365 if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
2366 $is_list = true;
2367 for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
2368 if($i != $keys[$i]) { //A key fails at position check.
2369 $is_list = false; //It is an associative array.
2370 break;
2371 }
2372 }
2373 }
2374
2375 foreach($arr as $key=>$value) {
2376 if(is_array($value)) { //Custom handling for arrays
2377 if($is_list) $parts[] = $this->array2json($value); /* :RECURSION: */
2378 else $parts[] = '"' . $key . '":' . $this->array2json($value); /* :RECURSION: */
2379 } else {
2380 $str = '';
2381 if(!$is_list) $str = '"' . $key . '":';
2382
2383 //Custom handling for multiple data types
2384 if(is_numeric($value)) $str .= $value; //Numbers
2385 elseif($value === false) $str .= 'false'; //The booleans
2386 elseif($value === true) $str .= 'true';
2387 else $str .= '"' . addslashes($value) . '"'; //All other things
2388 // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
2389
2390 $parts[] = $str;
2391 }
2392 }
2393 $json = implode(',',$parts);
2394
2395 if($is_list) return '[' . $json . ']';//Return numerical JSON
2396 return '{' . $json . '}';//Return associative JSON
2397 }
2398
2399 function show_admin_warning($message) {
2400 echo '<div id="updraftmessage" class="updated fade">';
2401 echo "<p>$message</p></div>";
2402 }
2403 function show_admin_warning_accessible() {
2404 $this->show_admin_warning("UpdraftPlus backup directory specified is accessible via the web. This is a potential security problem (people may be able to download your backups - which is undesirable if your database is not encrypted and if you have non-public assets amongst the files). If using Apache, enable .htaccess support to allow web access to be denied; otherwise, you should deny access manually.");
2405 }
2406 function show_admin_warning_googledrive() {
2407 $this->show_admin_warning('UpdraftPlus notice: <a href="?page=updraftplus&action=auth&updraftplus_googleauth=doit">Click here to authenticate your Google Drive account (you will not be able to back up to Google Drive without it).</a>');
2408 }
2409 function show_admin_warning_accessible_unknownresult() {
2410 $this->show_admin_warning("UpdraftPlus tried to check if the backup directory is accessible via web, but the result was unknown.");
2411 }
2412
2413
2414 }
2415
2416
2417 ?>
2418