InfiniteWP Client - Version 1.2.4

Version Description

  • Fix: Empty backup list when schedule backup is created/modified
Download this release

Release Info

Developer infinitewp
Plugin Icon 128x128 InfiniteWP Client
Version 1.2.4
Comparing to
See all releases

Code changes from version 1.2.3 to 1.2.4

Files changed (3) hide show
  1. backup.class.php +2806 -2801
  2. init.php +2 -2
  3. readme.txt +4 -1
backup.class.php CHANGED
@@ -1,2802 +1,2807 @@
1
- <?php
2
- /************************************************************
3
- * This plugin was modified by Revmakx *
4
- * Copyright (c) 2012 Revmakx *
5
- * www.revmakx.com *
6
- * *
7
- ************************************************************/
8
- /*************************************************************
9
- *
10
- * backup.class.php
11
- *
12
- * Manage Backups
13
- *
14
- *
15
- * Copyright (c) 2011 Prelovac Media
16
- * www.prelovac.com
17
- **************************************************************/
18
- define('IWP_BACKUP_DIR', WP_CONTENT_DIR . '/infinitewp/backups');
19
- define('IWP_DB_DIR', IWP_BACKUP_DIR . '/iwp_db');
20
-
21
- $zip_errors = array(
22
- 'No error',
23
- 'No error',
24
- 'Unexpected end of zip file',
25
- 'A generic error in the zipfile format was detected',
26
- 'zip was unable to allocate itself memory',
27
- 'A severe error in the zipfile format was detected',
28
- 'Entry too large to be split with zipsplit',
29
- 'Invalid comment format',
30
- 'zip -T failed or out of memory',
31
- 'The user aborted zip prematurely',
32
- 'zip encountered an error while using a temp file. Please check if this domain\'s account has enough disk space.',
33
- 'Read or seek error',
34
- 'zip has nothing to do',
35
- 'Missing or empty zip file',
36
- 'Error writing to a file. Please check if this domain\'s account has enough disk space.',
37
- 'zip was unable to create a file to write to',
38
- 'bad command line parameters',
39
- 'no error',
40
- 'zip could not open a specified file to read'
41
- );
42
- $unzip_errors = array(
43
- 'No error',
44
- 'One or more warning errors were encountered, but processing completed successfully anyway',
45
- 'A generic error in the zipfile format was detected',
46
- 'A severe error in the zipfile format was detected.',
47
- 'unzip was unable to allocate itself memory.',
48
- 'unzip was unable to allocate memory, or encountered an encryption error',
49
- 'unzip was unable to allocate memory during decompression to disk',
50
- 'unzip was unable allocate memory during in-memory decompression',
51
- 'unused',
52
- 'The specified zipfiles were not found',
53
- 'Bad command line parameters',
54
- 'No matching files were found',
55
- 50 => 'The disk is (or was) full during extraction',
56
- 51 => 'The end of the ZIP archive was encountered prematurely.',
57
- 80 => 'The user aborted unzip prematurely.',
58
- 81 => 'Testing or extraction of one or more files failed due to unsupported compression methods or unsupported decryption.',
59
- 82 => 'No files were found due to bad decryption password(s)'
60
- );
61
-
62
-
63
- class IWP_MMB_Backup extends IWP_MMB_Core
64
- {
65
- var $site_name;
66
- var $statuses;
67
- var $tasks;
68
- var $s3;
69
- var $ftp;
70
- var $dropbox;
71
- function __construct()
72
- {
73
- parent::__construct();
74
- $this->site_name = str_replace(array(
75
- "_",
76
- "/",
77
- "~"
78
- ), array(
79
- "",
80
- "-",
81
- "-"
82
- ), rtrim($this->remove_http(get_bloginfo('url')), "/"));
83
- $this->statuses = array(
84
- 'db_dump' => 1,
85
- 'db_zip' => 2,
86
- 'files_zip' => 3,
87
- 'finished' => 100
88
- );
89
- $this->tasks = get_option('iwp_client_backup_tasks');
90
- }
91
- function set_memory()
92
- {
93
- $changed = array('execution_time' => 0, 'memory_limit' => 0);
94
- @ignore_user_abort(true);
95
- $memory_limit = trim(ini_get('memory_limit'));
96
- $last = strtolower(substr($memory_limit, -1));
97
-
98
- if($last == 'g')
99
- $memory_limit = ((int) $memory_limit)*1024;
100
- else if($last == 'm')
101
- $memory_limit = (int) $memory_limit;
102
- if($last == 'k')
103
- $memory_limit = ((int) $memory_limit)/1024;
104
-
105
- if ( $memory_limit < 384 ) {
106
- @ini_set('memory_limit', '384M');
107
- $changed['memory_limit'] = 1;
108
- }
109
-
110
- if ( (int) @ini_get('max_execution_time') < 1200 ) {
111
- @ini_set('max_execution_time', 1200);//twenty minutes
112
- @set_time_limit(1200);
113
- $changed['execution_time'] = 1;
114
- }
115
-
116
- return $changed;
117
-
118
- }
119
- function get_backup_settings()
120
- {
121
- $backup_settings = get_option('iwp_client_backup_tasks');
122
- if (!empty($backup_settings))
123
- return $backup_settings;
124
- else
125
- return false;
126
- }
127
-
128
- function set_backup_task($params)
129
- {
130
- //$params => [$task_name, $args, $error]
131
- if (!empty($params)) {
132
-
133
- //Make sure backup cron job is set
134
- if (!wp_next_scheduled('iwp_client_backup_tasks')) {
135
- wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
136
- }
137
-
138
- extract($params);
139
-
140
- //$before = $this->get_backup_settings();
141
- $before = $this->tasks;
142
- if (!$before || empty($before))
143
- $before = array();
144
-
145
- if (isset($args['remove'])) {
146
- unset($before[$task_name]);
147
- $return = array(
148
- 'removed' => true
149
- );
150
- } else {
151
-
152
- if (is_array($params['account_info'])) { //only if sends from IWP Admin Panel first time(secure data)
153
- $args['account_info'] = $account_info;
154
- }
155
-
156
- $before[$task_name]['task_args'] = $args;
157
- //$before[$task_name]['task_args'] = $task_name;
158
-
159
- /*if (strlen($args['schedule']))
160
- $before[$task_name]['task_args']['next'] = $this->schedule_next($args['type'], $args['schedule']);*///to WP cron
161
- $before[$task_name]['task_args']['task_name'] = $task_name;
162
-
163
- $return = $before[$task_name];
164
- }
165
-
166
- //Update with error
167
- if (isset($error)) {
168
- if (is_array($error)) {
169
- $before[$task_name]['task_results'][count($before[$task_name]['task_results']) - 1]['error'] = $error['error'];
170
- } else {
171
- $before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['error'] = $error;
172
- }
173
- }
174
-
175
- // if (isset($time) && $time) { //set next result time before backup
176
- if (is_array($before[$task_name]['task_results'])) {
177
- $before[$task_name]['task_results'] = array_values($before[$task_name]['task_results']);
178
- }
179
- $before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = (isset($time) && $time) ? $time : time();
180
- //}
181
-
182
-
183
- $this->update_tasks($before);
184
- //update_option('iwp_client_backup_tasks', $before);
185
-
186
- if ($task_name == 'Backup Now') {
187
- $result = $this->backup($args, $task_name);
188
- $backup_settings = $this->tasks;
189
-
190
- if (is_array($result) && array_key_exists('error', $result)) {
191
- $return = $result;
192
- } else {
193
- $return = $backup_settings[$task_name];
194
- }
195
- }
196
- return $return;
197
- }
198
-
199
-
200
-
201
- return false;
202
- }
203
-
204
- //Cron check
205
- function check_backup_tasks()
206
- {
207
-
208
- $this->check_cron_remove();
209
-
210
- $settings = $this->tasks;
211
- if (is_array($settings) && !empty($settings)) {
212
- foreach ($settings as $task_name => $setting) {
213
-
214
- if ($setting['task_args']['next'] && $setting['task_args']['next'] < time()) {
215
- //if ($setting['task_args']['next'] && $_GET['force_backup']) {
216
- if ($setting['task_args']['url'] && $setting['task_args']['task_id'] && $setting['task_args']['site_key']) {
217
- //Check orphan task
218
- $check_data = array(
219
- 'task_name' => $task_name,
220
- 'task_id' => $setting['task_args']['task_id'],
221
- 'site_key' => $setting['task_args']['site_key']
222
- );
223
-
224
- $check = $this->validate_task($check_data, $setting['task_args']['url']);
225
-
226
- }
227
-
228
- $update = array(
229
- 'task_name' => $task_name,
230
- 'args' => $settings[$task_name]['task_args']
231
- );
232
-
233
-
234
- if($check != 'paused'){
235
- $update['time'] = time();
236
- }
237
-
238
- //Update task with next schedule
239
- $this->set_backup_task($update);
240
-
241
- if($check == 'paused'){
242
- continue;
243
- }
244
-
245
-
246
- $result = $this->backup($setting['task_args'], $task_name);
247
- $error = '';
248
- if (is_array($result) && array_key_exists('error', $result)) {
249
- $error = $result;
250
- $this->set_backup_task(array(
251
- 'task_name' => $task_name,
252
- 'args' => $settings[$task_name]['task_args'],
253
- 'error' => $error
254
- ));
255
- } else {
256
- $error = '';
257
- }
258
- break; //Only one backup per cron
259
- }
260
- }
261
- }
262
-
263
- }
264
-
265
-
266
- function task_now($task_name){
267
-
268
- $settings = $this->tasks;
269
- if(!array_key_exists($task_name,$settings)){
270
- return array('error' => $task_name." does not exist.");
271
- } else {
272
- $setting = $settings[$task_name];
273
- }
274
-
275
- $this->set_backup_task(array(
276
- 'task_name' => $task_name,
277
- 'args' => $settings[$task_name]['task_args'],
278
- 'time' => time()
279
- ));
280
-
281
- //Run backup
282
- $result = $this->backup($setting['task_args'], $task_name);
283
-
284
- //Check for error
285
- if (is_array($result) && array_key_exists('error', $result)) {
286
- $this->set_backup_task(array(
287
- 'task_name' => $task_name,
288
- 'args' => $settings[$task_name]['task_args'],
289
- 'error' => $result['error']
290
- ));
291
- return $result;
292
- } else {
293
- return $this->get_backup_stats();
294
- }
295
-
296
- }
297
-
298
- function delete_task_now($task_name){
299
- $tasks = $this->tasks;
300
- unset($tasks[$task_name]);
301
- $this->update_tasks($tasks);
302
- $this->cleanup();
303
-
304
- return $task_name;
305
-
306
- }
307
-
308
-
309
- /*
310
- * If Task Name not set then it's manual backup
311
- * Backup args:
312
- * type -> db, full
313
- * what -> daily, weekly, monthly
314
- * account_info -> ftp, amazons3, dropbox
315
- * exclude-> array of paths to exclude from backup
316
- */
317
-
318
- function backup($args, $task_name = false)
319
- {
320
- if (!$args || empty($args))
321
- return false;
322
-
323
- extract($args); //extract settings
324
-
325
- //$adminHistoryID - admin panel history ID for backup task.
326
-
327
-
328
- //Try increase memory limit and execution time
329
- $this->set_memory();
330
-
331
- //Remove old backup(s)
332
- $removed = $this->remove_old_backups($task_name);
333
- if (is_array($removed) && isset($removed['error'])) {
334
- //$error_message = $removed['error'];
335
- return $removed;
336
- }
337
-
338
- $new_file_path = IWP_BACKUP_DIR;
339
-
340
- if (!file_exists($new_file_path)) {
341
- if (!mkdir($new_file_path, 0755, true))
342
- return array(
343
- 'error' => 'Permission denied, make sure you have write permission to wp-content folder.'
344
- );
345
- }
346
-
347
- @file_put_contents($new_file_path . '/index.php', ''); //safe
348
-
349
- //Prepare .zip file name
350
- $hash = md5(time());
351
- $label = $type ? $type : 'manual';
352
- $backup_file = $new_file_path . '/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
353
- $backup_url = WP_CONTENT_URL . '/infinitewp/backups/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
354
-
355
- //Optimize tables?
356
- if (isset($optimize_tables) && !empty($optimize_tables)) {
357
- $this->optimize_tables();
358
- }
359
-
360
- //What to backup - db or full?
361
- if (trim($what) == 'db') {
362
- //Take database backup
363
- $this->update_status($task_name, 'db_dump');
364
- $GLOBALS['fail_safe_db'] = $this->tasks[$task_name]['task_args']['fail_safe_db'];
365
-
366
- $db_result = $this->backup_db();
367
- if ($db_result == false) {
368
- return array(
369
- 'error' => 'Failed to backup database.'
370
- );
371
- } else if (is_array($db_result) && isset($db_result['error'])) {
372
- return array(
373
- 'error' => $db_result['error']
374
- );
375
- } else {
376
- $this->update_status($task_name, 'db_dump', true);
377
- $this->update_status($task_name, 'db_zip');
378
-
379
- /*zip_backup_db*/
380
- $fail_safe_files = $this->tasks[$task_name]['task_args']['fail_safe_files'];
381
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
382
-
383
- if($fail_safe_files){
384
- $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
385
- }
386
- else{
387
- $comp_level = $disable_comp ? '-0' : '-1';
388
- chdir(IWP_BACKUP_DIR);
389
- $zip = $this->get_zip();
390
- $command = "$zip -q -r $comp_level $backup_file 'iwp_db'";
391
- iwp_mmb_print_flush('DB ZIP CMD: Start');
392
- ob_start();
393
- $result = $this->iwp_mmb_exec($command);
394
- ob_get_clean();
395
- iwp_mmb_print_flush('DB ZIP CMD: End');
396
- /*zip_backup_db */
397
- if(!$result){
398
- $zip_archive_db_result = false;
399
- if (class_exists("ZipArchive")) {
400
- $this->_log("DB zip, fallback to ZipArchive");
401
- iwp_mmb_print_flush('DB ZIP Archive: Start');
402
- $zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
403
- iwp_mmb_print_flush('DB ZIP Archive: End');
404
- }
405
-
406
- if (!$zip_archive_db_result) {
407
- $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
408
- }
409
- }
410
- }
411
-
412
- @unlink($db_result);
413
- @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
414
- @rmdir(IWP_DB_DIR);
415
- /*if (!$result) {
416
- return array(
417
- 'error' => 'Failed to zip database.'
418
- );
419
- }*///commented because of zipArchive
420
- $this->update_status($task_name, 'db_zip', true);
421
- }
422
- } elseif (trim($what) == 'full') {
423
- $content_backup = $this->backup_full($task_name, $backup_file, $exclude, $include);
424
- if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
425
- return array(
426
- 'error' => $content_backup['error']
427
- );
428
- }
429
- }
430
-
431
- //Update backup info
432
- if ($task_name) {
433
- //backup task (scheduled)
434
- $backup_settings = $this->tasks;
435
- $paths = array();
436
- $size = round(filesize($backup_file) / 1024, 2);
437
-
438
- if ($size > 1000) {
439
- $paths['size'] = round($size / 1024, 2) . " MB";//Modified by IWP //Mb => MB
440
- } else {
441
- $paths['size'] = $size . 'KB';//Modified by IWP //Kb => KB
442
- }
443
-
444
- $paths['backup_name'] = $backup_settings[$task_name]['task_args']['backup_name'];
445
-
446
- if ($task_name != 'Backup Now') {
447
- if (!$backup_settings[$task_name]['task_args']['del_host_file']) {
448
- $paths['server'] = array(
449
- 'file_path' => $backup_file,
450
- 'file_url' => $backup_url
451
- );
452
- }
453
- } else {
454
- $paths['server'] = array(
455
- 'file_path' => $backup_file,
456
- 'file_url' => $backup_url
457
- );
458
- }
459
-
460
-
461
- if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_ftp'])) {
462
- $paths['ftp'] = basename($backup_url);
463
- }
464
-
465
- if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_amazon_s3'])) {
466
- $paths['amazons3'] = basename($backup_url);
467
- }
468
-
469
- if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_dropbox'])) {
470
- $paths['dropbox'] = basename($backup_url);
471
- }
472
-
473
- if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_email'])) {
474
- $paths['email'] = basename($backup_url);
475
- }
476
-
477
- $temp = $backup_settings[$task_name]['task_results'];
478
- $temp = @array_values($temp);
479
- $paths['time'] = time();
480
-
481
-
482
- //if ($task_name != 'Backup Now') {
483
- $paths['backhack_status'] = $temp[count($temp) - 1]['backhack_status'];
484
- //$paths['status'] = $temp[count($temp) - 1]['status'];
485
- $temp[count($temp) - 1] = $paths;
486
-
487
- /*
488
- } else {
489
- $temp[count($temp)] = $paths;
490
- }
491
- */
492
-
493
- $backup_settings[$task_name]['task_results'] = $temp;
494
- $this->update_tasks($backup_settings);
495
- //update_option('iwp_client_backup_tasks', $backup_settings);
496
- }
497
-
498
-
499
- if ($task_name != 'Backup Now') {
500
-
501
- if (isset($account_info['iwp_ftp']) && !empty($account_info['iwp_ftp'])) {
502
- $this->update_status($task_name, 'ftp');
503
- $account_info['iwp_ftp']['backup_file'] = $backup_file;
504
- iwp_mmb_print_flush('FTP upload: Start');
505
- $ftp_result = $this->ftp_backup($account_info['iwp_ftp']);
506
- iwp_mmb_print_flush('FTP upload: End');
507
- if ($ftp_result !== true && $del_host_file) {
508
- @unlink($backup_file);
509
- }
510
-
511
- if (is_array($ftp_result) && isset($ftp_result['error'])) {
512
- return $ftp_result;
513
- }
514
- $this->wpdb_reconnect();
515
- $this->update_status($task_name, 'ftp', true);
516
- }
517
-
518
- if (isset($account_info['iwp_amazon_s3']) && !empty($account_info['iwp_amazon_s3'])) {
519
- $this->update_status($task_name, 's3');
520
- $account_info['iwp_amazon_s3']['backup_file'] = $backup_file;
521
- iwp_mmb_print_flush('Amazon S3 upload: Start');
522
- $amazons3_result = $this->amazons3_backup($account_info['iwp_amazon_s3']);
523
- iwp_mmb_print_flush('Amazon S3 upload: End');
524
- if ($amazons3_result !== true && $del_host_file) {
525
- @unlink($backup_file);
526
- }
527
- if (is_array($amazons3_result) && isset($amazons3_result['error'])) {
528
- return $amazons3_result;
529
- }
530
- $this->wpdb_reconnect();
531
- $this->update_status($task_name, 's3', true);
532
- }
533
-
534
- if (isset($account_info['iwp_dropbox']) && !empty($account_info['iwp_dropbox'])) {
535
- $this->update_status($task_name, 'dropbox');
536
- $account_info['iwp_dropbox']['backup_file'] = $backup_file;
537
- iwp_mmb_print_flush('Dropbox upload: Start');
538
- $dropbox_result = $this->dropbox_backup($account_info['iwp_dropbox']);
539
- iwp_mmb_print_flush('Dropbox upload: End');
540
- if ($dropbox_result !== true && $del_host_file) {
541
- @unlink($backup_file);
542
- }
543
-
544
- if (is_array($dropbox_result) && isset($dropbox_result['error'])) {
545
- return $dropbox_result;
546
- }
547
- $this->wpdb_reconnect();
548
- $this->update_status($task_name, 'dropbox', true);
549
- }
550
-
551
- if ($del_host_file) {
552
- @unlink($backup_file);
553
- }
554
-
555
- } //end additional
556
-
557
- $this->update_status($task_name,'finished',true);
558
-
559
- return $backup_url; //Return url to backup file
560
- }
561
-
562
-
563
- function backup_full($task_name, $backup_file, $exclude = array(), $include = array())
564
- {
565
-
566
- global $zip_errors;
567
- $sys = substr(PHP_OS, 0, 3);
568
-
569
- $this->update_status($task_name, 'db_dump');
570
- $GLOBALS['fail_safe_db'] = $this->tasks[$task_name]['task_args']['fail_safe_db'];
571
- $db_result = $this->backup_db();
572
-
573
- if ($db_result == false) {
574
- return array(
575
- 'error' => 'Failed to backup database.'
576
- );
577
- } else if (is_array($db_result) && isset($db_result['error'])) {
578
- return array(
579
- 'error' => $db_result['error']
580
- );
581
- }
582
-
583
- $this->update_status($task_name, 'db_dump', true);
584
- $this->update_status($task_name, 'db_zip');
585
-
586
- /*zip_backup_db*/
587
- $fail_safe_files = $this->tasks[$task_name]['task_args']['fail_safe_files'];
588
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
589
-
590
- if($fail_safe_files){
591
- $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
592
- }
593
- else{
594
- $comp_level = $disable_comp ? '-0' : '-1';
595
- $zip = $this->get_zip();
596
- iwp_mmb_print_flush('DB ZIP CMD: Start');
597
- //Add database file
598
- chdir(IWP_BACKUP_DIR);
599
- $command = "$zip -q -r $comp_level $backup_file 'iwp_db'";
600
- ob_start();
601
- $result = $this->iwp_mmb_exec($command);
602
- ob_get_clean();
603
- iwp_mmb_print_flush('DB ZIP CMD: End');
604
- /*zip_backup_db*/
605
-
606
- if(!$result){
607
- $zip_archive_db_result = false;
608
- if (class_exists("ZipArchive")) {
609
- iwp_mmb_print_flush('DB ZIP Archive: Start');
610
- $this->_log("DB zip, fallback to ZipArchive");
611
- $zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
612
- iwp_mmb_print_flush('DB ZIP Archive: End');
613
- }
614
-
615
- if (!$zip_archive_db_result) {
616
- $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
617
- }
618
- }
619
- }
620
- @unlink($db_result);
621
- @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
622
- @rmdir(IWP_DB_DIR);
623
-
624
- $this->update_status($task_name, 'db_zip', true);
625
-
626
-
627
- //Always remove backup folders
628
- $remove = array(
629
- trim(basename(WP_CONTENT_DIR)) . "/infinitewp/backups",
630
- trim(basename(WP_CONTENT_DIR)) . "/" . md5('iwp_mmb-client') . "/iwp_backups",
631
- trim(basename(WP_CONTENT_DIR)) . "/cache",
632
- trim(basename(WP_CONTENT_DIR)) . "/w3tc"
633
- );
634
-
635
- $exclude = array_merge($exclude, $remove);
636
-
637
- //Exclude paths
638
- $exclude_data = "-x";
639
-
640
- $exclude_file_data = '';
641
-
642
- if (!empty($exclude) && is_array($exclude)) {
643
- foreach ($exclude as $data) {
644
- if(empty($data))
645
- continue;
646
- if (is_dir(ABSPATH . $data)) {
647
- if ($sys == 'WIN')
648
- $exclude_data .= " $data/*.*";
649
- else
650
- $exclude_data .= " '$data/*'";
651
- }else {
652
- if ($sys == 'WIN'){
653
- if(file_exists(ABSPATH . $data)){
654
- $exclude_data .= " $data";
655
- $exclude_file_data .= " $data";
656
- }
657
- }else {
658
- if(file_exists(ABSPATH . $data)){
659
- $exclude_data .= " '$data'";
660
- $exclude_file_data .= " '$data'";
661
- }
662
- }
663
- }
664
- }
665
- }
666
-
667
- if($exclude_file_data){
668
- $exclude_file_data = "-x".$exclude_file_data;
669
- }
670
-
671
- /* foreach ($remove as $data) {
672
- if(empty($data))
673
- continue;
674
- if ($sys == 'WIN')
675
- $exclude_data .= " $data/*.*";
676
- else
677
- $exclude_data .= " '$data/*'";
678
- }*/ //commented for pclzip modifications
679
-
680
- //Include paths by default
681
- $add = array(
682
- trim(WPINC),
683
- trim(basename(WP_CONTENT_DIR)),
684
- "wp-admin"
685
- );
686
-
687
- $include_data = ". -i";
688
- foreach ($add as $data) {
689
- if ($sys == 'WIN')
690
- $include_data .= " $data/*.*";
691
- else
692
- $include_data .= " '$data/*'";
693
- }
694
-
695
- //Additional includes?
696
- if (!empty($include) && is_array($include)) {
697
- foreach ($include as $data) {
698
- if(empty($data))
699
- continue;
700
- if ($data) {
701
- if ($sys == 'WIN')
702
- $include_data .= " $data/*.*";
703
- else
704
- $include_data .= " '$data/*'";
705
- }
706
- }
707
- }
708
-
709
- $this->update_status($task_name, 'files_zip');
710
- chdir(ABSPATH);
711
-
712
- if($fail_safe_files){
713
- $this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
714
- }
715
- else{
716
- $do_cmd_zip_alternative = false;
717
- @copy($backup_file, $backup_file.'_2');
718
-
719
- iwp_mmb_print_flush('Files ZIP CMD: Start');
720
- $command = "$zip -q -j $comp_level $backup_file .* * $exclude_file_data";
721
- ob_start();
722
- $result_f = $this->iwp_mmb_exec($command, false, true);
723
- ob_get_clean();
724
- iwp_mmb_print_flush('Files ZIP CMD: 1/2 over');
725
- if (!$result_f || $result_f == 18) { // disregard permissions error, file can't be accessed
726
- $command = "$zip -q -r $comp_level $backup_file $include_data $exclude_data";
727
- ob_start();
728
- $result_d = $this->iwp_mmb_exec($command, false, true);
729
- ob_get_clean();
730
- if ($result_d && $result_d != 18) {
731
- @unlink($backup_file);
732
- $do_cmd_zip_alternative = true;
733
-
734
-
735
- if($result_d > 0 && $result_d < 18){
736
- //return array(
737
- // 'error' => 'Failed to archive files (' . $zip_errors[$result_d] . ') .'
738
- // );
739
- iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files (' . $zip_errors[$result_d] . ') .');
740
- }
741
- else{
742
- //return array(
743
- // 'error' => 'Failed to archive files.'
744
- //);
745
- iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files.');
746
- }
747
- }
748
- }
749
-
750
- if(!$do_cmd_zip_alternative){//if FILE ZIP CMD successful
751
- @unlink($backup_file.'_2');
752
- }
753
-
754
- iwp_mmb_print_flush('Files ZIP CMD: End');
755
- if (($result_f && $result_f != 18) || ($do_cmd_zip_alternative)) {
756
-
757
- if($do_cmd_zip_alternative){
758
- @copy($backup_file.'_2', $backup_file);
759
- @unlink($backup_file.'_2');
760
- }
761
-
762
- $zip_archive_result = false;
763
- if (class_exists("ZipArchive")) {
764
- iwp_mmb_print_flush('Files ZIP Archive: Start');
765
- $this->_log("Files zip fallback to ZipArchive");
766
- $zip_archive_result = $this->zip_archive_backup($task_name, $backup_file, $exclude, $include);
767
- iwp_mmb_print_flush('Files ZIP Archive: End');
768
- }
769
-
770
-
771
- if (!$zip_archive_result) {
772
- $this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
773
- }
774
- }
775
- }
776
-
777
- //Reconnect
778
- $this->wpdb_reconnect();
779
-
780
- $this->update_status($task_name, 'files_zip', true);
781
- return true;
782
- }
783
-
784
-
785
- function fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove){ //Try pclZip
786
- //$this->back_hack($task_name, 'Files ZIP PCL: Start');
787
- iwp_mmb_print_flush('Files ZIP PCL: Start');
788
- if (!isset($archive)) {
789
- define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
790
- //require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
791
- require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
792
- $archive = new IWPPclZip($backup_file);
793
- }
794
-
795
- //Include paths
796
- $include_data = array();
797
- if (!empty($include) && is_array($include)) {
798
- foreach ($include as $data) {
799
- if ($data && file_exists(ABSPATH . $data))
800
- $include_data[] = ABSPATH . $data . '/';
801
- }
802
- }
803
-
804
- foreach ($add as $data) {
805
- if (file_exists(ABSPATH . $data))
806
- $include_data[] = ABSPATH . $data . '/';
807
- }
808
-
809
- //Include root files
810
- if ($handle = opendir(ABSPATH)) {
811
- while (false !== ($file = readdir($handle))) {
812
- if ($file != "." && $file != ".." && !is_dir($file) && file_exists(ABSPATH . $file)) {
813
- $include_data[] = ABSPATH . $file;
814
- }
815
- }
816
- closedir($handle);
817
- }
818
-
819
- //exclude paths
820
- $exclude_data = array();
821
- if (!empty($exclude) && is_array($exclude)) {
822
- foreach ($exclude as $data) {
823
- if (is_dir(ABSPATH . $data))
824
- $exclude_data[] = $data . '/';
825
- else
826
- $exclude_data[] = $data;
827
- }
828
- }
829
-
830
- foreach ($remove as $rem) {
831
- $exclude_data[] = $rem . '/';
832
- }
833
-
834
- if($fail_safe_files && $disable_comp){
835
- $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
836
- }
837
- elseif(!$fail_safe_files && $disable_comp){
838
- $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_NO_COMPRESSION);
839
- }
840
- elseif($fail_safe_files && !$disable_comp){
841
- $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
842
- }
843
- else{
844
- $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data);
845
- }
846
-
847
- iwp_mmb_print_flush('Files ZIP PCL: End');
848
-
849
- if (!$result) {
850
- @unlink($backup_file);
851
- return array(
852
- 'error' => 'Failed to zip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
853
- );
854
- }
855
- //}
856
- }
857
- //Reconnect
858
- function fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp){
859
- //$this->back_hack($task_name, 'DB ZIP PCL: Start');
860
- iwp_mmb_print_flush('DB ZIP PCL: Start');
861
- define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
862
- require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
863
- $archive = new IWPPclZip($backup_file);
864
-
865
- if($fail_safe_files && $disable_comp){
866
- $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
867
- }
868
- elseif(!$fail_safe_files && $disable_comp){
869
- $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION);
870
- }
871
- elseif($fail_safe_files && !$disable_comp){
872
- $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
873
- }
874
- else{
875
- $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR);
876
- }
877
- //$this->back_hack($task_name, 'DB ZIP PCL: End');
878
- iwp_mmb_print_flush('DB ZIP PCL: End');
879
-
880
- @unlink($db_result);
881
- @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
882
- @rmdir(IWP_DB_DIR);
883
-
884
- if (!$result_db) {
885
- return array(
886
- 'error' => 'Failed to zip database. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
887
- );
888
- }
889
- }
890
- /**
891
- * Zipping database dump and index.php in folder iwp_db by ZipArchive class, requires php zip extension.
892
- *
893
- * @param string $task_name the name of backup task
894
- * @param string $db_result relative path to database dump file
895
- * @param string $backup_file absolute path to zip file
896
- * @return bool is compress successful or not
897
- */
898
- function zip_archive_backup_db($task_name, $db_result, $backup_file) {
899
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
900
- if (!$disable_comp) {
901
- $this->_log("Compression is not supported by ZipArchive");
902
- }
903
- $zip = new ZipArchive();
904
- $result = $zip->open($backup_file, ZIPARCHIVE::OVERWRITE); // Tries to open $backup_file for acrhiving
905
- if ($result === true) {
906
- $result = $result && $zip->addFile(IWP_BACKUP_DIR.'/iwp_db/index.php', "iwp_db/index.php"); // Tries to add iwp_db/index.php to $backup_file
907
- $result = $result && $zip->addFile($db_result, "iwp_db/" . basename($db_result)); // Tries to add db dump form iwp_db dir to $backup_file
908
- $result = $result && $zip->close(); // Tries to close $backup_file
909
- } else {
910
- $result = false;
911
- }
912
-
913
- return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
914
- }
915
-
916
- /**
917
- * Zipping whole site root folder and append to backup file with database dump
918
- * by ZipArchive class, requires php zip extension.
919
- *
920
- * @param string $task_name the name of backup task
921
- * @param string $backup_file absolute path to zip file
922
- * @param array $exclude array of files of folders to exclude, relative to site's root
923
- * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
924
- * @return array|bool true if successful or an array with error message if not
925
- */
926
- function zip_archive_backup($task_name, $backup_file, $exclude, $include, $overwrite = false) {
927
-
928
- $filelist = $this->get_backup_files($exclude, $include);
929
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
930
- if (!$disable_comp) {
931
- $this->_log("Compression is not supported by ZipArchive");
932
- }
933
- $zip = new ZipArchive();
934
- if ($overwrite) {
935
- $result = $zip->open($backup_file, ZipArchive::OVERWRITE); // Tries to open $backup_file for acrhiving
936
- } else {
937
- $result = $zip->open($backup_file); // Tries to open $backup_file for acrhiving
938
- }
939
- if ($result === true) {
940
- foreach ($filelist as $file) {
941
- iwp_mmb_auto_print('zip_archive_backup');
942
- $result = $result && $zip->addFile($file, sprintf("%s", str_replace(ABSPATH, '', $file))); // Tries to add a new file to $backup_file
943
- }
944
- $result = $result && $zip->close(); // Tries to close $backup_file
945
- } else {
946
- $result = false;
947
- }
948
- return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
949
- }
950
-
951
-
952
- /**
953
- * Gets an array of relative paths of all files in site root recursively.
954
- * By default, there are all files from root folder, all files from folders wp-admin, wp-content, wp-includes recursively.
955
- * Parameter $include adds other folders from site root, and excludes any file or folder by relative path to site's root.
956
- *
957
- * @param array $exclude array of files of folders to exclude, relative to site's root
958
- * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
959
- * @return array array with all files in site root dir
960
- */
961
- function get_backup_files($exclude, $include) {
962
-
963
- $add = array(
964
- trim(WPINC),
965
- trim(basename(WP_CONTENT_DIR)),
966
- "wp-admin"
967
- );
968
-
969
- $include = array_merge($add, $include);
970
-
971
- $filelist = array();
972
- if ($handle = opendir(ABSPATH)) {
973
- while (false !== ($file = readdir($handle))) {
974
- if (is_dir($file) && file_exists(ABSPATH . $file) && !(in_array($file, $include))) {
975
- $exclude[] = $file;
976
- }
977
- }
978
- closedir($handle);
979
- }
980
-
981
- $filelist = get_all_files_from_dir(ABSPATH, $exclude);
982
-
983
- return $filelist;
984
- }
985
-
986
-
987
- function backup_db()
988
- {
989
- $db_folder = IWP_DB_DIR . '/';
990
- if (!file_exists($db_folder)) {
991
- if (!mkdir($db_folder, 0755, true))
992
- return array(
993
- 'error' => 'Error creating database backup folder (' . $db_folder . '). Make sure you have corrrect write permissions.'
994
- );
995
- $db_index_file = '<?php
996
- global $old_url, $old_file_path;
997
- $old_url = \''.get_option('siteurl').'\';
998
- $old_file_path = \''.ABSPATH.'\';
999
- ';
1000
- @file_put_contents(IWP_BACKUP_DIR.'/iwp_db/index.php', $db_index_file);
1001
- }
1002
-
1003
- $file = $db_folder . DB_NAME . '.sql';
1004
-
1005
- if($GLOBALS['fail_safe_db']){
1006
- $result = $this->backup_db_php($file);
1007
- return $result;
1008
- }
1009
-
1010
- $result = $this->backup_db_dump($file); // try mysqldump always then fallback to php dump
1011
- return $result;
1012
- }
1013
-
1014
- function backup_db_dump($file)
1015
- {
1016
- global $wpdb;
1017
- $paths = $this->check_mysql_paths();
1018
- $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1019
- $command = $brace . $paths['mysqldump'] . $brace . ' --force --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables "' . DB_NAME . '" > ' . $brace . $file . $brace;
1020
- iwp_mmb_print_flush('DB DUMP CMD: Start');
1021
- ob_start();
1022
- $result = $this->iwp_mmb_exec($command);
1023
- ob_get_clean();
1024
- iwp_mmb_print_flush('DB DUMP CMD: End');
1025
-
1026
- if (!$result) { // Fallback to php
1027
- $result = $this->backup_db_php($file);
1028
- return $result;
1029
- }
1030
-
1031
- if (filesize($file) == 0 || !is_file($file) || !$result) {
1032
- @unlink($file);
1033
- return false;
1034
- } else {
1035
- return $file;
1036
- }
1037
- }
1038
-
1039
- function backup_db_php($file)
1040
- {
1041
- global $wpdb;
1042
-
1043
- if(empty($GLOBALS['fail_safe_db'])){
1044
- iwp_mmb_print_flush('DB DUMP PHP Normal: Start');
1045
- $fp = fopen( $file, 'w' );
1046
- if ( !mysql_ping( $wpdb->dbh ) ) {
1047
- mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
1048
- mysql_select_db( DB_NAME );
1049
- }
1050
- $_count = 0;
1051
- $insert_sql = '';
1052
- $result = mysql_query( 'SHOW TABLES' );
1053
- if(!$result)
1054
- {
1055
- return array(
1056
- 'error' => 'MySQL '.mysql_error()." "
1057
- );
1058
- }
1059
- while( $row = mysql_fetch_row( $result ) ) {
1060
- $tables[]=$row[0];
1061
- //array_push( $tables, $row[0] );
1062
- }
1063
-
1064
-
1065
- //$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
1066
- foreach ($tables as $table) {
1067
- iwp_mmb_auto_print('backup_db_php_normal');
1068
-
1069
- $insert_sql .= "DROP TABLE IF EXISTS $table;";
1070
- //create table
1071
- $table_descr_query = mysql_query("SHOW CREATE TABLE `$table`");
1072
- $fetch_table_descr_row = mysql_fetch_array( $table_descr_query );
1073
- $insert_sql .= "\n\n" . $fetch_table_descr_row[1] . ";\n\n";
1074
-
1075
- fwrite( $fp, $insert_sql );
1076
- $insert_sql = '';
1077
-
1078
- $table_query = mysql_query("SELECT * FROM `$table`");
1079
- $num_fields = mysql_num_fields($table_query);
1080
- while ( $fetch_row = mysql_fetch_array( $table_query ) ) {
1081
- $insert_sql .= "INSERT INTO $table VALUES(";
1082
- for ( $n=1; $n<=$num_fields; $n++ ) {
1083
- $m = $n - 1;
1084
-
1085
- if ( $fetch_row[$m] === NULL ) {
1086
- $insert_sql .= "NULL, ";
1087
- } else {
1088
- $insert_sql .= "'" . mysql_real_escape_string( $fetch_row[$m] ) . "', ";
1089
- }
1090
- }
1091
- $insert_sql = substr( $insert_sql, 0, -2 );
1092
- $insert_sql .= ");\n";
1093
-
1094
- fwrite( $fp, $insert_sql );
1095
- $insert_sql = '';
1096
-
1097
- // Help keep HTTP alive.
1098
- $_count++;
1099
- if ($_count >= 400) {
1100
- echo ' ';
1101
- flush();
1102
- $_count = 0;
1103
- }
1104
- } // End foreach $tables.
1105
-
1106
- $insert_sql .= "\n\n\n";
1107
-
1108
- // testing: mysql_close( $wpdb->dbh );
1109
- // Verify database is still connected and working properly. Sometimes mysql runs out of memory and dies in the above foreach.
1110
- // No point in reconnecting as we can NOT trust that our dump was succesful anymore (it most likely was not).
1111
- if ( @mysql_ping( $wpdb->dbh ) ) { // Still connected to database.
1112
- mysql_free_result( $table_query ); // Free memory.
1113
- } /*else { // Database not connected.
1114
-
1115
- return false;
1116
- }*/
1117
-
1118
- // Help keep HTTP alive.
1119
- echo ' ';
1120
- flush();
1121
-
1122
- //unset( $tables[$table_key] );
1123
- }
1124
- fclose( $fp );
1125
- unset ($fp);
1126
- iwp_mmb_print_flush('DB DUMP PHP Normal: End');
1127
- }
1128
- else{
1129
- iwp_mmb_print_flush('DB DUMP PHP Fail-safe: Start');
1130
- file_put_contents($file, '');//safe to reset any old data
1131
- $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
1132
- foreach ($tables as $table) {
1133
-
1134
- //drop existing table
1135
- $dump_data = "DROP TABLE IF EXISTS $table[0];";
1136
- file_put_contents($file, $dump_data, FILE_APPEND);
1137
- //create table
1138
- $create_table = $wpdb->get_row("SHOW CREATE TABLE $table[0]", ARRAY_N);
1139
- $dump_data = "\n\n" . $create_table[1] . ";\n\n";
1140
- file_put_contents($file, $dump_data, FILE_APPEND);
1141
-
1142
- $count = $wpdb->get_var("SELECT count(*) FROM $table[0]");
1143
- if ($count > 100)
1144
- $count = ceil($count / 100);
1145
- else if ($count > 0)
1146
- $count = 1;
1147
-
1148
- for ($i = 0; $i < $count; $i++) {
1149
- iwp_mmb_auto_print('backup_db_php_fail_safe');
1150
- $low_limit = $i * 100;
1151
- $qry = "SELECT * FROM $table[0] LIMIT $low_limit, 100";
1152
- $rows = $wpdb->get_results($qry, ARRAY_A);
1153
- if (is_array($rows)) {
1154
- foreach ($rows as $row) {
1155
- //insert single row
1156
- $dump_data = "INSERT INTO $table[0] VALUES(";
1157
- $num_values = count($row);
1158
- $j = 1;
1159
- foreach ($row as $value) {
1160
- $value = addslashes($value);
1161
- $value = preg_replace("/\n/Ui", "\\n", $value);
1162
- $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
1163
- $j++;
1164
- unset($value);
1165
- }
1166
- $dump_data .= ");\n";
1167
- file_put_contents($file, $dump_data, FILE_APPEND);
1168
- }
1169
- }
1170
- }
1171
- $dump_data = "\n\n\n";
1172
- file_put_contents($file, $dump_data, FILE_APPEND);
1173
-
1174
- unset($rows);
1175
- unset($dump_data);
1176
- }
1177
- iwp_mmb_print_flush('DB DUMP PHP Fail-safe: End');
1178
- }
1179
-
1180
- if (filesize($file) == 0 || !is_file($file)) {
1181
- @unlink($file);
1182
- return array(
1183
- 'error' => 'Database backup failed. Try to enable MySQL dump on your server.'
1184
- );
1185
- }
1186
-
1187
- return $file;
1188
-
1189
- }
1190
-
1191
- /**
1192
- * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
1193
- * Assumes that WP_Filesystem() has already been called and setup.
1194
- *
1195
- * @since 2.5.0
1196
- *
1197
- * @param string $from source directory
1198
- * @param string $to destination directory
1199
- * @param array $skip_list a list of files/folders to skip copying
1200
- * @return mixed WP_Error on failure, True on success.
1201
- */
1202
- function iwp_mmb_direct_to_any_copy_dir($from, $to, $skip_list = array() ) {//$from => direct file system, $to => automatic filesystem
1203
- global $wp_filesystem;
1204
-
1205
- $wp_temp_direct = new WP_Filesystem_Direct('');
1206
-
1207
-
1208
- $dirlist = $wp_temp_direct->dirlist($from);
1209
-
1210
- $from = trailingslashit($from);
1211
- $to = trailingslashit($to);
1212
-
1213
- $skip_regex = '';
1214
- foreach ( (array)$skip_list as $key => $skip_file )
1215
- $skip_regex .= preg_quote($skip_file, '!') . '|';
1216
-
1217
- if ( !empty($skip_regex) )
1218
- $skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i';
1219
-
1220
- foreach ( (array) $dirlist as $filename => $fileinfo ) {
1221
- if ( !empty($skip_regex) )
1222
- if ( preg_match($skip_regex, $from . $filename) )
1223
- continue;
1224
-
1225
- if ( 'f' == $fileinfo['type'] ) {
1226
- if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
1227
- // If copy failed, chmod file to 0644 and try again.
1228
- $wp_filesystem->chmod($to . $filename, 0644);
1229
- if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
1230
- return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename);
1231
- }
1232
- } elseif ( 'd' == $fileinfo['type'] ) {
1233
- if ( !$wp_filesystem->is_dir($to . $filename) ) {
1234
- if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
1235
- return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename);
1236
- }
1237
- $result = $this->iwp_mmb_direct_to_any_copy_dir($from . $filename, $to . $filename, $skip_list);
1238
- if ( is_wp_error($result) )
1239
- return $result;
1240
- }
1241
- }
1242
- return true;
1243
- }
1244
-
1245
- function iwp_mmb_direct_to_any_copy($source, $destination, $overwrite = false, $mode = false){
1246
- global $wp_filesystem;
1247
- if($wp_filesystem->method == 'direct'){
1248
- return $wp_filesystem->copy($source, $destination, $overwrite, $mode);
1249
- }
1250
- elseif($wp_filesystem->method == 'ftpext' || $wp_filesystem->method == 'ftpsockets'){
1251
- if ( ! $overwrite && $wp_filesystem->exists($destination) )
1252
- return false;
1253
- //$content = $this->get_contents($source);
1254
- // if ( false === $content)
1255
- // return false;
1256
-
1257
- //put content
1258
- //$tempfile = wp_tempnam($file);
1259
- $source_handle = fopen($source, 'r');
1260
- if ( ! $source_handle )
1261
- return false;
1262
-
1263
- //fwrite($temp, $contents);
1264
- //fseek($temp, 0); //Skip back to the start of the file being written to
1265
-
1266
- $sample_content = fread($source_handle, (1024 * 1024 * 2));//1024 * 1024 * 2 => 2MB
1267
- fseek($source_handle, 0); //Skip back to the start of the file being written to
1268
-
1269
- $type = $wp_filesystem->is_binary($sample_content) ? FTP_BINARY : FTP_ASCII;
1270
- unset($sample_content);
1271
- if($wp_filesystem->method == 'ftpext'){
1272
- $ret = @ftp_fput($wp_filesystem->link, $destination, $source_handle, $type);
1273
- }
1274
- elseif($wp_filesystem->method == 'ftpsockets'){
1275
- $wp_filesystem->ftp->SetType($type);
1276
- $ret = $wp_filesystem->ftp->fput($destination, $source_handle);
1277
- }
1278
-
1279
- fclose($source_handle);
1280
- unlink($source);//to immediately save system space
1281
- //unlink($tempfile);
1282
-
1283
- $wp_filesystem->chmod($destination, $mode);
1284
-
1285
- return $ret;
1286
-
1287
- //return $this->put_contents($destination, $content, $mode);
1288
- }
1289
- }
1290
-
1291
-
1292
- function restore($args)
1293
- {
1294
-
1295
- global $wpdb, $wp_filesystem;
1296
- if (empty($args)) {
1297
- return false;
1298
- }
1299
-
1300
- extract($args);
1301
- $this->set_memory();
1302
-
1303
- $unlink_file = true; //Delete file after restore
1304
-
1305
- include_once ABSPATH . 'wp-admin/includes/file.php';
1306
-
1307
- //Detect source
1308
- if ($backup_url) {
1309
- //This is for clone (overwrite)
1310
-
1311
- $backup_file = download_url($backup_url);
1312
- if (is_wp_error($backup_file)) {
1313
- return array(
1314
- 'error' => 'Unable to download backup file ('.$backup_file->get_error_message().')'
1315
- );
1316
- }
1317
- $what = 'full';
1318
- } else {
1319
- $tasks = $this->tasks;
1320
- $task = $tasks[$task_name];
1321
- if (isset($task['task_results'][$result_id]['server'])) {
1322
- $backup_file = $task['task_results'][$result_id]['server']['file_path'];
1323
- $unlink_file = false; //Don't delete file if stored on server
1324
-
1325
- } elseif (isset($task['task_results'][$result_id]['ftp'])) {
1326
- $ftp_file = $task['task_results'][$result_id]['ftp'];
1327
- $args = $task['task_args']['account_info']['iwp_ftp'];
1328
- $args['backup_file'] = $ftp_file;
1329
- iwp_mmb_print_flush('FTP download: Start');
1330
- $backup_file = $this->get_ftp_backup($args);
1331
- iwp_mmb_print_flush('FTP download: End');
1332
- if ($backup_file == false) {
1333
- return array(
1334
- 'error' => 'Failed to download file from FTP.'
1335
- );
1336
- }
1337
- } elseif (isset($task['task_results'][$result_id]['amazons3'])) {
1338
- $amazons3_file = $task['task_results'][$result_id]['amazons3'];
1339
- $args = $task['task_args']['account_info']['iwp_amazon_s3'];
1340
- $args['backup_file'] = $amazons3_file;
1341
- iwp_mmb_print_flush('Amazon S3 download: Start');
1342
- $backup_file = $this->get_amazons3_backup($args);
1343
- iwp_mmb_print_flush('Amazon S3 download: End');
1344
- if ($backup_file == false) {
1345
- return array(
1346
- 'error' => 'Failed to download file from Amazon S3.'
1347
- );
1348
- }
1349
- } elseif(isset($task['task_results'][$result_id]['dropbox'])){
1350
- $dropbox_file = $task['task_results'][$result_id]['dropbox'];
1351
- $args = $task['task_args']['account_info']['iwp_dropbox'];
1352
- $args['backup_file'] = $dropbox_file;
1353
- iwp_mmb_print_flush('Dropbox download: Start');
1354
- $backup_file = $this->get_dropbox_backup($args);
1355
- iwp_mmb_print_flush('Dropbox download: End');
1356
-
1357
- if ($backup_file == false) {
1358
- return array(
1359
- 'error' => 'Failed to download file from Dropbox.'
1360
- );
1361
- }
1362
- }
1363
-
1364
-
1365
- $what = $tasks[$task_name]['task_args']['what'];
1366
- }
1367
-
1368
-
1369
-
1370
- $this->wpdb_reconnect();
1371
-
1372
- /////////////////// dev ////////////////////////
1373
-
1374
-
1375
- if (!$this->is_server_writable()) {
1376
- return array(
1377
- 'error' => 'Failed, please add FTP details'
1378
- );
1379
- }
1380
-
1381
- $url = wp_nonce_url('index.php?page=iwp_no_page','iwp_fs_cred');
1382
- ob_start();
1383
- if (false === ($creds = request_filesystem_credentials($url, '', false, ABSPATH, null) ) ) {
1384
- return array(
1385
- 'error' => 'Unable to get file system credentials'
1386
- ); // stop processing here
1387
- }
1388
- ob_end_clean();
1389
-
1390
- if ( ! WP_Filesystem($creds, ABSPATH) ) {
1391
- //request_filesystem_credentials($url, '', true, false, null);
1392
- return array(
1393
- 'error' => 'Unable to initiate file system. Please check you have entered valid FTP credentials.'
1394
- ); // stop processing here
1395
- //return;
1396
- }
1397
-
1398
- require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');//will be used to copy from temp directory
1399
-
1400
- // do process
1401
- $temp_dir = get_temp_dir();
1402
- $new_temp_folder = untrailingslashit($temp_dir);
1403
- $temp_uniq = md5(microtime(1));//should be random
1404
- while (is_dir($new_temp_folder .'/'. $temp_uniq )) {
1405
- $temp_uniq = md5(microtime(1));
1406
- }
1407
- $new_temp_folder = trailingslashit($new_temp_folder .'/'. $temp_uniq);
1408
- $is_dir_created = mkdir($new_temp_folder);// new folder should be empty
1409
- if(!$is_dir_created){
1410
- return array(
1411
- 'error' => 'Unable to create a temporary directory.'
1412
- );
1413
- }
1414
-
1415
- //echo '<pre>$new_temp_folder:'; var_dump($new_temp_folder); echo '</pre>';
1416
-
1417
-
1418
- $remote_abspath = $wp_filesystem->abspath();
1419
- if(!empty($remote_abspath)){
1420
- $remote_abspath = trailingslashit($remote_abspath);
1421
- }else{
1422
- return array(
1423
- 'error' => 'Unable to locate WP root directory using file system.'
1424
- );
1425
- }
1426
-
1427
- //global $wp_filesystem;
1428
- // $wp_filesystem->put_contents(
1429
- // '/tmp/example.txt',
1430
- // 'Example contents of a file',
1431
- // FS_CHMOD_FILE // predefined mode settings for WP files
1432
- // );
1433
-
1434
- /////////////////// dev ////////////////////////
1435
-
1436
- if ($backup_file && file_exists($backup_file)) {
1437
- if ($overwrite) {//clone only fresh or existing to existing
1438
- //Keep old db credentials before overwrite
1439
- if (!$wp_filesystem->copy($remote_abspath . 'wp-config.php', $remote_abspath . 'iwp-temp-wp-config.php', true)) {
1440
- if($unlink_file) @unlink($backup_file);
1441
- return array(
1442
- 'error' => 'Error creating wp-config. Please check your write permissions.'
1443
- );
1444
- }
1445
-
1446
- $db_host = DB_HOST;
1447
- $db_user = DB_USER;
1448
- $db_password = DB_PASSWORD;
1449
- $home = rtrim(get_option('home'), "/");
1450
- $site_url = get_option('site_url');
1451
-
1452
- $clone_options = array();
1453
- if (trim($clone_from_url) || trim($iwp_clone) || trim($maintain_old_key)) {
1454
-
1455
- $clone_options['iwp_client_nossl_key'] = get_option('iwp_client_nossl_key');
1456
- $clone_options['iwp_client_public_key'] = get_option('iwp_client_public_key');
1457
- $clone_options['iwp_client_action_message_id'] = get_option('iwp_client_action_message_id');
1458
-
1459
- }
1460
-
1461
- $clone_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_backup_tasks'));
1462
- $clone_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
1463
- $clone_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
1464
-
1465
-
1466
- } else {
1467
- $restore_options = array();
1468
- $restore_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
1469
- $restore_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
1470
- $restore_options['iwp_client_user_hit_count'] = serialize(get_option('iwp_client_user_hit_count'));
1471
- $restore_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_backup_tasks'));
1472
- }
1473
-
1474
-
1475
-
1476
-
1477
- //Backup file will be extracted to a temporary path
1478
-
1479
- //chdir(ABSPATH);
1480
- $unzip = $this->get_unzip();
1481
- $command = "$unzip -o $backup_file -d $new_temp_folder";
1482
- iwp_mmb_print_flush('ZIP Extract CMD: Start');
1483
- ob_start();
1484
- $result = $this->iwp_mmb_exec($command);
1485
- ob_get_clean();
1486
- iwp_mmb_print_flush('ZIP Extract CMD: End');
1487
-
1488
- if (!$result) { //fallback to pclzip
1489
- define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
1490
- //require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
1491
- require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
1492
- iwp_mmb_print_flush('ZIP Extract PCL: Start');
1493
- $archive = new IWPPclZip($backup_file);
1494
- $result = $archive->extract(PCLZIP_OPT_PATH, $new_temp_folder, PCLZIP_OPT_REPLACE_NEWER);
1495
- iwp_mmb_print_flush('ZIP Extract PCL: End');
1496
- }
1497
- $this->wpdb_reconnect();
1498
-
1499
- if ($unlink_file) {
1500
- @unlink($backup_file);
1501
- }
1502
-
1503
- if (!$result) {
1504
- return array(
1505
- 'error' => 'Failed to unzip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
1506
- );
1507
- }
1508
-
1509
- $db_result = $this->restore_db($new_temp_folder);
1510
-
1511
- if (!$db_result) {
1512
- return array(
1513
- 'error' => 'Error restoring database.'
1514
- );
1515
- } else if(is_array($db_result) && isset($db_result['error'])){
1516
- return array(
1517
- 'error' => $db_result['error']
1518
- );
1519
- }
1520
-
1521
- } else {
1522
- return array(
1523
- 'error' => 'Backup file not found.'
1524
- );
1525
- }
1526
-
1527
-
1528
- //copy files from temp to ABSPATH
1529
- $copy_result = $this->iwp_mmb_direct_to_any_copy_dir($new_temp_folder, $remote_abspath);
1530
-
1531
- if ( is_wp_error($copy_result) ){
1532
- $wp_temp_direct2 = new WP_Filesystem_Direct('');
1533
- $wp_temp_direct2->delete($new_temp_folder, true);
1534
- return $copy_result;
1535
- }
1536
-
1537
-
1538
- $this->wpdb_reconnect();
1539
-
1540
-
1541
-
1542
- //Replace options and content urls
1543
- if ($overwrite) {//fresh WP package or existing to existing site
1544
- //Get New Table prefix
1545
- $new_table_prefix = trim($this->get_table_prefix());
1546
- //Retrieve old wp_config
1547
- //@unlink(ABSPATH . 'wp-config.php');
1548
- $wp_filesystem->delete($remote_abspath . 'wp-config.php', false, 'f');
1549
- //Replace table prefix
1550
- //$lines = file(ABSPATH . 'iwp-temp-wp-config.php');
1551
- $lines = $wp_filesystem->get_contents_array($remote_abspath . 'iwp-temp-wp-config.php');
1552
-
1553
- $new_lines = '';
1554
- foreach ($lines as $line) {
1555
- if (strstr($line, '$table_prefix')) {
1556
- $line = '$table_prefix = "' . $new_table_prefix . '";' . PHP_EOL;
1557
- }
1558
- $new_lines .= $line;
1559
- //file_put_contents(ABSPATH . 'wp-config.php', $line, FILE_APPEND);
1560
- }
1561
-
1562
- $wp_filesystem->put_contents($remote_abspath . 'wp-config.php', $new_lines);
1563
-
1564
- //@unlink(ABSPATH . 'iwp-temp-wp-config.php');
1565
- $wp_filesystem->delete($remote_abspath . 'iwp-temp-wp-config.php', false, 'f');
1566
-
1567
- //Replace options
1568
- $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
1569
- $old = $wpdb->get_var($query);
1570
- $old = rtrim($old, "/");
1571
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'home'";
1572
- $wpdb->query($wpdb->prepare($query, $home));
1573
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'siteurl'";
1574
- $wpdb->query($wpdb->prepare($query, $home));
1575
- //Replace content urls
1576
-
1577
- $regexp1 = 'src="(.*)'.$old.'(.*)"';
1578
- $regexp2 = 'href="(.*)'.$old.'(.*)"';
1579
- $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, %s,%s) WHERE post_content REGEXP %s OR post_content REGEXP %s";
1580
- $wpdb->query($wpdb->prepare($query, $old, $home, $regexp1, $regexp2));
1581
-
1582
- if (trim($new_password)) {
1583
- $new_password = wp_hash_password($new_password);
1584
- }
1585
- if (!trim($clone_from_url) && !trim($iwp_clone)) {
1586
- if ($new_user && $new_password) {
1587
- $query = "UPDATE " . $new_table_prefix . "users SET user_login = %s, user_pass = %s WHERE user_login = %s";
1588
- $wpdb->query($wpdb->prepare($query, $new_user, $new_password, $old_user));
1589
- }
1590
- } else {
1591
-
1592
- // if ($iwp_clone) {
1593
- if ($admin_email) {
1594
- //Clean Install
1595
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'admin_email'";
1596
- $wpdb->query($wpdb->prepare($query, $admin_email));
1597
- $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
1598
- $temp_user = $wpdb->get_row($query);
1599
- if (!empty($temp_user)) {
1600
- $query = "UPDATE " . $new_table_prefix . "users SET user_email=%s, user_login = %s, user_pass = %s WHERE user_login = %s";
1601
- $wpdb->query($wpdb->prepare($query, $admin_email, $new_user, $new_password, $temp_user->user_login));
1602
- }
1603
-
1604
- }
1605
- // }
1606
-
1607
- //if ($clone_from_url) {
1608
- if ($new_user && $new_password) {
1609
- $query = "UPDATE " . $new_table_prefix . "users SET user_pass = %s WHERE user_login = %s";
1610
- $wpdb->query($wpdb->prepare($query, $new_password, $new_user));
1611
- }
1612
- // }
1613
-
1614
- }
1615
-
1616
- if (is_array($clone_options) && !empty($clone_options)) {
1617
- foreach ($clone_options as $key => $option) {
1618
- if (!empty($key)) {
1619
- $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = %s";
1620
- $res = $wpdb->get_var($wpdb->prepare($query, $key));
1621
- if ($res == false) {
1622
- $query = "INSERT INTO " . $new_table_prefix . "options (option_value,option_name) VALUES(%s,%s)";
1623
- $wpdb->query($wpdb->prepare($query, $option, $key));
1624
- } else {
1625
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = %s";
1626
- $wpdb->query($wpdb->prepare($query, $option, $key));
1627
- }
1628
- }
1629
- }
1630
- }
1631
-
1632
- //Remove hit count
1633
- $query = "DELETE FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_user_hit_count'";
1634
- $wpdb->query($query);
1635
-
1636
- //Check for .htaccess permalinks update
1637
- $this->replace_htaccess($home, $remote_abspath);
1638
- } else {
1639
- //restore client options
1640
- if (is_array($restore_options) && !empty($restore_options)) {
1641
- foreach ($restore_options as $key => $option) {
1642
- if (!empty($key)) {
1643
- $query = "SELECT option_value FROM " . $wpdb->base_prefix . "options WHERE option_name = %s";
1644
- $res = $wpdb->get_var($wpdb->prepare($query, $key));
1645
- if ($res == false) {
1646
- $query = "INSERT INTO " . $wpdb->base_prefix . "options (option_value,option_name) VALUES(%s,%s)";
1647
- $wpdb->query($wpdb->prepare($query, $option, $key));
1648
- } else {
1649
- $query = "UPDATE " . $wpdb->base_prefix . "options SET option_value = %s WHERE option_name = %s";
1650
- $wpdb->query($wpdb->prepare($query, $option, $key));
1651
- }
1652
- }
1653
-
1654
- /*$test = update_option($key,$option);*/
1655
- }
1656
- }
1657
- }
1658
-
1659
- //clear the temp directory
1660
- $wp_temp_direct2 = new WP_Filesystem_Direct('');
1661
- $wp_temp_direct2->delete($new_temp_folder, true);
1662
-
1663
- return !empty($new_user) ? $new_user : true ;
1664
- }
1665
-
1666
- function restore_db($new_temp_folder)
1667
- {
1668
- global $wpdb;
1669
- $paths = $this->check_mysql_paths();
1670
- $file_path = $new_temp_folder . '/iwp_db';
1671
- @chmod($file_path,0755);
1672
- $file_name = glob($file_path . '/*.sql');
1673
- $file_name = $file_name[0];
1674
-
1675
- if(!$file_name){
1676
- return array('error' => 'Cannot access database file.');
1677
- }
1678
-
1679
- $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1680
- $command = $brace . $paths['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --default-character-set="utf8" ' . DB_NAME . ' < ' . $brace . $file_name . $brace;
1681
- iwp_mmb_print_flush('DB Restore CMD: Start');
1682
- ob_start();
1683
- $result = $this->iwp_mmb_exec($command);
1684
- ob_get_clean();
1685
- iwp_mmb_print_flush('DB Restore CMD: End');
1686
- if (!$result) {
1687
- //try php
1688
- $this->restore_db_php($file_name);
1689
- }
1690
-
1691
-
1692
- @unlink($file_name);
1693
- @unlink(dirname($file_name).'/index.php');
1694
- @rmdir(dirname($file_name));//remove its folder
1695
- return true;
1696
- }
1697
-
1698
- function restore_db_php($file_name)
1699
- {
1700
-
1701
- $this->wpdb_reconnect();
1702
- global $wpdb;
1703
-
1704
- $wpdb->query("SET NAMES 'utf8'");
1705
-
1706
- $current_query = '';
1707
- // Read in entire file
1708
- $lines = file($file_name);
1709
- // Loop through each line
1710
- if(!empty($lines)){
1711
- foreach ($lines as $line) {
1712
- iwp_mmb_auto_print('restore_db_php');
1713
- // Skip it if it's a comment
1714
- if (substr($line, 0, 2) == '--' || $line == '')
1715
- continue;
1716
-
1717
- // Add this line to the current query
1718
- $current_query .= $line;
1719
- // If it has a semicolon at the end, it's the end of the query
1720
- if (substr(trim($line), -1, 1) == ';') {
1721
- // Perform the query
1722
- $result = $wpdb->query($current_query);
1723
- if ($result === false)
1724
- return false;
1725
- // Reset temp variable to empty
1726
- $current_query = '';
1727
- }
1728
- }
1729
- }
1730
-
1731
- return true;
1732
- }
1733
-
1734
- function get_table_prefix()
1735
- {
1736
- $lines = file(ABSPATH . 'wp-config.php');
1737
- foreach ($lines as $line) {
1738
- if (strstr($line, '$table_prefix')) {
1739
- $pattern = "/(\'|\")[^(\'|\")]*/";
1740
- preg_match($pattern, $line, $matches);
1741
- $prefix = substr($matches[0], 1);
1742
- return $prefix;
1743
- break;
1744
- }
1745
- }
1746
- return 'wp_'; //default
1747
- }
1748
-
1749
- function optimize_tables()
1750
- {
1751
- global $wpdb;
1752
- $query = 'SHOW TABLE STATUS';
1753
- $tables = $wpdb->get_results($query, ARRAY_A);
1754
- foreach ($tables as $table) {
1755
- if (in_array($table['Engine'], array(
1756
- 'MyISAM',
1757
- 'ISAM',
1758
- 'HEAP',
1759
- 'MEMORY',
1760
- 'ARCHIVE'
1761
- )))
1762
- $table_string .= $table['Name'] . ",";
1763
- elseif ($table['Engine'] == 'InnoDB') {
1764
- $optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
1765
- }
1766
- }
1767
-
1768
- if(!empty($table_string)){
1769
- $table_string = rtrim($table_string, ',');
1770
- $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
1771
- }
1772
-
1773
- return $optimize ? true : false;
1774
- }
1775
-
1776
- ### Function: Auto Detect MYSQL and MYSQL Dump Paths
1777
- function check_mysql_paths()
1778
- {
1779
- global $wpdb;
1780
- $paths = array(
1781
- 'mysql' => '',
1782
- 'mysqldump' => ''
1783
- );
1784
- if (substr(PHP_OS, 0, 3) == 'WIN') {
1785
- $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
1786
- if ($mysql_install) {
1787
- $install_path = str_replace('\\', '/', $mysql_install->Value);
1788
- $paths['mysql'] = $install_path . 'bin/mysql.exe';
1789
- $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
1790
- } else {
1791
- $paths['mysql'] = 'mysql.exe';
1792
- $paths['mysqldump'] = 'mysqldump.exe';
1793
- }
1794
- } else {
1795
- $paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
1796
- if (empty($paths['mysql']))
1797
- $paths['mysql'] = 'mysql'; // try anyway
1798
-
1799
- $paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
1800
- if (empty($paths['mysqldump']))
1801
- $paths['mysqldump'] = 'mysqldump'; // try anyway
1802
-
1803
- }
1804
-
1805
-
1806
- return $paths;
1807
- }
1808
-
1809
- //Check if exec, system, passthru functions exist
1810
- function check_sys()
1811
- {
1812
- if ($this->iwp_mmb_function_exists('exec'))
1813
- return 'exec';
1814
-
1815
- if ($this->iwp_mmb_function_exists('system'))
1816
- return 'system';
1817
-
1818
- if ($this->iwp_mmb_function_exists('passhtru'))
1819
- return 'passthru';
1820
-
1821
- return false;
1822
-
1823
- }
1824
-
1825
- function iwp_mmb_exec($command, $string = false, $rawreturn = false)
1826
- {
1827
- if ($command == '')
1828
- return false;
1829
-
1830
- if ($this->iwp_mmb_function_exists('exec')) {
1831
- $log = @exec($command, $output, $return);
1832
-
1833
- if ($string)
1834
- return $log;
1835
- if ($rawreturn)
1836
- return $return;
1837
-
1838
- return $return ? false : true;
1839
- } elseif ($this->iwp_mmb_function_exists('system')) {
1840
- $log = @system($command, $return);
1841
-
1842
- if ($string)
1843
- return $log;
1844
-
1845
- if ($rawreturn)
1846
- return $return;
1847
-
1848
- return $return ? false : true;
1849
- } elseif ($this->iwp_mmb_function_exists('passthru') && !$string) {
1850
- $log = passthru($command, $return);
1851
-
1852
- if ($rawreturn)
1853
- return $return;
1854
-
1855
- return $return ? false : true;
1856
- }
1857
-
1858
- if ($rawreturn)
1859
- return -1;
1860
-
1861
- return false;
1862
- }
1863
-
1864
- function get_zip()
1865
- {
1866
- $zip = $this->iwp_mmb_exec('which zip', true);
1867
- if (!$zip)
1868
- $zip = "zip";
1869
- return $zip;
1870
- }
1871
-
1872
- function get_unzip()
1873
- {
1874
- $unzip = $this->iwp_mmb_exec('which unzip', true);
1875
- if (!$unzip)
1876
- $unzip = "unzip";
1877
- return $unzip;
1878
- }
1879
-
1880
- function check_backup_compat()
1881
- {
1882
- $reqs = array();
1883
- if (strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0) {
1884
- $reqs['Server OS']['status'] = 'Linux (or compatible)';
1885
- $reqs['Server OS']['pass'] = true;
1886
- } else {
1887
- $reqs['Server OS']['status'] = 'Windows';
1888
- $reqs['Server OS']['pass'] = true;
1889
- $pass = false;
1890
- }
1891
- $reqs['PHP Version']['status'] = phpversion();
1892
- if ((float) phpversion() >= 5.1) {
1893
- $reqs['PHP Version']['pass'] = true;
1894
- } else {
1895
- $reqs['PHP Version']['pass'] = false;
1896
- $pass = false;
1897
- }
1898
-
1899
-
1900
- if (is_writable(WP_CONTENT_DIR)) {
1901
- $reqs['Backup Folder']['status'] = "writable";
1902
- $reqs['Backup Folder']['pass'] = true;
1903
- } else {
1904
- $reqs['Backup Folder']['status'] = "not writable";
1905
- $reqs['Backup Folder']['pass'] = false;
1906
- }
1907
-
1908
-
1909
- $file_path = IWP_BACKUP_DIR;
1910
- $reqs['Backup Folder']['status'] .= ' (' . $file_path . ')';
1911
-
1912
- if ($func = $this->check_sys()) {
1913
- $reqs['Execute Function']['status'] = $func;
1914
- $reqs['Execute Function']['pass'] = true;
1915
- } else {
1916
- $reqs['Execute Function']['status'] = "not found";
1917
- $reqs['Execute Function']['info'] = "(will try PHP replacement)";
1918
- $reqs['Execute Function']['pass'] = false;
1919
- }
1920
- $reqs['Zip']['status'] = $this->get_zip();
1921
-
1922
- $reqs['Zip']['pass'] = true;
1923
-
1924
-
1925
-
1926
- $reqs['Unzip']['status'] = $this->get_unzip();
1927
-
1928
- $reqs['Unzip']['pass'] = true;
1929
-
1930
- $paths = $this->check_mysql_paths();
1931
-
1932
- if (!empty($paths['mysqldump'])) {
1933
- $reqs['MySQL Dump']['status'] = $paths['mysqldump'];
1934
- $reqs['MySQL Dump']['pass'] = true;
1935
- } else {
1936
- $reqs['MySQL Dump']['status'] = "not found";
1937
- $reqs['MySQL Dump']['info'] = "(will try PHP replacement)";
1938
- $reqs['MySQL Dump']['pass'] = false;
1939
- }
1940
-
1941
- $exec_time = ini_get('max_execution_time');
1942
- $reqs['Execution time']['status'] = $exec_time ? $exec_time . "s" : 'unknown';
1943
- $reqs['Execution time']['pass'] = true;
1944
-
1945
- $mem_limit = ini_get('memory_limit');
1946
- $reqs['Memory limit']['status'] = $mem_limit ? $mem_limit : 'unknown';
1947
- $reqs['Memory limit']['pass'] = true;
1948
-
1949
-
1950
- return $reqs;
1951
- }
1952
-
1953
- function ftp_backup($args)
1954
- {
1955
- extract($args);
1956
- //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder, $ftp_site_folder
1957
- $port = $ftp_port ? $ftp_port : 21; //default port is 21
1958
- if ($ftp_ssl) {
1959
- if (function_exists('ftp_ssl_connect')) {
1960
- $conn_id = ftp_ssl_connect($ftp_hostname,$port);
1961
- if ($conn_id === false) {
1962
- return array(
1963
- 'error' => 'Failed to connect to ' . $ftp_hostname,
1964
- 'partial' => 1
1965
- );
1966
- }
1967
- } else {
1968
- return array(
1969
- 'error' => 'Your server doesn\'t support FTP SSL',
1970
- 'partial' => 1
1971
- );
1972
- }
1973
- } else {
1974
- if (function_exists('ftp_connect')) {
1975
- $conn_id = ftp_connect($ftp_hostname,$port);
1976
- if ($conn_id === false) {
1977
- return array(
1978
- 'error' => 'Failed to connect to ' . $ftp_hostname,
1979
- 'partial' => 1
1980
- );
1981
- }
1982
- } else {
1983
- return array(
1984
- 'error' => 'Your server doesn\'t support FTP',
1985
- 'partial' => 1
1986
- );
1987
- }
1988
- }
1989
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
1990
- if ($login === false) {
1991
- return array(
1992
- 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
1993
- 'partial' => 1
1994
- );
1995
- }
1996
-
1997
- if($ftp_passive){
1998
- @ftp_pasv($conn_id,true);
1999
- }
2000
-
2001
- @ftp_mkdir($conn_id, $ftp_remote_folder);
2002
- if ($ftp_site_folder) {
2003
- $ftp_remote_folder .= '/' . $this->site_name;
2004
- }
2005
- @ftp_mkdir($conn_id, $ftp_remote_folder);
2006
-
2007
- $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
2008
-
2009
- if ($upload === false) { //Try ascii
2010
- $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_ASCII);
2011
- }
2012
- @ftp_close($conn_id);
2013
-
2014
- if ($upload === false) {
2015
- return array(
2016
- 'error' => 'Failed to upload file to FTP. Please check your specified path.',
2017
- 'partial' => 1
2018
- );
2019
- }
2020
-
2021
- return true;
2022
- }
2023
-
2024
- function remove_ftp_backup($args)
2025
- {
2026
- extract($args);
2027
- //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
2028
- $port = $ftp_port ? $ftp_port : 21; //default port is 21
2029
- if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
2030
- $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2031
- } else if (function_exists('ftp_connect')) {
2032
- $conn_id = ftp_connect($ftp_hostname,$port);
2033
- }
2034
-
2035
- if ($conn_id) {
2036
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2037
- if ($ftp_site_folder)
2038
- $ftp_remote_folder .= '/' . $this->site_name;
2039
-
2040
- if($ftp_passive){
2041
- @ftp_pasv($conn_id,true);
2042
- }
2043
-
2044
- $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $backup_file);
2045
-
2046
- ftp_close($conn_id);
2047
- }
2048
-
2049
- }
2050
-
2051
- function get_ftp_backup($args)
2052
- {
2053
- extract($args);
2054
- //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
2055
- $port = $ftp_port ? $ftp_port : 21; //default port is 21
2056
- if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
2057
- $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2058
-
2059
- } else if (function_exists('ftp_connect')) {
2060
- $conn_id = ftp_connect($ftp_hostname,$port);
2061
- if ($conn_id === false) {
2062
- return false;
2063
- }
2064
- }
2065
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2066
- if ($login === false) {
2067
- return false;
2068
- }
2069
-
2070
- if ($ftp_site_folder)
2071
- $ftp_remote_folder .= '/' . $this->site_name;
2072
-
2073
- if($ftp_passive){
2074
- @ftp_pasv($conn_id,true);
2075
- }
2076
-
2077
- //$temp = ABSPATH . 'iwp_temp_backup.zip';
2078
- $temp = wp_tempnam('iwp_temp_backup.zip');
2079
-
2080
- $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
2081
- if ($get === false) {
2082
- return false;
2083
- } else {
2084
- }
2085
- ftp_close($conn_id);
2086
-
2087
- return $temp;
2088
- }
2089
-
2090
-
2091
- function dropbox_backup($args){
2092
- extract($args);
2093
-
2094
- if(isset($consumer_secret) && !empty($consumer_secret)){
2095
-
2096
- require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2097
-
2098
- $dropbox = new Dropbox($consumer_key, $consumer_secret);
2099
- $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2100
-
2101
- if ($dropbox_site_folder == true)
2102
- $dropbox_destination .= '/' . $this->site_name . '/' . basename($backup_file);
2103
- else
2104
- $dropbox_destination .= '/' . basename($backup_file);
2105
-
2106
- try {
2107
- $dropbox->upload($backup_file, $dropbox_destination, true);
2108
- } catch (Exception $e) {
2109
- $this->_log($e->getMessage());
2110
- return array(
2111
- 'error' => $e->getMessage(),
2112
- 'partial' => 1
2113
- );
2114
- }
2115
-
2116
- return true;
2117
-
2118
- } else {
2119
- return array(
2120
- 'error' => 'Please connect your InfiniteWP panel with your Dropbox account.'
2121
- );
2122
- }
2123
-
2124
- }
2125
-
2126
-
2127
- function remove_dropbox_backup($args) {
2128
- extract($args);
2129
-
2130
- require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2131
-
2132
- $dropbox = new Dropbox($consumer_key, $consumer_secret);
2133
- $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2134
-
2135
- if ($dropbox_site_folder == true)
2136
- $dropbox_destination .= '/' . $this->site_name;
2137
-
2138
- try {
2139
- $dropbox->fileopsDelete($dropbox_destination . '/' . $backup_file);
2140
- } catch (Exception $e) {
2141
- $this->_log($e->getMessage());
2142
- /*return array(
2143
- 'error' => $e->getMessage(),
2144
- 'partial' => 1
2145
- );*/
2146
- }
2147
-
2148
- //return true;
2149
- }
2150
-
2151
-
2152
- function get_dropbox_backup($args) {
2153
- extract($args);
2154
-
2155
- require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2156
-
2157
- $dropbox = new Dropbox($consumer_key, $consumer_secret);
2158
- $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2159
-
2160
- if ($dropbox_site_folder == true)
2161
- $dropbox_destination .= '/' . $this->site_name;
2162
-
2163
- //$temp = ABSPATH . 'iwp_temp_backup.zip';
2164
- $temp = wp_tempnam('iwp_temp_backup.zip');
2165
-
2166
- try {
2167
-
2168
- $file = $dropbox->download($dropbox_destination.'/'.$backup_file);
2169
- $handle = @fopen($temp, 'w');
2170
- $result = fwrite($handle, $file);
2171
- fclose($handle);
2172
-
2173
- if($result)
2174
- return $temp;
2175
- else
2176
- return false;
2177
- } catch (Exception $e) {
2178
- $this->_log($e->getMessage());
2179
- return array(
2180
- 'error' => $e->getMessage(),
2181
- 'partial' => 1
2182
- );
2183
- }
2184
- }
2185
-
2186
-
2187
- function amazons3_backup($args)
2188
- {
2189
- if ($this->iwp_mmb_function_exists('curl_init')) {
2190
- require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
2191
-
2192
- extract($args);
2193
-
2194
- if ($as3_site_folder == true)
2195
- $as3_directory .= '/' . $this->site_name;
2196
-
2197
- try{
2198
-
2199
- CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true, 'use_ssl'=>false, 'ssl_verification'=>false), '@default' => 'development'));
2200
- $s3 = new AmazonS3();
2201
- $response = $s3->create_object($as3_bucket, $as3_directory . '/' . basename($backup_file), array('fileUpload' => $backup_file));
2202
- $upload = $response->isOk();
2203
- if($upload) {
2204
- return true;
2205
- } else {
2206
- return array(
2207
- 'error' => 'Failed to upload to Amazon S3. Please check your details and set upload/delete permissions on your bucket.',
2208
- 'partial' => 1
2209
- );
2210
- }
2211
-
2212
- }catch (Exception $e){
2213
- $err = $e->getMessage();
2214
- if($err){
2215
- return array(
2216
- 'error' => 'Failed to upload to AmazonS3 ('.$err.').'
2217
- );
2218
- } else {
2219
- return array(
2220
- 'error' => 'Failed to upload to Amazon S3.'
2221
- );
2222
- }
2223
- }
2224
- } else {
2225
- return array(
2226
- 'error' => 'You cannot use Amazon S3 on your server. Please enable curl first.',
2227
- 'partial' => 1
2228
- );
2229
- }
2230
- }
2231
-
2232
-
2233
- function remove_amazons3_backup($args)
2234
- {
2235
- if ($this->iwp_mmb_function_exists('curl_init')) {
2236
- require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
2237
- extract($args);
2238
- if ($as3_site_folder == true)
2239
- $as3_directory .= '/' . $this->site_name;
2240
- try{
2241
- CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true), '@default' => 'development'));
2242
- $s3 = new AmazonS3();
2243
- $s3->delete_object($as3_bucket, $as3_directory . '/' . $backup_file);
2244
- } catch (Exception $e){
2245
-
2246
- }
2247
- }
2248
- }
2249
-
2250
- function get_amazons3_backup($args)
2251
- {
2252
- require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
2253
- extract($args);
2254
- $temp = '';
2255
- try{
2256
- CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true), '@default' => 'development'));
2257
- $s3 = new AmazonS3();
2258
- if ($as3_site_folder == true)
2259
- $as3_directory .= '/' . $this->site_name;
2260
-
2261
- //$temp = ABSPATH . 'iwp_temp_backup.zip';
2262
- $temp = wp_tempnam('iwp_temp_backup.zip');
2263
- $s3->get_object($as3_bucket, $as3_directory . '/' . $backup_file, array("fileDownload" => $temp));
2264
- } catch (Exception $e){
2265
- return $temp;
2266
- }
2267
- return $temp;
2268
- }
2269
- //IWP Remove ends here
2270
-
2271
-
2272
- function schedule_next($type, $schedule)
2273
- {
2274
- $schedule = explode("|", $schedule);
2275
- if (empty($schedule))
2276
- return false;
2277
- switch ($type) {
2278
-
2279
- case 'daily':
2280
-
2281
- if (isset($schedule[1]) && $schedule[1]) {
2282
- $delay_time = $schedule[1] * 60;
2283
- }
2284
-
2285
- $current_hour = date("H");
2286
- $schedule_hour = $schedule[0];
2287
- if ($current_hour >= $schedule_hour){
2288
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 1, date("Y"));
2289
- //$time ='0001#'.$current_hour.'|'.$schedule_hour;
2290
-
2291
- }
2292
-
2293
- else{
2294
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2295
- //$time ='0000#'.$current_hour.'|'.$schedule_hour;
2296
- }
2297
- $time = time() + 30;
2298
-
2299
-
2300
- break;
2301
-
2302
-
2303
- case 'weekly':
2304
- if (isset($schedule[2]) && $schedule[2]) {
2305
- $delay_time = $schedule[2] * 60;
2306
- }
2307
- $current_weekday = date('w');
2308
- $schedule_weekday = $schedule[1];
2309
- $current_hour = date("H");
2310
- $schedule_hour = $schedule[0];
2311
-
2312
- if ($current_weekday > $schedule_weekday)
2313
- $weekday_offset = 7 - ($week_day - $task_schedule[1]);
2314
- else
2315
- $weekday_offset = $schedule_weekday - $current_weekday;
2316
-
2317
-
2318
- if (!$weekday_offset) { //today is scheduled weekday
2319
- if ($current_hour >= $schedule_hour)
2320
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 7, date("Y"));
2321
- else
2322
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2323
- } else {
2324
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + $weekday_offset, date("Y"));
2325
- }
2326
-
2327
- break;
2328
-
2329
- case 'monthly':
2330
- if (isset($schedule[2]) && $schedule[2]) {
2331
- $delay_time = $schedule[2] * 60;
2332
- }
2333
- $current_monthday = date('j');
2334
- $schedule_monthday = $schedule[1];
2335
- $current_hour = date("H");
2336
- $schedule_hour = $schedule[0];
2337
-
2338
- if ($current_monthday > $schedule_monthday) {
2339
- $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2340
- } else if ($current_monthday < $schedule_monthday) {
2341
- $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2342
- } else if ($current_monthday == $schedule_monthday) {
2343
- if ($current_hour >= $schedule_hour)
2344
- $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2345
- else
2346
- $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2347
- break;
2348
- }
2349
-
2350
- break;
2351
- default:
2352
- break;
2353
- }
2354
-
2355
- if (isset($delay_time) && $delay_time) {
2356
- $time += $delay_time;
2357
- }
2358
-
2359
- return $time;
2360
- }
2361
-
2362
-
2363
- //Parse task arguments for info on IWP Admin Panel
2364
- function get_backup_stats()
2365
- {
2366
- $stats = array();
2367
- $tasks = $this->tasks;
2368
- if (is_array($tasks) && !empty($tasks)) {
2369
- foreach ($tasks as $task_name => $info) {
2370
- if (is_array($info['task_results']) && !empty($info['task_results'])) {
2371
- foreach ($info['task_results'] as $key => $result) {
2372
- if (isset($result['server']) && !isset($result['error'])) {
2373
- if (!file_exists($result['server']['file_path'])) {
2374
- $info['task_results'][$key]['error'] = 'Backup created but manually removed from server.';
2375
- }
2376
- }
2377
- }
2378
- }
2379
- if (is_array($info['task_results']))
2380
- $stats[$task_name] = $info['task_results'];
2381
- }
2382
- }
2383
- return $stats;
2384
- }
2385
-
2386
-
2387
- function get_next_schedules()
2388
- {
2389
- $stats = array();
2390
- $tasks = $this->tasks;
2391
- if (is_array($tasks) && !empty($tasks)) {
2392
- foreach ($tasks as $task_name => $info) {
2393
- $stats[$task_name] = isset($info['task_args']['next']) ? $info['task_args']['next'] : array();
2394
- }
2395
- }
2396
- return $stats;
2397
- }
2398
-
2399
-
2400
- function remove_old_backups($task_name)
2401
- {
2402
- //Check for previous failed backups first
2403
- $this->cleanup();
2404
-
2405
- //Remove by limit
2406
- $backups = $this->tasks;
2407
- if ($task_name == 'Backup Now') {
2408
- $num = 0;
2409
- } else {
2410
- $num = 1;
2411
- }
2412
-
2413
-
2414
- if ((count($backups[$task_name]['task_results']) - $num) >= $backups[$task_name]['task_args']['limit']) {
2415
- //how many to remove ?
2416
- $remove_num = (count($backups[$task_name]['task_results']) - $num - $backups[$task_name]['task_args']['limit']) + 1;
2417
- for ($i = 0; $i < $remove_num; $i++) {
2418
- //Remove from the server
2419
- if (isset($backups[$task_name]['task_results'][$i]['server'])) {
2420
- @unlink($backups[$task_name]['task_results'][$i]['server']['file_path']);
2421
- }
2422
-
2423
- if (isset($backups[$task_name]['task_results'][$i]['ftp'])) {
2424
- $ftp_file = $backups[$task_name]['task_results'][$i]['ftp'];
2425
- $args = $backups[$task_name]['task_args']['account_info']['iwp_ftp'];
2426
- $args['backup_file'] = $ftp_file;
2427
- $this->remove_ftp_backup($args);
2428
- }
2429
-
2430
- if (isset($backups[$task_name]['task_results'][$i]['amazons3'])) {
2431
- $amazons3_file = $backups[$task_name]['task_results'][$i]['amazons3'];
2432
- $args = $backups[$task_name]['task_args']['account_info']['iwp_amazon_s3'];
2433
- $args['backup_file'] = $amazons3_file;
2434
- $this->remove_amazons3_backup($args);
2435
- }
2436
-
2437
- if (isset($backups[$task_name]['task_results'][$i]['dropbox']) && isset($backups[$task_name]['task_args']['account_info']['iwp_dropbox'])) {
2438
- //To do: dropbox remove
2439
- $dropbox_file = $backups[$task_name]['task_results'][$i]['dropbox'];
2440
- $args = $backups[$task_name]['task_args']['account_info']['iwp_dropbox'];
2441
- $args['backup_file'] = $dropbox_file;
2442
- $this->remove_dropbox_backup($args);
2443
- }
2444
- //Remove database backup info
2445
- unset($backups[$task_name]['task_results'][$i]);
2446
-
2447
- } //end foreach
2448
-
2449
- if (is_array($backups[$task_name]['task_results']))
2450
- $backups[$task_name]['task_results'] = array_values($backups[$task_name]['task_results']);
2451
- else
2452
- $backups[$task_name]['task_results']=array();
2453
-
2454
- $this->update_tasks($backups);
2455
-
2456
- return true;
2457
- }
2458
- }
2459
-
2460
- /**
2461
- * Delete specified backup
2462
- * Args: $task_name, $result_id
2463
- */
2464
-
2465
- function delete_backup($args)
2466
- {
2467
- if (empty($args))
2468
- return false;
2469
- extract($args);
2470
-
2471
- $tasks = $this->tasks;
2472
- $task = $tasks[$task_name];
2473
- $backups = $task['task_results'];
2474
- $backup = $backups[$result_id];
2475
-
2476
- if (isset($backup['server'])) {
2477
- @unlink($backup['server']['file_path']);
2478
- }
2479
-
2480
- /*
2481
- //IWP Remove starts here//IWP Remove ends here
2482
- */
2483
- //Remove from ftp
2484
- if (isset($backup['ftp'])) {
2485
- $ftp_file = $backup['ftp'];
2486
- $args = $tasks[$task_name]['task_args']['account_info']['iwp_ftp'];
2487
- $args['backup_file'] = $ftp_file;
2488
- $this->remove_ftp_backup($args);
2489
- }
2490
-
2491
- if (isset($backup['amazons3'])) {
2492
- $amazons3_file = $backup['amazons3'];
2493
- $args = $tasks[$task_name]['task_args']['account_info']['iwp_amazon_s3'];
2494
- $args['backup_file'] = $amazons3_file;
2495
- $this->remove_amazons3_backup($args);
2496
- }
2497
-
2498
- if (isset($backup['dropbox'])) {
2499
- $dropbox_file = $backup['dropbox'];
2500
- $args = $tasks[$task_name]['task_args']['account_info']['iwp_dropbox'];
2501
- $args['backup_file'] = $dropbox_file;
2502
- $this->remove_dropbox_backup($args);
2503
- }
2504
-
2505
-
2506
- unset($backups[$result_id]);
2507
-
2508
- if (count($backups)) {
2509
- $tasks[$task_name]['task_results'] = $backups;
2510
- } else {
2511
- unset($tasks[$task_name]['task_results']);
2512
- }
2513
-
2514
- $this->update_tasks($tasks);
2515
- //update_option('iwp_client_backup_tasks', $tasks);
2516
- return true;
2517
-
2518
- }
2519
-
2520
- function cleanup()
2521
- {
2522
- $tasks = $this->tasks;
2523
- $backup_folder = WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups/';
2524
- $backup_folder_new = IWP_BACKUP_DIR . '/';
2525
- $files = glob($backup_folder . "*");
2526
- $new = glob($backup_folder_new . "*");
2527
-
2528
- //Failed db files first
2529
- $db_folder = IWP_DB_DIR . '/';
2530
- $db_files = glob($db_folder . "*");
2531
- if (is_array($db_files) && !empty($db_files)) {
2532
- foreach ($db_files as $file) {
2533
- @unlink($file);
2534
- }
2535
- @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
2536
- @rmdir(IWP_DB_DIR);
2537
- }
2538
-
2539
-
2540
- //clean_old folder?
2541
- if ((basename($files[0]) == 'index.php' && count($files) == 1) || (!empty($files))) { //USE (!empty($files)
2542
- foreach ($files as $file) {
2543
- @unlink($file);
2544
- }
2545
- @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups');
2546
- @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client'));
2547
- }
2548
-
2549
- if (!empty($new)) {
2550
- foreach ($new as $b) {
2551
- $files[] = $b;
2552
- }
2553
- }
2554
- $deleted = array();
2555
-
2556
- if (is_array($files) && count($files)) {
2557
- $results = array();
2558
- if (!empty($tasks)) {
2559
- foreach ((array) $tasks as $task) {
2560
- if (isset($task['task_results']) && count($task['task_results'])) {
2561
- foreach ($task['task_results'] as $backup) {
2562
- if (isset($backup['server'])) {
2563
- $results[] = $backup['server']['file_path'];
2564
- }
2565
- }
2566
- }
2567
- }
2568
- }
2569
-
2570
- $num_deleted = 0;
2571
- foreach ($files as $file) {
2572
- if (!in_array($file, $results) && basename($file) != 'index.php') {
2573
- @unlink($file);
2574
- $deleted[] = basename($file);
2575
- $num_deleted++;
2576
- }
2577
- }
2578
- }
2579
-
2580
-
2581
-
2582
- return $deleted;
2583
- }
2584
-
2585
-
2586
- /*
2587
- */
2588
-
2589
- function validate_task($args, $url)
2590
- {
2591
- if (!class_exists('WP_Http')) {
2592
- include_once(ABSPATH . WPINC . '/class-http.php');
2593
- }
2594
- $params = array();
2595
- $params['body'] = $args;
2596
- $result = wp_remote_post($url, $params);
2597
- if (is_array($result) && $result['body'] == 'iwp_delete_task') {
2598
- //$tasks = $this->get_backup_settings();
2599
- $tasks = $this->tasks;
2600
- unset($tasks[$args['task_name']]);
2601
- $this->update_tasks($tasks);
2602
- $this->cleanup();
2603
- exit;
2604
- } elseif(is_array($result) && $result['body'] == 'iwp_pause_task'){
2605
- return 'paused';
2606
- }
2607
-
2608
- return 'ok';
2609
- }
2610
-
2611
- function update_status($task_name, $status, $completed = false)
2612
- {
2613
- /* Statuses:
2614
- 0 - Backup started
2615
- 1 - DB dump
2616
- 2 - DB ZIP
2617
- 3 - Files ZIP
2618
- 4 - Amazon S3
2619
- 5 - Dropbox
2620
- 6 - FTP
2621
- 7 - Email
2622
- 100 - Finished
2623
- */
2624
- //if ($task_name != 'Backup Now') {
2625
- $tasks = $this->tasks;
2626
- $index = count($tasks[$task_name]['task_results']) - 1;
2627
- //!is_array($tasks[$task_name]['task_results'][$index]['status']) &&
2628
- if (!is_array($tasks[$task_name]['task_results'][$index]['backhack_status'])) {
2629
- //$tasks[$task_name]['task_results'][$index]['status'] = array();
2630
- $tasks[$task_name]['task_results'][$index]['backhack_status'] = array();
2631
- }
2632
- $tasks[$task_name]['task_results'][$index]['backhack_status']['adminHistoryID'] = $GLOBALS['IWP_CLIENT_HISTORY_ID'];
2633
- if (!$completed) {
2634
- //$tasks[$task_name]['task_results'][$index]['status'][] = (int) $status * (-1);
2635
- $tasks[$task_name]['task_results'][$index]['backhack_status'][$status]['start'] = microtime(true);
2636
- } else {
2637
- $status_index = count($tasks[$task_name]['task_results'][$index]['status']) - 1;
2638
- //$tasks[$task_name]['task_results'][$index]['status'][$status_index] = abs($tasks[$task_name]['task_results'][$index]['status'][$status_index]);
2639
- $tasks[$task_name]['task_results'][$index]['backhack_status'][$status]['end'] = microtime(true);
2640
- }
2641
-
2642
- $this->update_tasks($tasks);
2643
- //update_option('iwp_client_backup_tasks',$tasks);
2644
- //}
2645
- }
2646
-
2647
- function update_tasks($tasks)
2648
- {
2649
- $this->tasks = $tasks;
2650
- update_option('iwp_client_backup_tasks', $tasks);
2651
- }
2652
-
2653
- function wpdb_reconnect(){
2654
- global $wpdb;
2655
- $old_wpdb = $wpdb;
2656
- //Reconnect to avoid timeout problem after ZIP files
2657
- if(class_exists('wpdb') && function_exists('wp_set_wpdb_vars')){
2658
- @mysql_close($wpdb->dbh);
2659
- $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
2660
- wp_set_wpdb_vars();
2661
- $wpdb->options = $old_wpdb->options;//fix for multi site full backup
2662
- }
2663
- }
2664
-
2665
- function replace_htaccess($url, $remote_abspath)
2666
- {
2667
- global $wp_filesystem;
2668
- //$file = @file_get_contents(ABSPATH.'.htaccess');
2669
- $file = $wp_filesystem->get_contents($remote_abspath.'.htaccess');
2670
- if ($file && strlen($file)) {
2671
- $args = parse_url($url);
2672
- $string = rtrim($args['path'], "/");
2673
- $regex = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
2674
- $replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
2675
- $file = preg_replace($regex, $replace, $file);
2676
- //@file_put_contents(ABSPATH.'.htaccess', $file);
2677
- $wp_filesystem->put_contents($remote_abspath.'.htaccess', $file);
2678
- }
2679
- }
2680
-
2681
- function check_cron_remove(){
2682
- if(empty($this->tasks) || (count($this->tasks) == 1 && isset($this->tasks['Backup Now'])) ){
2683
- wp_clear_scheduled_hook('iwp_client_backup_tasks');
2684
- exit;
2685
- }
2686
- }
2687
-
2688
-
2689
- public function readd_tasks( $params = array() ){
2690
- global $iwp_mmb_core;
2691
-
2692
- if( empty($params) || !isset($params['backups']) )
2693
- return $params;
2694
-
2695
- $before = array();
2696
- $tasks = $params['backups'];
2697
- if( !empty($tasks) ){
2698
- $iwp_mmb_backup = new IWP_MMB_Backup();
2699
-
2700
- if( function_exists( 'wp_next_scheduled' ) ){
2701
- if ( !wp_next_scheduled('iwp_client_backup_tasks') ) {
2702
- wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
2703
- }
2704
- }
2705
-
2706
- foreach( $tasks as $task ){
2707
- $before[$task['task_name']] = array();
2708
-
2709
- if(isset($task['secure'])){
2710
- if($decrypted = $iwp_mmb_core->_secure_data($task['secure'])){
2711
- $decrypted = maybe_unserialize($decrypted);
2712
- if(is_array($decrypted)){
2713
- foreach($decrypted as $key => $val){
2714
- if(!is_numeric($key))
2715
- $task[$key] = $val;
2716
- }
2717
- unset($task['secure']);
2718
- } else
2719
- $task['secure'] = $decrypted;
2720
- }
2721
-
2722
- }
2723
- if (isset($task['account_info']) && is_array($task['account_info'])) { //only if sends from panel first time(secure data)
2724
- $task['args']['account_info'] = $task['account_info'];
2725
- }
2726
-
2727
- $before[$task['task_name']]['task_args'] = $task['args'];
2728
- $before[$task['task_name']]['task_args']['next'] = $iwp_mmb_backup->schedule_next($task['args']['type'], $task['args']['schedule']);
2729
- }
2730
- }
2731
- update_option('iwp_client_backup_tasks', $before);
2732
-
2733
- unset($params['backups']);
2734
- return $params;
2735
- }
2736
-
2737
- function is_server_writable(){
2738
- if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), ABSPATH) != 'direct'))
2739
- return false;
2740
- else
2741
- return true;
2742
- }
2743
- }
2744
-
2745
- /*if( function_exists('add_filter') ){
2746
- add_filter( 'iwp_website_add', 'IWP_MMB_Backup::readd_tasks' );
2747
- }*/
2748
-
2749
- if(!function_exists('get_all_files_from_dir')) {
2750
- /**
2751
- * Get all files in directory
2752
- *
2753
- * @param string $path Relative or absolute path to folder
2754
- * @param array $exclude List of excluded files or folders, relative to $path
2755
- * @return array List of all files in folder $path, exclude all files in $exclude array
2756
- */
2757
- function get_all_files_from_dir($path, $exclude = array()) {
2758
- if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
2759
- global $directory_tree, $ignore_array;
2760
- $directory_tree = array();
2761
- foreach ($exclude as $file) {
2762
- if (!in_array($file, array('.', '..'))) {
2763
- if ($file[0] === "/") $path = substr($file, 1);
2764
- $ignore_array[] = "$path/$file";
2765
- }
2766
- }
2767
- get_all_files_from_dir_recursive($path);
2768
- return $directory_tree;
2769
- }
2770
- }
2771
-
2772
- if (!function_exists('get_all_files_from_dir_recursive')) {
2773
- /**
2774
- * Get all files in directory,
2775
- * wrapped function which writes in global variable
2776
- * and exclued files or folders are read from global variable
2777
- *
2778
- * @param string $path Relative or absolute path to folder
2779
- * @return void
2780
- */
2781
- function get_all_files_from_dir_recursive($path) {
2782
- if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
2783
- global $directory_tree, $ignore_array;
2784
- $directory_tree_temp = array();
2785
- $dh = @opendir($path);
2786
-
2787
- while (false !== ($file = @readdir($dh))) {
2788
- if (!in_array($file, array('.', '..'))) {
2789
- if (!in_array("$path/$file", $ignore_array)) {
2790
- if (!is_dir("$path/$file")) {
2791
- $directory_tree[] = "$path/$file";
2792
- } else {
2793
- get_all_files_from_dir_recursive("$path/$file");
2794
- }
2795
- }
2796
- }
2797
- }
2798
- @closedir($dh);
2799
- }
2800
- }
2801
-
 
 
 
 
 
