PluginProbe
ManageWP Worker / 3.9.22
ManageWP Worker v3.9.22
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.22, at backup.class.php

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