PluginProbe
ManageWP Worker / 3.9.21
ManageWP Worker v3.9.21
4.9.38 4.9.37 4.9.36 4.9.35 4.9.34 3.8.7 3.8.8 3.9.0 3.9.1 3.9.10 3.9.11 3.9.12 3.9.13 3.9.14 3.9.15 3.9.16 3.9.17 3.9.18 3.9.19 3.9.2 3.9.20 3.9.21 3.9.22 3.9.23 3.9.24 All 73 releases
worker / backup.class.php

backup.class.php in ManageWP Worker 3.9.21, at backup.class.php

2,302 lines 85.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*************************************************************
3 *
4 * backup.class.php
5 *
6 * Manage Backups
7 *
8 *
9 * Copyright (c) 2011 Prelovac Media
10 * www.prelovac.com
11 **************************************************************/
12 if(basename($_SERVER['SCRIPT_FILENAME']) == "backup.class.php"):
13 echo "Sorry but you cannot browse this file directly!";
14 exit;
15 endif;
16 define('MWP_BACKUP_DIR', WP_CONTENT_DIR . '/managewp/backups');
17 define('MWP_DB_DIR', MWP_BACKUP_DIR . '/mwp_db');
18
19 $zip_errors = array(
20 'No error',
21 'No error',
22 'Unexpected end of zip file',
23 'A generic error in the zipfile format was detected.',
24 'zip was unable to allocate itself memory',
25 'A severe error in the zipfile format was detected',
26 'Entry too large to be split with zipsplit',
27 'Invalid comment format',
28 'zip -T failed or out of memory',
29 'The user aborted zip prematurely',
30 'zip encountered an error while using a temp file',
31 'Read or seek error',
32 'zip has nothing to do',
33 'Missing or empty zip file',
34 'Error writing to a file',
35 'zip was unable to create a file to write to',
36 'bad command line parameters',
37 'no error',
38 'zip could not open a specified file to read'
39 );
40 $unzip_errors = array(
41 'No error',
42 'One or more warning errors were encountered, but processing completed successfully anyway',
43 'A generic error in the zipfile format was detected',
44 'A severe error in the zipfile format was detected.',
45 'unzip was unable to allocate itself memory.',
46 'unzip was unable to allocate memory, or encountered an encryption error',
47 'unzip was unable to allocate memory during decompression to disk',
48 'unzip was unable allocate memory during in-memory decompression',
49 'unused',
50 'The specified zipfiles were not found',
51 'Bad command line parameters',
52 'No matching files were found',
53 50 => 'The disk is (or was) full during extraction',
54 51 => 'The end of the ZIP archive was encountered prematurely.',
55 80 => 'The user aborted unzip prematurely.',
56 81 => 'Testing or extraction of one or more files failed due to unsupported compression methods or unsupported decryption.',
57 82 => 'No files were found due to bad decryption password(s)'
58 );
59
60
61 class MMB_Backup extends MMB_Core
62 {
63 var $site_name;
64 var $statuses;
65 var $tasks;
66 var $s3;
67 var $ftp;
68 var $dropbox;
69 function __construct()
70 {
71 parent::__construct();
72 $this->site_name = str_replace(array(
73 "_",
74 "/",
75 "~"
76 ), array(
77 "",
78 "-",
79 "-"
80 ), rtrim($this->remove_http(get_bloginfo('url')), "/"));
81 $this->statuses = array(
82 'db_dump' => 1,
83 'db_zip' => 2,
84 'files_zip' => 3,
85 's3' => 4,
86 'dropbox' => 5,
87 'ftp' => 6,
88 'email' => 7,
89 'finished' => 100
90 );
91 $this->tasks = get_option('mwp_backup_tasks');
92 }
93
94 function set_memory()
95 {
96 $changed = array('execution_time' => 0, 'memory_limit' => 0);
97
98 $memory_limit = trim(ini_get('memory_limit'));
99 $last = strtolower(substr($memory_limit, -1));
100
101 if($last == 'g')
102 $memory_limit = ((int) $memory_limit)*1024;
103 else if($last == 'm')
104 $memory_limit = (int) $memory_limit;
105 if($last == 'k')
106 $memory_limit = ((int) $memory_limit)/1024;
107
108 if ( $memory_limit < 384 ) {
109 @ini_set('memory_limit', '384M');
110 $changed['memory_limit'] = 1;
111 }
112
113 if ( (int) @ini_get('max_execution_time') < 600 ) {
114 @set_time_limit(600); //ten minutes
115 $changed['execution_time'] = 1;
116 }
117
118 return $changed;
119
120 }
121
122 function get_backup_settings()
123 {
124 $backup_settings = get_option('mwp_backup_tasks');
125
126 if (!empty($backup_settings))
127 return $backup_settings;
128 else
129 return false;
130 }
131
132 function set_backup_task($params)
133 {
134 //$params => [$task_name, $args, $error]
135 if (!empty($params)) {
136
137 //Make sure backup cron job is set
138 if (!wp_next_scheduled('mwp_backup_tasks')) {
139 wp_schedule_event( time(), 'tenminutes', 'mwp_backup_tasks' );
140 }
141
142 extract($params);
143
144 //$before = $this->get_backup_settings();
145 $before = $this->tasks;
146 if (!$before || empty($before))
147 $before = array();
148
149 if (isset($args['remove'])) {
150 unset($before[$task_name]);
151 $return = array(
152 'removed' => true
153 );
154 } else {
155 if (isset($params['account_info']) && is_array($params['account_info'])) { //only if sends from master first time(secure data)
156 $args['account_info'] = $account_info;
157 }
158
159 $before[$task_name]['task_args'] = $args;
160 if (strlen($args['schedule']))
161 $before[$task_name]['task_args']['next'] = $this->schedule_next($args['type'], $args['schedule']);
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 ($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'] = $time;
180 }
181
182 $this->update_tasks($before);
183 //update_option('mwp_backup_tasks', $before);
184
185 if ($task_name == 'Backup Now') {
186 $result = $this->backup($args, $task_name);
187 $backup_settings = $this->tasks;
188
189 if (is_array($result) && array_key_exists('error', $result)) {
190 $return = $result;
191 } else {
192 $return = $backup_settings[$task_name];
193 }
194 }
195 return $return;
196 }
197
198
199
200 return false;
201 }
202
203 //Cron check
204 function check_backup_tasks()
205 {
206
207 $this->check_cron_remove();
208
209 $settings = $this->tasks;
210 if (is_array($settings) && !empty($settings)) {
211 foreach ($settings as $task_name => $setting) {
212 if ($setting['task_args']['next'] && $setting['task_args']['next'] < time()) {
213 //if ($setting['task_args']['next'] && $_GET['force_backup']) {
214 if ($setting['task_args']['url'] && $setting['task_args']['task_id'] && $setting['task_args']['site_key']) {
215 //Check orphan task
216 $check_data = array(
217 'task_name' => $task_name,
218 'task_id' => $setting['task_args']['task_id'],
219 'site_key' => $setting['task_args']['site_key']
220 );
221
222 $check = $this->validate_task($check_data, $setting['task_args']['url']);
223
224 }
225
226 $update = array(
227 'task_name' => $task_name,
228 'args' => $settings[$task_name]['task_args']
229 );
230
231
232 if($check != 'paused'){
233 $update['time'] = time();
234 }
235
236 //Update task with next schedule
237 $this->set_backup_task($update);
238
239 if($check == 'paused'){
240 continue;
241 }
242
243
244 $result = $this->backup($setting['task_args'], $task_name);
245 $error = '';
246 if (is_array($result) && array_key_exists('error', $result)) {
247 $error = $result;
248 $this->set_backup_task(array(
249 'task_name' => $task_name,
250 'args' => $settings[$task_name]['task_args'],
251 'error' => $error
252 ));
253 } else {
254 $error = '';
255 }
256 break; //Only one backup per cron
257 }
258 }
259 }
260
261 }
262
263 function task_now($task_name){
264
265 $settings = $this->tasks;
266 if(!array_key_exists($task_name,$settings)){
267 return array('error' => $task_name." does not exist.");
268 } else {
269 $setting = $settings[$task_name];
270 }
271
272 $this->set_backup_task(array(
273 'task_name' => $task_name,
274 'args' => $settings[$task_name]['task_args'],
275 'time' => time()
276 ));
277
278 //Run backup
279 $result = $this->backup($setting['task_args'], $task_name);
280
281 //Check for error
282 if (is_array($result) && array_key_exists('error', $result)) {
283 $this->set_backup_task(array(
284 'task_name' => $task_name,
285 'args' => $settings[$task_name]['task_args'],
286 'error' => $result
287 ));
288 return $result;
289 } else {
290 return $this->get_backup_stats();
291 }
292 }
293
294
295
296 /*
297 * If Task Name not set then it's manual backup
298 * Backup args:
299 * type -> db, full
300 * what -> daily, weekly, monthly
301 * account_info -> ftp, amazons3, dropbox
302 * exclude-> array of paths to exclude from backup
303 */
304
305 function backup($args, $task_name = false)
306 {
307
308 $this->_log($this->tasks);
309
310 if (!$args || empty($args))
311 return false;
312
313 extract($args); //extract settings
314
315 //Try increase memory limit and execution time
316 $this->set_memory();
317
318 //Remove old backup(s)
319 $this->remove_old_backups($task_name);
320
321
322
323 $new_file_path = MWP_BACKUP_DIR;
324
325 if (!file_exists($new_file_path)) {
326 if (!mkdir($new_file_path, 0755, true))
327 return array(
328 'error' => 'Permission denied, make sure you have write permission to wp-content folder.'
329 );
330 }
331
332 @file_put_contents($new_file_path . '/index.php', ''); //safe
333
334 //Prepare .zip file name
335 $hash = md5(time());
336 $label = $type ? $type : 'manual';
337 $backup_file = $new_file_path . '/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
338 $backup_url = WP_CONTENT_URL . '/managewp/backups/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
339
340 //Optimize tables?
341 if (isset($optimize_tables) && !empty($optimize_tables)) {
342 $this->optimize_tables();
343 }
344
345 //What to backup - db or full?
346 if (trim($what) == 'db') {
347 //Take database backup
348 $this->update_status($task_name, $this->statuses['db_dump']);
349 $db_result = $this->backup_db();
350 if ($db_result == false) {
351 return array(
352 'error' => 'Failed to backup database.'
353 );
354 } else if (is_array($db_result) && isset($db_result['error'])) {
355 return array(
356 'error' => $db_result['error']
357 );
358 } else {
359 $this->update_status($task_name, $this->statuses['db_dump'], true);
360 $this->update_status($task_name, $this->statuses['db_zip']);
361
362 $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
363 $comp_level = $disable_comp ? '-0' : '-1';
364
365 @file_put_contents(MWP_BACKUP_DIR.'/mwp_db/index.php', '');
366 chdir(MWP_BACKUP_DIR);
367 $zip = $this->get_zip();
368 $command = "$zip -q -r $comp_level $backup_file 'mwp_db'";
369 ob_start();
370 $result = $this->mmb_exec($command);
371 ob_get_clean();
372
373 if (!$result) { // fallback to pclzip
374 define('PCLZIP_TEMPORARY_DIR', MWP_BACKUP_DIR . '/');
375 require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
376 $archive = new PclZip($backup_file);
377 if ($disable_comp) {
378 $result = $archive->add($db_result, PCLZIP_OPT_REMOVE_PATH, MWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION);
379 } else {
380 $result = $archive->add($db_result, PCLZIP_OPT_REMOVE_PATH, MWP_BACKUP_DIR);
381 }
382 @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
383 @unlink($db_result);
384 @rmdir(MWP_DB_DIR);
385
386 if (!$result) {
387 return array(
388 'error' => 'Failed to zip database (pclZip - ' . $archive->error_code . '): .' . $archive->error_string
389 );
390 }
391 }
392 @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
393 @unlink($db_result);
394 @rmdir(MWP_DB_DIR);
395
396 if (!$result) {
397 return array(
398 'error' => 'Failed to zip database.'
399 );
400 }
401 $this->update_status($task_name, $this->statuses['db_zip'], true);
402 }
403 } elseif (trim($what) == 'full') {
404 $content_backup = $this->backup_full($task_name, $backup_file, $exclude, $include);
405 if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
406 return array(
407 'error' => $content_backup['error']
408 );
409 }
410 }
411
412 //Update backup info
413 if ($task_name) {
414 //backup task (scheduled)
415 $backup_settings = $this->tasks;
416 $paths = array();
417 $size = ceil(filesize($backup_file) / 1024);
418
419 if ($size > 1000) {
420 $paths['size'] = ceil($size / 1024) . "Mb";
421 } else {
422 $paths['size'] = $size . 'kb';
423 }
424
425 if ($task_name != 'Backup Now') {
426 if (!$backup_settings[$task_name]['task_args']['del_host_file']) {
427 $paths['server'] = array(
428 'file_path' => $backup_file,
429 'file_url' => $backup_url
430 );
431 }
432 } else {
433 $paths['server'] = array(
434 'file_path' => $backup_file,
435 'file_url' => $backup_url
436 );
437 }
438
439 if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_ftp'])) {
440 $paths['ftp'] = basename($backup_url);
441 }
442
443 if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_amazon_s3'])) {
444 $paths['amazons3'] = basename($backup_url);
445 }
446
447 if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_dropbox'])) {
448 $paths['dropbox'] = basename($backup_url);
449 }
450
451 if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_email'])) {
452 $paths['email'] = basename($backup_url);
453 }
454
455 $temp = $backup_settings[$task_name]['task_results'];
456 $temp = array_values($temp);
457 $paths['time'] = time();
458
459 if ($task_name != 'Backup Now') {
460 $paths['status'] = $temp[count($temp) - 1]['status'];
461 $temp[count($temp) - 1] = $paths;
462
463 } else {
464 $temp[count($temp)] = $paths;
465 }
466
467 $backup_settings[$task_name]['task_results'] = $temp;
468 $this->update_tasks($backup_settings);
469 //update_option('mwp_backup_tasks', $backup_settings);
470 }
471
472
473 //Additional: Email, ftp, amazon_s3, dropbox...
474
475 if ($task_name != 'Backup Now') {
476 if (isset($account_info['mwp_ftp']) && !empty($account_info['mwp_ftp'])) {
477 $this->update_status($task_name, $this->statuses['ftp']);
478 $account_info['mwp_ftp']['backup_file'] = $backup_file;
479 $ftp_result = $this->ftp_backup($account_info['mwp_ftp']);
480
481 if ($ftp_result !== true && $del_host_file) {
482 @unlink($backup_file);
483 }
484
485 if (is_array($ftp_result) && isset($ftp_result['error'])) {
486 return $ftp_result;
487 }
488 $this->wpdb_reconnect();
489 $this->update_status($task_name, $this->statuses['ftp'], true);
490 }
491
492 if (isset($account_info['mwp_amazon_s3']) && !empty($account_info['mwp_amazon_s3'])) {
493 $this->update_status($task_name, $this->statuses['s3']);
494 $account_info['mwp_amazon_s3']['backup_file'] = $backup_file;
495 $amazons3_result = $this->amazons3_backup($account_info['mwp_amazon_s3']);
496 if ($amazons3_result !== true && $del_host_file) {
497 @unlink($backup_file);
498 }
499 if (is_array($amazons3_result) && isset($amazons3_result['error'])) {
500 return $amazons3_result;
501 }
502 $this->wpdb_reconnect();
503 $this->update_status($task_name, $this->statuses['s3'], true);
504 }
505
506 if (isset($account_info['mwp_dropbox']) && !empty($account_info['mwp_dropbox'])) {
507 $this->update_status($task_name, $this->statuses['dropbox']);
508 $account_info['mwp_dropbox']['backup_file'] = $backup_file;
509 $dropbox_result = $this->dropbox_backup($account_info['mwp_dropbox']);
510 if ($dropbox_result !== true && $del_host_file) {
511 @unlink($backup_file);
512 }
513
514 if (is_array($dropbox_result) && isset($dropbox_result['error'])) {
515 return $dropbox_result;
516 }
517 $this->wpdb_reconnect();
518 $this->update_status($task_name, $this->statuses['dropbox'], true);
519 }
520
521 if (isset($account_info['mwp_email']) && !empty($account_info['mwp_email'])) {
522 $this->update_status($task_name, $this->statuses['email']);
523 $account_info['mwp_email']['task_name'] = $task_name;
524 $account_info['mwp_email']['file_path'] = $backup_file;
525
526 $email_result = $this->email_backup($account_info['mwp_email']);
527 if (is_array($email_result) && isset($email_result['error'])) {
528 return $email_result;
529 }
530 $this->update_status($task_name, $this->statuses['email'], true);
531 }
532
533 if ($del_host_file) {
534 @unlink($backup_file);
535 }
536
537 } //end additional
538
539 //$this->update_status($task_name,$this->statuses['finished'],true);
540 return $backup_url; //Return url to backup file
541 }
542
543 function backup_full($task_name, $backup_file, $exclude = array(), $include = array())
544 {
545 global $zip_errors;
546 $sys = substr(PHP_OS, 0, 3);
547
548 $this->update_status($task_name, $this->statuses['db_dump']);
549 $db_result = $this->backup_db();
550
551 if ($db_result == false) {
552 return array(
553 'error' => 'Failed to backup database.'
554 );
555 } else if (is_array($db_result) && isset($db_result['error'])) {
556 return array(
557 'error' => $db_result['error']
558 );
559 }
560
561 $this->update_status($task_name, $this->statuses['db_dump'], true);
562 $this->update_status($task_name, $this->statuses['db_zip']);
563 $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
564 $comp_level = $disable_comp ? '-0' : '-1';
565 @file_put_contents(MWP_BACKUP_DIR.'/mwp_db/index.php', '');
566 $zip = $this->get_zip();
567 //Add database file
568 chdir(MWP_BACKUP_DIR);
569 $command = "$zip -q -r $comp_level $backup_file 'mwp_db'";
570 ob_start();
571 $result = $this->mmb_exec($command);
572 ob_get_clean();
573
574
575 if (!$result) {
576 $this->_log("DB zip fallback to pclZip");
577 define('PCLZIP_TEMPORARY_DIR', MWP_BACKUP_DIR . '/');
578 require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
579 $archive = new PclZip($backup_file);
580
581 if ($disable_comp) {
582 $result_db = $archive->add($db_result, PCLZIP_OPT_REMOVE_PATH, MWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION);
583 } else {
584 $result_db = $archive->add($db_result, PCLZIP_OPT_REMOVE_PATH, MWP_BACKUP_DIR);
585 }
586 @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
587 @unlink($db_result);
588 @rmdir(MWP_DB_DIR);
589
590 if (!$result_db) {
591 return array(
592 'error' => 'Failed to zip database. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
593 );
594 }
595 }
596 @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
597 @unlink($db_result);
598 @rmdir(MWP_DB_DIR);
599
600 $this->update_status($task_name, $this->statuses['db_zip'], true);
601
602
603 //Always remove backup folders
604 $remove = array(
605 trim(basename(WP_CONTENT_DIR)) . "/managewp/backups",
606 trim(basename(WP_CONTENT_DIR)) . "/" . md5('mmb-worker') . "/mwp_backups"
607 );
608
609 //Exclude paths
610 $exclude_data = "-x";
611
612 $exclude_file_data = '';
613
614 if (!empty($exclude)) {
615 foreach ($exclude as $data) {
616 if (is_dir(ABSPATH . $data)) {
617 if ($sys == 'WIN')
618 $exclude_data .= " $data/*.*";
619 else
620 $exclude_data .= " '$data/*'";
621
622
623 } else {
624 if ($sys == 'WIN'){
625 if(file_exists(ABSPATH . $data)){
626 $exclude_data .= " $data";
627 $exclude_file_data .= " $data";
628 }
629 } else {
630 if(file_exists(ABSPATH . $data)){
631 $exclude_data .= " '$data'";
632 $exclude_file_data .= " '$data'";
633 }
634 }
635 }
636 }
637 }
638
639 if($exclude_file_data){
640 $exclude_file_data = "-x".$exclude_file_data;
641 }
642
643 foreach ($remove as $data) {
644 if ($sys == 'WIN')
645 $exclude_data .= " $data/*.*";
646 else
647 $exclude_data .= " '$data/*'";
648 }
649
650 //Include paths by default
651 $add = array(
652 trim(WPINC),
653 trim(basename(WP_CONTENT_DIR)),
654 "wp-admin"
655 );
656
657 $include_data = ". -i";
658 foreach ($add as $data) {
659 if ($sys == 'WIN')
660 $include_data .= " $data/*.*";
661 else
662 $include_data .= " '$data/*'";
663 }
664
665 //Additional includes?
666 if (!empty($include)) {
667 foreach ($include as $data) {
668 if ($data) {
669 if ($sys == 'WIN')
670 $include_data .= " $data/*.*";
671 else
672 $include_data .= " '$data/*'";
673 }
674 }
675 }
676
677 $this->update_status($task_name, $this->statuses['files_zip']);
678 chdir(ABSPATH);
679 ob_start();
680 $command = "$zip -q -j $comp_level $backup_file .* * $exclude_file_data";
681 $result_f = $this->mmb_exec($command, false, true);
682 if (!$result_f || $result_f == 18) { // disregard permissions error, file can't be accessed
683 $command = "$zip -q -r $comp_level $backup_file $include_data $exclude_data";
684 $result_d = $this->mmb_exec($command, false, true);
685 if ($result_d && $result_d != 18) {
686 @unlink($backup_file);
687 if ($result_d > 0 && $result_d < 18)
688 return array(
689 'error' => 'Failed to archive files (' . $zip_errors[$result_d] . ') .'
690 );
691 else
692 return array(
693 'error' => 'Failed to archive files.'
694 );
695 }
696 }
697 ob_get_clean();
698
699 if ($result_f && $result_f != 18) { //Try pclZip
700 $this->_log("Files zip fallback to pclZip");
701 if (!isset($archive)) {
702 define('PCLZIP_TEMPORARY_DIR', MWP_BACKUP_DIR . '/');
703 require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
704 $archive = new PclZip($backup_file);
705 }
706
707 //Include paths
708 $include_data = array();
709 if (!empty($include)) {
710 foreach ($include as $data) {
711 if ($data && file_exists(ABSPATH . $data))
712 $include_data[] = ABSPATH . $data . '/';
713 }
714 }
715
716 foreach ($add as $data) {
717 if (file_exists(ABSPATH . $data))
718 $include_data[] = ABSPATH . $data . '/';
719 }
720
721 //Include root files
722 if ($handle = opendir(ABSPATH)) {
723 while (false !== ($file = readdir($handle))) {
724 if ($file != "." && $file != ".." && !is_dir($file) && file_exists(ABSPATH . $file)) {
725 $include_data[] = ABSPATH . $file;
726 }
727 }
728 closedir($handle);
729 }
730
731 if ($disable_comp) {
732 $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_NO_COMPRESSION);
733 } else {
734 $result = $archive->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH);
735 }
736 if (!$result) {
737 @unlink($backup_file);
738 return array(
739 'error' => 'Failed to zip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
740 );
741 }
742
743 //Now exclude paths
744 $exclude_data = array();
745 if (!empty($exclude)) {
746 foreach ($exclude as $data) {
747 if (is_dir(ABSPATH . $data))
748 $exclude_data[] = $data . '/';
749 else
750 $exclude_data[] = $data;
751 }
752 }
753
754 foreach ($remove as $rem) {
755 $exclude_data[] = $rem . '/';
756 }
757
758 $result_excl = $archive->delete(PCLZIP_OPT_BY_NAME, $exclude_data);
759 if (!$result_excl) {
760 @unlink($backup_file);
761 return array(
762 'error' => 'Failed to zip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
763 );
764 }
765
766 }
767
768 //Reconnect
769 $this->wpdb_reconnect();
770
771 $this->update_status($task_name, $this->statuses['files_zip'], true);
772 return true;
773 }
774
775
776 function backup_db()
777 {
778 $db_folder = MWP_DB_DIR . '/';
779 if (!file_exists($db_folder)) {
780 if (!mkdir($db_folder, 0755, true))
781 return array(
782 'error' => 'Error creating database backup folder (' . $db_folder . '). Make sure you have corrrect write permissions.'
783 );
784 }
785
786 $file = $db_folder . DB_NAME . '.sql';
787 $result = $this->backup_db_dump($file); // try mysqldump always then fallback to php dump
788 return $result;
789 }
790
791 function backup_db_dump($file)
792 {
793 global $wpdb;
794 $paths = $this->check_mysql_paths();
795 $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
796 $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;
797 ob_start();
798 $result = $this->mmb_exec($command);
799 ob_get_clean();
800
801 if (!$result) { // Fallback to php
802 $this->_log("DB dump fallback to php");
803 $result = $this->backup_db_php($file);
804 return $result;
805 }
806
807 if (filesize($file) == 0 || !is_file($file) || !$result) {
808 @unlink($file);
809 return false;
810 } else {
811 return $file;
812 }
813 }
814
815 function backup_db_php($file)
816 {
817 global $wpdb;
818 $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
819 foreach ($tables as $table) {
820 //drop existing table
821 $dump_data = "DROP TABLE IF EXISTS $table[0];";
822 //create table
823 $create_table = $wpdb->get_row("SHOW CREATE TABLE $table[0]", ARRAY_N);
824 $dump_data .= "\n\n" . $create_table[1] . ";\n\n";
825
826 $count = $wpdb->get_var("SELECT count(*) FROM $table[0]");
827 if ($count > 100)
828 $count = ceil($count / 100);
829 else if ($count > 0)
830 $count = 1;
831
832 for ($i = 0; $i < $count; $i++) {
833 $low_limit = $i * 100;
834 $qry = "SELECT * FROM $table[0] LIMIT $low_limit, 100";
835 $rows = $wpdb->get_results($qry, ARRAY_A);
836 if (is_array($rows)) {
837 foreach ($rows as $row) {
838 //insert single row
839 $dump_data .= "INSERT INTO $table[0] VALUES(";
840 $num_values = count($row);
841 $j = 1;
842 foreach ($row as $value) {
843 $value = addslashes($value);
844 $value = preg_replace("/\n/Ui", "\\n", $value);
845 $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
846 $j++;
847 unset($value);
848 }
849 $dump_data .= ");\n";
850 }
851 }
852 }
853 $dump_data .= "\n\n\n";
854
855 unset($rows);
856 file_put_contents($file, $dump_data, FILE_APPEND);
857 unset($dump_data);
858 }
859
860 if (filesize($file) == 0 || !is_file($file)) {
861 @unlink($file);
862 return array(
863 'error' => 'Database backup failed. Try to enable MySQL dump on your server.'
864 );
865 }
866
867 return $file;
868
869 }
870
871 function restore($args)
872 {
873 $this->_log($args);
874 global $wpdb;
875 if (empty($args)) {
876 return false;
877 }
878
879 extract($args);
880 $this->set_memory();
881
882 $unlink_file = true; //Delete file after restore
883
884 //Detect source
885 if ($backup_url) {
886 //This is for clone (overwrite)
887 include_once ABSPATH . 'wp-admin/includes/file.php';
888 $backup_file = download_url($backup_url);
889 if (is_wp_error($backup_file)) {
890 return array(
891 'error' => 'Unable to download backup file ('.$backup_file->get_error_message().')'
892 );
893 }
894 $what = 'full';
895 } else {
896 $tasks = $this->tasks;
897 $task = $tasks[$task_name];
898 if (isset($task['task_results'][$result_id]['server'])) {
899 $backup_file = $task['task_results'][$result_id]['server']['file_path'];
900 $unlink_file = false; //Don't delete file if stored on server
901 } elseif (isset($task['task_results'][$result_id]['ftp'])) {
902 $ftp_file = $task['task_results'][$result_id]['ftp'];
903 $args = $task['task_args']['account_info']['mwp_ftp'];
904 $args['backup_file'] = $ftp_file;
905 $backup_file = $this->get_ftp_backup($args);
906 if ($backup_file == false) {
907 return array(
908 'error' => 'Failed to download file from FTP.'
909 );
910 }
911 } elseif (isset($task['task_results'][$result_id]['amazons3'])) {
912 $amazons3_file = $task['task_results'][$result_id]['amazons3'];
913 $args = $task['task_args']['account_info']['mwp_amazon_s3'];
914 $args['backup_file'] = $amazons3_file;
915 $backup_file = $this->get_amazons3_backup($args);
916 if ($backup_file == false) {
917 return array(
918 'error' => 'Failed to download file from Amazon S3.'
919 );
920 }
921 } elseif(isset($task['task_results'][$result_id]['dropbox'])){
922 $dropbox_file = $task['task_results'][$result_id]['dropbox'];
923 $args = $task['task_args']['account_info']['mwp_dropbox'];
924 $args['backup_file'] = $dropbox_file;
925 $backup_file = $this->get_dropbox_backup($args);
926
927 if ($backup_file == false) {
928 return array(
929 'error' => 'Failed to download file from Dropbox.'
930 );
931 }
932 }
933
934 $what = $tasks[$task_name]['task_args']['what'];
935 }
936
937 $this->wpdb_reconnect();
938
939 if ($backup_file && file_exists($backup_file)) {
940 if ($overwrite) {
941 //Keep old db credentials before overwrite
942 if (!copy(ABSPATH . 'wp-config.php', ABSPATH . 'mwp-temp-wp-config.php')) {
943 @unlink($backup_file);
944 return array(
945 'error' => 'Error creating wp-config. Please check your write permissions.'
946 );
947 }
948
949 $db_host = DB_HOST;
950 $db_user = DB_USER;
951 $db_password = DB_PASSWORD;
952 $home = rtrim(get_option('home'), "/");
953 $site_url = get_option('site_url');
954
955 $clone_options = array();
956 if (trim($clone_from_url) || trim($mwp_clone)) {
957
958 $clone_options['_worker_nossl_key'] = get_option('_worker_nossl_key');
959 $clone_options['_worker_public_key'] = get_option('_worker_public_key');
960 $clone_options['_action_message_id'] = get_option('_action_message_id');
961
962 }
963 $clone_options['upload_path'] = get_option('upload_path');
964 $clone_options['upload_url_path'] = get_option('upload_url_path');
965
966 $clone_options['mwp_backup_tasks'] = serialize(get_option('mwp_backup_tasks'));
967 $clone_options['mwp_notifications'] = serialize(get_option('mwp_notifications'));
968 $clone_options['mwp_pageview_alerts'] = serialize(get_option('mwp_pageview_alerts'));
969
970
971 } else {
972 $restore_options = array();
973 $restore_options['mwp_notifications'] = get_option('mwp_notifications');
974 $restore_options['mwp_pageview_alerts'] = get_option('mwp_pageview_alerts');
975 $restore_options['user_hit_count'] = get_option('user_hit_count');
976 }
977
978
979 chdir(ABSPATH);
980 $unzip = $this->get_unzip();
981 $command = "$unzip -o $backup_file";
982 ob_start();
983 $result = $this->mmb_exec($command);
984 ob_get_clean();
985
986 if (!$result) { //fallback to pclzip
987 $this->_log("Files uznip fallback to pclZip");
988 define('PCLZIP_TEMPORARY_DIR', MWP_BACKUP_DIR . '/');
989 require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
990 $archive = new PclZip($backup_file);
991 $result = $archive->extract(PCLZIP_OPT_PATH, ABSPATH, PCLZIP_OPT_REPLACE_NEWER);
992 }
993
994 if ($unlink_file) {
995 @unlink($backup_file);
996 }
997
998 if (!$result) {
999 return array(
1000 'error' => 'Failed to unzip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
1001 );
1002 }
1003
1004 $db_result = $this->restore_db();
1005
1006 if (!$db_result) {
1007 return array(
1008 'error' => 'Error restoring database.'
1009 );
1010 } else if(is_array($db_result) && isset($db_result['error'])){
1011 return array(
1012 'error' => $db_result['error']
1013 );
1014 }
1015
1016 } else {
1017 return array(
1018 'error' => 'Error restoring. Cannot find backup file.'
1019 );
1020 }
1021
1022 $this->wpdb_reconnect();
1023
1024 //Replace options and content urls
1025 if ($overwrite) {
1026 //Get New Table prefix
1027 $new_table_prefix = trim($this->get_table_prefix());
1028 //Retrieve old wp_config
1029 @unlink(ABSPATH . 'wp-config.php');
1030 //Replace table prefix
1031 $lines = file(ABSPATH . 'mwp-temp-wp-config.php');
1032
1033 foreach ($lines as $line) {
1034 if (strstr($line, '$table_prefix')) {
1035 $line = '$table_prefix = "' . $new_table_prefix . '";' . PHP_EOL;
1036 }
1037 file_put_contents(ABSPATH . 'wp-config.php', $line, FILE_APPEND);
1038 }
1039
1040 @unlink(ABSPATH . 'mwp-temp-wp-config.php');
1041
1042 //Replace options
1043 $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
1044 $old = $wpdb->get_var($wpdb->prepare($query));
1045 $old = rtrim($old, "/");
1046 $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$home' WHERE option_name = 'home'";
1047 $wpdb->query($wpdb->prepare($query));
1048 $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$home' WHERE option_name = 'siteurl'";
1049 $wpdb->query($wpdb->prepare($query));
1050 //Replace content urls
1051 $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, '$old','$home') WHERE post_content REGEXP 'src=\"(.*)$old(.*)\"' OR post_content REGEXP 'href=\"(.*)$old(.*)\"'";
1052 $wpdb->query($wpdb->prepare($query));
1053
1054 if (trim($new_password)) {
1055 $new_password = wp_hash_password($new_password);
1056 }
1057 if (!trim($clone_from_url) && !trim($mwp_clone)) {
1058 if ($new_user && $new_password) {
1059 $query = "UPDATE " . $new_table_prefix . "users SET user_login = '$new_user', user_pass = '$new_password' WHERE user_login = '$old_user'";
1060 $wpdb->query($wpdb->prepare($query));
1061 }
1062 } else {
1063 if ($clone_from_url) {
1064 if ($new_user && $new_password) {
1065 $query = "UPDATE " . $new_table_prefix . "users SET user_pass = '$new_password' WHERE user_login = '$new_user'";
1066 $wpdb->query($wpdb->prepare($query));
1067 }
1068 }
1069
1070 if ($mwp_clone) {
1071 if ($admin_email) {
1072 //Clean Install
1073 $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$admin_email' WHERE option_name = 'admin_email'";
1074 $wpdb->query($wpdb->prepare($query));
1075 $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
1076 $temp_user = $wpdb->get_row($query);
1077 if (!empty($temp_user)) {
1078 $query = "UPDATE " . $new_table_prefix . "users SET user_email='$admin_email', user_login = '$new_user', user_pass = '$new_password' WHERE user_login = '$temp_user->user_login'";
1079 $wpdb->query($wpdb->prepare($query));
1080 }
1081
1082 }
1083 }
1084 }
1085
1086 if (is_array($clone_options) && !empty($clone_options)) {
1087 foreach ($clone_options as $key => $option) {
1088 if (!empty($key)) {
1089 $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = '$key'";
1090 $res = $wpdb->get_var($query);
1091 if ($res == false) {
1092 $query = "INSERT INTO " . $new_table_prefix . "options (option_value,option_name) VALUES('$option','$key')";
1093 $wpdb->query($wpdb->prepare($query));
1094 } else {
1095 $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$option' WHERE option_name = '$key'";
1096 $wpdb->query($wpdb->prepare($query));
1097 }
1098 }
1099 }
1100 }
1101
1102 //Remove hit count
1103 $query = "DELETE FROM " . $new_table_prefix . "options WHERE option_name = 'user_hit_count'";
1104 $wpdb->query($wpdb->prepare($query));
1105
1106 //Check for .htaccess permalinks update
1107 $this->replace_htaccess($home);
1108 } else {
1109
1110 //restore worker options
1111 if (is_array($restore_options) && !empty($restore_options)) {
1112 foreach ($restore_options as $key => $option) {
1113 update_option($key,$option);
1114 }
1115 }
1116
1117 }
1118
1119
1120
1121
1122 return true;
1123 }
1124
1125 function restore_db()
1126 {
1127 global $wpdb;
1128 $paths = $this->check_mysql_paths();
1129 $file_path = ABSPATH . 'mwp_db';
1130 @chmod($file_path,0755);
1131 $file_name = glob($file_path . '/*.sql');
1132 $file_name = $file_name[0];
1133
1134 if(!$file_name){
1135 return array('error' => 'Cannot access database file.');
1136 }
1137
1138 $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1139 $command = $brace . $paths['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --default-character-set="utf8" ' . DB_NAME . ' < ' . $brace . $file_name . $brace;
1140
1141 ob_start();
1142 $result = $this->mmb_exec($command);
1143 ob_get_clean();
1144 if (!$result) {
1145 $this->_log('DB restore fallback to PHP');
1146 //try php
1147 $this->restore_db_php($file_name);
1148 }
1149
1150
1151 @unlink($file_name);
1152 return true;
1153 }
1154
1155 function restore_db_php($file_name)
1156 {
1157 global $wpdb;
1158 $current_query = '';
1159 // Read in entire file
1160 $lines = file($file_name);
1161 // Loop through each line
1162 foreach ($lines as $line) {
1163 // Skip it if it's a comment
1164 if (substr($line, 0, 2) == '--' || $line == '')
1165 continue;
1166
1167 // Add this line to the current query
1168 $current_query .= $line;
1169 // If it has a semicolon at the end, it's the end of the query
1170 if (substr(trim($line), -1, 1) == ';') {
1171 // Perform the query
1172 $result = $wpdb->query($current_query);
1173 if ($result === false)
1174 return false;
1175 // Reset temp variable to empty
1176 $current_query = '';
1177 }
1178 }
1179
1180 @unlink($file_name);
1181 return true;
1182 }
1183
1184 function get_table_prefix()
1185 {
1186 $lines = file(ABSPATH . 'wp-config.php');
1187 foreach ($lines as $line) {
1188 if (strstr($line, '$table_prefix')) {
1189 $pattern = "/(\'|\")[^(\'|\")]*/";
1190 preg_match($pattern, $line, $matches);
1191 $prefix = substr($matches[0], 1);
1192 return $prefix;
1193 break;
1194 }
1195 }
1196 return 'wp_'; //default
1197 }
1198
1199 function optimize_tables()
1200 {
1201 global $wpdb;
1202 $query = 'SHOW TABLES';
1203 $tables = $wpdb->get_results($wpdb->prepare($query), ARRAY_A);
1204 foreach ($tables as $table) {
1205 if (in_array($table['Engine'], array(
1206 'MyISAM',
1207 'ISAM',
1208 'HEAP',
1209 'MEMORY',
1210 'ARCHIVE'
1211 )))
1212 $table_string .= $table['Name'] . ",";
1213 elseif ($table['Engine'] == 'InnoDB') {
1214 $optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
1215 }
1216 }
1217
1218 $table_string = rtrim($table_string);
1219 $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
1220
1221 return $optimize ? true : false;
1222 }
1223
1224 ### Function: Auto Detect MYSQL and MYSQL Dump Paths
1225 function check_mysql_paths()
1226 {
1227 global $wpdb;
1228 $paths = array(
1229 'mysql' => '',
1230 'mysqldump' => ''
1231 );
1232 if (substr(PHP_OS, 0, 3) == 'WIN') {
1233 $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
1234 if ($mysql_install) {
1235 $install_path = str_replace('\\', '/', $mysql_install->Value);
1236 $paths['mysql'] = $install_path . 'bin/mysql.exe';
1237 $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
1238 } else {
1239 $paths['mysql'] = 'mysql.exe';
1240 $paths['mysqldump'] = 'mysqldump.exe';
1241 }
1242 } else {
1243 $paths['mysql'] = $this->mmb_exec('which mysql', true);
1244 if (empty($paths['mysql']))
1245 $paths['mysql'] = 'mysql'; // try anyway
1246
1247 $paths['mysqldump'] = $this->mmb_exec('which mysqldump', true);
1248 if (empty($paths['mysqldump']))
1249 $paths['mysqldump'] = 'mysqldump'; // try anyway
1250
1251 }
1252
1253
1254 return $paths;
1255 }
1256
1257 //Check if exec, system, passthru functions exist
1258 function check_sys()
1259 {
1260 if ($this->mmb_function_exists('exec'))
1261 return 'exec';
1262
1263 if ($this->mmb_function_exists('system'))
1264 return 'system';
1265
1266 if ($this->mmb_function_exists('passhtru'))
1267 return 'passthru';
1268
1269 return false;
1270
1271 }
1272
1273 function mmb_exec($command, $string = false, $rawreturn = false)
1274 {
1275 if ($command == '')
1276 return false;
1277
1278 if ($this->mmb_function_exists('exec')) {
1279 $log = @exec($command, $output, $return);
1280 $this->_log("Type: exec");
1281 $this->_log("Command: ".$command);
1282 $this->_log("Return: ".$return);
1283 if ($string)
1284 return $log;
1285 if ($rawreturn)
1286 return $return;
1287
1288 return $return ? false : true;
1289 } elseif ($this->mmb_function_exists('system')) {
1290 $log = @system($command, $return);
1291 $this->_log("Type: system");
1292 $this->_log("Command: ".$command);
1293 $this->_log("Return: ".$return);
1294 if ($string)
1295 return $log;
1296
1297 if ($rawreturn)
1298 return $return;
1299
1300 return $return ? false : true;
1301 } elseif ($this->mmb_function_exists('passthru') && !$string) {
1302 $log = passthru($command, $return);
1303 $this->_log("Type: passthru");
1304 $this->_log("Command: ".$command);
1305 $this->_log("Return: ".$return);
1306 if ($rawreturn)
1307 return $return;
1308
1309 return $return ? false : true;
1310 }
1311
1312 if ($rawreturn)
1313 return -1;
1314
1315 return false;
1316 }
1317
1318 function get_zip()
1319 {
1320 $zip = $this->mmb_exec('which zip', true);
1321 if (!$zip)
1322 $zip = "zip";
1323 return $zip;
1324 }
1325
1326 function get_unzip()
1327 {
1328 $unzip = $this->mmb_exec('which unzip', true);
1329 if (!$unzip)
1330 $unzip = "unzip";
1331 return $unzip;
1332 }
1333
1334 function check_backup_compat()
1335 {
1336
1337 $reqs = array();
1338 if (strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0) {
1339 $reqs['Server OS']['status'] = 'Linux (or compatible)';
1340 $reqs['Server OS']['pass'] = true;
1341 } else {
1342 $reqs['Server OS']['status'] = 'Windows';
1343 $reqs['Server OS']['pass'] = true;
1344 $pass = false;
1345 }
1346 $reqs['PHP Version']['status'] = phpversion();
1347 if ((float) phpversion() >= 5.1) {
1348 $reqs['PHP Version']['pass'] = true;
1349 } else {
1350 $reqs['PHP Version']['pass'] = false;
1351 $pass = false;
1352 }
1353
1354
1355 if (is_writable(WP_CONTENT_DIR)) {
1356 $reqs['Backup Folder']['status'] = "writable";
1357 $reqs['Backup Folder']['pass'] = true;
1358 } else {
1359 $reqs['Backup Folder']['status'] = "not writable";
1360 $reqs['Backup Folder']['pass'] = false;
1361 }
1362
1363
1364 $file_path = MWP_BACKUP_DIR;
1365 $reqs['Backup Folder']['status'] .= ' (' . $file_path . ')';
1366
1367 if ($func = $this->check_sys()) {
1368 $reqs['Execute Function']['status'] = $func;
1369 $reqs['Execute Function']['pass'] = true;
1370 } else {
1371 $reqs['Execute Function']['status'] = "not found";
1372 $reqs['Execute Function']['info'] = "(will try PHP replacement)";
1373 $reqs['Execute Function']['pass'] = false;
1374 }
1375 $reqs['Zip']['status'] = $this->get_zip();
1376
1377 $reqs['Zip']['pass'] = true;
1378
1379
1380
1381 $reqs['Unzip']['status'] = $this->get_unzip();
1382
1383 $reqs['Unzip']['pass'] = true;
1384
1385 $paths = $this->check_mysql_paths();
1386
1387 if (!empty($paths['mysqldump'])) {
1388 $reqs['MySQL Dump']['status'] = $paths['mysqldump'];
1389 $reqs['MySQL Dump']['pass'] = true;
1390 } else {
1391 $reqs['MySQL Dump']['status'] = "not found";
1392 $reqs['MySQL Dump']['info'] = "(will try PHP replacement)";
1393 $reqs['MySQL Dump']['pass'] = false;
1394 }
1395
1396 $exec_time = ini_get('max_execution_time');
1397 $reqs['Execution time']['status'] = $exec_time ? $exec_time . "s" : 'unknown';
1398 $reqs['Execution time']['pass'] = true;
1399
1400 $mem_limit = ini_get('memory_limit');
1401 $reqs['Memory limit']['status'] = $mem_limit ? $mem_limit : 'unknown';
1402 $reqs['Memory limit']['pass'] = true;
1403
1404 $changed = $this->set_memory();
1405 if($changed['execution_time']){
1406 $exec_time = ini_get('max_execution_time');
1407 $reqs['Execution time']['status'] .= $exec_time ? ' (will try '.$exec_time . 's)' : ' (unknown)';
1408 }
1409 if($changed['memory_limit']){
1410 $mem_limit = ini_get('memory_limit');
1411 $reqs['Memory limit']['status'] .= $mem_limit ? ' (will try '.$mem_limit.')' : ' (unknown)';
1412 }
1413
1414 if(defined('MWP_SHOW_LOG') && MWP_SHOW_LOG == true){
1415 $md5 = get_option('mwp_log_md5');
1416 if ($md5 !== false) {
1417 global $mmb_plugin_url;
1418 $md5 = "<a href='$mmb_plugin_url/log_$md5' target='_blank'>$md5</a>";
1419 } else {
1420 $md5 = "not created";
1421 }
1422 $reqs['Backup Log']['status'] = $md5;
1423 $reqs['Backup Log']['pass'] = true;
1424 }
1425
1426 return $reqs;
1427 }
1428
1429 function email_backup($args)
1430 {
1431 $email = $args['email'];
1432
1433 if (!is_email($email)) {
1434 return array(
1435 'error' => 'Your email (' . $email . ') is not correct'
1436 );
1437 }
1438 $backup_file = $args['file_path'];
1439 $task_name = isset($args['task_name']) ? $args['task_name'] : '';
1440 if (file_exists($backup_file) && $email) {
1441 $attachments = array(
1442 $backup_file
1443 );
1444 $headers = 'From: ManageWP <no-reply@managewp.com>' . "\r\n";
1445 $subject = "ManageWP - " . $task_name . " - " . $this->site_name;
1446 ob_start();
1447 $result = wp_mail($email, $subject, $subject, $headers, $attachments);
1448 ob_end_clean();
1449
1450 }
1451
1452 if (!$result) {
1453 return array(
1454 'error' => 'Email not sent. Maybe your backup is too big for email or email server is not available on your website.'
1455 );
1456 }
1457 return true;
1458
1459 }
1460
1461 function ftp_backup($args)
1462 {
1463 extract($args);
1464 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder, $ftp_site_folder
1465 $port = $ftp_port ? $ftp_port : 21; //default port is 21
1466 if ($ftp_ssl) {
1467 if (function_exists('ftp_ssl_connect')) {
1468 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
1469 } else {
1470 return array(
1471 'error' => 'FTPS disabled: Please enable ftp_ssl_connect in PHP',
1472 'partial' => 1
1473 );
1474 }
1475 } else {
1476 if (function_exists('ftp_connect')) {
1477 $conn_id = ftp_connect($ftp_hostname,$port);
1478 if ($conn_id === false) {
1479 return array(
1480 'error' => 'Failed to connect to ' . $ftp_hostname,
1481 'partial' => 1
1482 );
1483 }
1484 } else {
1485 return array(
1486 'error' => 'FTP disabled: Please enable ftp_connect in PHP',
1487 'partial' => 1
1488 );
1489 }
1490 }
1491 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
1492 if ($login === false) {
1493 return array(
1494 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
1495 'partial' => 1
1496 );
1497 }
1498
1499 if($ftp_passive){
1500 @ftp_pasv($conn_id,true);
1501 }
1502
1503 @ftp_mkdir($conn_id, $ftp_remote_folder);
1504 if ($ftp_site_folder) {
1505 $ftp_remote_folder .= '/' . $this->site_name;
1506 }
1507 @ftp_mkdir($conn_id, $ftp_remote_folder);
1508
1509 $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
1510 if ($upload === false) { //Try ascii
1511 $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_ASCII);
1512 }
1513 ftp_close($conn_id);
1514
1515 if ($upload === false) {
1516 return array(
1517 'error' => 'Failed to upload file to FTP. Please check your specified path.',
1518 'partial' => 1
1519 );
1520 }
1521
1522 return true;
1523 }
1524
1525 function remove_ftp_backup($args)
1526 {
1527 extract($args);
1528 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
1529 $port = $ftp_port ? $ftp_port : 21; //default port is 21
1530 if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
1531 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
1532 } else if (function_exists('ftp_connect')) {
1533 $conn_id = ftp_connect($ftp_hostname,$port);
1534 }
1535
1536 if ($conn_id) {
1537 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
1538 if ($ftp_site_folder)
1539 $ftp_remote_folder .= '/' . $this->site_name;
1540
1541 if($ftp_passive){
1542 @ftp_pasv($conn_id,true);
1543 }
1544
1545 $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $backup_file);
1546
1547 ftp_close($conn_id);
1548 }
1549
1550 }
1551
1552 function get_ftp_backup($args)
1553 {
1554 extract($args);
1555 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
1556 $port = $ftp_port ? $ftp_port : 21; //default port is 21
1557 if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
1558 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
1559
1560 } else if (function_exists('ftp_connect')) {
1561 $conn_id = ftp_connect($ftp_hostname,$port);
1562 if ($conn_id === false) {
1563 return false;
1564 }
1565 }
1566 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
1567 if ($login === false) {
1568 return false;
1569 } else {
1570 }
1571
1572 if ($ftp_site_folder)
1573 $ftp_remote_folder .= '/' . $this->site_name;
1574
1575 if($ftp_passive){
1576 @ftp_pasv($conn_id,true);
1577 }
1578
1579 $temp = ABSPATH . 'mwp_temp_backup.zip';
1580 $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
1581 if ($get === false) {
1582 return false;
1583 } else {
1584 }
1585 ftp_close($conn_id);
1586
1587 return $temp;
1588 }
1589
1590 function dropbox_backup($args)
1591 {
1592
1593 extract($args);
1594
1595 if(isset($consumer_secret) && !empty($consumer_secret)){
1596 //New way
1597 require_once('lib/dropbox.oauth.php');
1598
1599 $dropbox = new Dropbox($consumer_key, $consumer_secret);
1600 $dropbox->setOAuthToken($oauth_token);
1601 $dropbox->setOAuthTokenSecret($oauth_token_secret);
1602
1603 if ($dropbox_site_folder == true)
1604 $dropbox_destination .= '/' . $this->site_name;
1605
1606 try{
1607
1608 $dropbox->filesPost($dropbox_destination, $backup_file,true);
1609
1610 } catch(Exception $e){
1611 return array(
1612 'error' => 'Dropbox upload error. '.$e->getMessage()
1613 );
1614 }
1615
1616 return true;
1617
1618 } else {
1619 //old way
1620 require_once('lib/dropbox.php');
1621
1622 //$email, $password, $backup_file, $destination, $dropbox_site_folder
1623
1624 $size = ceil(filesize($backup_file) / 1024);
1625 if ($size > 300000) {
1626 return array(
1627 'error' => 'Cannot upload file to Dropbox. Dropbox has upload limit of 300Mb per file.',
1628 'partial' => 1
1629 );
1630 }
1631
1632 if ($dropbox_site_folder == true)
1633 $dropbox_destination .= '/' . $this->site_name;
1634
1635 try {
1636 $uploader = new DropboxUploader($dropbox_username, $dropbox_password);
1637 $uploader->upload($backup_file, $dropbox_destination);
1638 }
1639 catch (Exception $e) {
1640 return array(
1641 'error' => $e->getMessage(),
1642 'partial' => 1
1643 );
1644 }
1645
1646 return true;
1647 }
1648
1649 }
1650
1651 function remove_dropbox_backup($args){
1652 extract($args);
1653 if(isset($consumer_secret) && !empty($consumer_secret)){
1654 //New way
1655 require_once('lib/dropbox.oauth.php');
1656
1657 $dropbox = new Dropbox($consumer_key, $consumer_secret);
1658 $dropbox->setOAuthToken($oauth_token);
1659 $dropbox->setOAuthTokenSecret($oauth_token_secret);
1660
1661 if ($dropbox_site_folder == true)
1662 $dropbox_destination .= '/' . $this->site_name;
1663
1664 try{
1665 $dropbox->fileopsDelete($dropbox_destination.'/'.$backup_file, true);
1666 } catch(Exception $e){
1667
1668 }
1669 }
1670 }
1671
1672 function get_dropbox_backup($args){
1673 extract($args);
1674
1675 if(isset($consumer_secret) && !empty($consumer_secret)){
1676 //New way
1677 require_once('lib/dropbox.oauth.php');
1678
1679 $dropbox = new Dropbox($consumer_key, $consumer_secret);
1680 $dropbox->setOAuthToken($oauth_token);
1681 $dropbox->setOAuthTokenSecret($oauth_token_secret);
1682
1683 if ($dropbox_site_folder == true)
1684 $dropbox_destination .= '/' . $this->site_name;
1685
1686 $temp = ABSPATH . 'mwp_temp_backup.zip';
1687
1688 try{
1689 $file = $dropbox->filesGet($dropbox_destination.'/'.$backup_file, true);
1690
1691 if(isset($file['data']) && !empty($file['data']) )
1692 $stream = base64_decode($file['data']);
1693 else
1694 return false;
1695
1696 $handle = @fopen($temp, 'w+');
1697 $result = fwrite($handle,$stream);
1698 fclose($handle);
1699
1700 if($result)
1701 return $temp;
1702 else
1703 return false;
1704
1705 } catch(Exception $e){
1706
1707
1708 return false;
1709 }
1710
1711 } else {
1712 return false;
1713 }
1714
1715
1716 }
1717
1718 function amazons3_backup($args)
1719 {
1720 if ($this->mmb_function_exists('curl_init')) {
1721 require_once('lib/s3.php');
1722 extract($args);
1723
1724 if ($as3_site_folder == true)
1725 $as3_directory .= '/' . $this->site_name;
1726
1727 $endpoint = isset($as3_bucket_region) ? $as3_bucket_region : 's3.amazonaws.com';
1728 try{
1729 $s3 = new mwpS3(trim($as3_access_key), trim(str_replace(' ', '+', $as3_secure_key)), false, $endpoint);
1730 if ($s3->putObjectFile($backup_file, $as3_bucket, $as3_directory . '/' . basename($backup_file), mwpS3::ACL_PRIVATE)) {
1731 return true;
1732 } else {
1733
1734 return array(
1735 'error' => 'Failed to upload to Amazon S3. Please check your details and set upload/delete permissions on your bucket.',
1736 'partial' => 1
1737 );
1738 }
1739
1740 }catch (Exception $e){
1741 $err = $e->getMessage();
1742 if($err){
1743 return array(
1744 'error' => 'Failed to upload to AmazonS3 ('.$err.').'
1745 );
1746 } else {
1747 return array(
1748 'error' => 'Failed to upload to Amazon S3.'
1749 );
1750 }
1751 }
1752
1753 } else {
1754 return array(
1755 'error' => 'You cannot use Amazon S3 on your server. Please enable curl extension first.',
1756 'partial' => 1
1757 );
1758 }
1759 }
1760
1761 function remove_amazons3_backup($args)
1762 {
1763 if ($this->mmb_function_exists('curl_init')) {
1764 require_once('lib/s3.php');
1765 extract($args);
1766 if ($as3_site_folder == true)
1767 $as3_directory .= '/' . $this->site_name;
1768 $endpoint = isset($as3_bucket_region) ? $as3_bucket_region : 's3.amazonaws.com';
1769 try{
1770 $s3 = new mwpS3(trim($as3_access_key), trim(str_replace(' ', '+', $as3_secure_key)), false, $endpoint);
1771 $s3->deleteObject($as3_bucket, $as3_directory . '/' . $backup_file);
1772 } catch (Exception $e){
1773
1774 }
1775 }
1776 }
1777
1778 function get_amazons3_backup($args)
1779 {
1780 require_once('lib/s3.php');
1781 extract($args);
1782 $endpoint = isset($as3_bucket_region) ? $as3_bucket_region : 's3.amazonaws.com';
1783 $temp = '';
1784 try{
1785 $s3 = new mwpS3($as3_access_key, str_replace(' ', '+', $as3_secure_key), false, $endpoint);
1786 if ($as3_site_folder == true)
1787 $as3_directory .= '/' . $this->site_name;
1788
1789 $temp = ABSPATH . 'mwp_temp_backup.zip';
1790 $s3->getObject($as3_bucket, $as3_directory . '/' . $backup_file, $temp);
1791 } catch (Exception $e){
1792 return $temp;
1793 }
1794 return $temp;
1795 }
1796
1797 function schedule_next($type, $schedule)
1798 {
1799 $schedule = explode("|", $schedule);
1800
1801 if (empty($schedule))
1802 return false;
1803 switch ($type) {
1804
1805 case 'daily':
1806
1807 if (isset($schedule[1]) && $schedule[1]) {
1808 $delay_time = $schedule[1] * 60;
1809 }
1810
1811 $current_hour = date("H");
1812 $schedule_hour = $schedule[0];
1813 if ($current_hour >= $schedule_hour)
1814 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 1, date("Y"));
1815 else
1816 $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
1817 break;
1818
1819
1820 case 'weekly':
1821 if (isset($schedule[2]) && $schedule[2]) {
1822 $delay_time = $schedule[2] * 60;
1823 }
1824 $current_weekday = date('w');
1825 $schedule_weekday = $schedule[1];
1826 $current_hour = date("H");
1827 $schedule_hour = $schedule[0];
1828
1829 if ($current_weekday > $schedule_weekday)
1830 $weekday_offset = 7 - ($week_day - $task_schedule[1]);
1831 else
1832 $weekday_offset = $schedule_weekday - $current_weekday;
1833
1834
1835 if (!$weekday_offset) { //today is scheduled weekday
1836 if ($current_hour >= $schedule_hour)
1837 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 7, date("Y"));
1838 else
1839 $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
1840 } else {
1841 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + $weekday_offset, date("Y"));
1842 }
1843
1844 break;
1845
1846 case 'monthly':
1847 if (isset($schedule[2]) && $schedule[2]) {
1848 $delay_time = $schedule[2] * 60;
1849 }
1850 $current_monthday = date('j');
1851 $schedule_monthday = $schedule[1];
1852 $current_hour = date("H");
1853 $schedule_hour = $schedule[0];
1854
1855 if ($current_monthday > $schedule_monthday) {
1856 $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
1857 } else if ($current_monthday < $schedule_monthday) {
1858 $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
1859 } else if ($current_monthday == $schedule_monthday) {
1860 if ($current_hour >= $schedule_hour)
1861 $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
1862 else
1863 $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
1864 break;
1865 }
1866
1867 break;
1868 default:
1869 break;
1870 }
1871
1872 if (isset($delay_time) && $delay_time) {
1873 $time += $delay_time;
1874 }
1875
1876 return $time;
1877
1878 }
1879
1880 //Parse task arguments for info on master
1881 function get_backup_stats()
1882 {
1883 $stats = array();
1884 $tasks = $this->tasks;
1885 if (is_array($tasks) && !empty($tasks)) {
1886 foreach ($tasks as $task_name => $info) {
1887 if (is_array($info['task_results']) && !empty($info['task_results'])) {
1888 foreach ($info['task_results'] as $key => $result) {
1889 if (isset($result['server']) && !isset($result['error'])) {
1890 if (!file_exists($result['server']['file_path'])) {
1891 $info['task_results'][$key]['error'] = 'Backup created but manually removed from server.';
1892 }
1893 }
1894 }
1895 }
1896 if (is_array($info['task_results']))
1897 $stats[$task_name] = array_values($info['task_results']);
1898
1899 }
1900 }
1901 return $stats;
1902 }
1903
1904 function get_next_schedules()
1905 {
1906 $stats = array();
1907 $tasks = $this->tasks;
1908 if (is_array($tasks) && !empty($tasks)) {
1909 foreach ($tasks as $task_name => $info) {
1910 $stats[$task_name] = isset($info['task_args']['next']) ? $info['task_args']['next'] : array();
1911 }
1912 }
1913 return $stats;
1914 }
1915
1916 function remove_old_backups($task_name)
1917 {
1918
1919 //Check for previous failed backups first
1920 $this->cleanup();
1921
1922 //Remove by limit
1923 $backups = $this->tasks;
1924 if ($task_name == 'Backup Now') {
1925 $num = 0;
1926 } else {
1927 $num = 1;
1928 }
1929
1930
1931 if ((count($backups[$task_name]['task_results']) - $num) >= $backups[$task_name]['task_args']['limit']) {
1932 //how many to remove ?
1933 $remove_num = (count($backups[$task_name]['task_results']) - $num - $backups[$task_name]['task_args']['limit']) + 1;
1934 for ($i = 0; $i < $remove_num; $i++) {
1935 //Remove from the server
1936 if (isset($backups[$task_name]['task_results'][$i]['server'])) {
1937 @unlink($backups[$task_name]['task_results'][$i]['server']['file_path']);
1938 }
1939
1940 //Remove from ftp
1941 if (isset($backups[$task_name]['task_results'][$i]['ftp']) && isset($backups[$task_name]['task_args']['account_info']['mwp_ftp'])) {
1942 $ftp_file = $backups[$task_name]['task_results'][$i]['ftp'];
1943 $args = $backups[$task_name]['task_args']['account_info']['mwp_ftp'];
1944 $args['backup_file'] = $ftp_file;
1945 $this->remove_ftp_backup($args);
1946 }
1947
1948 if (isset($backups[$task_name]['task_results'][$i]['amazons3']) && isset($backups[$task_name]['task_args']['account_info']['mwp_amazon_s3'])) {
1949 $amazons3_file = $backups[$task_name]['task_results'][$i]['amazons3'];
1950 $args = $backups[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
1951 $args['backup_file'] = $amazons3_file;
1952 $this->remove_amazons3_backup($args);
1953 }
1954
1955 if (isset($backups[$task_name]['task_results'][$i]['dropbox']) && isset($backups[$task_name]['task_args']['account_info']['mwp_dropbox'])) {
1956 //To do: dropbox remove
1957 $dropbox_file = $backups[$task_name]['task_results'][$i]['dropbox'];
1958 $args = $backups[$task_name]['task_args']['account_info']['mwp_dropbox'];
1959 $args['backup_file'] = $dropbox_file;
1960 $this->remove_dropbox_backup($args);
1961 }
1962
1963 //Remove database backup info
1964 unset($backups[$task_name]['task_results'][$i]);
1965
1966 } //end foreach
1967
1968 if (is_array($backups[$task_name]['task_results']))
1969 $backups[$task_name]['task_results'] = array_values($backups[$task_name]['task_results']);
1970 else
1971 $backups[$task_name]['task_results']=array();
1972
1973 $this->update_tasks($backups);
1974 //update_option('mwp_backup_tasks', $backups);
1975 }
1976 }
1977
1978 /**
1979 * Delete specified backup
1980 * Args: $task_name, $result_id
1981 */
1982
1983 function delete_backup($args)
1984 {
1985 if (empty($args))
1986 return false;
1987 extract($args);
1988
1989 $tasks = $this->tasks;
1990 $task = $tasks[$task_name];
1991 $backups = $task['task_results'];
1992 $backup = $backups[$result_id];
1993
1994 if (isset($backup['server'])) {
1995 @unlink($backup['server']['file_path']);
1996 }
1997
1998 //Remove from ftp
1999 if (isset($backup['ftp'])) {
2000 $ftp_file = $backup['ftp'];
2001 $args = $tasks[$task_name]['task_args']['account_info']['mwp_ftp'];
2002 $args['backup_file'] = $ftp_file;
2003 $this->remove_ftp_backup($args);
2004 }
2005
2006 if (isset($backup['amazons3'])) {
2007 $amazons3_file = $backup['amazons3'];
2008 $args = $tasks[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
2009 $args['backup_file'] = $amazons3_file;
2010 $this->remove_amazons3_backup($args);
2011 }
2012
2013 if (isset($backup['dropbox'])) {
2014 $dropbox_file = $backup['dropbox'];
2015 $args = $tasks[$task_name]['task_args']['account_info']['mwp_dropbox'];
2016 $args['backup_file'] = $dropbox_file;
2017 $this->remove_dropbox_backup($args);
2018 }
2019
2020 unset($backups[$result_id]);
2021
2022 if (count($backups)) {
2023 $tasks[$task_name]['task_results'] = $backups;
2024 } else {
2025 unset($tasks[$task_name]['task_results']);
2026 }
2027
2028 $this->update_tasks($tasks);
2029 //update_option('mwp_backup_tasks', $tasks);
2030 return true;
2031
2032 }
2033
2034 function cleanup()
2035 {
2036 $tasks = $this->tasks;
2037 $backup_folder = WP_CONTENT_DIR . '/' . md5('mmb-worker') . '/mwp_backups/';
2038 $backup_folder_new = MWP_BACKUP_DIR . '/';
2039 $files = glob($backup_folder . "*");
2040 $new = glob($backup_folder_new . "*");
2041
2042 //Failed db files first
2043 $db_folder = MWP_DB_DIR . '/';
2044 $db_files = glob($db_folder . "*");
2045 if (is_array($db_files) && !empty($db_files)) {
2046 foreach ($db_files as $file) {
2047 @unlink($file);
2048 }
2049 @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
2050 @rmdir(MWP_DB_DIR);
2051 }
2052
2053
2054 //clean_old folder?
2055 if ((isset($files[0]) && basename($files[0]) == 'index.php' && count($files) == 1) || (empty($files))) {
2056 foreach ($files as $file) {
2057 @unlink($file);
2058 }
2059 @rmdir(WP_CONTENT_DIR . '/' . md5('mmb-worker') . '/mwp_backups');
2060 @rmdir(WP_CONTENT_DIR . '/' . md5('mmb-worker'));
2061 }
2062
2063
2064 foreach ($new as $b) {
2065 $files[] = $b;
2066 }
2067 $deleted = array();
2068
2069 if (is_array($files) && count($files)) {
2070 $results = array();
2071 if (!empty($tasks)) {
2072 foreach ((array) $tasks as $task) {
2073 if (isset($task['task_results']) && count($task['task_results'])) {
2074 foreach ($task['task_results'] as $backup) {
2075 if (isset($backup['server'])) {
2076 $results[] = $backup['server']['file_path'];
2077 }
2078 }
2079 }
2080 }
2081 }
2082
2083 $num_deleted = 0;
2084 foreach ($files as $file) {
2085 if (!in_array($file, $results) && basename($file) != 'index.php') {
2086 @unlink($file);
2087 $deleted[] = basename($file);
2088 $num_deleted++;
2089 }
2090 }
2091 }
2092
2093
2094
2095 return $deleted;
2096 }
2097
2098
2099 function remote_backup_now($args)
2100 {
2101 $this->set_memory();
2102 if (!empty($args))
2103 extract($args);
2104
2105 $tasks = $this->tasks;
2106 $task = $tasks['Backup Now'];
2107
2108 if (!empty($task)) {
2109 extract($task['task_args']);
2110 }
2111
2112 $results = $task['task_results'];
2113
2114 if (is_array($results) && count($results)) {
2115 $backup_file = $results[count($results) - 1]['server']['file_path'];
2116 }
2117
2118 if ($backup_file && file_exists($backup_file)) {
2119 //FTP, Amazon S3 or Dropbox
2120 if (isset($account_info['mwp_ftp']) && !empty($account_info['mwp_ftp'])) {
2121 $account_info['mwp_ftp']['backup_file'] = $backup_file;
2122 $return = $this->ftp_backup($account_info['mwp_ftp']);
2123 }
2124
2125 if (isset($account_info['mwp_amazon_s3']) && !empty($account_info['mwp_amazon_s3'])) {
2126 $account_info['mwp_amazon_s3']['backup_file'] = $backup_file;
2127 $return = $this->amazons3_backup($account_info['mwp_amazon_s3']);
2128 }
2129
2130 if (isset($account_info['mwp_dropbox']) && !empty($account_info['mwp_dropbox'])) {
2131 $account_info['mwp_dropbox']['backup_file'] = $backup_file;
2132 $return = $this->dropbox_backup($account_info['mwp_dropbox']);
2133 }
2134
2135 if (isset($account_info['mwp_email']) && !empty($account_info['mwp_email'])) {
2136 $account_info['mwp_email']['file_path'] = $backup_file;
2137 $account_info['mwp_email']['task_name'] = 'Backup Now';
2138 $return = $this->email_backup($account_info['mwp_email']);
2139 }
2140
2141 @file_put_contents(MWP_BACKUP_DIR.'/mwp_db/index.php', '');
2142 if ($return == true && $del_host_file) {
2143 @unlink($backup_file);
2144 unset($tasks['Backup Now']['task_results'][count($results) - 1]['server']);
2145 $this->update_tasks($tasks);
2146 //update_option('mwp_backup_tasks', $tasks);
2147 }
2148
2149
2150
2151 } else {
2152 $return = array(
2153 'error' => 'Backup file not found on your server. Please try again.'
2154 );
2155 }
2156
2157 return $return;
2158
2159 }
2160
2161 function validate_task($args, $url)
2162 {
2163 if (!class_exists('WP_Http')) {
2164 include_once(ABSPATH . WPINC . '/class-http.php');
2165 }
2166 $params = array();
2167 $params['body'] = $args;
2168 $result = wp_remote_post($url, $params);
2169 if (is_array($result) && $result['body'] == 'mwp_delete_task') {
2170 //$tasks = $this->get_backup_settings();
2171 $tasks = $this->tasks;
2172 unset($tasks[$args['task_name']]);
2173 $this->update_tasks($tasks);
2174 $this->cleanup();
2175 exit;
2176 } elseif(is_array($result) && $result['body'] == 'mwp_pause_task'){
2177 return 'paused';
2178 }
2179
2180 return 'ok';
2181 }
2182
2183 function update_status($task_name, $status, $completed = false)
2184 {
2185 /* Statuses:
2186 0 - Backup started
2187 1 - DB dump
2188 2 - DB ZIP
2189 3 - Files ZIP
2190 4 - Amazon S3
2191 5 - Dropbox
2192 6 - FTP
2193 7 - Email
2194 100 - Finished
2195 */
2196 if ($task_name != 'Backup Now') {
2197 $tasks = $this->tasks;
2198 $index = count($tasks[$task_name]['task_results']) - 1;
2199 if (!is_array($tasks[$task_name]['task_results'][$index]['status'])) {
2200 $tasks[$task_name]['task_results'][$index]['status'] = array();
2201 }
2202 if (!$completed) {
2203 $tasks[$task_name]['task_results'][$index]['status'][] = (int) $status * (-1);
2204 } else {
2205 $status_index = count($tasks[$task_name]['task_results'][$index]['status']) - 1;
2206 $tasks[$task_name]['task_results'][$index]['status'][$status_index] = abs($tasks[$task_name]['task_results'][$index]['status'][$status_index]);
2207 }
2208
2209 $this->update_tasks($tasks);
2210 //update_option('mwp_backup_tasks',$tasks);
2211 }
2212 }
2213
2214 function update_tasks($tasks)
2215 {
2216 $this->tasks = $tasks;
2217 update_option('mwp_backup_tasks', $tasks);
2218 }
2219
2220 function wpdb_reconnect(){
2221 global $wpdb;
2222 //Reconnect to avoid timeout problem after ZIP files
2223 if(class_exists('wpdb') && function_exists('wp_set_wpdb_vars')){
2224 @mysql_close($wpdb->dbh);
2225 $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
2226 wp_set_wpdb_vars();
2227 }
2228 }
2229
2230 function replace_htaccess($url)
2231 {
2232 $file = @file_get_contents(ABSPATH.'.htaccess');
2233 if ($file && strlen($file)) {
2234 $args = parse_url($url);
2235 $string = rtrim($args['path'], "/");
2236 $regex = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
2237 $replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
2238 $file = preg_replace($regex, $replace, $file);
2239 @file_put_contents(ABSPATH.'.htaccess', $file);
2240 }
2241 }
2242
2243 function check_cron_remove(){
2244 if(empty($this->tasks) || (count($this->tasks) == 1 && isset($this->tasks['Backup Now'])) ){
2245 wp_clear_scheduled_hook('mwp_backup_tasks');
2246 exit;
2247 }
2248 }
2249
2250 public static function readd_tasks( $params = array() ){
2251 global $mmb_core;
2252
2253 if( empty($params) || !isset($params['backups']) )
2254 return $params;
2255
2256 $before = array();
2257 $tasks = $params['backups'];
2258 if( !empty($tasks) ){
2259 $mmb_backup = new MMB_Backup();
2260
2261 if( function_exists( 'wp_next_scheduled' ) ){
2262 if ( !wp_next_scheduled('mwp_backup_tasks') ) {
2263 wp_schedule_event( time(), 'tenminutes', 'mwp_backup_tasks' );
2264 }
2265 }
2266
2267 foreach( $tasks as $task ){
2268 $before[$task['task_name']] = array();
2269
2270 if(isset($task['secure'])){
2271 if($decrypted = $mmb_core->_secure_data($task['secure'])){
2272 $decrypted = maybe_unserialize($decrypted);
2273 if(is_array($decrypted)){
2274 foreach($decrypted as $key => $val){
2275 if(!is_numeric($key))
2276 $task[$key] = $val;
2277 }
2278 unset($task['secure']);
2279 } else
2280 $task['secure'] = $decrypted;
2281 }
2282
2283 }
2284 if (isset($task['account_info']) && is_array($task['account_info'])) { //only if sends from master first time(secure data)
2285 $task['args']['account_info'] = $task['account_info'];
2286 }
2287
2288 $before[$task['task_name']]['task_args'] = $task['args'];
2289 $before[$task['task_name']]['task_args']['next'] = $mmb_backup->schedule_next($task['args']['type'], $task['args']['schedule']);
2290 }
2291 }
2292 update_option('mwp_backup_tasks', $before);
2293
2294 unset($params['backups']);
2295 return $params;
2296 }
2297 }
2298
2299 if( function_exists('add_filter') ){
2300 add_filter( 'mwp_website_add', 'MMB_Backup::readd_tasks' );
2301 }
2302 ?>