2802
  ?>
1
+ <?php
2
+ /************************************************************
3
+ * This plugin was modified by Revmakx *
4
+ * Copyright (c) 2012 Revmakx *
5
+ * www.revmakx.com *
6
+ * *
7
+ ************************************************************/
8
+ /*************************************************************
9
+ *
10
+ * backup.class.php
11
+ *
12
+ * Manage Backups
13
+ *
14
+ *
15
+ * Copyright (c) 2011 Prelovac Media
16
+ * www.prelovac.com
17
+ **************************************************************/
18
+ define('IWP_BACKUP_DIR', WP_CONTENT_DIR . '/infinitewp/backups');
19
+ define('IWP_DB_DIR', IWP_BACKUP_DIR . '/iwp_db');
20
+
21
+ $zip_errors = array(
22
+ 'No error',
23
+ 'No error',
24
+ 'Unexpected end of zip file',
25
+ 'A generic error in the zipfile format was detected',
26
+ 'zip was unable to allocate itself memory',
27
+ 'A severe error in the zipfile format was detected',
28
+ 'Entry too large to be split with zipsplit',
29
+ 'Invalid comment format',
30
+ 'zip -T failed or out of memory',
31
+ 'The user aborted zip prematurely',
32
+ 'zip encountered an error while using a temp file. Please check if this domain\'s account has enough disk space.',
33
+ 'Read or seek error',
34
+ 'zip has nothing to do',
35
+ 'Missing or empty zip file',
36
+ 'Error writing to a file. Please check if this domain\'s account has enough disk space.',
37
+ 'zip was unable to create a file to write to',
38
+ 'bad command line parameters',
39
+ 'no error',
40
+ 'zip could not open a specified file to read'
41
+ );
42
+ $unzip_errors = array(
43
+ 'No error',
44
+ 'One or more warning errors were encountered, but processing completed successfully anyway',
45
+ 'A generic error in the zipfile format was detected',
46
+ 'A severe error in the zipfile format was detected.',
47
+ 'unzip was unable to allocate itself memory.',
48
+ 'unzip was unable to allocate memory, or encountered an encryption error',
49
+ 'unzip was unable to allocate memory during decompression to disk',
50
+ 'unzip was unable allocate memory during in-memory decompression',
51
+ 'unused',
52
+ 'The specified zipfiles were not found',
53
+ 'Bad command line parameters',
54
+ 'No matching files were found',
55
+ 50 => 'The disk is (or was) full during extraction',
56
+ 51 => 'The end of the ZIP archive was encountered prematurely.',
57
+ 80 => 'The user aborted unzip prematurely.',
58
+ 81 => 'Testing or extraction of one or more files failed due to unsupported compression methods or unsupported decryption.',
59
+ 82 => 'No files were found due to bad decryption password(s)'
60
+ );
61
+
62
+
63
+ class IWP_MMB_Backup extends IWP_MMB_Core
64
+ {
65
+ var $site_name;
66
+ var $statuses;
67
+ var $tasks;
68
+ var $s3;
69
+ var $ftp;
70
+ var $dropbox;
71
+ function __construct()
72
+ {
73
+ parent::__construct();
74
+ $this->site_name = str_replace(array(
75
+ "_",
76
+ "/",
77
+ "~"
78
+ ), array(
79
+ "",
80
+ "-",
81
+ "-"
82
+ ), rtrim($this->remove_http(get_bloginfo('url')), "/"));
83
+ $this->statuses = array(
84
+ 'db_dump' => 1,
85
+ 'db_zip' => 2,
86
+ 'files_zip' => 3,
87
+ 'finished' => 100
88
+ );
89
+ $this->tasks = get_option('iwp_client_backup_tasks');
90
+ }
91
+ function set_memory()
92
+ {
93
+ $changed = array('execution_time' => 0, 'memory_limit' => 0);
94
+ @ignore_user_abort(true);
95
+ $memory_limit = trim(ini_get('memory_limit'));
96
+ $last = strtolower(substr($memory_limit, -1));
97
+
98
+ if($last == 'g')
99
+ $memory_limit = ((int) $memory_limit)*1024;
100
+ else if($last == 'm')
101
+ $memory_limit = (int) $memory_limit;
102
+ if($last == 'k')
103
+ $memory_limit = ((int) $memory_limit)/1024;
104
+
105
+ if ( $memory_limit < 384 ) {
106
+ @ini_set('memory_limit', '384M');
107
+ $changed['memory_limit'] = 1;
108
+ }
109
+
110
+ if ( (int) @ini_get('max_execution_time') < 1200 ) {
111
+ @ini_set('max_execution_time', 1200);//twenty minutes
112
+ @set_time_limit(1200);
113
+ $changed['execution_time'] = 1;
114
+ }
115
+
116
+ return $changed;
117
+
118
+ }
119
+ function get_backup_settings()
120
+ {
121
+ $backup_settings = get_option('iwp_client_backup_tasks');
122
+ if (!empty($backup_settings))
123
+ return $backup_settings;
124
+ else
125
+ return false;
126
+ }
127
+
128
+ function set_backup_task($params)
129
+ {
130
+ //$params => [$task_name, $args, $error]
131
+ if (!empty($params)) {
132
+
133
+ //Make sure backup cron job is set
134
+ if (!wp_next_scheduled('iwp_client_backup_tasks')) {
135
+ wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
136
+ }
137
+
138
+ extract($params);
139
+
140
+ //$before = $this->get_backup_settings();
141
+ $before = $this->tasks;
142
+ if (!$before || empty($before))
143
+ $before = array();
144
+
145
+ if (isset($args['remove'])) {
146
+ unset($before[$task_name]);
147
+ $return = array(
148
+ 'removed' => true
149
+ );
150
+ } else {
151
+
152
+ if (is_array($params['account_info'])) { //only if sends from IWP Admin Panel first time(secure data)
153
+ $args['account_info'] = $account_info;
154
+ }
155
+
156
+ $before[$task_name]['task_args'] = $args;
157
+ //$before[$task_name]['task_args'] = $task_name;
158
+
159
+ /*if (strlen($args['schedule']))
160
+ $before[$task_name]['task_args']['next'] = $this->schedule_next($args['type'], $args['schedule']);*///to WP cron
161
+ $before[$task_name]['task_args']['task_name'] = $task_name;
162
+
163
+ $return = $before[$task_name];
164
+ }
165
+
166
+ //Update with error
167
+ if (isset($error)) {
168
+ if (is_array($error)) {
169
+ $before[$task_name]['task_results'][count($before[$task_name]['task_results']) - 1]['error'] = $error['error'];
170
+ } else {
171
+ $before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['error'] = $error;
172
+ }
173
+ }
174
+
175
+ // if (isset($time) && $time) { //set next result time before backup
176
+ if (is_array($before[$task_name]['task_results'])) {
177
+ $before[$task_name]['task_results'] = array_values($before[$task_name]['task_results']);
178
+ }
179
+ //$before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = (isset($time) && $time) ? $time : time();
180
+ //}
181
+ if (isset($time) && $time) { //This will occur for schedule runtask.
182
+ $before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = $time;
183
+ }else{
184
+ if($task_name == 'Backup Now')
185
+ $before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = time();
186
+ }
187
+
188
+ $this->update_tasks($before);
189
+ //update_option('iwp_client_backup_tasks', $before);
190
+
191
+ if ($task_name == 'Backup Now') {
192
+ $result = $this->backup($args, $task_name);
193
+ $backup_settings = $this->tasks;
194
+
195
+ if (is_array($result) && array_key_exists('error', $result)) {
196
+ $return = $result;
197
+ } else {
198
+ $return = $backup_settings[$task_name];
199
+ }
200
+ }
201
+ return $return;
202
+ }
203
+
204
+
205
+
206
+ return false;
207
+ }
208
+
209
+ //Cron check
210
+ function check_backup_tasks()
211
+ {
212
+
213
+ $this->check_cron_remove();
214
+
215
+ $settings = $this->tasks;
216
+ if (is_array($settings) && !empty($settings)) {
217
+ foreach ($settings as $task_name => $setting) {
218
+
219
+ if ($setting['task_args']['next'] && $setting['task_args']['next'] < time()) {
220
+ //if ($setting['task_args']['next'] && $_GET['force_backup']) {
221
+ if ($setting['task_args']['url'] && $setting['task_args']['task_id'] && $setting['task_args']['site_key']) {
222
+ //Check orphan task
223
+ $check_data = array(
224
+ 'task_name' => $task_name,
225
+ 'task_id' => $setting['task_args']['task_id'],
226
+ 'site_key' => $setting['task_args']['site_key']
227
+ );
228
+
229
+ $check = $this->validate_task($check_data, $setting['task_args']['url']);
230
+
231
+ }
232
+
233
+ $update = array(
234
+ 'task_name' => $task_name,
235
+ 'args' => $settings[$task_name]['task_args']
236
+ );
237
+
238
+
239
+ if($check != 'paused'){
240
+ $update['time'] = time();
241
+ }
242
+
243
+ //Update task with next schedule
244
+ $this->set_backup_task($update);
245
+
246
+ if($check == 'paused'){
247
+ continue;
248
+ }
249
+
250
+
251
+ $result = $this->backup($setting['task_args'], $task_name);
252
+ $error = '';
253
+ if (is_array($result) && array_key_exists('error', $result)) {
254
+ $error = $result;
255
+ $this->set_backup_task(array(
256
+ 'task_name' => $task_name,
257
+ 'args' => $settings[$task_name]['task_args'],
258
+ 'error' => $error
259
+ ));
260
+ } else {
261
+ $error = '';
262
+ }
263
+ break; //Only one backup per cron
264
+ }
265
+ }
266
+ }
267
+
268
+ }
269
+
270
+
271
+ function task_now($task_name){
272
+
273
+ $settings = $this->tasks;
274
+ if(!array_key_exists($task_name,$settings)){
275
+ return array('error' => $task_name." does not exist.");
276
+ } else {
277
+ $setting = $settings[$task_name];
278
+ }
279
+
280
+ $this->set_backup_task(array(
281
+ 'task_name' => $task_name,
282
+ 'args' => $settings[$task_name]['task_args'],
283
+ 'time' => time()
284
+ ));
285
+
286
+ //Run backup
287
+ $result = $this->backup($setting['task_args'], $task_name);
288
+
289
+ //Check for error
290
+ if (is_array($result) && array_key_exists('error', $result)) {
291
+ $this->set_backup_task(array(
292
+ 'task_name' => $task_name,
293
+ 'args' => $settings[$task_name]['task_args'],
294
+ 'error' => $result['error']
295
+ ));
296
+ return $result;
297
+ } else {
298
+ return $this->get_backup_stats();
299
+ }
300
+
301
+ }
302
+
303
+ function delete_task_now($task_name){
304
+ $tasks = $this->tasks;
305
+ unset($tasks[$task_name]);
306
+ $this->update_tasks($tasks);
307
+ $this->cleanup();
308
+
309
+ return $task_name;
310
+
311
+ }
312
+
313
+
314
+ /*
315
+ * If Task Name not set then it's manual backup
316
+ * Backup args:
317
+ * type -> db, full
318
+ * what -> daily, weekly, monthly
319
+ * account_info -> ftp, amazons3, dropbox
320
+ * exclude-> array of paths to exclude from backup
321
+ */
322
+
323
+ function backup($args, $task_name = false)
324
+ {
325
+ if (!$args || empty($args))
326
+ return false;
327
+
328
+ extract($args); //extract settings
329
+
330
+ //$adminHistoryID - admin panel history ID for backup task.
331
+
332
+
333
+ //Try increase memory limit and execution time
334
+ $this->set_memory();
335
+
336
+ //Remove old backup(s)
337
+ $removed = $this->remove_old_backups($task_name);
338
+ if (is_array($removed) && isset($removed['error'])) {
339
+ //$error_message = $removed['error'];
340
+ return $removed;
341
+ }
342
+
343
+ $new_file_path = IWP_BACKUP_DIR;
344
+
345
+ if (!file_exists($new_file_path)) {
346
+ if (!mkdir($new_file_path, 0755, true))
347
+ return array(
348
+ 'error' => 'Permission denied, make sure you have write permission to wp-content folder.'
349
+ );
350
+ }
351
+
352
+ @file_put_contents($new_file_path . '/index.php', ''); //safe
353
+
354
+ //Prepare .zip file name
355
+ $hash = md5(time());
356
+ $label = $type ? $type : 'manual';
357
+ $backup_file = $new_file_path . '/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
358
+ $backup_url = WP_CONTENT_URL . '/infinitewp/backups/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
359
+
360
+ //Optimize tables?
361
+ if (isset($optimize_tables) && !empty($optimize_tables)) {
362
+ $this->optimize_tables();
363
+ }
364
+
365
+ //What to backup - db or full?
366
+ if (trim($what) == 'db') {
367
+ //Take database backup
368
+ $this->update_status($task_name, 'db_dump');
369
+ $GLOBALS['fail_safe_db'] = $this->tasks[$task_name]['task_args']['fail_safe_db'];
370
+
371
+ $db_result = $this->backup_db();
372
+ if ($db_result == false) {
373
+ return array(
374
+ 'error' => 'Failed to backup database.'
375
+ );
376
+ } else if (is_array($db_result) && isset($db_result['error'])) {
377
+ return array(
378
+ 'error' => $db_result['error']
379
+ );
380
+ } else {
381
+ $this->update_status($task_name, 'db_dump', true);
382
+ $this->update_status($task_name, 'db_zip');
383
+
384
+ /*zip_backup_db*/
385
+ $fail_safe_files = $this->tasks[$task_name]['task_args']['fail_safe_files'];
386
+ $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
387
+
388
+ if($fail_safe_files){
389
+ $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
390
+ }
391
+ else{
392
+ $comp_level = $disable_comp ? '-0' : '-1';
393
+ chdir(IWP_BACKUP_DIR);
394
+ $zip = $this->get_zip();
395
+ $command = "$zip -q -r $comp_level $backup_file 'iwp_db'";
396
+ iwp_mmb_print_flush('DB ZIP CMD: Start');
397
+ ob_start();
398
+ $result = $this->iwp_mmb_exec($command);
399
+ ob_get_clean();
400
+ iwp_mmb_print_flush('DB ZIP CMD: End');
401
+ /*zip_backup_db */
402
+ if(!$result){
403
+ $zip_archive_db_result = false;
404
+ if (class_exists("ZipArchive")) {
405
+ $this->_log("DB zip, fallback to ZipArchive");
406
+ iwp_mmb_print_flush('DB ZIP Archive: Start');
407
+ $zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
408
+ iwp_mmb_print_flush('DB ZIP Archive: End');
409
+ }
410
+
411
+ if (!$zip_archive_db_result) {
412
+ $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
413
+ }
414
+ }
415
+ }
416
+
417
+ @unlink($db_result);
418
+ @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
419
+ @rmdir(IWP_DB_DIR);
420
+ /*if (!$result) {
421
+ return array(
422
+ 'error' => 'Failed to zip database.'
423
+ );
424
+ }*///commented because of zipArchive
425
+ $this->update_status($task_name, 'db_zip', true);
426
+ }
427
+ } elseif (trim($what) == 'full') {
428
+ $content_backup = $this->backup_full($task_name, $backup_file, $exclude, $include);
429
+ if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
430
+ return array(
431
+ 'error' => $content_backup['error']
432
+ );
433
+ }
434
+ }
435
+
436
+ //Update backup info
437
+ if ($task_name) {
438
+ //backup task (scheduled)
439
+ $backup_settings = $this->tasks;
440
+ $paths = array();
441
+ $size = round(filesize($backup_file) / 1024, 2);
442
+
443
+ if ($size > 1000) {
444
+ $paths['size'] = round($size / 1024, 2) . " MB";//Modified by IWP //Mb => MB
445
+ } else {
446
+ $paths['size'] = $size . 'KB';//Modified by IWP //Kb => KB
447
+ }
448
+
449
+ $paths['backup_name'] = $backup_settings[$task_name]['task_args']['backup_name'];
450
+
451
+ if ($task_name != 'Backup Now') {
452
+ if (!$backup_settings[$task_name]['task_args']['del_host_file']) {
453
+ $paths['server'] = array(
454
+ 'file_path' => $backup_file,
455
+ 'file_url' => $backup_url
456
+ );
457
+ }
458
+ } else {
459
+ $paths['server'] = array(
460
+ 'file_path' => $backup_file,
461
+ 'file_url' => $backup_url
462
+ );
463
+ }
464
+
465
+
466
+ if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_ftp'])) {
467
+ $paths['ftp'] = basename($backup_url);
468
+ }
469
+
470
+ if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_amazon_s3'])) {
471
+ $paths['amazons3'] = basename($backup_url);
472
+ }
473
+
474
+ if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_dropbox'])) {
475
+ $paths['dropbox'] = basename($backup_url);
476
+ }
477
+
478
+ if (isset($backup_settings[$task_name]['task_args']['account_info']['iwp_email'])) {
479
+ $paths['email'] = basename($backup_url);
480
+ }
481
+
482
+ $temp = $backup_settings[$task_name]['task_results'];
483
+ $temp = @array_values($temp);
484
+ $paths['time'] = time();
485
+
486
+
487
+ //if ($task_name != 'Backup Now') {
488
+ $paths['backhack_status'] = $temp[count($temp) - 1]['backhack_status'];
489
+ //$paths['status'] = $temp[count($temp) - 1]['status'];
490
+ $temp[count($temp) - 1] = $paths;
491
+
492
+ /*
493
+ } else {
494
+ $temp[count($temp)] = $paths;
495
+ }
496
+ */
497
+
498
+ $backup_settings[$task_name]['task_results'] = $temp;
499
+ $this->update_tasks($backup_settings);
500
+ //update_option('iwp_client_backup_tasks', $backup_settings);
501
+ }
502
+
503
+
504
+ if ($task_name != 'Backup Now') {
505
+
506
+ if (isset($account_info['iwp_ftp']) && !empty($account_info['iwp_ftp'])) {
507
+ $this->update_status($task_name, 'ftp');
508
+ $account_info['iwp_ftp']['backup_file'] = $backup_file;
509
+ iwp_mmb_print_flush('FTP upload: Start');
510
+ $ftp_result = $this->ftp_backup($account_info['iwp_ftp']);
511
+ iwp_mmb_print_flush('FTP upload: End');
512
+ if ($ftp_result !== true && $del_host_file) {
513
+ @unlink($backup_file);
514
+ }
515
+
516
+ if (is_array($ftp_result) && isset($ftp_result['error'])) {
517
+ return $ftp_result;
518
+ }
519
+ $this->wpdb_reconnect();
520
+ $this->update_status($task_name, 'ftp', true);
521
+ }
522
+
523
+ if (isset($account_info['iwp_amazon_s3']) && !empty($account_info['iwp_amazon_s3'])) {
524
+ $this->update_status($task_name, 's3');
525
+ $account_info['iwp_amazon_s3']['backup_file'] = $backup_file;
526
+ iwp_mmb_print_flush('Amazon S3 upload: Start');
527
+ $amazons3_result = $this->amazons3_backup($account_info['iwp_amazon_s3']);
528
+ iwp_mmb_print_flush('Amazon S3 upload: End');
529
+ if ($amazons3_result !== true && $del_host_file) {
530
+ @unlink($backup_file);
531
+ }
532
+ if (is_array($amazons3_result) && isset($amazons3_result['error'])) {
533
+ return $amazons3_result;
534
+ }
535
+ $this->wpdb_reconnect();
536
+ $this->update_status($task_name, 's3', true);
537
+ }
538
+
539
+ if (isset($account_info['iwp_dropbox']) && !empty($account_info['iwp_dropbox'])) {
540
+ $this->update_status($task_name, 'dropbox');
541
+ $account_info['iwp_dropbox']['backup_file'] = $backup_file;
542
+ iwp_mmb_print_flush('Dropbox upload: Start');
543
+ $dropbox_result = $this->dropbox_backup($account_info['iwp_dropbox']);
544
+ iwp_mmb_print_flush('Dropbox upload: End');
545
+ if ($dropbox_result !== true && $del_host_file) {
546
+ @unlink($backup_file);
547
+ }
548
+
549
+ if (is_array($dropbox_result) && isset($dropbox_result['error'])) {
550
+ return $dropbox_result;
551
+ }
552
+ $this->wpdb_reconnect();
553
+ $this->update_status($task_name, 'dropbox', true);
554
+ }
555
+
556
+ if ($del_host_file) {
557
+ @unlink($backup_file);
558
+ }
559
+
560
+ } //end additional
561
+
562
+ $this->update_status($task_name,'finished',true);
563
+
564
+ return $backup_url; //Return url to backup file
565
+ }
566
+
567
+
568
+ function backup_full($task_name, $backup_file, $exclude = array(), $include = array())
569
+ {
570
+
571
+ global $zip_errors;
572
+ $sys = substr(PHP_OS, 0, 3);
573
+
574
+ $this->update_status($task_name, 'db_dump');
575
+ $GLOBALS['fail_safe_db'] = $this->tasks[$task_name]['task_args']['fail_safe_db'];
576
+ $db_result = $this->backup_db();
577
+
578
+ if ($db_result == false) {
579
+ return array(
580
+ 'error' => 'Failed to backup database.'
581
+ );
582
+ } else if (is_array($db_result) && isset($db_result['error'])) {
583
+ return array(
584
+ 'error' => $db_result['error']
585
+ );
586
+ }
587
+
588
+ $this->update_status($task_name, 'db_dump', true);
589
+ $this->update_status($task_name, 'db_zip');
590
+
591
+ /*zip_backup_db*/
592
+ $fail_safe_files = $this->tasks[$task_name]['task_args']['fail_safe_files'];
593
+ $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
594
+
595
+ if($fail_safe_files){
596
+ $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
597
+ }
598
+ else{
599
+ $comp_level = $disable_comp ? '-0' : '-1';
600
+ $zip = $this->get_zip();
601
+ iwp_mmb_print_flush('DB ZIP CMD: Start');
602
+ //Add database file
603
+ chdir(IWP_BACKUP_DIR);
604
+ $command = "$zip -q -r $comp_level $backup_file 'iwp_db'";
605
+ ob_start();
606
+ $result = $this->iwp_mmb_exec($command);
607
+ ob_get_clean();
608
+ iwp_mmb_print_flush('DB ZIP CMD: End');
609
+ /*zip_backup_db*/
610
+
611
+ if(!$result){
612
+ $zip_archive_db_result = false;
613
+ if (class_exists("ZipArchive")) {
614
+ iwp_mmb_print_flush('DB ZIP Archive: Start');
615
+ $this->_log("DB zip, fallback to ZipArchive");
616
+ $zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
617
+ iwp_mmb_print_flush('DB ZIP Archive: End');
618
+ }
619
+
620
+ if (!$zip_archive_db_result) {
621
+ $this->fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp);
622
+ }
623
+ }
624
+ }
625
+ @unlink($db_result);
626
+ @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
627
+ @rmdir(IWP_DB_DIR);
628
+
629
+ $this->update_status($task_name, 'db_zip', true);
630
+
631
+
632
+ //Always remove backup folders
633
+ $remove = array(
634
+ trim(basename(WP_CONTENT_DIR)) . "/infinitewp/backups",
635
+ trim(basename(WP_CONTENT_DIR)) . "/" . md5('iwp_mmb-client') . "/iwp_backups",
636
+ trim(basename(WP_CONTENT_DIR)) . "/cache",
637
+ trim(basename(WP_CONTENT_DIR)) . "/w3tc"
638
+ );
639
+
640
+ $exclude = array_merge($exclude, $remove);
641
+
642
+ //Exclude paths
643
+ $exclude_data = "-x";
644
+
645
+ $exclude_file_data = '';
646
+
647
+ if (!empty($exclude) && is_array($exclude)) {
648
+ foreach ($exclude as $data) {
649
+ if(empty($data))
650
+ continue;
651
+ if (is_dir(ABSPATH . $data)) {
652
+ if ($sys == 'WIN')
653
+ $exclude_data .= " $data/*.*";
654
+ else
655
+ $exclude_data .= " '$data/*'";
656
+ }else {
657
+ if ($sys == 'WIN'){
658
+ if(file_exists(ABSPATH . $data)){
659
+ $exclude_data .= " $data";
660
+ $exclude_file_data .= " $data";
661
+ }
662
+ }else {
663
+ if(file_exists(ABSPATH . $data)){
664
+ $exclude_data .= " '$data'";
665
+ $exclude_file_data .= " '$data'";
666
+ }
667
+ }
668
+ }
669
+ }
670
+ }
671
+
672
+ if($exclude_file_data){
673
+ $exclude_file_data = "-x".$exclude_file_data;
674
+ }
675
+
676
+ /* foreach ($remove as $data) {
677
+ if(empty($data))
678
+ continue;
679
+ if ($sys == 'WIN')
680
+ $exclude_data .= " $data/*.*";
681
+ else
682
+ $exclude_data .= " '$data/*'";
683
+ }*/ //commented for pclzip modifications
684
+
685
+ //Include paths by default
686
+ $add = array(
687
+ trim(WPINC),
688
+ trim(basename(WP_CONTENT_DIR)),
689
+ "wp-admin"
690
+ );
691
+
692
+ $include_data = ". -i";
693
+ foreach ($add as $data) {
694
+ if ($sys == 'WIN')
695
+ $include_data .= " $data/*.*";
696
+ else
697
+ $include_data .= " '$data/*'";
698
+ }
699
+
700
+ //Additional includes?
701
+ if (!empty($include) && is_array($include)) {
702
+ foreach ($include as $data) {
703
+ if(empty($data))
704
+ continue;
705
+ if ($data) {
706
+ if ($sys == 'WIN')
707
+ $include_data .= " $data/*.*";
708
+ else
709
+ $include_data .= " '$data/*'";
710
+ }
711
+ }
712
+ }
713
+
714
+ $this->update_status($task_name, 'files_zip');
715
+ chdir(ABSPATH);
716
+
717
+ if($fail_safe_files){
718
+ $this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
719
+ }
720
+ else{
721
+ $do_cmd_zip_alternative = false;
722
+ @copy($backup_file, $backup_file.'_2');
723
+
724
+ iwp_mmb_print_flush('Files ZIP CMD: Start');
725
+ $command = "$zip -q -j $comp_level $backup_file .* * $exclude_file_data";
726
+ ob_start();
727
+ $result_f = $this->iwp_mmb_exec($command, false, true);
728
+ ob_get_clean();
729
+ iwp_mmb_print_flush('Files ZIP CMD: 1/2 over');
730
+ if (!$result_f || $result_f == 18) { // disregard permissions error, file can't be accessed
731
+ $command = "$zip -q -r $comp_level $backup_file $include_data $exclude_data";
732
+ ob_start();
733
+ $result_d = $this->iwp_mmb_exec($command, false, true);
734
+ ob_get_clean();
735
+ if ($result_d && $result_d != 18) {
736
+ @unlink($backup_file);
737
+ $do_cmd_zip_alternative = true;
738
+
739
+
740
+ if($result_d > 0 && $result_d < 18){
741
+ //return array(
742
+ // 'error' => 'Failed to archive files (' . $zip_errors[$result_d] . ') .'
743
+ // );
744
+ iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files (' . $zip_errors[$result_d] . ') .');
745
+ }
746
+ else{
747
+ //return array(
748
+ // 'error' => 'Failed to archive files.'
749
+ //);
750
+ iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files.');
751
+ }
752
+ }
753
+ }
754
+
755
+ if(!$do_cmd_zip_alternative){//if FILE ZIP CMD successful
756
+ @unlink($backup_file.'_2');
757
+ }
758
+
759
+ iwp_mmb_print_flush('Files ZIP CMD: End');
760
+ if (($result_f && $result_f != 18) || ($do_cmd_zip_alternative)) {
761
+
762
+ if($do_cmd_zip_alternative){
763
+ @copy($backup_file.'_2', $backup_file);
764
+ @unlink($backup_file.'_2');
765
+ }
766
+
767
+ $zip_archive_result = false;
768
+ if (class_exists("ZipArchive")) {
769
+ iwp_mmb_print_flush('Files ZIP Archive: Start');
770
+ $this->_log("Files zip fallback to ZipArchive");
771
+ $zip_archive_result = $this->zip_archive_backup($task_name, $backup_file, $exclude, $include);
772
+ iwp_mmb_print_flush('Files ZIP Archive: End');
773
+ }
774
+
775
+
776
+ if (!$zip_archive_result) {
777
+ $this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
778
+ }
779
+ }
780
+ }
781
+
782
+ //Reconnect
783
+ $this->wpdb_reconnect();
784
+
785
+ $this->update_status($task_name, 'files_zip', true);
786
+ return true;
787
+ }
788
+
789
+
790
+ function fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove){ //Try pclZip
791
+ //$this->back_hack($task_name, 'Files ZIP PCL: Start');
792
+ iwp_mmb_print_flush('Files ZIP PCL: Start');
793
+ if (!isset($archive)) {
794
+ define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
795
+ //require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
796
+ require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
797
+ $archive = new IWPPclZip($backup_file);
798
+ }
799
+
800
+ //Include paths
801
+ $include_data = array();
802
+ if (!empty($include) && is_array($include)) {
803
+ foreach ($include as $data) {
804
+ if ($data && file_exists(ABSPATH . $data))
805
+ $include_data[] = ABSPATH . $data . '/';
806
+ }
807
+ }
808
+
809
+ foreach ($add as $data) {
810
+ if (file_exists(ABSPATH . $data))
811
+ $include_data[] = ABSPATH . $data . '/';
812
+ }
813
+
814
+ //Include root files
815
+ if ($handle = opendir(ABSPATH)) {
816
+ while (false !== ($file = readdir($handle))) {
817
+ if ($file != "." && $file != ".." && !is_dir($file) && file_exists(ABSPATH . $file)) {
818
+ $include_data[] = ABSPATH . $file;
819
+ }
820
+ }
821
+ closedir($handle);
822
+ }
823
+
824
+ //exclude paths
825
+ $exclude_data = array();
826
+ if (!empty($exclude) && is_array($exclude)) {
827
+ foreach ($exclude as $data) {
828
+ if (is_dir(ABSPATH . $data))
829
+ $exclude_data[] = $data . '/';
830
+ else
831
+ $exclude_data[] = $data;
832
+ }
833
+ }
834
+
835
+ foreach ($remove as $rem) {
836
+ $exclude_data[] = $rem . '/';
837
+ }
838
+
839
+ if($fail_safe_files && $disable_comp){
840
+ $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
841
+ }
842
+ elseif(!$fail_safe_files && $disable_comp){
843
+ $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_NO_COMPRESSION);
844
+ }
845
+ elseif($fail_safe_files && !$disable_comp){
846
+ $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
847
+ }
848
+ else{
849
+ $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_IWP_EXCLUDE, $exclude_data);
850
+ }
851
+
852
+ iwp_mmb_print_flush('Files ZIP PCL: End');
853
+
854
+ if (!$result) {
855
+ @unlink($backup_file);
856
+ return array(
857
+ 'error' => 'Failed to zip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
858
+ );
859
+ }
860
+ //}
861
+ }
862
+ //Reconnect
863
+ function fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp){
864
+ //$this->back_hack($task_name, 'DB ZIP PCL: Start');
865
+ iwp_mmb_print_flush('DB ZIP PCL: Start');
866
+ define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
867
+ require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
868
+ $archive = new IWPPclZip($backup_file);
869
+
870
+ if($fail_safe_files && $disable_comp){
871
+ $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
872
+ }
873
+ elseif(!$fail_safe_files && $disable_comp){
874
+ $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION);
875
+ }
876
+ elseif($fail_safe_files && !$disable_comp){
877
+ $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
878
+ }
879
+ else{
880
+ $result_db = $archive->add(IWP_DB_DIR, PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR);
881
+ }
882
+ //$this->back_hack($task_name, 'DB ZIP PCL: End');
883
+ iwp_mmb_print_flush('DB ZIP PCL: End');
884
+
885
+ @unlink($db_result);
886
+ @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
887
+ @rmdir(IWP_DB_DIR);
888
+
889
+ if (!$result_db) {
890
+ return array(
891
+ 'error' => 'Failed to zip database. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
892
+ );
893
+ }
894
+ }
895
+ /**
896
+ * Zipping database dump and index.php in folder iwp_db by ZipArchive class, requires php zip extension.
897
+ *
898
+ * @param string $task_name the name of backup task
899
+ * @param string $db_result relative path to database dump file
900
+ * @param string $backup_file absolute path to zip file
901
+ * @return bool is compress successful or not
902
+ */
903
+ function zip_archive_backup_db($task_name, $db_result, $backup_file) {
904
+ $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
905
+ if (!$disable_comp) {
906
+ $this->_log("Compression is not supported by ZipArchive");
907
+ }
908
+ $zip = new ZipArchive();
909
+ $result = $zip->open($backup_file, ZIPARCHIVE::OVERWRITE); // Tries to open $backup_file for acrhiving
910
+ if ($result === true) {
911
+ $result = $result && $zip->addFile(IWP_BACKUP_DIR.'/iwp_db/index.php', "iwp_db/index.php"); // Tries to add iwp_db/index.php to $backup_file
912
+ $result = $result && $zip->addFile($db_result, "iwp_db/" . basename($db_result)); // Tries to add db dump form iwp_db dir to $backup_file
913
+ $result = $result && $zip->close(); // Tries to close $backup_file
914
+ } else {
915
+ $result = false;
916
+ }
917
+
918
+ return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
919
+ }
920
+
921
+ /**
922
+ * Zipping whole site root folder and append to backup file with database dump
923
+ * by ZipArchive class, requires php zip extension.
924
+ *
925
+ * @param string $task_name the name of backup task
926
+ * @param string $backup_file absolute path to zip file
927
+ * @param array $exclude array of files of folders to exclude, relative to site's root
928
+ * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
929
+ * @return array|bool true if successful or an array with error message if not
930
+ */
931
+ function zip_archive_backup($task_name, $backup_file, $exclude, $include, $overwrite = false) {
932
+
933
+ $filelist = $this->get_backup_files($exclude, $include);
934
+ $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
935
+ if (!$disable_comp) {
936
+ $this->_log("Compression is not supported by ZipArchive");
937
+ }
938
+ $zip = new ZipArchive();
939
+ if ($overwrite) {
940
+ $result = $zip->open($backup_file, ZipArchive::OVERWRITE); // Tries to open $backup_file for acrhiving
941
+ } else {
942
+ $result = $zip->open($backup_file); // Tries to open $backup_file for acrhiving
943
+ }
944
+ if ($result === true) {
945
+ foreach ($filelist as $file) {
946
+ iwp_mmb_auto_print('zip_archive_backup');
947
+ $result = $result && $zip->addFile($file, sprintf("%s", str_replace(ABSPATH, '', $file))); // Tries to add a new file to $backup_file
948
+ }
949
+ $result = $result && $zip->close(); // Tries to close $backup_file
950
+ } else {
951
+ $result = false;
952
+ }
953
+ return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
954
+ }
955
+
956
+
957
+ /**
958
+ * Gets an array of relative paths of all files in site root recursively.
959
+ * By default, there are all files from root folder, all files from folders wp-admin, wp-content, wp-includes recursively.
960
+ * Parameter $include adds other folders from site root, and excludes any file or folder by relative path to site's root.
961
+ *
962
+ * @param array $exclude array of files of folders to exclude, relative to site's root
963
+ * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
964
+ * @return array array with all files in site root dir
965
+ */
966
+ function get_backup_files($exclude, $include) {
967
+
968
+ $add = array(
969
+ trim(WPINC),
970
+ trim(basename(WP_CONTENT_DIR)),
971
+ "wp-admin"
972
+ );
973
+
974
+ $include = array_merge($add, $include);
975
+
976
+ $filelist = array();
977
+ if ($handle = opendir(ABSPATH)) {
978
+ while (false !== ($file = readdir($handle))) {
979
+ if (is_dir($file) && file_exists(ABSPATH . $file) && !(in_array($file, $include))) {
980
+ $exclude[] = $file;
981
+ }
982
+ }
983
+ closedir($handle);
984
+ }
985
+
986
+ $filelist = get_all_files_from_dir(ABSPATH, $exclude);
987
+
988
+ return $filelist;
989
+ }
990
+
991
+
992
+ function backup_db()
993
+ {
994
+ $db_folder = IWP_DB_DIR . '/';
995
+ if (!file_exists($db_folder)) {
996
+ if (!mkdir($db_folder, 0755, true))
997
+ return array(
998
+ 'error' => 'Error creating database backup folder (' . $db_folder . '). Make sure you have corrrect write permissions.'
999
+ );
1000
+ $db_index_file = '<?php
1001
+ global $old_url, $old_file_path;
1002
+ $old_url = \''.get_option('siteurl').'\';
1003
+ $old_file_path = \''.ABSPATH.'\';
1004
+ ';
1005
+ @file_put_contents(IWP_BACKUP_DIR.'/iwp_db/index.php', $db_index_file);
1006
+ }
1007
+
1008
+ $file = $db_folder . DB_NAME . '.sql';
1009
+
1010
+ if($GLOBALS['fail_safe_db']){
1011
+ $result = $this->backup_db_php($file);
1012
+ return $result;
1013
+ }
1014
+
1015
+ $result = $this->backup_db_dump($file); // try mysqldump always then fallback to php dump
1016
+ return $result;
1017
+ }
1018
+
1019
+ function backup_db_dump($file)
1020
+ {
1021
+ global $wpdb;
1022
+ $paths = $this->check_mysql_paths();
1023
+ $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1024
+ $command = $brace . $paths['mysqldump'] . $brace . ' --force --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables "' . DB_NAME . '" > ' . $brace . $file . $brace;
1025
+ iwp_mmb_print_flush('DB DUMP CMD: Start');
1026
+ ob_start();
1027
+ $result = $this->iwp_mmb_exec($command);
1028
+ ob_get_clean();
1029
+ iwp_mmb_print_flush('DB DUMP CMD: End');
1030
+
1031
+ if (!$result) { // Fallback to php
1032
+ $result = $this->backup_db_php($file);
1033
+ return $result;
1034
+ }
1035
+
1036
+ if (filesize($file) == 0 || !is_file($file) || !$result) {
1037
+ @unlink($file);
1038
+ return false;
1039
+ } else {
1040
+ return $file;
1041
+ }
1042
+ }
1043
+
1044
+ function backup_db_php($file)
1045
+ {
1046
+ global $wpdb;
1047
+
1048
+ if(empty($GLOBALS['fail_safe_db'])){
1049
+ iwp_mmb_print_flush('DB DUMP PHP Normal: Start');
1050
+ $fp = fopen( $file, 'w' );
1051
+ if ( !mysql_ping( $wpdb->dbh ) ) {
1052
+ mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
1053
+ mysql_select_db( DB_NAME );
1054
+ }
1055
+ $_count = 0;
1056
+ $insert_sql = '';
1057
+ $result = mysql_query( 'SHOW TABLES' );
1058
+ if(!$result)
1059
+ {
1060
+ return array(
1061
+ 'error' => 'MySQL '.mysql_error()." "
1062
+ );
1063
+ }
1064
+ while( $row = mysql_fetch_row( $result ) ) {
1065
+ $tables[]=$row[0];
1066
+ //array_push( $tables, $row[0] );
1067
+ }
1068
+
1069
+
1070
+ //$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
1071
+ foreach ($tables as $table) {
1072
+ iwp_mmb_auto_print('backup_db_php_normal');
1073
+
1074
+ $insert_sql .= "DROP TABLE IF EXISTS $table;";
1075
+ //create table
1076
+ $table_descr_query = mysql_query("SHOW CREATE TABLE `$table`");
1077
+ $fetch_table_descr_row = mysql_fetch_array( $table_descr_query );
1078
+ $insert_sql .= "\n\n" . $fetch_table_descr_row[1] . ";\n\n";
1079
+
1080
+ fwrite( $fp, $insert_sql );
1081
+ $insert_sql = '';
1082
+
1083
+ $table_query = mysql_query("SELECT * FROM `$table`");
1084
+ $num_fields = mysql_num_fields($table_query);
1085
+ while ( $fetch_row = mysql_fetch_array( $table_query ) ) {
1086
+ $insert_sql .= "INSERT INTO $table VALUES(";
1087
+ for ( $n=1; $n<=$num_fields; $n++ ) {
1088
+ $m = $n - 1;
1089
+
1090
+ if ( $fetch_row[$m] === NULL ) {
1091
+ $insert_sql .= "NULL, ";
1092
+ } else {
1093
+ $insert_sql .= "'" . mysql_real_escape_string( $fetch_row[$m] ) . "', ";
1094
+ }
1095
+ }
1096
+ $insert_sql = substr( $insert_sql, 0, -2 );
1097
+ $insert_sql .= ");\n";
1098
+
1099
+ fwrite( $fp, $insert_sql );
1100
+ $insert_sql = '';
1101
+
1102
+ // Help keep HTTP alive.
1103
+ $_count++;
1104
+ if ($_count >= 400) {
1105
+ echo ' ';
1106
+ flush();
1107
+ $_count = 0;
1108
+ }
1109
+ } // End foreach $tables.
1110
+
1111
+ $insert_sql .= "\n\n\n";
1112
+
1113
+ // testing: mysql_close( $wpdb->dbh );
1114
+ // Verify database is still connected and working properly. Sometimes mysql runs out of memory and dies in the above foreach.
1115
+ // No point in reconnecting as we can NOT trust that our dump was succesful anymore (it most likely was not).
1116
+ if ( @mysql_ping( $wpdb->dbh ) ) { // Still connected to database.
1117
+ mysql_free_result( $table_query ); // Free memory.
1118
+ } /*else { // Database not connected.
1119
+
1120
+ return false;
1121
+ }*/
1122
+
1123
+ // Help keep HTTP alive.
1124
+ echo ' ';
1125
+ flush();
1126
+
1127
+ //unset( $tables[$table_key] );
1128
+ }
1129
+ fclose( $fp );
1130
+ unset ($fp);
1131
+ iwp_mmb_print_flush('DB DUMP PHP Normal: End');
1132
+ }
1133
+ else{
1134
+ iwp_mmb_print_flush('DB DUMP PHP Fail-safe: Start');
1135
+ file_put_contents($file, '');//safe to reset any old data
1136
+ $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
1137
+ foreach ($tables as $table) {
1138
+
1139
+ //drop existing table
1140
+ $dump_data = "DROP TABLE IF EXISTS $table[0];";
1141
+ file_put_contents($file, $dump_data, FILE_APPEND);
1142
+ //create table
1143
+ $create_table = $wpdb->get_row("SHOW CREATE TABLE $table[0]", ARRAY_N);
1144
+ $dump_data = "\n\n" . $create_table[1] . ";\n\n";
1145
+ file_put_contents($file, $dump_data, FILE_APPEND);
1146
+
1147
+ $count = $wpdb->get_var("SELECT count(*) FROM $table[0]");
1148
+ if ($count > 100)
1149
+ $count = ceil($count / 100);
1150
+ else if ($count > 0)
1151
+ $count = 1;
1152
+
1153
+ for ($i = 0; $i < $count; $i++) {
1154
+ iwp_mmb_auto_print('backup_db_php_fail_safe');
1155
+ $low_limit = $i * 100;
1156
+ $qry = "SELECT * FROM $table[0] LIMIT $low_limit, 100";
1157
+ $rows = $wpdb->get_results($qry, ARRAY_A);
1158
+ if (is_array($rows)) {
1159
+ foreach ($rows as $row) {
1160
+ //insert single row
1161
+ $dump_data = "INSERT INTO $table[0] VALUES(";
1162
+ $num_values = count($row);
1163
+ $j = 1;
1164
+ foreach ($row as $value) {
1165
+ $value = addslashes($value);
1166
+ $value = preg_replace("/\n/Ui", "\\n", $value);
1167
+ $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
1168
+ $j++;
1169
+ unset($value);
1170
+ }
1171
+ $dump_data .= ");\n";
1172
+ file_put_contents($file, $dump_data, FILE_APPEND);
1173
+ }
1174
+ }
1175
+ }
1176
+ $dump_data = "\n\n\n";
1177
+ file_put_contents($file, $dump_data, FILE_APPEND);
1178
+
1179
+ unset($rows);
1180
+ unset($dump_data);
1181
+ }
1182
+ iwp_mmb_print_flush('DB DUMP PHP Fail-safe: End');
1183
+ }
1184
+
1185
+ if (filesize($file) == 0 || !is_file($file)) {
1186
+ @unlink($file);
1187
+ return array(
1188
+ 'error' => 'Database backup failed. Try to enable MySQL dump on your server.'
1189
+ );
1190
+ }
1191
+
1192
+ return $file;
1193
+
1194
+ }
1195
+
1196
+ /**
1197
+ * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
1198
+ * Assumes that WP_Filesystem() has already been called and setup.
1199
+ *
1200
+ * @since 2.5.0
1201
+ *
1202
+ * @param string $from source directory
1203
+ * @param string $to destination directory
1204
+ * @param array $skip_list a list of files/folders to skip copying
1205
+ * @return mixed WP_Error on failure, True on success.
1206
+ */
1207
+ function iwp_mmb_direct_to_any_copy_dir($from, $to, $skip_list = array() ) {//$from => direct file system, $to => automatic filesystem
1208
+ global $wp_filesystem;
1209
+
1210
+ $wp_temp_direct = new WP_Filesystem_Direct('');
1211
+
1212
+
1213
+ $dirlist = $wp_temp_direct->dirlist($from);
1214
+
1215
+ $from = trailingslashit($from);
1216
+ $to = trailingslashit($to);
1217
+
1218
+ $skip_regex = '';
1219
+ foreach ( (array)$skip_list as $key => $skip_file )
1220
+ $skip_regex .= preg_quote($skip_file, '!') . '|';
1221
+
1222
+ if ( !empty($skip_regex) )
1223
+ $skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i';
1224
+
1225
+ foreach ( (array) $dirlist as $filename => $fileinfo ) {
1226
+ if ( !empty($skip_regex) )
1227
+ if ( preg_match($skip_regex, $from . $filename) )
1228
+ continue;
1229
+
1230
+ if ( 'f' == $fileinfo['type'] ) {
1231
+ if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
1232
+ // If copy failed, chmod file to 0644 and try again.
1233
+ $wp_filesystem->chmod($to . $filename, 0644);
1234
+ if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
1235
+ return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename);
1236
+ }
1237
+ } elseif ( 'd' == $fileinfo['type'] ) {
1238
+ if ( !$wp_filesystem->is_dir($to . $filename) ) {
1239
+ if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
1240
+ return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename);
1241
+ }
1242
+ $result = $this->iwp_mmb_direct_to_any_copy_dir($from . $filename, $to . $filename, $skip_list);
1243
+ if ( is_wp_error($result) )
1244
+ return $result;
1245
+ }
1246
+ }
1247
+ return true;
1248
+ }
1249
+
1250
+ function iwp_mmb_direct_to_any_copy($source, $destination, $overwrite = false, $mode = false){
1251
+ global $wp_filesystem;
1252
+ if($wp_filesystem->method == 'direct'){
1253
+ return $wp_filesystem->copy($source, $destination, $overwrite, $mode);
1254
+ }
1255
+ elseif($wp_filesystem->method == 'ftpext' || $wp_filesystem->method == 'ftpsockets'){
1256
+ if ( ! $overwrite && $wp_filesystem->exists($destination) )
1257
+ return false;
1258
+ //$content = $this->get_contents($source);
1259
+ // if ( false === $content)
1260
+ // return false;
1261
+
1262
+ //put content
1263
+ //$tempfile = wp_tempnam($file);
1264
+ $source_handle = fopen($source, 'r');
1265
+ if ( ! $source_handle )
1266
+ return false;
1267
+
1268
+ //fwrite($temp, $contents);
1269
+ //fseek($temp, 0); //Skip back to the start of the file being written to
1270
+
1271
+ $sample_content = fread($source_handle, (1024 * 1024 * 2));//1024 * 1024 * 2 => 2MB
1272
+ fseek($source_handle, 0); //Skip back to the start of the file being written to
1273
+
1274
+ $type = $wp_filesystem->is_binary($sample_content) ? FTP_BINARY : FTP_ASCII;
1275
+ unset($sample_content);
1276
+ if($wp_filesystem->method == 'ftpext'){
1277
+ $ret = @ftp_fput($wp_filesystem->link, $destination, $source_handle, $type);
1278
+ }
1279
+ elseif($wp_filesystem->method == 'ftpsockets'){
1280
+ $wp_filesystem->ftp->SetType($type);
1281
+ $ret = $wp_filesystem->ftp->fput($destination, $source_handle);
1282
+ }
1283
+
1284
+ fclose($source_handle);
1285
+ unlink($source);//to immediately save system space
1286
+ //unlink($tempfile);
1287
+
1288
+ $wp_filesystem->chmod($destination, $mode);
1289
+
1290
+ return $ret;
1291
+
1292
+ //return $this->put_contents($destination, $content, $mode);
1293
+ }
1294
+ }
1295
+
1296
+
1297
+ function restore($args)
1298
+ {
1299
+
1300
+ global $wpdb, $wp_filesystem;
1301
+ if (empty($args)) {
1302
+ return false;
1303
+ }
1304
+
1305
+ extract($args);
1306
+ $this->set_memory();
1307
+
1308
+ $unlink_file = true; //Delete file after restore
1309
+
1310
+ include_once ABSPATH . 'wp-admin/includes/file.php';
1311
+
1312
+ //Detect source
1313
+ if ($backup_url) {
1314
+ //This is for clone (overwrite)
1315
+
1316
+ $backup_file = download_url($backup_url);
1317
+ if (is_wp_error($backup_file)) {
1318
+ return array(
1319
+ 'error' => 'Unable to download backup file ('.$backup_file->get_error_message().')'
1320
+ );
1321
+ }
1322
+ $what = 'full';
1323
+ } else {
1324
+ $tasks = $this->tasks;
1325
+ $task = $tasks[$task_name];
1326
+ if (isset($task['task_results'][$result_id]['server'])) {
1327
+ $backup_file = $task['task_results'][$result_id]['server']['file_path'];
1328
+ $unlink_file = false; //Don't delete file if stored on server
1329
+
1330
+ } elseif (isset($task['task_results'][$result_id]['ftp'])) {
1331
+ $ftp_file = $task['task_results'][$result_id]['ftp'];
1332
+ $args = $task['task_args']['account_info']['iwp_ftp'];
1333
+ $args['backup_file'] = $ftp_file;
1334
+ iwp_mmb_print_flush('FTP download: Start');
1335
+ $backup_file = $this->get_ftp_backup($args);
1336
+ iwp_mmb_print_flush('FTP download: End');
1337
+ if ($backup_file == false) {
1338
+ return array(
1339
+ 'error' => 'Failed to download file from FTP.'
1340
+ );
1341
+ }
1342
+ } elseif (isset($task['task_results'][$result_id]['amazons3'])) {
1343
+ $amazons3_file = $task['task_results'][$result_id]['amazons3'];
1344
+ $args = $task['task_args']['account_info']['iwp_amazon_s3'];
1345
+ $args['backup_file'] = $amazons3_file;
1346
+ iwp_mmb_print_flush('Amazon S3 download: Start');
1347
+ $backup_file = $this->get_amazons3_backup($args);
1348
+ iwp_mmb_print_flush('Amazon S3 download: End');
1349
+ if ($backup_file == false) {
1350
+ return array(
1351
+ 'error' => 'Failed to download file from Amazon S3.'
1352
+ );
1353
+ }
1354
+ } elseif(isset($task['task_results'][$result_id]['dropbox'])){
1355
+ $dropbox_file = $task['task_results'][$result_id]['dropbox'];
1356
+ $args = $task['task_args']['account_info']['iwp_dropbox'];
1357
+ $args['backup_file'] = $dropbox_file;
1358
+ iwp_mmb_print_flush('Dropbox download: Start');
1359
+ $backup_file = $this->get_dropbox_backup($args);
1360
+ iwp_mmb_print_flush('Dropbox download: End');
1361
+
1362
+ if ($backup_file == false) {
1363
+ return array(
1364
+ 'error' => 'Failed to download file from Dropbox.'
1365
+ );
1366
+ }
1367
+ }
1368
+
1369
+
1370
+ $what = $tasks[$task_name]['task_args']['what'];
1371
+ }
1372
+
1373
+
1374
+
1375
+ $this->wpdb_reconnect();
1376
+
1377
+ /////////////////// dev ////////////////////////
1378
+
1379
+
1380
+ if (!$this->is_server_writable()) {
1381
+ return array(
1382
+ 'error' => 'Failed, please add FTP details'
1383
+ );
1384
+ }
1385
+
1386
+ $url = wp_nonce_url('index.php?page=iwp_no_page','iwp_fs_cred');
1387
+ ob_start();
1388
+ if (false === ($creds = request_filesystem_credentials($url, '', false, ABSPATH, null) ) ) {
1389
+ return array(
1390
+ 'error' => 'Unable to get file system credentials'
1391
+ ); // stop processing here
1392
+ }
1393
+ ob_end_clean();
1394
+
1395
+ if ( ! WP_Filesystem($creds, ABSPATH) ) {
1396
+ //request_filesystem_credentials($url, '', true, false, null);
1397
+ return array(
1398
+ 'error' => 'Unable to initiate file system. Please check you have entered valid FTP credentials.'
1399
+ ); // stop processing here
1400
+ //return;
1401
+ }
1402
+
1403
+ require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');//will be used to copy from temp directory
1404
+
1405
+ // do process
1406
+ $temp_dir = get_temp_dir();
1407
+ $new_temp_folder = untrailingslashit($temp_dir);
1408
+ $temp_uniq = md5(microtime(1));//should be random
1409
+ while (is_dir($new_temp_folder .'/'. $temp_uniq )) {
1410
+ $temp_uniq = md5(microtime(1));
1411
+ }
1412
+ $new_temp_folder = trailingslashit($new_temp_folder .'/'. $temp_uniq);
1413
+ $is_dir_created = mkdir($new_temp_folder);// new folder should be empty
1414
+ if(!$is_dir_created){
1415
+ return array(
1416
+ 'error' => 'Unable to create a temporary directory.'
1417
+ );
1418
+ }
1419
+
1420
+ //echo '<pre>$new_temp_folder:'; var_dump($new_temp_folder); echo '</pre>';
1421
+
1422
+
1423
+ $remote_abspath = $wp_filesystem->abspath();
1424
+ if(!empty($remote_abspath)){
1425
+ $remote_abspath = trailingslashit($remote_abspath);
1426
+ }else{
1427
+ return array(
1428
+ 'error' => 'Unable to locate WP root directory using file system.'
1429
+ );
1430
+ }
1431
+
1432
+ //global $wp_filesystem;
1433
+ // $wp_filesystem->put_contents(
1434
+ // '/tmp/example.txt',
1435
+ // 'Example contents of a file',
1436
+ // FS_CHMOD_FILE // predefined mode settings for WP files
1437
+ // );
1438
+
1439
+ /////////////////// dev ////////////////////////
1440
+
1441
+ if ($backup_file && file_exists($backup_file)) {
1442
+ if ($overwrite) {//clone only fresh or existing to existing
1443
+ //Keep old db credentials before overwrite
1444
+ if (!$wp_filesystem->copy($remote_abspath . 'wp-config.php', $remote_abspath . 'iwp-temp-wp-config.php', true)) {
1445
+ if($unlink_file) @unlink($backup_file);
1446
+ return array(
1447
+ 'error' => 'Error creating wp-config. Please check your write permissions.'
1448
+ );
1449
+ }
1450
+
1451
+ $db_host = DB_HOST;
1452
+ $db_user = DB_USER;
1453
+ $db_password = DB_PASSWORD;
1454
+ $home = rtrim(get_option('home'), "/");
1455
+ $site_url = get_option('site_url');
1456
+
1457
+ $clone_options = array();
1458
+ if (trim($clone_from_url) || trim($iwp_clone) || trim($maintain_old_key)) {
1459
+
1460
+ $clone_options['iwp_client_nossl_key'] = get_option('iwp_client_nossl_key');
1461
+ $clone_options['iwp_client_public_key'] = get_option('iwp_client_public_key');
1462
+ $clone_options['iwp_client_action_message_id'] = get_option('iwp_client_action_message_id');
1463
+
1464
+ }
1465
+
1466
+ $clone_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_backup_tasks'));
1467
+ $clone_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
1468
+ $clone_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
1469
+
1470
+
1471
+ } else {
1472
+ $restore_options = array();
1473
+ $restore_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
1474
+ $restore_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
1475
+ $restore_options['iwp_client_user_hit_count'] = serialize(get_option('iwp_client_user_hit_count'));
1476
+ $restore_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_backup_tasks'));
1477
+ }
1478
+
1479
+
1480
+
1481
+
1482
+ //Backup file will be extracted to a temporary path
1483
+
1484
+ //chdir(ABSPATH);
1485
+ $unzip = $this->get_unzip();
1486
+ $command = "$unzip -o $backup_file -d $new_temp_folder";
1487
+ iwp_mmb_print_flush('ZIP Extract CMD: Start');
1488
+ ob_start();
1489
+ $result = $this->iwp_mmb_exec($command);
1490
+ ob_get_clean();
1491
+ iwp_mmb_print_flush('ZIP Extract CMD: End');
1492
+
1493
+ if (!$result) { //fallback to pclzip
1494
+ define('PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
1495
+ //require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
1496
+ require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
1497
+ iwp_mmb_print_flush('ZIP Extract PCL: Start');
1498
+ $archive = new IWPPclZip($backup_file);
1499
+ $result = $archive->extract(PCLZIP_OPT_PATH, $new_temp_folder, PCLZIP_OPT_REPLACE_NEWER);
1500
+ iwp_mmb_print_flush('ZIP Extract PCL: End');
1501
+ }
1502
+ $this->wpdb_reconnect();
1503
+
1504
+ if ($unlink_file) {
1505
+ @unlink($backup_file);
1506
+ }
1507
+
1508
+ if (!$result) {
1509
+ return array(
1510
+ 'error' => 'Failed to unzip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
1511
+ );
1512
+ }
1513
+
1514
+ $db_result = $this->restore_db($new_temp_folder);
1515
+
1516
+ if (!$db_result) {
1517
+ return array(
1518
+ 'error' => 'Error restoring database.'
1519
+ );
1520
+ } else if(is_array($db_result) && isset($db_result['error'])){
1521
+ return array(
1522
+ 'error' => $db_result['error']
1523
+ );
1524
+ }
1525
+
1526
+ } else {
1527
+ return array(
1528
+ 'error' => 'Backup file not found.'
1529
+ );
1530
+ }
1531
+
1532
+
1533
+ //copy files from temp to ABSPATH
1534
+ $copy_result = $this->iwp_mmb_direct_to_any_copy_dir($new_temp_folder, $remote_abspath);
1535
+
1536
+ if ( is_wp_error($copy_result) ){
1537
+ $wp_temp_direct2 = new WP_Filesystem_Direct('');
1538
+ $wp_temp_direct2->delete($new_temp_folder, true);
1539
+ return $copy_result;
1540
+ }
1541
+
1542
+
1543
+ $this->wpdb_reconnect();
1544
+
1545
+
1546
+
1547
+ //Replace options and content urls
1548
+ if ($overwrite) {//fresh WP package or existing to existing site
1549
+ //Get New Table prefix
1550
+ $new_table_prefix = trim($this->get_table_prefix());
1551
+ //Retrieve old wp_config
1552
+ //@unlink(ABSPATH . 'wp-config.php');
1553
+ $wp_filesystem->delete($remote_abspath . 'wp-config.php', false, 'f');
1554
+ //Replace table prefix
1555
+ //$lines = file(ABSPATH . 'iwp-temp-wp-config.php');
1556
+ $lines = $wp_filesystem->get_contents_array($remote_abspath . 'iwp-temp-wp-config.php');
1557
+
1558
+ $new_lines = '';
1559
+ foreach ($lines as $line) {
1560
+ if (strstr($line, '$table_prefix')) {
1561
+ $line = '$table_prefix = "' . $new_table_prefix . '";' . PHP_EOL;
1562
+ }
1563
+ $new_lines .= $line;
1564
+ //file_put_contents(ABSPATH . 'wp-config.php', $line, FILE_APPEND);
1565
+ }
1566
+
1567
+ $wp_filesystem->put_contents($remote_abspath . 'wp-config.php', $new_lines);
1568
+
1569
+ //@unlink(ABSPATH . 'iwp-temp-wp-config.php');
1570
+ $wp_filesystem->delete($remote_abspath . 'iwp-temp-wp-config.php', false, 'f');
1571
+
1572
+ //Replace options
1573
+ $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
1574
+ $old = $wpdb->get_var($query);
1575
+ $old = rtrim($old, "/");
1576
+ $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'home'";
1577
+ $wpdb->query($wpdb->prepare($query, $home));
1578
+ $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'siteurl'";
1579
+ $wpdb->query($wpdb->prepare($query, $home));
1580
+ //Replace content urls
1581
+
1582
+ $regexp1 = 'src="(.*)'.$old.'(.*)"';
1583
+ $regexp2 = 'href="(.*)'.$old.'(.*)"';
1584
+ $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, %s,%s) WHERE post_content REGEXP %s OR post_content REGEXP %s";
1585
+ $wpdb->query($wpdb->prepare($query, $old, $home, $regexp1, $regexp2));
1586
+
1587
+ if (trim($new_password)) {
1588
+ $new_password = wp_hash_password($new_password);
1589
+ }
1590
+ if (!trim($clone_from_url) && !trim($iwp_clone)) {
1591
+ if ($new_user && $new_password) {
1592
+ $query = "UPDATE " . $new_table_prefix . "users SET user_login = %s, user_pass = %s WHERE user_login = %s";
1593
+ $wpdb->query($wpdb->prepare($query, $new_user, $new_password, $old_user));
1594
+ }
1595
+ } else {
1596
+
1597
+ // if ($iwp_clone) {
1598
+ if ($admin_email) {
1599
+ //Clean Install
1600
+ $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'admin_email'";
1601
+ $wpdb->query($wpdb->prepare($query, $admin_email));
1602
+ $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
1603
+ $temp_user = $wpdb->get_row($query);
1604
+ if (!empty($temp_user)) {
1605
+ $query = "UPDATE " . $new_table_prefix . "users SET user_email=%s, user_login = %s, user_pass = %s WHERE user_login = %s";
1606
+ $wpdb->query($wpdb->prepare($query, $admin_email, $new_user, $new_password, $temp_user->user_login));
1607
+ }
1608
+
1609
+ }
1610
+ // }
1611
+
1612
+ //if ($clone_from_url) {
1613
+ if ($new_user && $new_password) {
1614
+ $query = "UPDATE " . $new_table_prefix . "users SET user_pass = %s WHERE user_login = %s";
1615
+ $wpdb->query($wpdb->prepare($query, $new_password, $new_user));
1616
+ }
1617
+ // }
1618
+
1619
+ }
1620
+
1621
+ if (is_array($clone_options) && !empty($clone_options)) {
1622
+ foreach ($clone_options as $key => $option) {
1623
+ if (!empty($key)) {
1624
+ $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = %s";
1625
+ $res = $wpdb->get_var($wpdb->prepare($query, $key));
1626
+ if ($res == false) {
1627
+ $query = "INSERT INTO " . $new_table_prefix . "options (option_value,option_name) VALUES(%s,%s)";
1628
+ $wpdb->query($wpdb->prepare($query, $option, $key));
1629
+ } else {
1630
+ $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = %s";
1631
+ $wpdb->query($wpdb->prepare($query, $option, $key));
1632
+ }
1633
+ }
1634
+ }
1635
+ }
1636
+
1637
+ //Remove hit count
1638
+ $query = "DELETE FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_user_hit_count'";
1639
+ $wpdb->query($query);
1640
+
1641
+ //Check for .htaccess permalinks update
1642
+ $this->replace_htaccess($home, $remote_abspath);
1643
+ } else {
1644
+ //restore client options
1645
+ if (is_array($restore_options) && !empty($restore_options)) {
1646
+ foreach ($restore_options as $key => $option) {
1647
+ if (!empty($key)) {
1648
+ $query = "SELECT option_value FROM " . $wpdb->base_prefix . "options WHERE option_name = %s";
1649
+ $res = $wpdb->get_var($wpdb->prepare($query, $key));
1650
+ if ($res == false) {
1651
+ $query = "INSERT INTO " . $wpdb->base_prefix . "options (option_value,option_name) VALUES(%s,%s)";
1652
+ $wpdb->query($wpdb->prepare($query, $option, $key));
1653
+ } else {
1654
+ $query = "UPDATE " . $wpdb->base_prefix . "options SET option_value = %s WHERE option_name = %s";
1655
+ $wpdb->query($wpdb->prepare($query, $option, $key));
1656
+ }
1657
+ }
1658
+
1659
+ /*$test = update_option($key,$option);*/
1660
+ }
1661
+ }
1662
+ }
1663
+
1664
+ //clear the temp directory
1665
+ $wp_temp_direct2 = new WP_Filesystem_Direct('');
1666
+ $wp_temp_direct2->delete($new_temp_folder, true);
1667
+
1668
+ return !empty($new_user) ? $new_user : true ;
1669
+ }
1670
+
1671
+ function restore_db($new_temp_folder)
1672
+ {
1673
+ global $wpdb;
1674
+ $paths = $this->check_mysql_paths();
1675
+ $file_path = $new_temp_folder . '/iwp_db';
1676
+ @chmod($file_path,0755);
1677
+ $file_name = glob($file_path . '/*.sql');
1678
+ $file_name = $file_name[0];
1679
+
1680
+ if(!$file_name){
1681
+ return array('error' => 'Cannot access database file.');
1682
+ }
1683
+
1684
+ $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1685
+ $command = $brace . $paths['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --default-character-set="utf8" ' . DB_NAME . ' < ' . $brace . $file_name . $brace;
1686
+ iwp_mmb_print_flush('DB Restore CMD: Start');
1687
+ ob_start();
1688
+ $result = $this->iwp_mmb_exec($command);
1689
+ ob_get_clean();
1690
+ iwp_mmb_print_flush('DB Restore CMD: End');
1691
+ if (!$result) {
1692
+ //try php
1693
+ $this->restore_db_php($file_name);
1694
+ }
1695
+
1696
+
1697
+ @unlink($file_name);
1698
+ @unlink(dirname($file_name).'/index.php');
1699
+ @rmdir(dirname($file_name));//remove its folder
1700
+ return true;
1701
+ }
1702
+
1703
+ function restore_db_php($file_name)
1704
+ {
1705
+
1706
+ $this->wpdb_reconnect();
1707
+ global $wpdb;
1708
+
1709
+ $wpdb->query("SET NAMES 'utf8'");
1710
+
1711
+ $current_query = '';
1712
+ // Read in entire file
1713
+ $lines = file($file_name);
1714
+ // Loop through each line
1715
+ if(!empty($lines)){
1716
+ foreach ($lines as $line) {
1717
+ iwp_mmb_auto_print('restore_db_php');
1718
+ // Skip it if it's a comment
1719
+ if (substr($line, 0, 2) == '--' || $line == '')
1720
+ continue;
1721
+
1722
+ // Add this line to the current query
1723
+ $current_query .= $line;
1724
+ // If it has a semicolon at the end, it's the end of the query
1725
+ if (substr(trim($line), -1, 1) == ';') {
1726
+ // Perform the query
1727
+ $result = $wpdb->query($current_query);
1728
+ if ($result === false)
1729
+ return false;
1730
+ // Reset temp variable to empty
1731
+ $current_query = '';
1732
+ }
1733
+ }
1734
+ }
1735
+
1736
+ return true;
1737
+ }
1738
+
1739
+ function get_table_prefix()
1740
+ {
1741
+ $lines = file(ABSPATH . 'wp-config.php');
1742
+ foreach ($lines as $line) {
1743
+ if (strstr($line, '$table_prefix')) {
1744
+ $pattern = "/(\'|\")[^(\'|\")]*/";
1745
+ preg_match($pattern, $line, $matches);
1746
+ $prefix = substr($matches[0], 1);
1747
+ return $prefix;
1748
+ break;
1749
+ }
1750
+ }
1751
+ return 'wp_'; //default
1752
+ }
1753
+
1754
+ function optimize_tables()
1755
+ {
1756
+ global $wpdb;
1757
+ $query = 'SHOW TABLE STATUS';
1758
+ $tables = $wpdb->get_results($query, ARRAY_A);
1759
+ foreach ($tables as $table) {
1760
+ if (in_array($table['Engine'], array(
1761
+ 'MyISAM',
1762
+ 'ISAM',
1763
+ 'HEAP',
1764
+ 'MEMORY',
1765
+ 'ARCHIVE'
1766
+ )))
1767
+ $table_string .= $table['Name'] . ",";
1768
+ elseif ($table['Engine'] == 'InnoDB') {
1769
+ $optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
1770
+ }
1771
+ }
1772
+
1773
+ if(!empty($table_string)){
1774
+ $table_string = rtrim($table_string, ',');
1775
+ $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
1776
+ }
1777
+
1778
+ return $optimize ? true : false;
1779
+ }
1780
+
1781
+ ### Function: Auto Detect MYSQL and MYSQL Dump Paths
1782
+ function check_mysql_paths()
1783
+ {
1784
+ global $wpdb;
1785
+ $paths = array(
1786
+ 'mysql' => '',
1787
+ 'mysqldump' => ''
1788
+ );
1789
+ if (substr(PHP_OS, 0, 3) == 'WIN') {
1790
+ $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
1791
+ if ($mysql_install) {
1792
+ $install_path = str_replace('\\', '/', $mysql_install->Value);
1793
+ $paths['mysql'] = $install_path . 'bin/mysql.exe';
1794
+ $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
1795
+ } else {
1796
+ $paths['mysql'] = 'mysql.exe';
1797
+ $paths['mysqldump'] = 'mysqldump.exe';
1798
+ }
1799
+ } else {
1800
+ $paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
1801
+ if (empty($paths['mysql']))
1802
+ $paths['mysql'] = 'mysql'; // try anyway
1803
+
1804
+ $paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
1805
+ if (empty($paths['mysqldump']))
1806
+ $paths['mysqldump'] = 'mysqldump'; // try anyway
1807
+
1808
+ }
1809
+
1810
+
1811
+ return $paths;
1812
+ }
1813
+
1814
+ //Check if exec, system, passthru functions exist
1815
+ function check_sys()
1816
+ {
1817
+ if ($this->iwp_mmb_function_exists('exec'))
1818
+ return 'exec';
1819
+
1820
+ if ($this->iwp_mmb_function_exists('system'))
1821
+ return 'system';
1822
+
1823
+ if ($this->iwp_mmb_function_exists('passhtru'))
1824
+ return 'passthru';
1825
+
1826
+ return false;
1827
+
1828
+ }
1829
+
1830
+ function iwp_mmb_exec($command, $string = false, $rawreturn = false)
1831
+ {
1832
+ if ($command == '')
1833
+ return false;
1834
+
1835
+ if ($this->iwp_mmb_function_exists('exec')) {
1836
+ $log = @exec($command, $output, $return);
1837
+
1838
+ if ($string)
1839
+ return $log;
1840
+ if ($rawreturn)
1841
+ return $return;
1842
+
1843
+ return $return ? false : true;
1844
+ } elseif ($this->iwp_mmb_function_exists('system')) {
1845
+ $log = @system($command, $return);
1846
+
1847
+ if ($string)
1848
+ return $log;
1849
+
1850
+ if ($rawreturn)
1851
+ return $return;
1852
+
1853
+ return $return ? false : true;
1854
+ } elseif ($this->iwp_mmb_function_exists('passthru') && !$string) {
1855
+ $log = passthru($command, $return);
1856
+
1857
+ if ($rawreturn)
1858
+ return $return;
1859
+
1860
+ return $return ? false : true;
1861
+ }
1862
+
1863
+ if ($rawreturn)
1864
+ return -1;
1865
+
1866
+ return false;
1867
+ }
1868
+
1869
+ function get_zip()
1870
+ {
1871
+ $zip = $this->iwp_mmb_exec('which zip', true);
1872
+ if (!$zip)
1873
+ $zip = "zip";
1874
+ return $zip;
1875
+ }
1876
+
1877
+ function get_unzip()
1878
+ {
1879
+ $unzip = $this->iwp_mmb_exec('which unzip', true);
1880
+ if (!$unzip)
1881
+ $unzip = "unzip";
1882
+ return $unzip;
1883
+ }
1884
+
1885
+ function check_backup_compat()
1886
+ {
1887
+ $reqs = array();
1888
+ if (strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0) {
1889
+ $reqs['Server OS']['status'] = 'Linux (or compatible)';
1890
+ $reqs['Server OS']['pass'] = true;
1891
+ } else {
1892
+ $reqs['Server OS']['status'] = 'Windows';
1893
+ $reqs['Server OS']['pass'] = true;
1894
+ $pass = false;
1895
+ }
1896
+ $reqs['PHP Version']['status'] = phpversion();
1897
+ if ((float) phpversion() >= 5.1) {
1898
+ $reqs['PHP Version']['pass'] = true;
1899
+ } else {
1900
+ $reqs['PHP Version']['pass'] = false;
1901
+ $pass = false;
1902
+ }
1903
+
1904
+
1905
+ if (is_writable(WP_CONTENT_DIR)) {
1906
+ $reqs['Backup Folder']['status'] = "writable";
1907
+ $reqs['Backup Folder']['pass'] = true;
1908
+ } else {
1909
+ $reqs['Backup Folder']['status'] = "not writable";
1910
+ $reqs['Backup Folder']['pass'] = false;
1911
+ }
1912
+
1913
+
1914
+ $file_path = IWP_BACKUP_DIR;
1915
+ $reqs['Backup Folder']['status'] .= ' (' . $file_path . ')';
1916
+
1917
+ if ($func = $this->check_sys()) {
1918
+ $reqs['Execute Function']['status'] = $func;
1919
+ $reqs['Execute Function']['pass'] = true;
1920
+ } else {
1921
+ $reqs['Execute Function']['status'] = "not found";
1922
+ $reqs['Execute Function']['info'] = "(will try PHP replacement)";
1923
+ $reqs['Execute Function']['pass'] = false;
1924
+ }
1925
+ $reqs['Zip']['status'] = $this->get_zip();
1926
+
1927
+ $reqs['Zip']['pass'] = true;
1928
+
1929
+
1930
+
1931
+ $reqs['Unzip']['status'] = $this->get_unzip();
1932
+
1933
+ $reqs['Unzip']['pass'] = true;
1934
+
1935
+ $paths = $this->check_mysql_paths();
1936
+
1937
+ if (!empty($paths['mysqldump'])) {
1938
+ $reqs['MySQL Dump']['status'] = $paths['mysqldump'];
1939
+ $reqs['MySQL Dump']['pass'] = true;
1940
+ } else {
1941
+ $reqs['MySQL Dump']['status'] = "not found";
1942
+ $reqs['MySQL Dump']['info'] = "(will try PHP replacement)";
1943
+ $reqs['MySQL Dump']['pass'] = false;
1944
+ }
1945
+
1946
+ $exec_time = ini_get('max_execution_time');
1947
+ $reqs['Execution time']['status'] = $exec_time ? $exec_time . "s" : 'unknown';
1948
+ $reqs['Execution time']['pass'] = true;
1949
+
1950
+ $mem_limit = ini_get('memory_limit');
1951
+ $reqs['Memory limit']['status'] = $mem_limit ? $mem_limit : 'unknown';
1952
+ $reqs['Memory limit']['pass'] = true;
1953
+
1954
+
1955
+ return $reqs;
1956
+ }
1957
+
1958
+ function ftp_backup($args)
1959
+ {
1960
+ extract($args);
1961
+ //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder, $ftp_site_folder
1962
+ $port = $ftp_port ? $ftp_port : 21; //default port is 21
1963
+ if ($ftp_ssl) {
1964
+ if (function_exists('ftp_ssl_connect')) {
1965
+ $conn_id = ftp_ssl_connect($ftp_hostname,$port);
1966
+ if ($conn_id === false) {
1967
+ return array(
1968
+ 'error' => 'Failed to connect to ' . $ftp_hostname,
1969
+ 'partial' => 1
1970
+ );
1971
+ }
1972
+ } else {
1973
+ return array(
1974
+ 'error' => 'Your server doesn\'t support FTP SSL',
1975
+ 'partial' => 1
1976
+ );
1977
+ }
1978
+ } else {
1979
+ if (function_exists('ftp_connect')) {
1980
+ $conn_id = ftp_connect($ftp_hostname,$port);
1981
+ if ($conn_id === false) {
1982
+ return array(
1983
+ 'error' => 'Failed to connect to ' . $ftp_hostname,
1984
+ 'partial' => 1
1985
+ );
1986
+ }
1987
+ } else {
1988
+ return array(
1989
+ 'error' => 'Your server doesn\'t support FTP',
1990
+ 'partial' => 1
1991
+ );
1992
+ }
1993
+ }
1994
+ $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
1995
+ if ($login === false) {
1996
+ return array(
1997
+ 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
1998
+ 'partial' => 1
1999
+ );
2000
+ }
2001
+
2002
+ if($ftp_passive){
2003
+ @ftp_pasv($conn_id,true);
2004
+ }
2005
+
2006
+ @ftp_mkdir($conn_id, $ftp_remote_folder);
2007
+ if ($ftp_site_folder) {
2008
+ $ftp_remote_folder .= '/' . $this->site_name;
2009
+ }
2010
+ @ftp_mkdir($conn_id, $ftp_remote_folder);
2011
+
2012
+ $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
2013
+
2014
+ if ($upload === false) { //Try ascii
2015
+ $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_ASCII);
2016
+ }
2017
+ @ftp_close($conn_id);
2018
+
2019
+ if ($upload === false) {
2020
+ return array(
2021
+ 'error' => 'Failed to upload file to FTP. Please check your specified path.',
2022
+ 'partial' => 1
2023
+ );
2024
+ }
2025
+
2026
+ return true;
2027
+ }
2028
+
2029
+ function remove_ftp_backup($args)
2030
+ {
2031
+ extract($args);
2032
+ //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
2033
+ $port = $ftp_port ? $ftp_port : 21; //default port is 21
2034
+ if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
2035
+ $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2036
+ } else if (function_exists('ftp_connect')) {
2037
+ $conn_id = ftp_connect($ftp_hostname,$port);
2038
+ }
2039
+
2040
+ if ($conn_id) {
2041
+ $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2042
+ if ($ftp_site_folder)
2043
+ $ftp_remote_folder .= '/' . $this->site_name;
2044
+
2045
+ if($ftp_passive){
2046
+ @ftp_pasv($conn_id,true);
2047
+ }
2048
+
2049
+ $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $backup_file);
2050
+
2051
+ ftp_close($conn_id);
2052
+ }
2053
+
2054
+ }
2055
+
2056
+ function get_ftp_backup($args)
2057
+ {
2058
+ extract($args);
2059
+ //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
2060
+ $port = $ftp_port ? $ftp_port : 21; //default port is 21
2061
+ if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
2062
+ $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2063
+
2064
+ } else if (function_exists('ftp_connect')) {
2065
+ $conn_id = ftp_connect($ftp_hostname,$port);
2066
+ if ($conn_id === false) {
2067
+ return false;
2068
+ }
2069
+ }
2070
+ $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2071
+ if ($login === false) {
2072
+ return false;
2073
+ }
2074
+
2075
+ if ($ftp_site_folder)
2076
+ $ftp_remote_folder .= '/' . $this->site_name;
2077
+
2078
+ if($ftp_passive){
2079
+ @ftp_pasv($conn_id,true);
2080
+ }
2081
+
2082
+ //$temp = ABSPATH . 'iwp_temp_backup.zip';
2083
+ $temp = wp_tempnam('iwp_temp_backup.zip');
2084
+
2085
+ $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
2086
+ if ($get === false) {
2087
+ return false;
2088
+ } else {
2089
+ }
2090
+ ftp_close($conn_id);
2091
+
2092
+ return $temp;
2093
+ }
2094
+
2095
+
2096
+ function dropbox_backup($args){
2097
+ extract($args);
2098
+
2099
+ if(isset($consumer_secret) && !empty($consumer_secret)){
2100
+
2101
+ require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2102
+
2103
+ $dropbox = new Dropbox($consumer_key, $consumer_secret);
2104
+ $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2105
+
2106
+ if ($dropbox_site_folder == true)
2107
+ $dropbox_destination .= '/' . $this->site_name . '/' . basename($backup_file);
2108
+ else
2109
+ $dropbox_destination .= '/' . basename($backup_file);
2110
+
2111
+ try {
2112
+ $dropbox->upload($backup_file, $dropbox_destination, true);
2113
+ } catch (Exception $e) {
2114
+ $this->_log($e->getMessage());
2115
+ return array(
2116
+ 'error' => $e->getMessage(),
2117
+ 'partial' => 1
2118
+ );
2119
+ }
2120
+
2121
+ return true;
2122
+
2123
+ } else {
2124
+ return array(
2125
+ 'error' => 'Please connect your InfiniteWP panel with your Dropbox account.'
2126
+ );
2127
+ }
2128
+
2129
+ }
2130
+
2131
+
2132
+ function remove_dropbox_backup($args) {
2133
+ extract($args);
2134
+
2135
+ require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2136
+
2137
+ $dropbox = new Dropbox($consumer_key, $consumer_secret);
2138
+ $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2139
+
2140
+ if ($dropbox_site_folder == true)
2141
+ $dropbox_destination .= '/' . $this->site_name;
2142
+
2143
+ try {
2144
+ $dropbox->fileopsDelete($dropbox_destination . '/' . $backup_file);
2145
+ } catch (Exception $e) {
2146
+ $this->_log($e->getMessage());
2147
+ /*return array(
2148
+ 'error' => $e->getMessage(),
2149
+ 'partial' => 1
2150
+ );*/
2151
+ }
2152
+
2153
+ //return true;
2154
+ }
2155
+
2156
+
2157
+ function get_dropbox_backup($args) {
2158
+ extract($args);
2159
+
2160
+ require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2161
+
2162
+ $dropbox = new Dropbox($consumer_key, $consumer_secret);
2163
+ $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2164
+
2165
+ if ($dropbox_site_folder == true)
2166
+ $dropbox_destination .= '/' . $this->site_name;
2167
+
2168
+ //$temp = ABSPATH . 'iwp_temp_backup.zip';
2169
+ $temp = wp_tempnam('iwp_temp_backup.zip');
2170
+
2171
+ try {
2172
+
2173
+ $file = $dropbox->download($dropbox_destination.'/'.$backup_file);
2174
+ $handle = @fopen($temp, 'w');
2175
+ $result = fwrite($handle, $file);
2176
+ fclose($handle);
2177
+
2178
+ if($result)
2179
+ return $temp;
2180
+ else
2181
+ return false;
2182
+ } catch (Exception $e) {
2183
+ $this->_log($e->getMessage());
2184
+ return array(
2185
+ 'error' => $e->getMessage(),
2186
+ 'partial' => 1
2187
+ );
2188
+ }
2189
+ }
2190
+
2191
+
2192
+ function amazons3_backup($args)
2193
+ {
2194
+ if ($this->iwp_mmb_function_exists('curl_init')) {
2195
+ require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
2196
+
2197
+ extract($args);
2198
+
2199
+ if ($as3_site_folder == true)
2200
+ $as3_directory .= '/' . $this->site_name;
2201
+
2202
+ try{
2203
+
2204
+ CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true, 'use_ssl'=>false, 'ssl_verification'=>false), '@default' => 'development'));
2205
+ $s3 = new AmazonS3();
2206
+ $response = $s3->create_object($as3_bucket, $as3_directory . '/' . basename($backup_file), array('fileUpload' => $backup_file));
2207
+ $upload = $response->isOk();
2208
+ if($upload) {
2209
+ return true;
2210
+ } else {
2211
+ return array(
2212
+ 'error' => 'Failed to upload to Amazon S3. Please check your details and set upload/delete permissions on your bucket.',
2213
+ 'partial' => 1
2214
+ );
2215
+ }
2216
+
2217
+ }catch (Exception $e){
2218
+ $err = $e->getMessage();
2219
+ if($err){
2220
+ return array(
2221
+ 'error' => 'Failed to upload to AmazonS3 ('.$err.').'
2222
+ );
2223
+ } else {
2224
+ return array(
2225
+ 'error' => 'Failed to upload to Amazon S3.'
2226
+ );
2227
+ }
2228
+ }
2229
+ } else {
2230
+ return array(
2231
+ 'error' => 'You cannot use Amazon S3 on your server. Please enable curl first.',
2232
+ 'partial' => 1
2233
+ );
2234
+ }
2235
+ }
2236
+
2237
+
2238
+ function remove_amazons3_backup($args)
2239
+ {
2240
+ if ($this->iwp_mmb_function_exists('curl_init')) {
2241
+ require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
2242
+ extract($args);
2243
+ if ($as3_site_folder == true)
2244
+ $as3_directory .= '/' . $this->site_name;
2245
+ try{
2246
+ CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true), '@default' => 'development'));
2247
+ $s3 = new AmazonS3();
2248
+ $s3->delete_object($as3_bucket, $as3_directory . '/' . $backup_file);
2249
+ } catch (Exception $e){
2250
+
2251
+ }
2252
+ }
2253
+ }
2254
+
2255
+ function get_amazons3_backup($args)
2256
+ {
2257
+ require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3/sdk.class.php');
2258
+ extract($args);
2259
+ $temp = '';
2260
+ try{
2261
+ CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true), '@default' => 'development'));
2262
+ $s3 = new AmazonS3();
2263
+ if ($as3_site_folder == true)
2264
+ $as3_directory .= '/' . $this->site_name;
2265
+
2266
+ //$temp = ABSPATH . 'iwp_temp_backup.zip';
2267
+ $temp = wp_tempnam('iwp_temp_backup.zip');
2268
+ $s3->get_object($as3_bucket, $as3_directory . '/' . $backup_file, array("fileDownload" => $temp));
2269
+ } catch (Exception $e){
2270
+ return $temp;
2271
+ }
2272
+ return $temp;
2273
+ }
2274
+ //IWP Remove ends here
2275
+
2276
+
2277
+ function schedule_next($type, $schedule)
2278
+ {
2279
+ $schedule = explode("|", $schedule);
2280
+ if (empty($schedule))
2281
+ return false;
2282
+ switch ($type) {
2283
+
2284
+ case 'daily':
2285
+
2286
+ if (isset($schedule[1]) && $schedule[1]) {
2287
+ $delay_time = $schedule[1] * 60;
2288
+ }
2289
+
2290
+ $current_hour = date("H");
2291
+ $schedule_hour = $schedule[0];
2292
+ if ($current_hour >= $schedule_hour){
2293
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 1, date("Y"));
2294
+ //$time ='0001#'.$current_hour.'|'.$schedule_hour;
2295
+
2296
+ }
2297
+
2298
+ else{
2299
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2300
+ //$time ='0000#'.$current_hour.'|'.$schedule_hour;
2301
+ }
2302
+ $time = time() + 30;
2303
+
2304
+
2305
+ break;
2306
+
2307
+
2308
+ case 'weekly':
2309
+ if (isset($schedule[2]) && $schedule[2]) {
2310
+ $delay_time = $schedule[2] * 60;
2311
+ }
2312
+ $current_weekday = date('w');
2313
+ $schedule_weekday = $schedule[1];
2314
+ $current_hour = date("H");
2315
+ $schedule_hour = $schedule[0];
2316
+
2317
+ if ($current_weekday > $schedule_weekday)
2318
+ $weekday_offset = 7 - ($week_day - $task_schedule[1]);
2319
+ else
2320
+ $weekday_offset = $schedule_weekday - $current_weekday;
2321
+
2322
+
2323
+ if (!$weekday_offset) { //today is scheduled weekday
2324
+ if ($current_hour >= $schedule_hour)
2325
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 7, date("Y"));
2326
+ else
2327
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2328
+ } else {
2329
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + $weekday_offset, date("Y"));
2330
+ }
2331
+
2332
+ break;
2333
+
2334
+ case 'monthly':
2335
+ if (isset($schedule[2]) && $schedule[2]) {
2336
+ $delay_time = $schedule[2] * 60;
2337
+ }
2338
+ $current_monthday = date('j');
2339
+ $schedule_monthday = $schedule[1];
2340
+ $current_hour = date("H");
2341
+ $schedule_hour = $schedule[0];
2342
+
2343
+ if ($current_monthday > $schedule_monthday) {
2344
+ $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2345
+ } else if ($current_monthday < $schedule_monthday) {
2346
+ $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2347
+ } else if ($current_monthday == $schedule_monthday) {
2348
+ if ($current_hour >= $schedule_hour)
2349
+ $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2350
+ else
2351
+ $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2352
+ break;
2353
+ }
2354
+
2355
+ break;
2356
+ default:
2357
+ break;
2358
+ }
2359
+
2360
+ if (isset($delay_time) && $delay_time) {
2361
+ $time += $delay_time;
2362
+ }
2363
+
2364
+ return $time;
2365
+ }
2366
+
2367
+
2368
+ //Parse task arguments for info on IWP Admin Panel
2369
+ function get_backup_stats()
2370
+ {
2371
+ $stats = array();
2372
+ $tasks = $this->tasks;
2373
+ if (is_array($tasks) && !empty($tasks)) {
2374
+ foreach ($tasks as $task_name => $info) {
2375
+ if (is_array($info['task_results']) && !empty($info['task_results'])) {
2376
+ foreach ($info['task_results'] as $key => $result) {
2377
+ if (isset($result['server']) && !isset($result['error'])) {
2378
+ if (!file_exists($result['server']['file_path'])) {
2379
+ $info['task_results'][$key]['error'] = 'Backup created but manually removed from server.';
2380
+ }
2381
+ }
2382
+ }
2383
+ }
2384
+ if (is_array($info['task_results']))
2385
+ $stats[$task_name] = $info['task_results'];
2386
+ }
2387
+ }
2388
+ return $stats;
2389
+ }
2390
+
2391
+
2392
+ function get_next_schedules()
2393
+ {
2394
+ $stats = array();
2395
+ $tasks = $this->tasks;
2396
+ if (is_array($tasks) && !empty($tasks)) {
2397
+ foreach ($tasks as $task_name => $info) {
2398
+ $stats[$task_name] = isset($info['task_args']['next']) ? $info['task_args']['next'] : array();
2399
+ }
2400
+ }
2401
+ return $stats;
2402
+ }
2403
+
2404
+
2405
+ function remove_old_backups($task_name)
2406
+ {
2407
+ //Check for previous failed backups first
2408
+ $this->cleanup();
2409
+
2410
+ //Remove by limit
2411
+ $backups = $this->tasks;
2412
+ if ($task_name == 'Backup Now') {
2413
+ $num = 0;
2414
+ } else {
2415
+ $num = 1;
2416
+ }
2417
+
2418
+
2419
+ if ((count($backups[$task_name]['task_results']) - $num) >= $backups[$task_name]['task_args']['limit']) {
2420
+ //how many to remove ?
2421
+ $remove_num = (count($backups[$task_name]['task_results']) - $num - $backups[$task_name]['task_args']['limit']) + 1;
2422
+ for ($i = 0; $i < $remove_num; $i++) {
2423
+ //Remove from the server
2424
+ if (isset($backups[$task_name]['task_results'][$i]['server'])) {
2425
+ @unlink($backups[$task_name]['task_results'][$i]['server']['file_path']);
2426
+ }
2427
+
2428
+ if (isset($backups[$task_name]['task_results'][$i]['ftp'])) {
2429
+ $ftp_file = $backups[$task_name]['task_results'][$i]['ftp'];
2430
+ $args = $backups[$task_name]['task_args']['account_info']['iwp_ftp'];
2431
+ $args['backup_file'] = $ftp_file;
2432
+ $this->remove_ftp_backup($args);
2433
+ }
2434
+
2435
+ if (isset($backups[$task_name]['task_results'][$i]['amazons3'])) {
2436
+ $amazons3_file = $backups[$task_name]['task_results'][$i]['amazons3'];
2437
+ $args = $backups[$task_name]['task_args']['account_info']['iwp_amazon_s3'];
2438
+ $args['backup_file'] = $amazons3_file;
2439
+ $this->remove_amazons3_backup($args);
2440
+ }
2441
+
2442
+ if (isset($backups[$task_name]['task_results'][$i]['dropbox']) && isset($backups[$task_name]['task_args']['account_info']['iwp_dropbox'])) {
2443
+ //To do: dropbox remove
2444
+ $dropbox_file = $backups[$task_name]['task_results'][$i]['dropbox'];
2445
+ $args = $backups[$task_name]['task_args']['account_info']['iwp_dropbox'];
2446
+ $args['backup_file'] = $dropbox_file;
2447
+ $this->remove_dropbox_backup($args);
2448
+ }
2449
+ //Remove database backup info
2450
+ unset($backups[$task_name]['task_results'][$i]);
2451
+
2452
+ } //end foreach
2453
+
2454
+ if (is_array($backups[$task_name]['task_results']))
2455
+ $backups[$task_name]['task_results'] = array_values($backups[$task_name]['task_results']);
2456
+ else
2457
+ $backups[$task_name]['task_results']=array();
2458
+
2459
+ $this->update_tasks($backups);
2460
+
2461
+ return true;
2462
+ }
2463
+ }
2464
+
2465
+ /**
2466
+ * Delete specified backup
2467
+ * Args: $task_name, $result_id
2468
+ */
2469
+
2470
+ function delete_backup($args)
2471
+ {
2472
+ if (empty($args))
2473
+ return false;
2474
+ extract($args);
2475
+
2476
+ $tasks = $this->tasks;
2477
+ $task = $tasks[$task_name];
2478
+ $backups = $task['task_results'];
2479
+ $backup = $backups[$result_id];
2480
+
2481
+ if (isset($backup['server'])) {
2482
+ @unlink($backup['server']['file_path']);
2483
+ }
2484
+
2485
+ /*
2486
+ //IWP Remove starts here//IWP Remove ends here
2487
+ */
2488
+ //Remove from ftp
2489
+ if (isset($backup['ftp'])) {
2490
+ $ftp_file = $backup['ftp'];
2491
+ $args = $tasks[$task_name]['task_args']['account_info']['iwp_ftp'];
2492
+ $args['backup_file'] = $ftp_file;
2493
+ $this->remove_ftp_backup($args);
2494
+ }
2495
+
2496
+ if (isset($backup['amazons3'])) {
2497
+ $amazons3_file = $backup['amazons3'];
2498
+ $args = $tasks[$task_name]['task_args']['account_info']['iwp_amazon_s3'];
2499
+ $args['backup_file'] = $amazons3_file;
2500
+ $this->remove_amazons3_backup($args);
2501
+ }
2502
+
2503
+ if (isset($backup['dropbox'])) {
2504
+ $dropbox_file = $backup['dropbox'];
2505
+ $args = $tasks[$task_name]['task_args']['account_info']['iwp_dropbox'];
2506
+ $args['backup_file'] = $dropbox_file;
2507
+ $this->remove_dropbox_backup($args);
2508
+ }
2509
+
2510
+
2511
+ unset($backups[$result_id]);
2512
+
2513
+ if (count($backups)) {
2514
+ $tasks[$task_name]['task_results'] = $backups;
2515
+ } else {
2516
+ unset($tasks[$task_name]['task_results']);
2517
+ }
2518
+
2519
+ $this->update_tasks($tasks);
2520
+ //update_option('iwp_client_backup_tasks', $tasks);
2521
+ return true;
2522
+
2523
+ }
2524
+
2525
+ function cleanup()
2526
+ {
2527
+ $tasks = $this->tasks;
2528
+ $backup_folder = WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups/';
2529
+ $backup_folder_new = IWP_BACKUP_DIR . '/';
2530
+ $files = glob($backup_folder . "*");
2531
+ $new = glob($backup_folder_new . "*");
2532
+
2533
+ //Failed db files first
2534
+ $db_folder = IWP_DB_DIR . '/';
2535
+ $db_files = glob($db_folder . "*");
2536
+ if (is_array($db_files) && !empty($db_files)) {
2537
+ foreach ($db_files as $file) {
2538
+ @unlink($file);
2539
+ }
2540
+ @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
2541
+ @rmdir(IWP_DB_DIR);
2542
+ }
2543
+
2544
+
2545
+ //clean_old folder?
2546
+ if ((basename($files[0]) == 'index.php' && count($files) == 1) || (!empty($files))) { //USE (!empty($files)
2547
+ foreach ($files as $file) {
2548
+ @unlink($file);
2549
+ }
2550
+ @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups');
2551
+ @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client'));
2552
+ }
2553
+
2554
+ if (!empty($new)) {
2555
+ foreach ($new as $b) {
2556
+ $files[] = $b;
2557
+ }
2558
+ }
2559
+ $deleted = array();
2560
+
2561
+ if (is_array($files) && count($files)) {
2562
+ $results = array();
2563
+ if (!empty($tasks)) {
2564
+ foreach ((array) $tasks as $task) {
2565
+ if (isset($task['task_results']) && count($task['task_results'])) {
2566
+ foreach ($task['task_results'] as $backup) {
2567
+ if (isset($backup['server'])) {
2568
+ $results[] = $backup['server']['file_path'];
2569
+ }
2570
+ }
2571
+ }
2572
+ }
2573
+ }
2574
+
2575
+ $num_deleted = 0;
2576
+ foreach ($files as $file) {
2577
+ if (!in_array($file, $results) && basename($file) != 'index.php') {
2578
+ @unlink($file);
2579
+ $deleted[] = basename($file);
2580
+ $num_deleted++;
2581
+ }
2582
+ }
2583
+ }
2584
+
2585
+
2586
+
2587
+ return $deleted;
2588
+ }
2589
+
2590
+
2591
+ /*
2592
+ */
2593
+
2594
+ function validate_task($args, $url)
2595
+ {
2596
+ if (!class_exists('WP_Http')) {
2597
+ include_once(ABSPATH . WPINC . '/class-http.php');
2598
+ }
2599
+ $params = array();
2600
+ $params['body'] = $args;
2601
+ $result = wp_remote_post($url, $params);
2602
+ if (is_array($result) && $result['body'] == 'iwp_delete_task') {
2603
+ //$tasks = $this->get_backup_settings();
2604
+ $tasks = $this->tasks;
2605
+ unset($tasks[$args['task_name']]);
2606
+ $this->update_tasks($tasks);
2607
+ $this->cleanup();
2608
+ exit;
2609
+ } elseif(is_array($result) && $result['body'] == 'iwp_pause_task'){
2610
+ return 'paused';
2611
+ }
2612
+
2613
+ return 'ok';
2614
+ }
2615
+
2616
+ function update_status($task_name, $status, $completed = false)
2617
+ {
2618
+ /* Statuses:
2619
+ 0 - Backup started
2620
+ 1 - DB dump
2621
+ 2 - DB ZIP
2622
+ 3 - Files ZIP
2623
+ 4 - Amazon S3
2624
+ 5 - Dropbox
2625
+ 6 - FTP
2626
+ 7 - Email
2627
+ 100 - Finished
2628
+ */
2629
+ //if ($task_name != 'Backup Now') {
2630
+ $tasks = $this->tasks;
2631
+ $index = count($tasks[$task_name]['task_results']) - 1;
2632
+ //!is_array($tasks[$task_name]['task_results'][$index]['status']) &&
2633
+ if (!is_array($tasks[$task_name]['task_results'][$index]['backhack_status'])) {
2634
+ //$tasks[$task_name]['task_results'][$index]['status'] = array();
2635
+ $tasks[$task_name]['task_results'][$index]['backhack_status'] = array();
2636
+ }
2637
+ $tasks[$task_name]['task_results'][$index]['backhack_status']['adminHistoryID'] = $GLOBALS['IWP_CLIENT_HISTORY_ID'];
2638
+ if (!$completed) {
2639
+ //$tasks[$task_name]['task_results'][$index]['status'][] = (int) $status * (-1);
2640
+ $tasks[$task_name]['task_results'][$index]['backhack_status'][$status]['start'] = microtime(true);
2641
+ } else {
2642
+ $status_index = count($tasks[$task_name]['task_results'][$index]['status']) - 1;
2643
+ //$tasks[$task_name]['task_results'][$index]['status'][$status_index] = abs($tasks[$task_name]['task_results'][$index]['status'][$status_index]);
2644
+ $tasks[$task_name]['task_results'][$index]['backhack_status'][$status]['end'] = microtime(true);
2645
+ }
2646
+
2647
+ $this->update_tasks($tasks);
2648
+ //update_option('iwp_client_backup_tasks',$tasks);
2649
+ //}
2650
+ }
2651
+
2652
+ function update_tasks($tasks)
2653
+ {
2654
+ $this->tasks = $tasks;
2655
+ update_option('iwp_client_backup_tasks', $tasks);
2656
+ }
2657
+
2658
+ function wpdb_reconnect(){
2659
+ global $wpdb;
2660
+ $old_wpdb = $wpdb;
2661
+ //Reconnect to avoid timeout problem after ZIP files
2662
+ if(class_exists('wpdb') && function_exists('wp_set_wpdb_vars')){
2663
+ @mysql_close($wpdb->dbh);
2664
+ $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
2665
+ wp_set_wpdb_vars();
2666
+ $wpdb->options = $old_wpdb->options;//fix for multi site full backup
2667
+ }
2668
+ }
2669
+
2670
+ function replace_htaccess($url, $remote_abspath)
2671
+ {
2672
+ global $wp_filesystem;
2673
+ //$file = @file_get_contents(ABSPATH.'.htaccess');
2674
+ $file = $wp_filesystem->get_contents($remote_abspath.'.htaccess');
2675
+ if ($file && strlen($file)) {
2676
+ $args = parse_url($url);
2677
+ $string = rtrim($args['path'], "/");
2678
+ $regex = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
2679
+ $replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
2680
+ $file = preg_replace($regex, $replace, $file);
2681
+ //@file_put_contents(ABSPATH.'.htaccess', $file);
2682
+ $wp_filesystem->put_contents($remote_abspath.'.htaccess', $file);
2683
+ }
2684
+ }
2685
+
2686
+ function check_cron_remove(){
2687
+ if(empty($this->tasks) || (count($this->tasks) == 1 && isset($this->tasks['Backup Now'])) ){
2688
+ wp_clear_scheduled_hook('iwp_client_backup_tasks');
2689
+ exit;
2690
+ }
2691
+ }
2692
+
2693
+
2694
+ public function readd_tasks( $params = array() ){
2695
+ global $iwp_mmb_core;
2696
+
2697
+ if( empty($params) || !isset($params['backups']) )
2698
+ return $params;
2699
+
2700
+ $before = array();
2701
+ $tasks = $params['backups'];
2702
+ if( !empty($tasks) ){
2703
+ $iwp_mmb_backup = new IWP_MMB_Backup();
2704
+
2705
+ if( function_exists( 'wp_next_scheduled' ) ){
2706
+ if ( !wp_next_scheduled('iwp_client_backup_tasks') ) {
2707
+ wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
2708
+ }
2709
+ }
2710
+
2711
+ foreach( $tasks as $task ){
2712
+ $before[$task['task_name']] = array();
2713
+
2714
+ if(isset($task['secure'])){
2715
+ if($decrypted = $iwp_mmb_core->_secure_data($task['secure'])){
2716
+ $decrypted = maybe_unserialize($decrypted);
2717
+ if(is_array($decrypted)){
2718
+ foreach($decrypted as $key => $val){
2719
+ if(!is_numeric($key))
2720
+ $task[$key] = $val;
2721
+ }
2722
+ unset($task['secure']);
2723
+ } else
2724
+ $task['secure'] = $decrypted;
2725
+ }
2726
+
2727
+ }
2728
+ if (isset($task['account_info']) && is_array($task['account_info'])) { //only if sends from panel first time(secure data)
2729
+ $task['args']['account_info'] = $task['account_info'];
2730
+ }
2731
+
2732
+ $before[$task['task_name']]['task_args'] = $task['args'];
2733
+ $before[$task['task_name']]['task_args']['next'] = $iwp_mmb_backup->schedule_next($task['args']['type'], $task['args']['schedule']);
2734
+ }
2735
+ }
2736
+ update_option('iwp_client_backup_tasks', $before);
2737
+
2738
+ unset($params['backups']);
2739
+ return $params;
2740
+ }
2741
+
2742
+ function is_server_writable(){
2743
+ if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), ABSPATH) != 'direct'))
2744
+ return false;
2745
+ else
2746
+ return true;
2747
+ }
2748
+ }
2749
+
2750
+ /*if( function_exists('add_filter') ){
2751
+ add_filter( 'iwp_website_add', 'IWP_MMB_Backup::readd_tasks' );
2752
+ }*/
2753
+
2754
+ if(!function_exists('get_all_files_from_dir')) {
2755
+ /**
2756
+ * Get all files in directory
2757
+ *
2758
+ * @param string $path Relative or absolute path to folder
2759
+ * @param array $exclude List of excluded files or folders, relative to $path
2760
+ * @return array List of all files in folder $path, exclude all files in $exclude array
2761
+ */
2762
+ function get_all_files_from_dir($path, $exclude = array()) {
2763
+ if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
2764
+ global $directory_tree, $ignore_array;
2765
+ $directory_tree = array();
2766
+ foreach ($exclude as $file) {
2767
+ if (!in_array($file, array('.', '..'))) {
2768
+ if ($file[0] === "/") $path = substr($file, 1);
2769
+ $ignore_array[] = "$path/$file";
2770
+ }
2771
+ }
2772
+ get_all_files_from_dir_recursive($path);
2773
+ return $directory_tree;
2774
+ }
2775
+ }
2776
+
2777
+ if (!function_exists('get_all_files_from_dir_recursive')) {
2778
+ /**
2779
+ * Get all files in directory,
2780
+ * wrapped function which writes in global variable
2781
+ * and exclued files or folders are read from global variable
2782
+ *
2783
+ * @param string $path Relative or absolute path to folder
2784
+ * @return void
2785
+ */
2786
+ function get_all_files_from_dir_recursive($path) {
2787
+ if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
2788
+ global $directory_tree, $ignore_array;
2789
+ $directory_tree_temp = array();
2790
+ $dh = @opendir($path);
2791
+
2792
+ while (false !== ($file = @readdir($dh))) {
2793
+ if (!in_array($file, array('.', '..'))) {
2794
+ if (!in_array("$path/$file", $ignore_array)) {
2795
+ if (!is_dir("$path/$file")) {
2796
+ $directory_tree[] = "$path/$file";
2797
+ } else {
2798
+ get_all_files_from_dir_recursive("$path/$file");
2799
+ }
2800
+ }
2801
+ }
2802
+ }
2803
+ @closedir($dh);
2804
+ }
2805
+ }
2806
+
2807
  ?>
