-
Notifications
You must be signed in to change notification settings - Fork 0
/
backups.php
827 lines (594 loc) · 24.1 KB
/
backups.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
<?php
/*
Plugin Name: Backups
Plugin URI: http://www.atomicsmash.co.uk
Description: Backup your site to Amazon S3
Version: 0.1.0
Author: Atomic Smash
Author URI: https://www.atomicsmash.co.uk
*/
namespace Backups;
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception as S3;
if (!defined('ABSPATH'))exit; //Exit if accessed directly
if ( defined( 'WP_CLI' ) && WP_CLI && !class_exists( 'Backups_Commands' ) ) {
$autoload = dirname( __FILE__ ) . '/vendor/autoload.php';
if ( file_exists( $autoload ) ) {
require_once $autoload;
}
/**
* Backup your WordPress site
*
* @when before_wp_load
*/
class Backups_Commands extends \WP_CLI_Command {
private function connect_to_s3(){
$s3 = new S3Client([
'version' => 'latest',
'region' => BACKUPS_S3_REGION,
'credentials' => [
'key' => BACKUPS_S3_ACCESS_KEY_ID,
'secret' => BACKUPS_S3_SECRET_ACCESS_KEY,
],
]);
return $s3;
}
private function get_selected_s3_bucket(){
if ( defined('BACKUPS_S3_BUCKET') ) {
$selected_s3_bucket = BACKUPS_S3_BUCKET;
}else{
$selected_s3_bucket = get_option('backups_s3_selected_bucket');
if( $selected_s3_bucket == "" ){
\WP_CLI::error('No bucket selected, please run through setup process by running "wp backups select_bucket"');
}
}
return $selected_s3_bucket;
}
private function check_config_details_exist(){
if ( !defined('BACKUPS_S3_ACCESS_KEY_ID') || !defined('BACKUPS_S3_SECRET_ACCESS_KEY') || !defined('BACKUPS_S3_REGION') || BACKUPS_S3_ACCESS_KEY_ID == "" || BACKUPS_S3_SECRET_ACCESS_KEY == "" || BACKUPS_S3_REGION == "" ) {
echo \WP_CLI::colorize( "%rS3 access details don't currently exist in your config files 😓!%n\n" );
// Add config details
echo \WP_CLI::colorize( "%YAdd these new config details to your wp-config file:%n\n");
echo \WP_CLI::colorize( "%Ydefine('BACKUPS_S3_REGION','eu-west-2'); // eu-west-2 is London%n\n");
echo \WP_CLI::colorize( "%Ydefine('BACKUPS_S3_ACCESS_KEY_ID','');%n\n");
echo \WP_CLI::colorize( "%Ydefine('BACKUPS_S3_SECRET_ACCESS_KEY','');%n\n");
echo \WP_CLI::colorize( "%YOnce these are in place, re-run %n");
echo \WP_CLI::colorize( "%r'wp backups create_bucket'%n\n\n");
echo \WP_CLI::colorize( "%YIf you need help, visit https://github.com/AtomicSmash/backups/wiki/Getting-AWS-credentials to learn how to create an IAM user.%n\n");
return false;
}else{
return true;
}
}
/**
* Setup Backups bucket and create lifecycle policy.
*
* ## OPTIONS
*
* <bucket_name>
* : Name of bucket to create
*
*/
public function create_bucket( $args, $assoc_args ){
// Get bucket name
$bucket_name = $args[0];
\WP_CLI::confirm( 'Create bucket ' . $bucket_name . '.backup ?', $assoc_args = array( 'continue' => 'yes' ) );
// If 'Y' create backup bucket
if( isset( $assoc_args['continue'] )){
$s3 = $this->connect_to_s3();
$creation_success = true;
// Create standard backup bucket
try {
$result = $s3->createBucket([
'Bucket' => $bucket_name . ".backup"
]);
} catch ( S3 $e ) {
echo \WP_CLI::colorize( "%rThere was a problem creating the bucket. It might already exist 🤔%n\n");
$creation_success = false;
}
}
if( $creation_success == true ){
update_option( 'backups_s3_selected_bucket', $bucket_name . '.backup', 0 );
\WP_CLI::success( "Backups bucket created and selected 👌");
}
}
/**
* Check to see if there are working AWS creds
*/
public function check_credentials(){
if( $this->check_config_details_exist() == false ){
return \WP_CLI::error( "Config details missing" );
}
$s3 = $this->connect_to_s3();
try {
$result = $s3->listBuckets(array());
} catch ( S3 $e ) {
echo \WP_CLI::warning( "There was an error connecting to S3 😣\n\nThis was the error:\n" );
echo $e->getAwsErrorCode()."\n";
return false;
};
return \WP_CLI::success( "Connection to S3 was successfull 😄");
}
public function select_bucket( $args ){
$connected_to_S3 = true;
$selected_bucket_check = 0;
//ASTODO This get_option could be a helper
$selected_s3_bucket = get_option('backups_s3_selected_bucket');
if( $this->check_config_details_exist() == false ){
return \WP_CLI::error( "Config details missing" );
}
// Check to see if there user is trying to set a specific bucket
if( isset( $args[0] )){
$selected_s3_bucket = $args[0];
update_option( 'backups_s3_selected_bucket', $selected_s3_bucket, 0 );
\WP_CLI::success( "Selected bucket updated" );
echo \WP_CLI::colorize( "%PYou can now run 'wp backups backup' to start backing up your site %n\n");
echo \WP_CLI::colorize( "%YOr 'wp backups development_sql_sync' to sync your local development DB%n\n");
return 1;
}
// Test if bucket has not yet been selected
if( $selected_s3_bucket == "" ){
echo \WP_CLI::colorize( "%YNo bucket is currently selected.%n\n");
echo \WP_CLI::colorize( "%RPlease re-run 'wp backups select_bucket' followed by the bucket name. %n\n");
echo \WP_CLI::colorize( "%PFor example: 'wp backups select_bucket website.backup'%n\n");
}
echo \WP_CLI::colorize( "%YAvailable buckets:%n\n");
$s3 = $this->connect_to_s3();
//ASTODO this should be the built in config_check function
try {
$result = $s3->listBuckets( array() );
}catch( S3 $e ) {
$connected_to_S3 = false;
};
//ASTODO END replace
if( $connected_to_S3 == true ){
foreach ($result['Buckets'] as $bucket) {
echo $bucket['Name'];
if( $bucket['Name'] == $selected_s3_bucket ){
$selected_bucket_check = 1;
echo \WP_CLI::colorize( "%r - currently selected%n");
};
echo "\n";
}
}else{
return \WP_CLI::error( "Error connecting to Amazon S3, please check your credentials." );
}
if( $selected_bucket_check == 0 && $selected_s3_bucket != "" ){
return \WP_CLI::error( "There is a selected bucket (". $selected_s3_bucket ."), but it doesn't seem to exits on S3?" );
}
}
/**
* Copy files to S3. You can choose whether to sync the DB, files or both.
*
* ## OPTIONS
*
* [--type=<type>]
* : What would you likw to sync? All,database or media.
*
* ## EXAMPLES
*
* $ wp backups backup
* Success: Will sync media and database to S3
*
* $ wp backups backup --type=database
* Success: Will sync the database to S3
*
* $ wp backups backup --type=media
* Success: Will sync media to S3
*
*/
public function backup( $args, $assoc_args ){
if( ! isset( $assoc_args['type'] ) ){
$assoc_args['type'] = "all";
}
if( $assoc_args['type'] == "all" || $assoc_args['type'] == "database" ){
$this->backup_database( $args, $assoc_args );
}
if( $assoc_args['type'] == "all" || $assoc_args['type'] == "media" ){
$this->backup_media( $args, $assoc_args );
}
}
/**
* Sync files to S3. You can also just sync in one direction, this is good for backups
*/
private function backup_media( $args, $assoc_args ) {
$selected_s3_bucket = get_option('backups_s3_selected_bucket');
$wp_upload_dir = wp_upload_dir();
// if( $this->check_config_details_exist() == false ){
// return WP_CLI::error( "Config details missing" );
// }
//ASTODO extract this to a check method
if( $selected_s3_bucket == "" ){
echo WP_CLI::colorize( "%YNo bucket is currently selected. Run %n");
echo WP_CLI::colorize( "%r'wp backups create_bucket'%n");
echo WP_CLI::colorize( "%Y%n or ");
echo WP_CLI::colorize( "%r'wp backups select_bucket'%n");
echo WP_CLI::colorize( "%Y%n\n");
return false;
}
\WP_CLI::log( \WP_CLI::colorize( "%YStarting to sync media files%n" ));
$missing_files = $this->find_files_to_sync();
// ASTODO this should be a CLI option
$direction = 'both';
//ASTODO This isn't needed!
$s3 = new S3Client([
'version' => 'latest',
'region' => BACKUPS_S3_REGION,
'credentials' => [
'key' => BACKUPS_S3_ACCESS_KEY_ID,
'secret' => BACKUPS_S3_SECRET_ACCESS_KEY,
],
]);
try {
$keyPrefix = '';
$options = array(
// 'params' => array('ACL' => 'public-read'),
'concurrency' => 20,
'debug' => true
);
//ASTODO check count
//ASTODO Don't sync sql-backup folder
// Upload missing files
foreach($missing_files['display'] as $file){
if( $direction == 'both' || $direction == 'down' ){
if( $file['location'] == 'remote'){
//Check to see if the missing $file is actually a folder
$ext = pathinfo($file['file'], PATHINFO_EXTENSION);
//Check to see if the directory exists
if (!file_exists(dirname($wp_upload_dir['basedir']."/".$file['file']))) {
mkdir(dirname($wp_upload_dir['basedir']."/".$file['file']),0755, true);
};
if($ext != ""){
$result = $s3->getObject([
'Bucket' => $selected_s3_bucket,
'Key' => $file['file'],
'SaveAs' => $wp_upload_dir['basedir']."/".$file['file']
]);
}
$results['files'][] = $file['file'];
\WP_CLI::log( \WP_CLI::colorize( "%gSynced: ".$file['file'] . "%n%y - ⬇ downloaded from S3%n" ));
}
}
if( $direction == 'both' || $direction == 'up' ){
if( $file['location'] == 'local'){
$result = $s3->putObject(array(
'Bucket' => $selected_s3_bucket,
'Key' => $file['file'],
'SourceFile' => $wp_upload_dir['basedir']."/".$file['file']
));
$results['files'][] = $file['file'];
\WP_CLI::log( \WP_CLI::colorize( "%gSynced: ".$file['file']."%n%y - ⬆ uploaded to S3%n" ));
}
}
}
} catch ( S3 $e ) {
echo "There was an error uploading the file.<br><br> Exception: $e";
}
return \WP_CLI::success( "Media library sync complete! ✅" );
}
private function find_files_to_sync(){
// These need to be reduced
$selected_s3_bucket = get_option('backups_s3_selected_bucket');
$ignore = array("DS_Store","htaccess");
// Instantiate an Amazon S3 client.
//ASTODO This isn't needed!
$s3 = new S3Client([
'version' => 'latest',
'region' => BACKUPS_S3_REGION,
'credentials' => [
'key' => BACKUPS_S3_ACCESS_KEY_ID,
'secret' => BACKUPS_S3_SECRET_ACCESS_KEY,
],
]);
$iterator = $s3->getIterator('ListObjects', array(
'Bucket' => $selected_s3_bucket
));
$found_files_remotely = array();
if( count( $iterator ) > 0 ){
foreach ($iterator as $object) {
if ( strpos( $object['Key'], 'database-backups' ) === false && strpos( $object['Key'], 'data/development' ) === false ) {
$found_files_remotely[] = $object['Key'];
}
}
}
$wp_upload_dir = wp_upload_dir();
$iter = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($wp_upload_dir['basedir'], \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST,
\RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
// $paths = array($wp_upload_dir['basedir']);
$found_files_locally = array();
foreach ($iter as $path => $dir) {
// if ($dir->isDir()) {
$filetype = pathinfo($dir);
//This would be nicer to have this in the RecursiveIteratorIterator
if (isset($filetype['extension']) && !in_array($filetype['extension'], $ignore)) {
if ( strpos( $path, 'database-backups' ) === false && strpos( $path, 'data/development' ) === false ) {
$found_files_locally[] = str_replace($wp_upload_dir['basedir'].'/','',$path);
}
}
}
$missing_locally = array_diff( $found_files_remotely, $found_files_locally );
$missing_display = array();
if( count( $missing_locally ) > 0 ){
foreach( $missing_locally as $missing_file ){
$missing_display[] = array(
'file' => $missing_file,
'location' => 'remote'
);
}
}
$missing_remotely = array_diff( $found_files_locally, $found_files_remotely );
if( count( $missing_remotely ) > 0 ){
foreach( $missing_remotely as $missing_file ){
$missing_display[] = array(
'file' => $missing_file,
'location' => 'local'
);
}
}
// reset array keys
$missing_locally = array_values($missing_locally);
$missing_remotely = array_values($missing_remotely);
$missing_files = array();
$missing_files['missing_locally'] = $missing_locally;
$missing_files['missing_remotely'] = $missing_remotely;
$missing_files['display'] = $missing_display;
return $missing_files;
}
/*
* Backup a WordPress website
*/
private function backup_database( $args, $assoc_args){
\WP_CLI::log( \WP_CLI::colorize( "%YStarted database backup%n" ));
$wp_upload_dir = wp_upload_dir();
// Check to see if the backup folder exists
if (!file_exists( $wp_upload_dir['basedir'] . "/database-backups/" )) {
mkdir( $wp_upload_dir['basedir'] . "/database-backups/" ,0755 );
echo \WP_CLI::colorize( "%yThe directory 'wp-content/uploads/database-backups/' was successfully created.%n\n");
};
// if( ! isset( $assoc_args['dev'] ) || $assoc_args['dev'] != true ){
// // generate a hash based on the date and a random number
// $database_filename = hash( 'ripemd160', date('ymd-h:i:s') . rand( 1, 99999 ) ) . ".sql";
// }else{
// $database_filename = 'development.sql';
// }
$database_filename = hash( 'ripemd160', date('ymd-h:i:s') . rand( 1, 99999 ) ) . ".sql";
\WP_CLI::log( " > Backing up database to '/database-backups/" . $database_filename . "' 💾" );
// Create a backup with a file name involving the datestamp and a rand number to make it harder to
// guess the backup filenames and reduce the risk of being able to download backups
$output = shell_exec( "wp db export " . $wp_upload_dir['basedir'] . "/database-backups/" . $database_filename . " --allow-root --path=".ABSPATH);
$s3 = $this->connect_to_s3();
//ASTODO centralise this get option, once it's centalised there will be a way of overriding it via config
$selected_s3_bucket = get_option('backups_s3_selected_bucket');
\WP_CLI::log( " > Sending SQL file to S3 📡" );
//ASTODO check to see if backup actually worked
if( $selected_s3_bucket != "" ){
// Transfer the file to S3
$success = false;
try {
$result = $s3->putObject(array(
'Bucket' => $selected_s3_bucket,
'Key' => "database-backups/".date('d-m-Y--h:i:s').".sql",
'SourceFile' => $wp_upload_dir['basedir'] . "/database-backups/" . $database_filename
));
$success = true;
} catch ( S3 $e ) {
echo " > There was an error uploading the backup database 😕";
}
// If successfully transfered, delete local copy
}
if( ! isset( $assoc_args['dev'] ) || $assoc_args['dev'] != true ){
$output = shell_exec( "rm -rf " . $wp_upload_dir['basedir'] . "/database-backups/" . $database_filename );
\WP_CLI::log( " > Deleting local copy of DB 🗑" );
}
if( $success == true ){
return \WP_CLI::success( "DB backup complete! ✅" );
}else{
return \WP_CLI::error( "There was an issue backing up the database" );
}
}
/**
* Add life cycle policy to the SQL folder. This will help reduce file build up
*
* ## OPTIONS
*
* <number_of_days>
* : Name of bucket to create
*
* ## EXAMPLES
*
* $ wp add_lifecycle
* Success: Will sync all uploads to S3
*
*/
public function setup_autodelete_sql( $args, $assoc_args ){
$selected_s3_bucket = get_option('backups_s3_selected_bucket');
if( $selected_s3_bucket == "" ){
\WP_CLI::log( \WP_CLI::colorize( "%YNo bucket is currently selected. Run %n") );
\WP_CLI::log( \WP_CLI::colorize( "%r'wp backups create_bucket'%n") );
\WP_CLI::log( \WP_CLI::colorize( "%Y%n\n") );
return false;
}
// Get expirty time in number of days
$backup_life = $args[0];
$s3 = $this->connect_to_s3();
// Setup lifecycle policy for DB backups
$result = $s3->putBucketLifecycleConfiguration([
'Bucket' => $selected_s3_bucket,
'LifecycleConfiguration' => [
'Rules' => [[
'Expiration' => [
'Days' => $backup_life,
],
'ID' => "SQL backups",
'Filter' => [
'Prefix' => 'database-backups'
],
'Status' => 'Enabled'
]]
]
]);
\WP_CLI::success( "Autodelete lifecycle added to '/database-backups/' 🤓");
}
/**
* Sync local development SQL
*
* ## OPTIONS
*
* [--sync-direction=<type>]
* : Direction to push or pull the development DB to AWS
*
*/
public function development_sql_sync( $args, $assoc_args ){
if( $this->check_config_details_exist() == false ){
return \WP_CLI::error( "Config details missing" );
}
$s3 = $this->connect_to_s3();
// Define filenames and paths for backup
// ASTODO should these be bundled into helper methods?
$database_folder = 'data/';
$database_filename = 'development.sql';
$database_output_path = $database_folder . $database_filename;
$selected_s3_bucket = $this->get_selected_s3_bucket();
\WP_CLI::log( "Checking S3 for status of the development DB 📡" );
// Check to see if a remote database can be found
$remote_database_found = false;
try {
$result = $s3->getObject([
'Bucket' => $selected_s3_bucket,
'Key' => $database_output_path,
]);
$remote_database_found = true;
} catch ( S3 $e ) {
$remote_database_found = false;
}
if( $remote_database_found ){
$current_time = new \DateTime();
$file_on_s3 = $result->toArray();
$remote_file_datetime = $file_on_s3['LastModified'];
$remote_time_diff = human_time_diff( $remote_file_datetime->getTimestamp(), $current_time->getTimestamp() );
$remote_time_diff_line = "Remote development SQL file is " . $remote_time_diff . " old.";
//ASTODO Add time diff for local file
}else{
$remote_time_diff_line = "No remote DB found";
}
// If no options are provided, just return the timestamp
if( !isset( $assoc_args['sync-direction'] ) ){
echo \WP_CLI::colorize( "%yNo sync direction set, so just checking status of remote database:%n\n");
// add if to change language if it's old or new
\WP_CLI::log( $remote_time_diff_line );
\WP_CLI::log( "" );
\WP_CLI::log( "To ⬆ upload your CURRENT local database to S3, run:" );
\WP_CLI::log( " wp backups development_sql_sync --sync-direction=push" );
if( $remote_database_found ){
\WP_CLI::log( "" );
\WP_CLI::log( "To ⬇ download this file from S3, run:" );
\WP_CLI::log( " wp backups development_sql_sync --sync-direction=pull" );
}
return;
}
if( isset( $assoc_args['sync-direction'] ) && $assoc_args['sync-direction'] == 'push' ){
\WP_CLI::log( $remote_time_diff_line );
if( $remote_database_found ){
\WP_CLI::confirm( "Are you sure you want to overwrite the remote database?", $assoc_args );
$this->backup_remote_development_sql_file( $s3, $selected_s3_bucket, $database_output_path, $database_folder );
}else{
\WP_CLI::confirm( "Are you sure you want to upload the current local database?", $assoc_args );
}
// Transfer the file to S3
$success = false;
// Check to see if the backup folder exists
if (!file_exists( $database_folder )) {
mkdir( $database_folder ,0755 );
echo \WP_CLI::colorize( "%yThe directory '/data/' was successfully created.%n\n");
};
\WP_CLI::log( " > Backing up database to " . $database_output_path . "' 💾" );
$output = shell_exec( "wp db export " . $database_output_path . " --allow-root --path=".ABSPATH);
\WP_CLI::log( " > Uploading DB" );
// ASTODO 'putting' an object could be extracted
try {
$result = $s3->putObject(array(
'Bucket' => $selected_s3_bucket,
'Key' => $database_output_path,
'SourceFile' => $database_output_path
));
$success = true;
} catch ( S3 $e ) {
$success = false;
}
if( $success ){
\WP_CLI::log( \WP_CLI::colorize( "%g > Synced " . $database_output_path . "%n%y - ⬆ uploaded to S3%n" ));
}else{
\WP_CLI::log( " > There was an issue uploading the backup database 😕" );
}
}
if( isset( $assoc_args['sync-direction'] ) && $assoc_args['sync-direction'] == 'pull' ){
if( $remote_time_diff_line == "No remote DB found" ){
\WP_CLI::error( "No remote databse to pull" );
}
\WP_CLI::success( $remote_time_diff_line );
if ( file_exists( $database_output_path ) ) {
\WP_CLI::confirm( "Are you sure you want to overwrite the local sql file?", $assoc_args );
$this->backup_local_development_sql_file( $s3, $selected_s3_bucket, $database_output_path, $database_folder );
}else{
echo \WP_CLI::colorize( "%yNo database currently exist locally, so nothing will be overwritten%n\n");
}
$this->backup_remote_development_sql_file( $s3, $selected_s3_bucket, $database_output_path, $database_folder );
// Transfer the file to S3
$success = false;
// Check to see if the backup folder exists
// ASTODO this should be extracted
if ( !file_exists( $database_folder ) ) {
mkdir( $database_folder ,0755 );
echo \WP_CLI::colorize( "%yThe directory '/data/' was successfully created.%n\n");
};
\WP_CLI::log( " > Saving remote database to " . $database_filename . "' on your machine 💾" );
// ASTODO 'putting' an object could be extracted
try {
$result = $s3->getObject([
'Bucket' => $selected_s3_bucket,
'Key' => $database_output_path,
'SaveAs' => $database_output_path
]);
\WP_CLI::log( \WP_CLI::colorize( "%g > Synced " . $database_output_path . "%n%y - ⬇ downloaded from S3%n" ));
} catch ( S3 $e ) {
echo " > There was an issue downloading the backup database 😕";
}
$this->import_development_db();
}
}
//ASTODO get all this variables into the cronstruct
private function backup_local_development_sql_file( $s3, $selected_s3_bucket, $database_output_path, $database_folder ){
//Backup local
$output = shell_exec( "cp ".$database_output_path." ".$database_folder."development-".date('d-m-y__H-i-w').".sql" );
\WP_CLI::log( " > Local development database copied to: " . "development-".date('d-m-y__H-i-w').".sql" );
}
private function backup_remote_development_sql_file( $s3, $selected_s3_bucket, $database_output_path, $database_folder ){
//Backup S3
try {
$result = $s3->copyObject(array(
'Bucket' => $selected_s3_bucket,
'Key' => $database_folder."development-".date('d-m-y__H-i-w').".sql",
'CopySource' => $selected_s3_bucket . "/" . $database_output_path
));
$success = true;
} catch ( S3 $e ) {
echo $e->getAwsErrorCode()."\n";
$success = false;
}
if( $success ){
\WP_CLI::log( " > Remote development database copied to: " . "development-".date('d-m-y__H-i-w').".sql" );
}else{
\WP_CLI::log( " > There was an issue backing up the remote DB" );
}
}
private function import_development_db(){
\WP_CLI::confirm( "Now you have the latest development DB, would you like to import it?" );
$output = shell_exec( "wp db import data/development.sql --allow-root --path=" . ABSPATH);
\WP_CLI::log( \WP_CLI::colorize( "%gDatabase imported%n" ));
}
}
\WP_CLI::add_command( 'backups', '\BACKUPS\Backups_Commands' );
};