init.php CHANGED
@@ -4,7 +4,7 @@ Plugin Name: InfiniteWP - Client
4
  Plugin URI: http://infinitewp.com/
5
  Description: This is the client plugin of InfiniteWP that communicates with the InfiniteWP Admin panel.
6
  Author: Revmakx
7
- Version: 1.2.3
8
  Author URI: http://www.revmakx.com
9
  */
10
  /************************************************************
@@ -26,7 +26,7 @@ Author URI: http://www.revmakx.com
26
  **************************************************************/
27
 
28
  if(!defined('IWP_MMB_CLIENT_VERSION'))
29
- define('IWP_MMB_CLIENT_VERSION', '1.2.3');
30
 
31
 
32
  if ( !defined('IWP_MMB_XFRAME_COOKIE')){
4
  Plugin URI: http://infinitewp.com/
5
  Description: This is the client plugin of InfiniteWP that communicates with the InfiniteWP Admin panel.
6
  Author: Revmakx
7
+ Version: 1.2.4
8
  Author URI: http://www.revmakx.com
9
  */
10
  /************************************************************
26
  **************************************************************/
27
 
28
  if(!defined('IWP_MMB_CLIENT_VERSION'))
29
+ define('IWP_MMB_CLIENT_VERSION', '1.2.4');
30
 
31
 
32
  if ( !defined('IWP_MMB_XFRAME_COOKIE')){
readme.txt CHANGED
@@ -2,7 +2,7 @@
2
  Contributors: infinitewp
3
  Tags: admin, administration, amazon, api, authentication, automatic, dashboard, dropbox, events, integration, manage, multisite, multiple, notification, performance, s3, security, seo, stats, tracking, infinitewp, updates, backup, restore, iwp, infinite
4
  Requires at least: 3.0
5
- Tested up to: 3.6
6
  Stable tag: trunk
7
 
8
  Install this plugin on unlimited sites and manage them all from a central dashboard.
@@ -48,6 +48,9 @@ Credits: [Vladimir Prelovac](http://prelovac.com/vladimir) for his worker plugin
48
 
49
  == Changelog ==
50
 
 
 
 
51
  = 1.2.3 =
52
  * Fix: Gravity forms update support
53
 
2
  Contributors: infinitewp
3
  Tags: admin, administration, amazon, api, authentication, automatic, dashboard, dropbox, events, integration, manage, multisite, multiple, notification, performance, s3, security, seo, stats, tracking, infinitewp, updates, backup, restore, iwp, infinite
4
  Requires at least: 3.0
5
+ Tested up to: 3.6.1
6
  Stable tag: trunk
7
 
8
  Install this plugin on unlimited sites and manage them all from a central dashboard.
48
 
49
  == Changelog ==
50
 
51
+ = 1.2.4 =
52
+ * Fix: Empty backup list when schedule backup is created/modified
53
+
54
  = 1.2.3 =
55
  * Fix: Gravity forms update support
56