PluginProbe
InfiniteWP Client / trunk
InfiniteWP Client vtrunk
1.13.10 1.13.7 trunk 0.1.4 0.1.5 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.1.0 1.1.1 1.1.10 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 1.1.9 1.11.0 1.11.1 1.12.1 1.12.3 All 92 releases
iwp-client / backup.class.singlecall.php

backup.class.singlecall.php in InfiniteWP Client trunk, at backup.class.singlecall.php

3,793 lines 142.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1
2 <?php
3
4 /************************************************************
5 * This plugin was modified by Revmakx *
6 * Copyright (c) 2012 Revmakx *
7 * www.revmakx.com *
8 * *
9 ************************************************************/
10 /*************************************************************
11 *
12 * backup.class.php
13 *
14 * Manage Backups
15 *
16 *
17 * Copyright (c) 2011 Prelovac Media
18 * www.prelovac.com
19 **************************************************************/
20 if ( ! defined('ABSPATH') )
21 die();
22
23 if(!defined('IWP_BACKUP_DIR')){
24 define('IWP_BACKUP_DIR', WP_CONTENT_DIR . '/infinitewp/backups');
25 }
26
27 if(!defined('IWP_DB_DIR')){
28 define('IWP_DB_DIR', IWP_BACKUP_DIR . '/iwp_db');
29 }
30
31 if(!defined('IWP_PCLZIP_TEMPORARY_DIR')){
32 define('IWP_PCLZIP_TEMPORARY_DIR', WP_CONTENT_DIR . '/infinitewp/temp/');
33 }
34
35 $zip_errors = array(
36 'No error',
37 'No error',
38 'Unexpected end of zip file',
39 'A generic error in the zipfile format was detected',
40 'zip was unable to allocate itself memory',
41 'A severe error in the zipfile format was detected',
42 'Entry too large to be split with zipsplit',
43 'Invalid comment format',
44 'zip -T failed or out of memory',
45 'The user aborted zip prematurely',
46 'zip encountered an error while using a temp file. Please check if this domain\'s account has enough disk space.',
47 'Read or seek error',
48 'zip has nothing to do',
49 'Missing or empty zip file',
50 'Error writing to a file. Please check if this domain\'s account has enough disk space.',
51 'zip was unable to create a file to write to',
52 'bad command line parameters',
53 'no error',
54 'zip could not open a specified file to read'
55 );
56 $unzip_errors = array(
57 'No error',
58 'One or more warning errors were encountered, but processing completed successfully anyway',
59 'A generic error in the zipfile format was detected',
60 'A severe error in the zipfile format was detected.',
61 'unzip was unable to allocate itself memory.',
62 'unzip was unable to allocate memory, or encountered an encryption error',
63 'unzip was unable to allocate memory during decompression to disk',
64 'unzip was unable allocate memory during in-memory decompression',
65 'unused',
66 'The specified zipfiles were not found',
67 'Bad command line parameters',
68 'No matching files were found',
69 50 => 'The disk is (or was) full during extraction',
70 51 => 'The end of the ZIP archive was encountered prematurely.',
71 80 => 'The user aborted unzip prematurely.',
72 81 => 'Testing or extraction of one or more files failed due to unsupported compression methods or unsupported decryption.',
73 82 => 'No files were found due to bad decryption password(s)'
74 );
75
76 class IWP_MMB_Backup_Singlecall extends IWP_MMB_Core
77 {
78 var $site_name;
79 var $statuses;
80 var $tasks;
81 var $s3;
82 var $ftp;
83 var $dropbox;
84 function __construct()
85 {
86 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
87 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/iwp-file-iterator.php';
88 parent::__construct();
89 $this->site_name = str_replace(array(
90 "_",
91 "/",
92 "~"
93 ), array(
94 "",
95 "-",
96 "-"
97 ), rtrim($this->remove_http(get_bloginfo('url')), "/"));
98 $this->statuses = array(
99 'db_dump' => 1,
100 'db_zip' => 2,
101 'files_zip' => 3,
102 'finished' => 100
103 );
104
105
106
107 }
108 function set_resource_limit()
109 {
110 $changed = array('execution_time' => 0, 'memory_limit' => 0);
111 @ignore_user_abort(true);
112
113 // $memory_limit = trim(ini_get('memory_limit'));
114 // $last = strtolower(substr($memory_limit, -1));
115 //
116 // if($last == 'g')
117 // $memory_limit = ((int) $memory_limit)*1024;
118 // elseif($last == 'm')
119 // $memory_limit = (int) $memory_limit;
120 // elseif($last == 'k')
121 // $memory_limit = ((int) $memory_limit)/1024;
122 //
123 // if ( $memory_limit < 384 ) {
124 // @ini_set('memory_limit', '384M');
125 // $changed['memory_limit'] = 1;
126 // }
127
128 @ini_set('memory_limit', -1);
129 $changed['memory_limit'] = 1;
130
131 if ( (int) @ini_get('max_execution_time') < 1200 ) {
132 @ini_set('max_execution_time', 1200);//twenty minutes
133 @set_time_limit(1200);
134 $changed['execution_time'] = 1;
135 }
136
137 return $changed;
138
139 }
140
141 /*function get_backup_settings()
142 {
143 $backup_settings = get_option('iwp_client_backup_tasks');
144 if (!empty($backup_settings))
145 return $backup_settings;
146 else
147 return false;
148 }*/
149
150 function set_backup_task($params){
151 global $iwp_mmb_activities_log;
152
153 if (!empty($params)) {
154 $historyID = '';
155 $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'processing', 'statusMsg' => 'verificationInitiated'), $params);
156
157 $this->set_resource_limit();
158
159 $this->tasks = $this->get_this_tasks('requestParams');
160
161 if(!empty($this->tasks['account_info']) && !empty($this->tasks['account_info']['iwp_dropbox'])){
162 if(empty($this->tasks['account_info']['iwp_dropbox']['dropbox_access_token']) && time() > 1498608000){
163 return array('error' => 'Please update your cloud backup addon to v1.2.0 or above to use Dropbox API V2', 'error_code' => 'drop_box_update');
164 }elseif(!is_new_dropbox_compatible()){
165 return array('error' => 'Please upgrade your PHP version to 5.3.3 or above to use Dropbox V2 API', 'error_code' => 'drop_box_version_incompitability');
166 }
167 upgradeOldDropBoxBackupList($this->tasks['account_info']['iwp_dropbox']);
168 }
169 if ((!defined('DISABLE_IWP_CLOUD_VERIFICATION')) && (empty($this->tasks['args']['disable_iwp_cloud_verification']))) {
170 $backup_repo_test_obj = new IWP_BACKUP_REPO_TEST();
171 $backup_repo_test_result = $backup_repo_test_obj->repositoryTestConnection($this->tasks['account_info']);
172 if (!empty($backup_repo_test_result['error']) && $backup_repo_test_result['status'] != 'success') {
173 return array('error' => $backup_repo_test_result['error'], 'error_code' => $backup_repo_test_result['error_code']);
174 }
175 }
176
177 extract($params);
178
179 //if ($task_name == 'Backup Now') {
180
181 $result = $this->backup($args, $task_name);
182
183 $backup_settings = $this->get_this_tasks();
184
185 if (is_array($result) && array_key_exists('error', $result)) {
186 $return = $result;
187 } else {
188 $iwp_mmb_activities_log->iwp_mmb_collect_backup_details($params);
189
190 $return = unserialize($backup_settings['taskResults']);
191 }
192 //}
193
194 return $return;
195 }
196
197 return false;
198 }
199
200
201 function delete_task_now($task_name){
202 global $wpdb, $iwp_backup_core;
203
204 $table_name = $wpdb->base_prefix . "iwp_backup_status";
205
206 $tasks = $this->tasks;
207 //unset($tasks[$task_name]);
208
209 $stats = array();
210 $new_backup_method = $iwp_backup_core->get_backup_history();
211 $task_res = array();
212 if (!empty($new_backup_method)) {
213 foreach ($new_backup_method as $time => $value) {
214 if ($value['label'] == $task_name) {
215 unset($new_backup_method[$time]);
216 }
217 }
218 }
219 $iwp_backup_core->save_history($new_backup_method);
220 $delete_query = $wpdb->prepare(
221 "DELETE FROM {$table_name} WHERE taskName = %s",
222 $task_name
223 );
224 $deleteRes = $wpdb->query($delete_query);
225
226 $this->update_tasks($tasks);
227 $this->cleanup();
228
229 return $task_name;
230
231 }
232
233 /*
234 * If Task Name not set then it's manual backup
235 * Backup args:
236 * type -> db, full
237 * what -> daily, weekly, monthly
238 * account_info -> ftp, amazons3, dropbox
239 * exclude-> array of paths to exclude from backup
240 */
241
242 function backup($args, $task_name = false)
243 {
244 if (!$args || empty($args))
245 return false;
246
247 extract($args); //extract settings
248
249 //Remove old backup(s)
250 $removed = $this->remove_old_backups($task_name);
251 if (is_array($removed) && isset($removed['error'])) {
252 //$error_message = $removed['error'];
253 return $removed;
254 }
255
256 $new_file_path = IWP_BACKUP_DIR;
257
258 if (!file_exists($new_file_path)) {
259 if (!mkdir($new_file_path, 0755, true))
260 return array(
261 'error' => 'Permission denied, make sure you have write permission to wp-content folder.', 'error_code' => 'permission_denied_wpcontent_folder'
262 );
263 }
264
265 @file_put_contents($new_file_path . '/index.php', ''); //safe
266
267 //pclzip temp folder creation
268
269 if(!(file_exists(IWP_PCLZIP_TEMPORARY_DIR) && is_dir(IWP_PCLZIP_TEMPORARY_DIR)))
270 {
271 $mkdir = @mkdir(IWP_PCLZIP_TEMPORARY_DIR, 0755, true);
272 if(!$mkdir){
273 return array('error' => 'Error creating database backup folder (' . IWP_PCLZIP_TEMPORARY_DIR . '). Make sure you have corrrect write permissions.');
274 }
275 }
276 if(is_writable(IWP_PCLZIP_TEMPORARY_DIR))
277 {
278 @file_put_contents(IWP_PCLZIP_TEMPORARY_DIR . '/index.php', ''); //safe
279 }
280 else
281 {
282 $chmod = chmod(IWP_PCLZIP_TEMPORARY_DIR, 777);
283 if(!is_writable(IWP_PCLZIP_TEMPORARY_DIR)){
284 return array('error' => IWP_PCLZIP_TEMPORARY_DIR.' directory is not writable. Please set 755 or 777 file permission and try again.');
285 }
286 }
287
288 //Prepare .zip file name
289 $hash = md5(microtime(true).uniqid('',true).substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(20,60)));
290 $label = $type ? $type : 'manual';
291 $backup_file = $new_file_path . '/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
292 $backup_url = content_url() . '/infinitewp/backups/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
293
294 //Optimize tables?
295 if (isset($optimize_tables) && !empty($optimize_tables)) {
296 $this->optimize_tables();
297 }
298
299 $exclude_file_size = $this->tasks['args']['exclude_file_size'];
300 $exclude_extensions = $this->tasks['args']['exclude_extensions'];
301 $disable_comp = $this->tasks['args']['disable_comp'];
302 $comp_level = $disable_comp ? '-0' : '-1';
303
304 //What to backup - db or full?
305 if (trim($what) == 'db') {
306
307 $db_backup = $this->backup_db_alone($task_name, $backup_file, $comp_level);
308
309 if (is_array($db_backup) && array_key_exists('error', $db_backup)) {
310 return array(
311 'error' => $db_backup['error'], 'error_code' => $db_backup['error_code']
312 );
313 }
314
315 }
316 elseif(trim($what) == 'files'){
317 $content_backup = $this->backup_files_alone($task_name, $backup_file, $exclude, $include, $comp_level, $exclude_file_size, $exclude_extensions);
318 if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
319 return array(
320 'error' => $content_backup['error'], 'error_code' => $content_backup['error_code']
321 );
322 }
323 }
324 elseif (trim($what) == 'full') {
325 $db_backup = $this->backup_db_alone($task_name, $backup_file, $comp_level);
326 if (is_array($db_backup) && array_key_exists('error', $db_backup)) {
327 return array(
328 'error' => $db_backup['error'], 'error_code' => $db_backup['error_code']
329 );
330 }
331 $content_backup = $this->backup_files_alone($task_name, $backup_file, $exclude, $include, $comp_level, $exclude_file_size, $exclude_extensions);
332 if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
333 return array(
334 'error' => $content_backup['error'], 'error_code' => $content_backup['error_code']
335 );
336 }
337 }
338
339
340 //Update backup info
341 if ($task_name) {
342 //backup task (scheduled)
343
344 $backup_settings = $this->tasks;
345 $paths = array();
346 $size = round(iwp_mmb_get_file_size($backup_file) / 1024, 2);
347
348 if ($size > 1000) {
349 $paths['size'] = round($size / 1024, 2) . " MB";//Modified by IWP //Mb => MB
350 } else {
351 $paths['size'] = $size . 'KB';//Modified by IWP //Kb => KB
352 }
353
354 $paths['backup_name'] = $backup_settings['args']['backup_name'];
355 $paths['mechanism'] = 'singleCall';
356
357 $paths['server'] = array(
358 'file_path' => $backup_file,
359 'file_url' => $backup_url);
360
361 $paths['time'] = time();
362 $paths['adminHistoryID'] = $GLOBALS['IWP_CLIENT_HISTORY_ID']; //['adminHistoryID'] = $GLOBALS['IWP_CLIENT_HISTORY_ID'];
363
364
365 if (isset($backup_settings['account_info']['iwp_ftp'])) {
366
367 $this->update_status($task_name,'ftp');
368
369 $paths['ftp'] = basename($backup_url);
370
371 $backup_settings['account_info']['iwp_ftp']['backup_file'] = $backup_file;
372 iwp_mmb_print_flush('FTP upload: Start');
373 $ftp_result = $this->ftp_backup($backup_settings['account_info']['iwp_ftp']);
374 iwp_mmb_print_flush('FTP upload: End');
375 if ($ftp_result !== true && $del_host_file) {
376 @unlink($backup_file);
377 }
378
379 if (is_array($ftp_result) && isset($ftp_result['error'])) {
380 return $ftp_result;
381 }
382 $this->update_status($task_name,'ftp', true);
383
384 unset($paths['server']);
385 }
386
387 if (isset($backup_settings['account_info']['iwp_amazon_s3'])) {
388
389 $this->update_status($task_name,'amazon_s3');
390
391 $paths['amazons3'] = basename($backup_url);
392
393 $backup_settings['account_info']['iwp_amazon_s3']['backup_file'] = $backup_file;
394 iwp_mmb_print_flush('Amazon S3 upload: Start');
395 if(is_new_s3_compatible()){
396 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
397 $new_s3_obj = new IWP_MMB_S3_SINGLECALL();
398 $amazons3_result = $new_s3_obj->amazons3_backup($backup_settings['account_info']['iwp_amazon_s3']);
399 }
400 else{
401 $amazons3_result = $this->amazons3_backup_bwd_comp($backup_settings['account_info']['iwp_amazon_s3']);
402 }
403 iwp_mmb_print_flush('Amazon S3 upload: End');
404 if ($amazons3_result !== true && $del_host_file) {
405 @unlink($backup_file);
406 }
407 if (is_array($amazons3_result) && isset($amazons3_result['error'])) {
408 return $amazons3_result;
409 }
410
411 $this->update_status($task_name,'amazon_s3', true);
412
413 unset($paths['server']);
414 }
415
416 if (isset($backup_settings['account_info']['iwp_dropbox'])) {
417
418 $this->update_status($task_name,'dropbox');
419
420 $paths['dropbox'] = basename($backup_url);
421
422 $backup_settings['account_info']['iwp_dropbox']['backup_file'] = $backup_file;
423 iwp_mmb_print_flush('Dropbox upload: Start');
424 $dropbox_result = $this->dropbox_backup($backup_settings['account_info']['iwp_dropbox']);
425 iwp_mmb_print_flush('Dropbox upload: End');
426 if ($dropbox_result !== true && $del_host_file) {
427 @unlink($backup_file);
428 }
429
430 if (is_array($dropbox_result) && isset($dropbox_result['error'])) {
431 return $dropbox_result;
432 }
433
434 $this->update_status($task_name,'dropbox', true);
435 unset($paths['server']);
436 }
437
438 if (isset($backup_settings['account_info']['iwp_gdrive'])) {
439
440 $this->update_status($task_name,'gDrive');
441
442 $paths['gDrive'] = basename($backup_url);
443
444
445 $backup_settings['account_info']['iwp_gdrive']['backup_file'] = $backup_file;
446 iwp_mmb_print_flush('google Drive upload: Start');
447 $gdrive_result = $this->google_drive_backup($backup_settings['account_info']['iwp_gdrive']);
448 iwp_mmb_print_flush('google Drive upload: End');
449
450 if ($gdrive_result == false && $del_host_file) {
451 @unlink($backup_file);
452 }
453
454 if (is_array($gdrive_result) && isset($gdrive_result['error'])) {
455 return $gdrive_result;
456 }
457
458 $paths['gDrive'] = $gdrive_result; //different from other upload ; storing the gDrive backupfile ID in the paths array for delete operation
459 $paths['gDriveOrgFileName'] = basename($backup_url);
460
461 $this->update_status($task_name,'gDrive', true);
462 unset($paths['server']);
463 }
464
465 }
466
467 if ($del_host_file) {
468 @unlink($backup_file);
469 }
470 $this->update_status($task_name,'finished',true, $paths);
471 $removed = $this->remove_old_backups($task_name);
472 if (is_array($removed) && isset($removed['error'])) {
473 //$error_message = $removed['error'];
474 return $removed;
475 }
476
477 return $backup_url;
478 }
479
480 function backup_db_alone($task_name, $backup_file, $comp_level){
481
482 //Take database backup
483 $this->update_status($task_name, 'db_dump');
484 //$this->statusLog();
485 $GLOBALS['fail_safe_db'] = $this->tasks['args']['fail_safe_db'];
486
487 $db_result = $this->backup_db();
488
489 if ($db_result == false) {
490 return array(
491 'error' => 'Failed to backup database.', 'error_code' => 'backup_database_failed'
492 );
493 } else if (is_array($db_result) && isset($db_result['error'])) {
494 return array(
495 'error' => $db_result['error'], 'error_code' => $db_result['error_code']
496 );
497 } else {
498 $this->update_status($task_name, 'db_dump', true);
499 //$this->statusLog();
500
501 $this->update_status($task_name, 'db_zip');
502 //$this->statusLog();
503
504 /*zip_backup_db*/
505 $fail_safe_db = $this->tasks['args']['fail_safe_db'];
506 $disable_comp = $this->tasks['args']['disable_comp'];
507
508 if($fail_safe_db){
509 $pcl_result = $this->fail_safe_pcl_db($backup_file,$fail_safe_db,$disable_comp);
510 if(is_array($pcl_result) && isset($pcl_result['error'])){
511 return $pcl_result;
512 }
513 }
514 else{
515 chdir(IWP_BACKUP_DIR);
516 $zip = $this->get_zip();
517 $command = "$zip -q -r $comp_level $backup_file 'iwp_db'";
518 iwp_mmb_print_flush('DB ZIP CMD: Start');
519 ob_start();
520 $result = $this->iwp_mmb_exec($command);
521 ob_get_clean();
522 iwp_mmb_print_flush('DB ZIP CMD Result: '.$result);
523 iwp_mmb_print_flush('DB ZIP CMD: End');
524 /*zip_backup_db */
525 if(!$result){
526 $zip_archive_db_result = false;
527 if (class_exists("ZipArchive")) {
528 $this->_log("DB zip, fallback to ZipArchive");
529 iwp_mmb_print_flush('DB ZIP Archive: Start');
530 $zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
531 iwp_mmb_print_flush('DB ZIP Archive Result: '.$zip_archive_db_result);
532 iwp_mmb_print_flush('DB ZIP Archive: End');
533 }
534
535 if (!$zip_archive_db_result) {
536 $pcl_result = $this->fail_safe_pcl_db($backup_file,$fail_safe_db,$disable_comp);
537 if(is_array($pcl_result) && isset($pcl_result['error'])){
538 return $pcl_result;
539 }
540 }
541 }
542 }
543
544 @unlink($db_result);
545 @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
546 @rmdir(IWP_DB_DIR);
547
548 $this->update_status($task_name, 'db_zip', true);
549 //$this->statusLog();
550
551 return true;
552 }
553
554 }
555
556
557
558 function backup_files_alone($task_name, $backup_file, $exclude = array(), $include = array(), $comp_level = 0, $exclude_file_size = 0, $exclude_extensions = "")
559 {
560 global $zip_errors;
561 $sys = substr(PHP_OS, 0, 3);
562
563 if(empty($exclude_extensions))
564 {
565 $exclude_extensions = array();
566 }
567 else if($exclude_extensions == 'eg. .zip,.mp4')
568 {
569 $exclude_extensions = array();
570 }
571 else
572 {
573 $exclude_extensions_array = explode(",",$exclude_extensions);
574 $exclude_extensions = array();
575 $exclude_extensions = $exclude_extensions_array;
576 }
577
578 //Always remove backup folders
579 $remove = array(
580 trim(basename(WP_CONTENT_DIR)) . "/infinitewp/backups",
581 trim(basename(WP_CONTENT_DIR)) . "/" . md5('iwp_mmb-client') . "/iwp_backups",
582 trim(basename(WP_CONTENT_DIR)) . "/cache",
583 trim(basename(WP_CONTENT_DIR)) . "/managewp/backups",
584 trim(basename(WP_CONTENT_DIR)) . "/backupwordpress",
585 trim(basename(WP_CONTENT_DIR)) . "/contents/cache",
586 trim(basename(WP_CONTENT_DIR)) . "/content/cache",
587 trim(basename(WP_CONTENT_DIR)) . "/old-cache",
588 trim(basename(WP_CONTENT_DIR)) . "/cmscommander/backups",
589 trim(basename(WP_CONTENT_DIR)) . "/gt-cache",
590 trim(basename(WP_CONTENT_DIR)) . "/wfcache",
591 trim(basename(WP_CONTENT_DIR)) . "/bps-backup",
592 trim(basename(WP_CONTENT_DIR)) . "/old-cache",
593 trim(basename(WP_CONTENT_DIR)) . "/nfwlog",
594 trim(basename(WP_CONTENT_DIR)) . "/upgrade",
595 trim(basename(WP_CONTENT_DIR)) . "/nfwlog",
596 trim(basename(WP_CONTENT_DIR)) . "/wflogs",
597 trim(basename(WP_CONTENT_DIR)) . "/debug.log",
598 trim(basename(WP_CONTENT_DIR)) . "/wptouch-data/infinity-cache/",
599 trim(basename(WP_CONTENT_DIR)) . "/mysql.sql",
600 trim(basename(WP_CONTENT_DIR)) . "/wishlist-backup",
601 trim(basename(WP_CONTENT_DIR)) . "/w3tc",
602 trim(basename(WP_CONTENT_DIR)) . "/logs",
603 trim(basename(WP_CONTENT_DIR)) . "/widget_cache",
604 trim(basename(WP_CONTENT_DIR)) . "/tmp",
605 trim(basename(WP_CONTENT_DIR)) . "/updraft",
606 trim(basename(WP_CONTENT_DIR)) . "/updraftplus",
607 trim(basename(WP_CONTENT_DIR)) . "/backups",
608 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp-clone",
609 trim(basename(WP_CONTENT_DIR)) . "/uploads/uploads/db-backup",
610 trim(basename(WP_CONTENT_DIR)) . "/uploads/ithemes-security/backups",
611 trim(basename(WP_CONTENT_DIR)) . "/uploads/mainwp/backup",
612 trim(basename(WP_CONTENT_DIR)) . "/uploads/backupbuddy_backups",
613 trim(basename(WP_CONTENT_DIR)) . "/uploads/vcf",
614 trim(basename(WP_CONTENT_DIR)) . "/uploads/pb_backupbuddy",
615 trim(basename(WP_CONTENT_DIR)) . "/uploads/sucuri",
616 trim(basename(WP_CONTENT_DIR)) . "/uploads/aiowps_backups",
617 trim(basename(WP_CONTENT_DIR)) . "/uploads/mainwp",
618 trim(basename(WP_CONTENT_DIR)) . "/uploads/snapshots",
619 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp_system",
620 trim(basename(WP_CONTENT_DIR)) . "/uploads/wpcf7_captcha",
621 trim(basename(WP_CONTENT_DIR)) . "/uploads/wc-logs",
622 trim(basename(WP_CONTENT_DIR)) . "/uploads/siteorigin-widgets",
623 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp-hummingbird-cache",
624 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp-security-audit-log",
625 trim(basename(WP_CONTENT_DIR)) . "/uploads/backwpup-12b462-backups",
626 trim(basename(WP_CONTENT_DIR)) . "/uploads/wpallimport",
627 trim(basename(WP_CONTENT_DIR)) . "/uploads/backwpup-12b462-logs",
628 trim(basename(WP_CONTENT_DIR)) . "/uploads/backwpup-12b462-temp",
629 trim(basename(WP_CONTENT_DIR)) . "/Dropbox_Backup",
630 trim(basename(WP_PLUGIN_DIR)) . "/cache",
631 "wp-admin/error_log",
632 "wp-admin/php_errorlog",
633 "error_log",
634 "error.log",
635 "debug.log",
636 "WS_FTP.LOG",
637 "security.log",
638 "wp-tcapsule-bridge.zip",
639 "dbcache",
640 "pgcache",
641 "objectcache",
642 "wp-snapshots",
643 "site_map.xml",
644 "iwp-clone-log.txt",
645 "iwp-restore-log.txt",
646 "wp-content/wpmerge-temp"
647 );
648
649 //removing files which are larger than the specified size
650 //Note: in multicall the exclude process is done on pclzip.
651 if((!empty($exclude_file_size))||(!empty($exclude_extensions)))
652 {
653 //removing files which are larger than the specified size
654 $total_files_array = get_all_files_from_dir(ABSPATH, $remove);
655 $files_excluded_by_size = array();
656 foreach($total_files_array as $key => $value)
657 {
658 $this_base_name = basename($value);
659 $skip_after_ext = false;
660 //file extension based exclude
661 if(is_array($exclude_extensions) && (!empty($exclude_extensions)))
662 {
663 foreach($exclude_extensions as $ext)
664 {
665 $this_pos = strrpos($this_base_name, $ext);
666 if($this_pos !== false)
667 {
668 if(substr($this_base_name, $this_pos) == $ext)
669 {
670 $files_excluded_by_size[] = substr($value, strlen(ABSPATH));
671 $skip_after_ext = true; //to skip the file exclude by size
672 break;
673 }
674 }
675 }
676 }
677 if($skip_after_ext)
678 {
679 continue;
680 }
681 //file size based exclude
682 if(!empty($exclude_file_size))
683 {
684 if(iwp_mmb_get_file_size($value) >= $exclude_file_size*1024*1024)
685 {
686 $files_excluded_by_size[] = substr($value, strlen(ABSPATH));
687 }
688 }
689 }
690 $remove = array_merge($remove, $files_excluded_by_size);
691 }
692
693 if (is_array($exclude)) {
694 $exclude = array_merge($exclude, $remove);
695 }else{
696 $exclude = $remove;
697 }
698
699 //Exclude paths
700 $exclude_data = "-x";
701
702 $exclude_file_data = '';
703
704 if (!empty($exclude) && is_array($exclude)) {
705 foreach ($exclude as $data) {
706 if(empty($data))
707 continue;
708 if (is_dir(ABSPATH . $data)) {
709 if ($sys == 'WIN')
710 $exclude_data .= " $data/*.*";
711 else
712 $exclude_data .= " '$data/*'";
713 }else {
714 if ($sys == 'WIN'){
715 if(file_exists(ABSPATH . $data)){
716 $exclude_data .= " $data";
717 $exclude_file_data .= " $data";
718 }
719 }else {
720 if(file_exists(ABSPATH . $data)){
721 $exclude_data .= " '$data'";
722 $exclude_file_data .= " '$data'";
723 }
724 }
725 }
726 }
727 }
728
729 if($exclude_file_data){
730 $exclude_file_data = "-x".$exclude_file_data;
731 }
732
733
734 //Include paths by default
735 $add = array(
736 trim(WPINC),
737 trim(basename(WP_CONTENT_DIR)),
738 "wp-admin"
739 );
740
741 $include_data = ". -i";
742 foreach ($add as $data) {
743 if ($sys == 'WIN')
744 $include_data .= " $data/*.*";
745 else
746 $include_data .= " '$data/*'";
747 }
748
749 //Additional includes?
750 if (!empty($include) && is_array($include)) {
751 foreach ($include as $data) {
752 if(empty($data))
753 continue;
754 if ($data) {
755 if ($sys == 'WIN')
756 $include_data .= " $data/*.*";
757 else
758 $include_data .= " '$data/*'";
759 }
760 }
761 }
762
763 $this->update_status($task_name, 'files_zip');
764 chdir(ABSPATH);
765
766 $fail_safe_files = $this->tasks['args']['fail_safe_files'];
767 if (!isset($disable_comp)) {
768 $disable_comp = false;
769 }
770 if($fail_safe_files){
771 $pcl_result = $this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
772 if(is_array($pcl_result) && isset($pcl_result['error'])){
773 return $pcl_result;
774 }
775 }
776 else
777 {
778 $do_cmd_zip_alternative = false;
779 @copy($backup_file, $backup_file.'_2');
780
781 iwp_mmb_print_flush('Files ZIP CMD: Start');
782 $command = "zip -q -j $comp_level $backup_file .* * $exclude_file_data";
783 ob_start();
784 $result_f = $this->iwp_mmb_exec($command, false, true);
785 ob_get_clean();
786 iwp_mmb_print_flush('Files ZIP CMD Result: '.$result_f);
787 iwp_mmb_print_flush('Files ZIP CMD: 1/2 over');
788 if (!$result_f || $result_f == 18) { // disregard permissions error, file can't be accessed
789 $command = "zip -q -r $comp_level $backup_file $include_data $exclude_data";
790 ob_start();
791 $result_d = $this->iwp_mmb_exec($command, false, true);
792 ob_get_clean();
793 if (!$result_d || ($result_d && $result_d != 18)){
794 @unlink($backup_file);
795 $do_cmd_zip_alternative = true;
796
797
798 if($result_d > 0 && $result_d < 18){
799 iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files (' . $zip_errors[$result_d] . ') .');
800 }
801 else{
802 iwp_mmb_print_flush('Files ZIP CMD: Failed to archive files.');
803 }
804 }
805 }
806
807 if(!$do_cmd_zip_alternative){//if FILE ZIP CMD successful
808 @unlink($backup_file.'_2');
809 }
810
811 iwp_mmb_print_flush('Files ZIP CMD: End');
812 if (($result_f && $result_f != 18) || ($do_cmd_zip_alternative)) {
813
814 if($do_cmd_zip_alternative){
815 @copy($backup_file.'_2', $backup_file);
816 @unlink($backup_file.'_2');
817 }
818
819 $zip_archive_result = false;
820 if (class_exists("ZipArchive")) {
821 iwp_mmb_print_flush('Files ZIP Archive: Start');
822 $this->_log("Files zip fallback to ZipArchive");
823 $zip_archive_result = $this->zip_archive_backup($task_name, $backup_file, $exclude, $include);
824 iwp_mmb_print_flush('Files ZIP Archive Result: '.$zip_archive_result);
825 iwp_mmb_print_flush('Files ZIP Archive: End');
826 }
827
828 if (!$zip_archive_result) {
829 $pcl_result = $this->fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove);
830 if(is_array($pcl_result) && isset($pcl_result['error'])){
831 return $pcl_result;
832 }
833 }
834 }
835 }
836
837 //Reconnect
838 $this->wpdb_reconnect();
839
840 $this->update_status($task_name, 'files_zip', true);
841 return true;
842 }
843
844
845
846 function fail_safe_pcl_files($task_name, $backup_file, $exclude, $include, $fail_safe_files, $disable_comp, $add, $remove){ //Try pclZip
847 //$this->back_hack($task_name, 'Files ZIP PCL: Start');
848 iwp_mmb_print_flush('Files ZIP PCL: Start');
849 if (!isset($archive)) {
850 //define('IWP_PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
851 //require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
852 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
853 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/iwp-file-iterator.php';
854 $archive = new IWPPclZip($backup_file);
855 }
856
857 //Include paths
858 $include_data = array();
859 if (!empty($include) && is_array($include)) {
860 foreach ($include as $data) {
861 if ($data && file_exists(ABSPATH . $data))
862 $include_data[] = ABSPATH . $data . '/';
863 }
864 }
865
866 foreach ($add as $data) {
867 if (file_exists(ABSPATH . $data))
868 $include_data[] = ABSPATH . $data . '/';
869 }
870
871 //Include root files
872 if ($handle = opendir(ABSPATH)) {
873 while (false !== ($file = readdir($handle))) {
874 if ($file != "." && $file != ".." && !is_dir($file) && file_exists(ABSPATH . $file)) {
875 $include_data[] = ABSPATH . $file;
876 }
877 }
878 closedir($handle);
879 }
880
881 //exclude paths
882 $exclude_data = array();
883 if (!empty($exclude) && is_array($exclude)) {
884 foreach ($exclude as $data) {
885 if (is_dir(ABSPATH . $data))
886 $exclude_data[] = $data . '/';
887 else
888 $exclude_data[] = $data;
889 }
890 }
891
892 foreach ($remove as $rem) {
893 $exclude_data[] = $rem . '/';
894 }
895
896 if($fail_safe_files && $disable_comp){
897 $result = $archive->add($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, IWP_PCLZIP_OPT_NO_COMPRESSION, IWP_PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
898 }
899 elseif(!$fail_safe_files && $disable_comp){
900 $result = $archive->add($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, IWP_PCLZIP_OPT_NO_COMPRESSION);
901 }
902 elseif($fail_safe_files && !$disable_comp){
903 $result = $archive->add($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, IWP_PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
904 }
905 else{
906 $result = $archive->add($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data);
907 }
908
909 iwp_mmb_print_flush('Files ZIP PCL: End');
910
911 if (!$result) {
912 @unlink($backup_file);
913 return array(
914 'error' => 'Failed to zip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string, 'error_code' => 'failed_zip_files_pclZip_error'
915 );
916 }
917 //}
918 }
919 //Reconnect
920 function fail_safe_pcl_db($backup_file,$fail_safe_files,$disable_comp){
921 //$this->back_hack($task_name, 'DB ZIP PCL: Start');
922 iwp_mmb_print_flush('DB ZIP PCL: Start');
923 //define('IWP_PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
924 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
925 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/iwp-file-iterator.php';
926 $archive = new IWPPclZip($backup_file);
927
928 if($fail_safe_files && $disable_comp){
929 $result_db = $archive->add(IWP_DB_DIR, IWP_PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, IWP_PCLZIP_OPT_NO_COMPRESSION, IWP_PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
930 }
931 elseif(!$fail_safe_files && $disable_comp){
932 $result_db = $archive->add(IWP_DB_DIR, IWP_PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, IWP_PCLZIP_OPT_NO_COMPRESSION);
933 }
934 elseif($fail_safe_files && !$disable_comp){
935 $result_db = $archive->add(IWP_DB_DIR, IWP_PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, IWP_PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
936 }
937 else{
938 $result_db = $archive->add(IWP_DB_DIR, IWP_PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR);
939 }
940 //$this->back_hack($task_name, 'DB ZIP PCL: End');
941 iwp_mmb_print_flush('DB ZIP PCL: End');
942
943 @unlink($db_result);
944 @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
945 @rmdir(IWP_DB_DIR);
946
947 if (!$result_db) {
948 return array(
949 'error' => 'Failed to zip database. pclZip error (' . $archive->error_code . '): .' . $archive->error_string, 'error_code' => 'failed_to_zip_database_pclZip_error'
950 );
951 }
952 }
953 /**
954 * Zipping database dump and index.php in folder iwp_db by ZipArchive class, requires php zip extension.
955 *
956 * @param string $task_name the name of backup task
957 * @param string $db_result relative path to database dump file
958 * @param string $backup_file absolute path to zip file
959 * @return bool is compress successful or not
960 */
961 function zip_archive_backup_db($task_name, $db_result, $backup_file) {
962 $disable_comp = $this->tasks['args']['disable_comp'];
963 if (!$disable_comp) {
964 $this->_log("Compression is not supported by ZipArchive");
965 }
966 $zip = new ZipArchive();
967
968 $result = $zip->open($backup_file, ZIPARCHIVE::OVERWRITE); // Tries to open $backup_file for acrhiving
969 if ($result === true) {
970 $result = $result && $zip->addFile(IWP_BACKUP_DIR.'/iwp_db/index.php', "iwp_db/index.php"); // Tries to add iwp_db/index.php to $backup_file
971 $result = $result && $zip->addFile($db_result, "iwp_db/" . basename($db_result)); // Tries to add db dump form iwp_db dir to $backup_file
972 $result = $result && $zip->close(); // Tries to close $backup_file
973 } else {
974 $result = false;
975 }
976
977 return $result; // true if $backup_file iz zipped successfully, false if error is occurred in zip process
978 }
979
980 /**
981 * Zipping whole site root folder and append to backup file with database dump
982 * by ZipArchive class, requires php zip extension.
983 *
984 * @param string $task_name the name of backup task
985 * @param string $backup_file absolute path to zip file
986 * @param array $exclude array of files of folders to exclude, relative to site's root
987 * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
988 * @return array|bool true if successful or an array with error message if not
989 */
990 function zip_archive_backup($task_name, $backup_file, $exclude, $include, $overwrite = false) {
991 $filelist = $this->get_backup_files($exclude, $include);
992 $disable_comp = $this->tasks['args']['disable_comp'];
993 if (!$disable_comp) {
994 $this->_log("Compression is not supported by ZipArchive");
995 }
996
997 $zip = new ZipArchive();
998
999 if ($overwrite) {
1000 $result = $zip->open($backup_file, ZipArchive::OVERWRITE); // Tries to open $backup_file for acrhiving
1001 }
1002 else{
1003 if(file_exists($backup_file)){
1004 $result = $zip->open($backup_file); // Tries to open $backup_file for acrhiving
1005 }else{
1006 $result = $zip->open($backup_file, ZIPARCHIVE::CREATE);
1007 }
1008 }
1009
1010 $max_mb_size=1;
1011 if ($result === true) {
1012 $size_checker = 0;
1013 foreach ($filelist as $file) {
1014 iwp_mmb_auto_print('zip_archive_backup');
1015 if(is_readable($file)){ //checking file is readable
1016 $file_size_in_bytes=filesize($file); //getting file size
1017 if($file_size_in_bytes > $max_mb_size*1024*1024){ //if file size more than 1 MB it will be added sepearately
1018 $result = $result && $zip->close();
1019 $size_checker = 0; //reset $size_checker
1020 if(file_exists($backup_file)){
1021 $result = $zip->open($backup_file);
1022 }
1023 $result = $result && $zip->addFile($file, sprintf("%s", str_replace(ABSPATH, '', $file))); // Tries to add a new file to $backup_file
1024 $result = $result && $zip->close();
1025 $size_checker = 0; //reset $size_checker
1026 if(file_exists($backup_file)){
1027 $result = $zip->open($backup_file);
1028 }
1029 }
1030 else{
1031 if($size_checker<$max_mb_size*1024*1024){ //checking $size_checker
1032 $result = $result && $zip->addFile($file, sprintf("%s", str_replace(ABSPATH, '', $file))); // Tries to add a new file to $backup_file
1033 $size_checker = $size_checker + $file_size_in_bytes; //adding added file size
1034 }
1035 else {
1036 $result = $result && $zip->close();
1037 $size_checker = 0; //reset $size_checker
1038 if(file_exists($backup_file)){
1039 $result = $zip->open($backup_file);
1040 }
1041 $result = $result && $zip->addFile($file, sprintf("%s", str_replace(ABSPATH, '', $file))); // Tries to add a new file to $backup_file
1042 $size_checker=$size_checker + $file_size_in_bytes; //adding added file size
1043 }
1044 }
1045 }
1046 }
1047 $result = $result && $zip->close(); // Tries to close $backup_file
1048 }else{
1049 $result = false;
1050 }
1051 return $result; // true if $backup_file iz zipped successfully, false if error is occurred in zip process
1052 }
1053
1054
1055 /**
1056 * Gets an array of relative paths of all files in site root recursively.
1057 * By default, there are all files from root folder, all files from folders wp-admin, wp-content, wp-includes recursively.
1058 * Parameter $include adds other folders from site root, and excludes any file or folder by relative path to site's root.
1059 *
1060 * @param array $exclude array of files of folders to exclude, relative to site's root
1061 * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
1062 * @return array array with all files in site root dir
1063 */
1064 function get_backup_files($exclude, $include) {
1065
1066 $add = array(
1067 trim(WPINC),
1068 trim(basename(WP_CONTENT_DIR)),
1069 "wp-admin"
1070 );
1071
1072 $include = array_merge($add, $include);
1073
1074 $filelist = array();
1075 if ($handle = opendir(ABSPATH)) {
1076 while (false !== ($file = readdir($handle))) {
1077 if (is_dir($file) && file_exists(ABSPATH . $file) && !(in_array($file, $include))) {
1078 $exclude[] = $file;
1079 }
1080 }
1081 closedir($handle);
1082 }
1083
1084 $filelist = get_all_files_from_dir(ABSPATH, $exclude);
1085 return $filelist;
1086 }
1087
1088
1089 function backup_db()
1090 {
1091 $db_folder = IWP_DB_DIR . '/';
1092 if (!file_exists($db_folder)) {
1093 if (!mkdir($db_folder, 0755, true))
1094 return array(
1095 'error' => 'Error creating database backup folder (' . $db_folder . '). Make sure you have corrrect write permissions.', 'error_code' => 'error_creating_db_folder_check_perm'
1096 );
1097 $db_index_file = '<?php
1098 global $old_url, $old_file_path;
1099 $old_url = \''.get_option('siteurl').'\';
1100 $old_file_path = \''.ABSPATH.'\';
1101 ';
1102 @file_put_contents(IWP_BACKUP_DIR.'/iwp_db/index.php', $db_index_file);
1103 }
1104 $db_file = DB_NAME;
1105 $db_file .='_'.$this->generate_hash();
1106
1107 $file = $db_folder . $db_file . '.sql';
1108
1109 if($GLOBALS['fail_safe_db']){
1110 $result = $this->backup_db_php($file);
1111 return $result;
1112 }
1113
1114 $func = $this->check_sys();
1115 $db_result = true;
1116 if($func == false){
1117 $db_result = false;
1118 }
1119 if ($db_result) {
1120
1121 $db_result = $this->backup_db_dump($file);
1122 }
1123
1124 if ($db_result == false) {
1125
1126 $db_result = $this->backup_db_php($file);
1127 }
1128 return $db_result;
1129 }
1130
1131 function generate_hash(){
1132 return md5(microtime(true).uniqid('',true).substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(20,60)));
1133 }
1134
1135 function backup_db_dump($file)
1136 {
1137 global $wpdb;
1138 $paths = $this->getMySQLPath();
1139 if(empty($paths['mysqldump'])){
1140 // Fallback to $this->backup_db_php($file);
1141 return false;
1142 }
1143 $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1144 $exclude_tables = $this->tasks['args']['exclude_tables'];
1145 //$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;
1146 $this_prefix = $wpdb->esc_like($wpdb->base_prefix);
1147 $command0 = $wpdb->get_col('SHOW TABLES LIKE "'.$this_prefix.'%"');
1148 $full_table = array();
1149 $structure_only_table = array();
1150 if (!empty($exclude_tables)) {
1151 foreach ($command0 as $tk => $table) {
1152 foreach ($exclude_tables as $ke => $exclude_table) {
1153 $structure = false;
1154 if (strpos($table, $exclude_table)) {
1155 $structure = true;
1156 break;
1157 }
1158 }
1159 if ($structure) {
1160 $structure_only_table [] = $table;
1161 }else{
1162 $full_table [] = $table;
1163 }
1164 }
1165 }else{
1166 $full_table = $command0;
1167 }
1168 $wp_tables = join("\" \"",$full_table);
1169 $msqld_max_allowed_packet = (defined('IWP_MYSQLDUMP_MAX_ALLOWED_PACKET') && (is_int(IWP_MYSQLDUMP_MAX_ALLOWED_PACKET) || is_string(IWP_MYSQLDUMP_MAX_ALLOWED_PACKET))) ? IWP_MYSQLDUMP_MAX_ALLOWED_PACKET : '8M';
1170 $host_string = '--host="' . DB_HOST . '"';
1171 $parsed_db = $wpdb->parse_db_host(DB_HOST);
1172 if (!empty($parsed_db[0])) {
1173 $host_string = '--host="' . $parsed_db[0] . '"';
1174 if(!empty($parsed_db[1])){
1175 $host_string .= ' --port=' . $parsed_db[1];
1176 }
1177 }
1178 $command = $brace . $paths['mysqldump'] . $brace . ' --force '.$host_string.' --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --max_allowed_packet='.$msqld_max_allowed_packet.' --net_buffer_length=1M --skip-comments --skip-set-charset --allow-keywords --dump-date --add-drop-table --skip-lock-tables --extended-insert "' . DB_NAME . '" "'.$wp_tables.'" > ' . $brace . $file . $brace;
1179 iwp_mmb_print_flush('DB DUMP CMD: Start');
1180 ob_start();
1181 if (!empty($structure_only_table)) {
1182 $structure_only_wp_table = join("\" \"",$structure_only_table);
1183 $structure_command = $brace . $paths['mysqldump'] . $brace . ' --force '.$host_string.' --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables --no-data "' . DB_NAME . '" "'.$structure_only_wp_table.'" >> ' . $brace . $file . $brace;
1184 // $result = $this->iwp_mmb_exec($structure_command);
1185 $command.=' && '.$structure_command;
1186
1187 }
1188 $result = $this->iwp_mmb_exec($command);
1189 ob_get_clean();
1190 iwp_mmb_print_flush('DB DUMP CMD: End');
1191
1192 if(!$result && !defined('IWP_MYSQLDUMP_MAX_ALLOWED_PACKET')){
1193 // It will work when the Mysqldump comment available, but due to low max_allowed_packet size. Mysqldump not working, so we are manually increasing the max_allowed_packet size
1194
1195 global $iwp_mmb_core;
1196 $msqld_max_allowed_packet = $iwp_mmb_core->get_max_allowed_packet();
1197 $command = $brace . $paths['mysqldump'] . $brace . ' --force --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --max_allowed_packet='.$msqld_max_allowed_packet.' --net_buffer_length=1M --skip-comments --skip-set-charset --allow-keywords --dump-date --add-drop-table --skip-lock-tables --extended-insert "' . DB_NAME . '" "'.$wp_tables.'" > ' . $brace . $file . $brace;
1198
1199 iwp_mmb_print_flush('DB DUMP CMD RETRY: Start');
1200 ob_start();
1201 if (!empty($structure_only_table)) {
1202 $command.=' && '.$structure_command;
1203 }
1204 $result = $this->iwp_mmb_exec($command);
1205 ob_get_clean();
1206 iwp_mmb_print_flush('DB DUMP CMD RETRY: End');
1207 }
1208
1209 if (!$result) { // Fallback to php
1210 return false;
1211 }
1212
1213 if (iwp_mmb_get_file_size($file) == 0 || !is_file($file) || !$result) {
1214 @unlink($file);
1215 return false;
1216 } else {
1217 return $file;
1218 }
1219 }
1220
1221 function backup_db_php($file)
1222 {
1223 global $wpdb;
1224 $exclude_tables = $this->tasks['args']['exclude_tables'];
1225 if(empty($GLOBALS['fail_safe_db'])){
1226 iwp_mmb_print_flush('DB DUMP PHP Normal: Start');
1227 $fp = fopen( $file, 'w' );
1228 $_count = 0;
1229 $insert_sql = '';
1230 $this_prefix = $wpdb->esc_like($wpdb->base_prefix);
1231 $result = $wpdb->get_results( 'SHOW TABLES LIKE "'.$this_prefix.'%"');
1232 if(!$result)
1233 {
1234 return array(
1235 'error' => 'MySQL '.$wpdb->print_error()." ", 'error_code' => 'MySQL '.str_replace(" ", "_", $wpdb->print_error())." "
1236 );
1237 }
1238
1239 foreach($result as $index => $value) {
1240 foreach($value as $tableName) {
1241 //echo $tableName . '<br />';
1242 $tables[]=$tableName;
1243 }
1244 }
1245
1246
1247 foreach ($tables as $table) {
1248 iwp_mmb_auto_print('backup_db_php_normal');
1249 $insert_sql .= "DROP TABLE IF EXISTS `$table`;";
1250 $table_descr_query = $wpdb->get_results("SHOW CREATE TABLE `$table`", ARRAY_N);
1251
1252 $insert_sql .= "\n\n" . $table_descr_query[0][1] . ";\n\n";
1253 fwrite( $fp, $insert_sql );
1254 $insert_sql = '';
1255 $skipThisTable = false;
1256 if (!empty($exclude_tables)) {
1257 foreach ($exclude_tables as $ke => $exclude_table) {
1258 if (strpos($table[0], $exclude_table)) {
1259 $skipThisTable = true;
1260 break;
1261 }
1262 }
1263 }
1264 if ($skipThisTable) {
1265 continue;
1266 }
1267 $table_query = $wpdb->get_results("SELECT * FROM `$table`", ARRAY_N);
1268 $num_fields = $wpdb->num_rows;
1269
1270 foreach ($table_query as $final) {
1271 $counts=count($final);
1272 $insert_sql .= "INSERT INTO $table VALUES(";
1273
1274 for ($i=0; $i <$counts ; $i++) {
1275 if($final[$i]== NULL) {
1276 $insert_sql .= "'', ";
1277 }
1278 else {
1279 $value = addslashes($final[$i]);
1280 $value = preg_replace("/\n/Ui", "\\n", $value);
1281 $insert_sql .= "'" .$value. "', ";
1282 }
1283 //mb_convert_encoding(esc_sql($final[$i] ), "HTML-ENTITIES", "ISO-8859-1")
1284 }
1285 $insert_sql = substr( $insert_sql, 0, -2 );
1286 $insert_sql .= ");\n";
1287 fwrite( $fp, $insert_sql );
1288 $insert_sql = '';
1289 $_count++;
1290 if ($_count >= 400) {
1291 echo ' ';
1292 flush();
1293 $_count = 0;
1294 }
1295 }
1296 $insert_sql .= "\n\n\n";
1297
1298 $wpdb->flush(); // Free memory.
1299 // Help keep HTTP alive.
1300 echo ' ';
1301 flush();
1302
1303 //unset( $tables[$table_key] );
1304 }
1305 fclose( $fp );
1306 unset ($fp);
1307 iwp_mmb_print_flush('DB DUMP PHP Normal: End');
1308 }
1309 else{
1310 $max_row_limit = 100;
1311 if(defined('IWP_PHP_DB_ROWS') && (is_int(IWP_PHP_DB_ROWS) || is_string(IWP_PHP_DB_ROWS))){
1312 if(IWP_PHP_DB_ROWS > $max_row_limit ){
1313 $max_row_limit = IWP_PHP_DB_ROWS;
1314 }
1315 }
1316
1317 iwp_mmb_print_flush('DB DUMP PHP Fail-safe: Start');
1318 file_put_contents($file, '');//safe to reset any old data
1319 //$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
1320 $this_prefix = $wpdb->esc_like($wpdb->base_prefix);
1321 $tables = $wpdb->get_results('SHOW TABLES LIKE "'.$this_prefix.'%"', ARRAY_N);
1322 foreach ($tables as $table) {
1323
1324 //drop existing table
1325 $dump_data = "DROP TABLE IF EXISTS `$table[0]`;";
1326 file_put_contents($file, $dump_data, FILE_APPEND);
1327 //create table
1328 $create_table = $wpdb->get_row("SHOW CREATE TABLE `$table[0]`", ARRAY_N);
1329 $dump_data = "\n\n" . $create_table[1] . ";\n\n";
1330 file_put_contents($file, $dump_data, FILE_APPEND);
1331
1332 $skipThisTable = false;
1333 if (!empty($exclude_tables)) {
1334 foreach ($exclude_tables as $ke => $exclude_table) {
1335 if (!empty($exclude_table) && strpos($table[0], $exclude_table)) {
1336 $skipThisTable = true;
1337 break;
1338 }
1339 }
1340 }
1341 if ($skipThisTable) {
1342 continue;
1343 }
1344
1345 $count = $wpdb->get_var("SELECT count(*) FROM `$table[0]`");
1346 if ($count > $max_row_limit)
1347 $count = ceil($count / $max_row_limit);
1348 else if ($count > 0)
1349 $count = 1;
1350
1351 for ($i = 0; $i < $count; $i++) {
1352 iwp_mmb_auto_print('backup_db_php_fail_safe');
1353 $low_limit = $i * $max_row_limit;
1354 $qry = "SELECT * FROM `$table[0]` LIMIT $low_limit, $max_row_limit";
1355 $rows = $wpdb->get_results($qry, ARRAY_A);
1356 if (is_array($rows)) {
1357 foreach ($rows as $row) {
1358 //insert single row
1359 $dump_data = "INSERT INTO `$table[0]` VALUES(";
1360 $num_values = count($row);
1361 $j = 1;
1362 foreach ($row as $value) {
1363 $value = addslashes($value);
1364 $value = preg_replace("/\n/Ui", "\\n", $value);
1365 $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
1366 $j++;
1367 unset($value);
1368 }
1369 $dump_data .= ");\n";
1370 file_put_contents($file, $dump_data, FILE_APPEND);
1371 }
1372 }
1373 }
1374 $dump_data = "\n\n\n";
1375 file_put_contents($file, $dump_data, FILE_APPEND);
1376
1377 unset($rows);
1378 unset($dump_data);
1379 }
1380 iwp_mmb_print_flush('DB DUMP PHP Fail-safe: End');
1381 }
1382
1383 if (iwp_mmb_get_file_size($file) == 0 || !is_file($file)) {
1384 @unlink($file);
1385 return array(
1386 'error' => 'Database backup failed. Try to enable MySQL dump on your server.', 'error_code' => 'database_backup_failed_enable_MySQL_dump_server'
1387 );
1388 }
1389
1390 return $file;
1391
1392 }
1393
1394 /**
1395 * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
1396 * Assumes that WP_Filesystem() has already been called and setup.
1397 *
1398 * @since 2.5.0
1399 *
1400 * @param string $from source directory
1401 * @param string $to destination directory
1402 * @param array $skip_list a list of files/folders to skip copying
1403 * @return mixed WP_Error on failure, True on success.
1404 */
1405
1406 function get_table_prefix()
1407 {
1408 $lines = file(ABSPATH . 'wp-config.php');
1409 foreach ($lines as $line) {
1410 if (strstr($line, '$table_prefix')) {
1411 $pattern = "/(\'|\")[^(\'|\")]*/";
1412 preg_match($pattern, $line, $matches);
1413 $prefix = substr($matches[0], 1);
1414 return $prefix;
1415 break;
1416 }
1417 }
1418 return 'wp_'; //default
1419 }
1420
1421 function optimize_tables()
1422 {
1423 global $wpdb;
1424 $query = 'SHOW TABLE STATUS';
1425 $tables = $wpdb->get_results($query, ARRAY_A);
1426 $table_string = '';
1427 foreach ($tables as $table) {
1428 if (in_array($table['Engine'], array(
1429 'MyISAM',
1430 'ISAM',
1431 'HEAP',
1432 'MEMORY',
1433 'ARCHIVE'
1434 )))
1435 $table_string .= $table['Name'] . ",";
1436 elseif ($table['Engine'] == 'InnoDB') {
1437 $optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
1438 }
1439 }
1440
1441 if(!empty($table_string)){
1442 $table_string = rtrim($table_string, ',');
1443 $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
1444 }
1445
1446 return $optimize ? true : false;
1447 }
1448
1449 ### Function: Auto Detect MYSQL and MYSQL Dump Paths
1450 function check_mysql_paths()
1451 {
1452 global $wpdb;
1453 $paths = array(
1454 'mysql' => '',
1455 'mysqldump' => ''
1456 );
1457 if (substr(PHP_OS, 0, 3) == 'WIN') {
1458 $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
1459 if ($mysql_install) {
1460 $install_path = str_replace('\\', '/', $mysql_install->Value);
1461 $paths['mysql'] = $install_path . 'bin/mysql.exe';
1462 $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
1463 } else {
1464 $paths['mysql'] = 'mysql.exe';
1465 $paths['mysqldump'] = 'mysqldump.exe';
1466 }
1467 } else {
1468 $paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
1469 if (empty($paths['mysql']))
1470 $paths['mysql'] = 'mysql'; // try anyway
1471
1472 $paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
1473 if (empty($paths['mysqldump']))
1474 $paths['mysqldump'] = 'mysqldump'; // try anyway
1475
1476 }
1477
1478
1479 return $paths;
1480 }
1481
1482 public function getMySQLPath(){
1483 global $wpdb;
1484 $paths = array(
1485 'mysql' => '',
1486 'mysqldump' => ''
1487 );
1488 if (substr(PHP_OS, 0, 3) == 'WIN') {
1489 $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
1490 if ($mysql_install) {
1491 $install_path = str_replace('\\', '/', $mysql_install->Value);
1492 $paths['mysql'] = $install_path . '/bin/mysql.exe';
1493 $paths['mysqldump'] = $install_path . '/bin/mysqldump.exe';
1494 } else {
1495 $paths['mysql'] = 'mysql.exe';
1496 $paths['mysqldump'] = 'mysqldump.exe';
1497 }
1498 } else{
1499 if(defined('IWP_MYSQLDUMP_EXECUTABLE') && IWP_MYSQLDUMP_EXECUTABLE){
1500 $mysqlPath = IWP_MYSQLDUMP_EXECUTABLE;
1501 }else{
1502 $mysqlPath = iwp_mmb_build_mysqldump_list();
1503 }
1504 $bin = explode(',' , $mysqlPath);
1505 $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1506 $db_folder = IWP_DB_DIR . '/';
1507 $temp_sql_file_name = "iwp_temp.sql";
1508 $file = $db_folder . $temp_sql_file_name;
1509 $host_string = '--host="' . DB_HOST . '"';
1510 $parsed_db = $wpdb->parse_db_host(DB_HOST);
1511 if (!empty($parsed_db[0])) {
1512 $host_string = '--host="' . $parsed_db[0] . '"';
1513 if(!empty($parsed_db[1])){
1514 $host_string .= ' --port=' . $parsed_db[1];
1515 }
1516 }
1517 foreach ($bin as $key => $value) {
1518 $command = $brace . $value . $brace . ' --force '.$host_string.' --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables --extended-insert=FALSE "' . DB_NAME . '" ""'.$wpdb->base_prefix.'options"" > ' . $brace . $file . $brace;
1519 $result = $this->iwp_mmb_exec($command);
1520 if (!$result) {
1521 continue;
1522 }
1523
1524 if (iwp_mmb_get_file_size($file) == 0 || !is_file($file) || !$result) {
1525 continue;
1526 }
1527 unlink($file);
1528 $paths = array(
1529 'mysql' => $value,
1530 'mysqldump' => $value
1531 );
1532
1533 return $paths;
1534 }
1535 unlink($file);
1536 }
1537 if (empty($paths['mysql'])){
1538 $paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
1539 }
1540
1541 if (empty($paths['mysqldump'])){
1542 $paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
1543 }
1544 return $paths;
1545 }
1546
1547 //Check if exec, system, passthru functions exist
1548 function check_sys()
1549 {
1550 if ($this->iwp_mmb_function_exists('exec'))
1551 return 'exec';
1552
1553 if ($this->iwp_mmb_function_exists('system'))
1554 return 'system';
1555
1556 if ($this->iwp_mmb_function_exists('passthru'))
1557 return 'passthru';
1558
1559 return false;
1560
1561 }
1562
1563 function iwp_mmb_exec($command, $string = false, $rawreturn = false)
1564 {
1565 if ($command == '')
1566 return false;
1567
1568 if ($this->iwp_mmb_function_exists('exec')) {
1569 $log = @exec($command, $output, $return);
1570
1571 if ($string)
1572 return $log;
1573 if ($rawreturn)
1574 return $return;
1575
1576 return $return ? false : true;
1577 } elseif ($this->iwp_mmb_function_exists('system')) {
1578 $log = @system($command, $return);
1579
1580 if ($string)
1581 return $log;
1582
1583 if ($rawreturn)
1584 return $return;
1585
1586 return $return ? false : true;
1587 } elseif ($this->iwp_mmb_function_exists('passthru') && !$string) {
1588 $log = passthru($command, $return);
1589
1590 if ($rawreturn)
1591 return $return;
1592
1593 return $return ? false : true;
1594 }
1595
1596 if ($rawreturn)
1597 return -1;
1598
1599 return false;
1600 }
1601
1602 function get_zip()
1603 {
1604 $zip = $this->iwp_mmb_exec('which zip', true);
1605 if (!$zip)
1606 $zip = "zip";
1607 return $zip;
1608 }
1609
1610 function get_unzip()
1611 {
1612 $unzip = $this->iwp_mmb_exec('which unzip', true);
1613 if (!$unzip)
1614 $unzip = "unzip";
1615 return $unzip;
1616 }
1617 function getDirectorySize($directory)
1618 {
1619 $dirSize=0;
1620 $fileCount=0;
1621 $dirInfo = array(
1622 'dirSize' => 0,
1623 'fileCount' => 0
1624 );
1625
1626 if(!$dh=opendir($directory))
1627 {
1628 return false;
1629 }
1630
1631 while($file = readdir($dh))
1632 {
1633 if($file == "." || $file == "..")
1634 {
1635 continue;
1636 }
1637
1638 if(is_file($directory."/".$file))
1639 {
1640 $dirInfo['dirSize'] += filesize($directory."/".$file);
1641 $dirInfo['fileCount'] += 1;
1642 }
1643
1644 if(is_dir($directory."/".$file))
1645 {
1646 $teminfo = $this->getDirectorySize($directory."/".$file);
1647 if(isset($teminfo['dirSize'])) $dirInfo['dirSize'] += $teminfo['dirSize'];
1648 if(isset($teminfo['fileCount'])) $dirInfo['fileCount'] += $teminfo['fileCount'];
1649 }
1650 }
1651
1652 closedir($dh);
1653
1654 return $dirInfo;
1655 }
1656
1657 function get_database_size() {
1658 global $wpdb;
1659
1660 $total_size = 0;
1661 $total_size_with_exclusions = 0;
1662 $rows = $wpdb->get_results( "SHOW TABLE STATUS", ARRAY_A );
1663 foreach( $rows as $row ) {
1664 $excluded = true; // Default.
1665
1666 // TABLE STATUS.
1667 $rowsb = $wpdb->get_results( "CHECK TABLE `{$row['Name']}`", ARRAY_A );
1668 foreach( $rowsb as $rowb ) {
1669 if ( $rowb['Msg_type'] == 'status' ) {
1670 $status = $rowb['Msg_text'];
1671 }
1672 }
1673 unset( $rowsb );
1674
1675 // TABLE SIZE.
1676 $size = ( $row['Data_length'] + $row['Index_length'] );
1677 $total_size += $size;
1678 }
1679 return $total_size;
1680 }
1681
1682 function loopback_test() {
1683 $loopback_url = admin_url('admin-ajax.php');
1684 //pb_backupbuddy::status( 'details', 'Testing loopback connections by connecting back to site at the URL: `' . $loopback_url . '`. It should display simply "0" or "-1" in the body.' );
1685
1686 $response = wp_remote_get(
1687 $loopback_url,
1688 array(
1689 'method' => 'GET',
1690 'timeout' => 8, // X second delay. A loopback should be very fast.
1691 'redirection' => 5,
1692 'httpversion' => '1.0',
1693 'blocking' => true,
1694 'headers' => array(),
1695 'body' => null,
1696 'cookies' => array()
1697 )
1698 );
1699
1700 if( is_wp_error( $response ) ) { // Loopback failed. Some kind of error.
1701 $error = $response->get_error_message();
1702 //pb_backupbuddy::status( 'error', 'Loopback test error: `' . $error . '`.' );
1703 return 'Error: ' . $error;
1704 } else {
1705 if ( ( $response['body'] == '-1' ) || ( $response['body'] == '0' ) ) { // Loopback succeeded.
1706 //pb_backupbuddy::status( 'details', 'HTTP Loopback test success. Returned `' . $response['body'] . '`.' );
1707 return true;
1708 } else { // Loopback failed.
1709 $error = 'Connected to server but unexpected output: ' . htmlentities( $response['body'] );
1710 //pb_backupbuddy::status( 'error', $error );
1711 return $error;
1712 }
1713 }
1714 }
1715
1716 function is_php( $bits ) {
1717
1718 $result = ( ( PHP_INT_SIZE * 8 ) == $bits ) ? true : false;
1719
1720 return $result;
1721
1722 }
1723
1724 function stat( $filename ) {
1725
1726 $result = false;
1727
1728 // If the file is readable then we should be able to stat it
1729 if ( @is_readable( $filename ) ) {
1730
1731 $stats = @stat( $filename );
1732
1733 if ( false !== $stats ) {
1734
1735 // Looks like we got some valid data - for now just process the size
1736 if ( $this->is_php( 32 ) ) {
1737
1738 // PHP is 32 bits so we may have a file size problem over 2GB.
1739 // This is one way to test for a file size problem - there are others
1740 if ( 0 > $stats[ 'size' ] ) {
1741
1742 // Unsigned long has been interpreted as a signed int and has sign bit
1743 // set so is appearing as negative - magically convert it to a double
1744 // Note: this only works to give us an extension from 2GB to 4GB but that
1745 // should be enough as the underlying OS probably can't support >4GB or
1746 // zip command cannot anyway
1747 $stats[ 'dsize' ] = ( (double)0x80000000 + ( $stats[ 'size' ] & 0x7FFFFFFF ) );
1748
1749 } else {
1750
1751 // Assume it's valid
1752 $stats[ 'dsize' ] = (double)$stats[ 'size' ];
1753
1754 }
1755
1756 } else {
1757
1758 // Looks like 64 bit PHP so file size should be fine
1759 // Force added item to double for consistency
1760 $stats[ 'dsize' ] = (double)$stats[ 'size' ];
1761
1762 }
1763
1764 // Add an additional item for short octal representation of mode
1765 $stats[ 'mode_octal_four' ] = substr( sprintf( '%o', $stats[ 'mode' ] ), -4 );
1766
1767 $result = $stats;
1768
1769 } else {
1770
1771 // Hmm, stat() failed for some reason - could be an LFS problem with the
1772 // way PHP has been built :-(
1773 // TODO: Consider alternatives - may be able to use exec to run the
1774 // command line stat function which _should_ be ok and we can map output
1775 // into the same array format. This does depend on having exec() and the
1776 // stat command available and it's definitely not a nice option
1777 $result = false;
1778
1779 }
1780
1781 }
1782
1783 return $result;
1784 }
1785
1786
1787 function getDirectoryInfo() {
1788 $tests = array();
1789
1790 $uploads_dirs = wp_upload_dir();
1791 $directories = array(
1792 ABSPATH . '',
1793 ABSPATH . 'wp-includes/',
1794 ABSPATH . 'wp-admin/',
1795 ABSPATH . 'wp-content/themes/',
1796 ABSPATH . 'wp-content/plugins/',
1797 ABSPATH . 'wp-content/',
1798 rtrim( $uploads_dirs['basedir'], '\\/' ) . '/',
1799 ABSPATH . 'wp-includes/',
1800
1801 );
1802
1803 foreach( $directories as $directory ) {
1804
1805 $mode_octal_four = '<i>Unknown</i>';
1806 $owner = '<i>Unknown</i>';
1807
1808 $stats = $this->stat( $directory );
1809 if ( false !== $stats ) {
1810 $mode_octal_four = $stats['mode_octal_four'];
1811 $owner = $stats['uid'] . ':' . $stats['gid'];
1812 }
1813 $this_test = array(
1814 'title' => '/' . str_replace( ABSPATH, '', $directory ),
1815 'suggestion' => '<= 755',
1816 'value' => $mode_octal_four,
1817 'owner' => $owner,
1818 );
1819 if ( false === $stats || $mode_octal_four > 755 ) {
1820 $this_test['status'] = 'WARNING';
1821 } else {
1822 $this_test['status'] = 'OK';
1823 }
1824 array_push( $tests, $this_test );
1825
1826 } // end foreach.
1827 return $tests;
1828
1829 }
1830
1831 function check_backup_compat()
1832 {
1833 global $wpdb, $iwp_backup_core;
1834 $reqs = array();
1835 $reqs['serverInfo']['server_os']['name'] = 'Server OS';
1836 if (strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0) {
1837 $reqs['serverInfo']['server_os']['status'] = php_uname('s')." ".php_uname('v');
1838 $reqs['serverInfo']['server_os']['pass'] = true;
1839 } else {
1840 $reqs['serverInfo']['server_os']['status'] = php_uname('s')." ".php_uname('v');
1841 $reqs['serverInfo']['server_os']['pass'] = 'ok';
1842 }
1843 $reqs['serverInfo']['server_os']['suggeted'] = 'Linux';
1844
1845 $reqs['serverInfo']['php_version']['name'] = 'PHP Version';
1846 $reqs['serverInfo']['php_version']['status'] = phpversion();
1847 $reqs['serverInfo']['php_version']['suggeted'] = '>= 5.2 (5.2.16+ best)';
1848 if ((float) phpversion() >= 5.1) {
1849 $reqs['serverInfo']['php_version']['pass'] = true;
1850 } else {
1851 $reqs['serverInfo']['php_version']['pass'] = false;
1852 }
1853
1854 $reqs['mysqlInfo']['mysql_version']['name'] = 'MySql Version';
1855 $reqs['mysqlInfo']['mysql_version']['status'] = $wpdb->db_version();
1856 $reqs['mysqlInfo']['mysql_version']['suggeted'] = '>= 5.0';
1857
1858 if ((float) $wpdb->db_version() >= 5.0) {
1859 $reqs['mysqlInfo']['mysql_version']['pass'] = true;
1860 } else {
1861 $reqs['mysqlInfo']['mysql_version']['pass'] = false;
1862 }
1863
1864 $reqs['serverInfo']['php_max_execution_time']['name'] = 'PHP max_execution_time';
1865 $reqs['serverInfo']['php_max_execution_time']['status'] = ini_get( 'max_execution_time' );
1866 $reqs['serverInfo']['php_max_execution_time']['suggeted'] = '>= 30 seconds (30+ best)';
1867
1868 if (str_ireplace( 's', '', ini_get( 'max_execution_time' ) ) < 30) {
1869 $reqs['serverInfo']['php_max_execution_time']['pass'] = false;
1870 } else {
1871 $reqs['serverInfo']['php_max_execution_time']['pass'] = true;
1872 }
1873
1874 if ( !ini_get( 'memory_limit' ) ) {
1875 $parent_class_val = 'unknown';
1876 } else {
1877 $parent_class_val = ini_get( 'memory_limit' );
1878 }
1879 $reqs['serverInfo']['php_memory_limit']['name'] = 'PHP Memory Limit';
1880 $reqs['serverInfo']['php_memory_limit']['status'] = $parent_class_val;
1881 $reqs['serverInfo']['php_memory_limit']['suggeted'] = '>= 128M (256M+ best)';
1882
1883 if ( preg_match( '/(\d+)(\w*)/', $parent_class_val, $matches ) ) {
1884 $parent_class_val = $matches[1];
1885 $unit = $matches[2];
1886 // Up memory limit if currently lower than 256M.
1887 if ( 'g' !== strtolower( $unit ) ) {
1888 if ( ( $parent_class_val < 128 ) || ( 'm' !== strtolower( $unit ) ) ) {
1889 $reqs['serverInfo']['php_memory_limit']['pass'] = false;
1890 } else {
1891 $reqs['serverInfo']['php_memory_limit']['pass'] = true;
1892 }
1893 }
1894 } else {
1895 $reqs['serverInfo']['php_memory_limit']['pass'] = false;
1896 }
1897
1898 //$reqs['serverInfo']['Site Information']['status'] = $this->getDirectorySize(ABSPATH);
1899 $tempInfo = $this->getDirectorySize(ABSPATH);
1900
1901
1902 $reqs['serverInfo']['site_size']['name'] = 'Site size';
1903 $reqs['serverInfo']['site_size']['status'] = ($tempInfo['dirSize']/1048576). " MB";
1904 $reqs['serverInfo']['site_size']['pass'] = true;
1905 $reqs['serverInfo']['site_size']['suggeted'] = 'N/A';
1906
1907 $reqs['serverInfo']['site_number_of_files']['name'] = 'Site number of files';
1908 $reqs['serverInfo']['site_number_of_files']['status'] = $tempInfo['fileCount'];
1909 $reqs['serverInfo']['site_number_of_files']['pass'] = true;
1910 $reqs['serverInfo']['site_number_of_files']['suggeted'] = 'N/A';
1911
1912 $reqs['mysqlInfo']['database_size']['name'] = 'Database Size';
1913 $reqs['mysqlInfo']['database_size']['status'] = $this->get_database_size();
1914 $reqs['mysqlInfo']['database_size']['pass'] = true;
1915 $reqs['mysqlInfo']['database_size']['suggeted'] = 'N/A';
1916
1917 $reqs['serverInfo']['http_loopback']['name'] = 'Http Loopbacks';
1918 if($this->loopback_test() === true) {
1919 $reqs['serverInfo']['http_loopback']['status'] = true;
1920 $reqs['serverInfo']['http_loopback']['pass'] = true;
1921 } else {
1922 $reqs['serverInfo']['http_loopback']['status'] = false;
1923 $reqs['serverInfo']['http_loopback']['pass'] = false;
1924 }
1925 $reqs['serverInfo']['http_loopback']['suggeted'] = "enabled";
1926
1927 $reqs['serverInfo']['php_architecture']['name'] = 'PHP Architecture';
1928 $reqs['serverInfo']['php_architecture']['status'] = ( PHP_INT_SIZE * 8 ) . '-bit';
1929 $reqs['serverInfo']['php_architecture']['pass'] = true;
1930 $reqs['serverInfo']['php_architecture']['suggeted'] = '64-bit';
1931
1932 // http Server Software
1933 if ( isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
1934 $server_software = $_SERVER['SERVER_SOFTWARE'];
1935 } else {
1936 $server_software = 'Unknown';
1937 }
1938 $reqs['serverInfo']['http_server_software']['name'] = 'Http Server Software';
1939 $reqs['serverInfo']['http_server_software']['status'] = $server_software;
1940 $reqs['serverInfo']['http_server_software']['pass'] = true;
1941 $reqs['serverInfo']['http_server_software']['suggeted'] = 'N/A';
1942
1943 $reqs['serverInfo']['php_sapi']['name'] = 'PHP SAPI';
1944 $reqs['serverInfo']['php_sapi']['status'] = PHP_SAPI;
1945 $reqs['serverInfo']['php_sapi']['pass'] = true;
1946 $reqs['serverInfo']['php_sapi']['suggeted'] = 'N/A';
1947
1948 $reqs['directoryInfo']['status'] = $this->getDirectoryInfo();
1949
1950
1951
1952 $reqs['serverInfo']['backup_folder']['name'] = "Backup Folder";
1953 if (is_writable(WP_CONTENT_DIR)) {
1954 $reqs['serverInfo']['backup_folder']['status'] = "writable";
1955 $reqs['serverInfo']['backup_folder']['pass'] = true;
1956 } else {
1957 $reqs['serverInfo']['backup_folder']['status'] = "not writable";
1958 $reqs['serverInfo']['backup_folder']['pass'] = false;
1959 }
1960 $reqs['serverInfo']['backup_folder']['suggeted'] = 'Need to writable';
1961
1962
1963 $file_path = IWP_BACKUP_DIR;
1964 $reqs['serverInfo']['backup_folder']['status'] .= ' (' . $file_path . ')';
1965
1966 $reqs['serverInfo']['execute_function']['name'] = 'Execute Function';
1967 if ($func = $this->check_sys()) {
1968 $reqs['serverInfo']['execute_function']['status'] = $func;
1969 $reqs['serverInfo']['execute_function']['pass'] = true;
1970 } else {
1971 $reqs['serverInfo']['execute_function']['status'] = "not found";
1972 $reqs['serverInfo']['execute_function']['pass'] = false;
1973 }
1974 $reqs['serverInfo']['execute_function']['suggeted'] = 'Need any one of support exec, system, passthru (or will try PHP replacement)';
1975 $reqs['serverInfo']['zip']['name'] = 'Zip';
1976 $reqs['serverInfo']['zip']['status'] = $this->get_zip();
1977 $reqs['serverInfo']['zip']['suggeted'] = 'System Zip need or will try PHP replacement';
1978 $reqs['serverInfo']['zip']['pass'] = true;
1979
1980
1981
1982 $reqs['serverInfo']['unzip']['name'] = 'Unzip';
1983 $reqs['serverInfo']['unzip']['status'] = $this->get_unzip();
1984 $reqs['serverInfo']['unzip']['suggeted'] = 'System Zip need or will try PHP replacement';
1985 $reqs['serverInfo']['unzip']['pass'] = true;
1986
1987 $paths = $this->check_mysql_paths();
1988 $reqs['mysqlInfo']['mysql_dump']['name'] = 'MySQL Dump';
1989 if (!empty($paths['mysqldump'])) {
1990 $reqs['mysqlInfo']['mysql_dump']['status'] = $paths['mysqldump'];
1991 $reqs['mysqlInfo']['mysql_dump']['pass'] = true;
1992 } else {
1993 $reqs['mysqlInfo']['mysql_dump']['status'] = "not found";
1994 $reqs['mysqlInfo']['mysql_dump']['pass'] = false;
1995 }
1996 $reqs['mysqlInfo']['mysql_dump']['suggeted'] = "Command line [fastest] > PHP-based [slowest] (or will try PHP replacement)";
1997
1998 $exec_time = ini_get('max_execution_time');
1999 $reqs['serverInfo']['mysql_dump']['name'] = 'Execution time';
2000 $reqs['serverInfo']['mysql_dump']['status'] = $exec_time ? $exec_time . "s" : 'unknown';
2001 $reqs['serverInfo']['mysql_dump']['pass'] = true;
2002 $reqs['serverInfo']['mysql_dump']['suggeted'] = 'N/A';
2003
2004 $mem_limit = ini_get('memory_limit');
2005 $reqs['serverInfo']['memory_limit']['name'] = 'Memory limit';
2006 $reqs['serverInfo']['memory_limit']['status'] = $mem_limit ? $mem_limit : 'unknown';
2007 $reqs['serverInfo']['memory_limit']['pass'] = true;
2008 $reqs['serverInfo']['memory_limit']['suggeted'] = 'N/A';
2009
2010 $reqs['functionList']['file_put_content']['name'] = "File Put Content";
2011 if(function_exists('file_put_contents')) {
2012 $reqs['functionList']['file_put_content']['status'] = "Available";
2013 $reqs['functionList']['file_put_content']['pass'] = true;
2014 } else {
2015 $reqs['functionList']['file_put_content']['status'] = "Not Available";
2016 $reqs['functionList']['file_put_content']['pass'] = false;
2017
2018 }
2019 $reqs['functionList']['file_put_content']['suggeted'] = 'N/A';
2020
2021 $reqs['functionList']['ftp_functions']['name'] = "FTP Funtions";
2022 if(function_exists('ftp_connect')) {
2023 $reqs['functionList']['ftp_functions']['status'] = "Available";
2024 $reqs['functionList']['ftp_functions']['pass'] = true;
2025 } else {
2026 $reqs['functionList']['ftp_functions']['status'] = "Not Available";
2027 $reqs['functionList']['ftp_functions']['pass'] = false;
2028 $reqs['functionList']['ftp_functions']['pass'] = false;
2029 }
2030 $reqs['functionList']['ftp_functions']['suggeted'] = 'N/A';
2031 $curl_info = curl_version();
2032 $reqs['serverInfo']['curl_version']['name'] = 'Curl Version';
2033 $reqs['serverInfo']['curl_version']['status'] = $curl_info['version'];
2034 $reqs['serverInfo']['curl_version']['pass'] = true;
2035 $reqs['serverInfo']['curl_version']['suggeted'] = 'N/A';
2036
2037 $reqs['serverInfo']['ssl_ersion']['name'] = 'SSL Version';
2038 $reqs['serverInfo']['ssl_ersion']['status'] = $curl_info['ssl_version'];
2039 $reqs['serverInfo']['ssl_ersion']['pass'] = true;
2040 $reqs['serverInfo']['ssl_ersion']['suggeted'] = 'N/A';
2041
2042 //$hosting_bytes_free = $iwp_backup_core->get_hosting_disk_quota_free();
2043 $quota_free = 'N/A';
2044 $no_low_quota = true;
2045 $no_low_disk_space = true;
2046 /*if (is_array($hosting_bytes_free)) {
2047 $perc = round(100*$hosting_bytes_free[1]/(max($hosting_bytes_free[2], 1)), 1);
2048 $quota_free = round($hosting_bytes_free[3]/1048576, 1)." MB";
2049 if ($hosting_bytes_free[3] < 1048576*50) {
2050 $no_low_quota = true;
2051 }
2052 }*/
2053 $disk_free_space = function_exists('disk_free_space') ? @disk_free_space(IWP_BACKUP_DIR) : false;
2054 if ($disk_free_space == false) {
2055 $quota_free = 'Unknown';
2056 } else {
2057 $disk_free_mb = round($disk_free_space/1048576, 1)." MB";
2058 if ($disk_free_space < 50*1048576){
2059 $no_low_disk_space = true;
2060 }
2061 }
2062 /*$reqs['serverInfo']['quota_free']['name'] = 'CPanel Quota';
2063 $reqs['serverInfo']['quota_free']['status'] = $quota_free;
2064 $reqs['serverInfo']['quota_free']['pass'] = $no_low_quota;
2065 $reqs['serverInfo']['quota_free']['suggeted'] = 'N/A';*/
2066
2067 $reqs['serverInfo']['disk_free_space']['name'] = 'Free Disk space';
2068 $reqs['serverInfo']['disk_free_space']['status'] = $disk_free_mb;
2069 $reqs['serverInfo']['disk_free_space']['pass'] = $no_low_quota;
2070 $reqs['serverInfo']['disk_free_space']['suggeted'] = 'N/A';
2071 return $reqs;
2072 }
2073
2074 function ftp_backup($args)
2075 {
2076 global $iwp_backup_core;
2077 extract($args);
2078 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder, $ftp_site_folder
2079 if(isset($use_sftp) && $use_sftp==1) {
2080 $port = $ftp_port ? $ftp_port : 22; //default port is 22
2081 /*
2082 * SFTP section start here phpseclib library is used for this functionality
2083 */
2084 $iwp_mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
2085 $path = $iwp_mmb_plugin_dir.'/lib/phpseclib/phpseclib/phpseclib';
2086 set_include_path(get_include_path() . PATH_SEPARATOR . $path);
2087 include_once('Net/SFTP.php');
2088
2089
2090 $sftp = new Net_SFTP($ftp_hostname, $port);
2091 if(!$sftp) {
2092 return array(
2093 'error' => 'Failed to connect to ' . $ftp_hostname,
2094 'partial' => 1
2095 );
2096 }
2097 $iwp_backup_core->ensure_phpseclib('Crypt_Blowfish', 'Crypt/Blowfish');
2098 if (!$sftp->login($ftp_username, $ftp_password)) {
2099 return array(
2100 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
2101 'partial' => 1
2102 );
2103 } else {
2104 if ($ftp_site_folder) {
2105 $ftp_remote_folder .= '/' . $this->site_name;
2106 }
2107 $remote_loation = basename($backup_file);
2108 $local_location = $backup_file;
2109 $sftp->mkdir($ftp_remote_folder,-1,true);
2110 $sftp->chdir($ftp_remote_folder);
2111 //$this->iwp_sftp_mkdir($sftp,'sftpbackup/test123/test1/test2');
2112 $upload = $sftp->put(basename($backup_file), $backup_file, NET_SFTP_LOCAL_FILE);
2113
2114 if ($upload === false) {
2115 return array(
2116 'error' => 'Failed to upload file to FTP. Please check your specified path.',
2117 'partial' => 1
2118 );
2119 }
2120 //SFTP library has automatic connection closed. So no need to call seperate connection close function
2121 }
2122
2123 } else {
2124 $port = $ftp_port ? $ftp_port : 21; //default port is 21
2125 if ($ftp_ssl) {
2126 if (function_exists('ftp_ssl_connect')) {
2127 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2128 if ($conn_id === false) {
2129 return array(
2130 'error' => 'Failed to connect to ' . $ftp_hostname,
2131 'error_code' => 'failed_to_connect_ftp_if_ftp_ssl',
2132 'partial' => 1
2133 );
2134 }
2135 } else {
2136 return array(
2137 'error' => 'Your server doesn\'t support FTP SSL',
2138 'error_code' => 'no_ftp_ssl_support',
2139 'partial' => 1
2140 );
2141 }
2142 } else {
2143 if (function_exists('ftp_connect')) {
2144 $conn_id = ftp_connect($ftp_hostname,$port);
2145 if ($conn_id === false) {
2146 return array(
2147 'error' => 'Failed to connect to ' . $ftp_hostname,
2148 'error_code' => 'failed_to_connect_ftp',
2149 'partial' => 1
2150 );
2151 }
2152 } else {
2153 return array(
2154 'error' => 'Your server doesn\'t support FTP',
2155 'error_code' => 'no_ftp_support',
2156 'partial' => 1
2157 );
2158 }
2159 }
2160 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2161 if ($login === false) {
2162 return array(
2163 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
2164 'error_code' => 'ftp_login_failed',
2165 'partial' => 1
2166 );
2167 }
2168
2169 if($ftp_passive){
2170 @ftp_pasv($conn_id,true);
2171 }
2172
2173 @ftp_mkdir($conn_id, $ftp_remote_folder);
2174 if ($ftp_site_folder) {
2175 $ftp_remote_folder .= '/' . $this->site_name;
2176 }
2177 @ftp_mkdir($conn_id, $ftp_remote_folder);
2178
2179 $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
2180
2181 if ($upload === false) { //Try ascii
2182 $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_ASCII);
2183 }
2184 @ftp_close($conn_id);
2185
2186 if ($upload === false) {
2187 return array(
2188 'error' => 'Failed to upload file to FTP. Please check your specified path.',
2189 'error_code' => 'failed_to_upload_file_check_path',
2190 'partial' => 1
2191 );
2192 }
2193 }
2194 return true;
2195 }
2196
2197 function remove_ftp_backup($args)
2198 {
2199 global $iwp_backup_core;
2200 extract($args);
2201 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
2202 if(isset($use_sftp) && $use_sftp==1) {
2203 $port = $ftp_port ? $ftp_port : 22; //default port is 22
2204 /*
2205 * SFTP section start here phpseclib library is used for this functionality
2206 */
2207 $iwp_mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
2208 $path = $iwp_mmb_plugin_dir.'/lib/phpseclib/phpseclib/phpseclib';
2209 set_include_path(get_include_path() . PATH_SEPARATOR . $path);
2210 include_once('Net/SFTP.php');
2211
2212
2213 $sftp = new Net_SFTP($ftp_hostname,$port);
2214 if(!$sftp) {
2215 return array(
2216 'error' => 'Failed to connect to ' . $ftp_hostname,
2217 'partial' => 1
2218 );
2219 }
2220 $iwp_backup_core->ensure_phpseclib('Crypt_Blowfish', 'Crypt/Blowfish');
2221 if (!$sftp->login($ftp_username, $ftp_password)) {
2222 return array(
2223 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
2224 'partial' => 1
2225 );
2226 } else {
2227 if ($ftp_site_folder) {
2228 $ftp_remote_folder = rtrim($ftp_remote_folder, '/');
2229 $ftp_remote_folder .= '/' . $this->site_name;
2230 }
2231
2232 $sftp->chdir($ftp_remote_folder);
2233
2234 if(!is_array($backup_file)){
2235 $temp_backup_file = $backup_file;
2236 $backup_file = array();
2237 $backup_file[] = $temp_backup_file;
2238 }
2239 foreach($backup_file as $key => $value){
2240 $sftp->delete(basename($value));
2241 }
2242
2243 }
2244 //SFTP library has automatic connection closed. So no need to call seperate connection close function
2245
2246 } else {
2247 $port = $ftp_port ? $ftp_port : 21; //default port is 21
2248 if (!empty($ftp_ssl) && $ftp_ssl && function_exists('ftp_ssl_connect')) {
2249 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2250 } else if (function_exists('ftp_connect')) {
2251 $conn_id = ftp_connect($ftp_hostname,$port);
2252 }
2253
2254 if ($conn_id) {
2255 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2256 if ($ftp_site_folder)
2257 $ftp_remote_folder .= '/' . $this->site_name;
2258
2259 if($ftp_passive){
2260 @ftp_pasv($conn_id,true);
2261 }
2262
2263 if(!is_array($backup_file))
2264 {
2265 $temp_backup_file = $backup_file;
2266 $backup_file = array();
2267 $backup_file[] = $temp_backup_file;
2268 }
2269
2270 foreach($backup_file as $key => $value)
2271 {
2272 $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $value);
2273 }
2274 ftp_close($conn_id);
2275 }
2276 }
2277
2278 }
2279
2280
2281 function dropbox_backup($args){
2282 extract($args);
2283
2284 if ($this->iwp_mmb_function_exists('curl_init')) {
2285 if((isset($consumer_secret) && !empty($consumer_secret)) || (isset($dropbox_access_token) && !empty($dropbox_access_token))){
2286
2287 if(!isset($dropbox_access_token) && empty($dropbox_access_token)){
2288
2289 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2290
2291 $dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
2292 $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2293 $oldVersion = true;
2294 if ($dropbox_site_folder == true)
2295 $dropbox_destination .= '/' . $this->site_name . '/' . basename($backup_file);
2296 else
2297 $dropbox_destination .= '/' . basename($backup_file);
2298 }else{
2299 if(!isset($dropbox_email) && empty($dropbox_email)){
2300 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/API.php';
2301 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/Exception.php';
2302 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/ConsumerAbstract.php';
2303 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/Curl.php';
2304
2305 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
2306
2307 $oauth = new IWP_Dropbox_OAuth_Consumer_Curl($dropbox_app_key, $dropbox_app_secure_key);
2308 $oauth->setToken($dropbox_access_token);
2309 $dropbox = new IWP_Dropbox_API($oauth);
2310
2311 }else{
2312 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
2313
2314 try{
2315 set_iwp_dropbox_auth_setting($args);
2316 $helper = new IWP_MMB_UploadModule_dropbox();
2317 $dropbox = $helper->bootstrap();
2318 }
2319 catch(Exception $e){
2320
2321 }
2322 }
2323 $oldRoot = 'Apps/InfiniteWP/';
2324 $oldVersion = false;
2325 $path = '';
2326 $dropbox_destination = $oldRoot.ltrim(trim($dropbox_destination), '/');
2327 $dropbox_destination = rtrim($dropbox_destination, '/');
2328 if (isset($dropbox_site_folder) && $dropbox_site_folder == true){
2329 $dropbox_destination .= '/'.$this->site_name;
2330 }
2331 $folders = explode('/',$dropbox_destination);
2332 foreach ($folders as $key => $name) {
2333 $path.=trim($name).'/';
2334 }
2335 $dropbox_destination = $path;
2336 }
2337
2338 try {
2339 if ($oldVersion) {
2340 $dropbox->upload($backup_file, $dropbox_destination, true);
2341 }else{
2342 $dropbox->putFile($backup_file, $dropbox_destination, true);
2343 }
2344 } catch (Exception $e) {
2345 $this->_log($e->getMessage());
2346 return array(
2347 'error' => $e->getMessage(),
2348 'partial' => 1
2349 );
2350 }
2351
2352 return true;
2353
2354 } else {
2355 return array(
2356 'error' => 'Please connect your InfiniteWP panel with your Dropbox account.',
2357 'error_code' => 'please_connect_dropbox_account_with_panel'
2358 );
2359 }
2360 }
2361 else {
2362 return array(
2363 'error' => 'You cannot use Dropbox on your server. Please enable curl first.',
2364 'partial' => 1, 'error_code' => 'cannot_use_dropbox_enable_curl_first'
2365 );
2366 }
2367
2368 }
2369
2370
2371 function remove_dropbox_backup($args) {
2372 extract($args);
2373
2374 if(!isset($dropbox_access_token) && empty($dropbox_access_token)){
2375
2376 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
2377
2378 $dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
2379 $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2380 if ($dropbox_site_folder == true)
2381 $dropbox_destination .= '/' . $this->site_name;
2382 $oldVersion = true;
2383 }else{
2384 if(!isset($dropbox_email) && empty($dropbox_email)){
2385 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/API.php';
2386 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/Exception.php';
2387 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/ConsumerAbstract.php';
2388 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/Curl.php';
2389
2390 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
2391
2392 $oauth = new IWP_Dropbox_OAuth_Consumer_Curl($dropbox_app_key, $dropbox_app_secure_key);
2393 $oauth->setToken($dropbox_access_token);
2394 $dropbox = new IWP_Dropbox_API($oauth);
2395
2396 }else{
2397 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
2398
2399 try{
2400 set_iwp_dropbox_auth_setting($args);
2401 $helper = new IWP_MMB_UploadModule_dropbox();
2402 $dropbox = $helper->bootstrap();
2403 }
2404 catch(Exception $e){
2405
2406 }
2407 }
2408 $oldRoot = 'Apps/InfiniteWP/';
2409 $dropbox_destination = $oldRoot.ltrim(trim($dropbox_destination), '/');
2410 $dropbox_destination = rtrim($dropbox_destination, '/');
2411 if (isset($dropbox_site_folder) && $dropbox_site_folder == true){
2412 $dropbox_destination .= '/'.$this->site_name;
2413 }
2414 $folders = explode('/',$dropbox_destination);
2415 if (!isset($path)) {
2416 $path = '';
2417 }
2418 foreach ($folders as $key => $name) {
2419 $path.=trim($name).'/';
2420 }
2421 $dropbox_destination = $path;
2422 $oldVersion = false;
2423 }
2424
2425
2426
2427 $temp_backup_file = $backup_file;
2428 if(!is_array($backup_file))
2429 {
2430 $backup_file = array();
2431 $backup_file[] = $temp_backup_file;
2432 }
2433 foreach($backup_file as $key => $value)
2434 {
2435 try {
2436 if (is_object($dropbox)) {
2437 if ($oldVersion) {
2438 $dropbox->fileopsDelete($dropbox_destination . '/' . $value);
2439 }else{
2440 $dropbox->delete($dropbox_destination . '/' . $value);
2441 }
2442 }
2443 } catch (Exception $e) {
2444 $this->_log($e->getMessage());
2445 /*return array(
2446 'error' => $e->getMessage(),
2447 'partial' => 1
2448 );*/
2449 }
2450 }
2451 //return true;
2452 }
2453
2454 function amazons3_backup_bwd_comp($args)
2455 {
2456 if ($this->iwp_mmb_function_exists('curl_init')) {
2457 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3_bwd_comp/sdk.class.php');
2458 extract($args);
2459
2460 if ($as3_site_folder == true)
2461 {
2462 if(!empty($as3_directory))
2463 {
2464 $as3_directory .= '/' . $this->site_name;
2465 }
2466 else
2467 {
2468 $as3_directory = $this->site_name;
2469 }
2470 }
2471 if(empty($as3_directory))
2472 {
2473 $as3_file = basename($backup_file);
2474 }
2475 else
2476 {
2477 $as3_file = $as3_directory . '/' . basename($backup_file);
2478 }
2479 try{
2480
2481 CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true, 'use_ssl'=>false, 'ssl_verification'=>false), '@default' => 'development'));
2482 $s3 = new AmazonS3();
2483 $response = $s3->create_object($as3_bucket, $as3_file, array('fileUpload' => $backup_file));
2484 $s3->set_object_acl($as3_bucket, $as3_file, AmazonS3::ACL_PRIVATE);
2485 $upload = $response->isOk();
2486 if($upload) {
2487 return true;
2488 } else {
2489 return array(
2490 'error' => 'Failed to upload to Amazon S3. Please check your details and set upload/delete permissions on your bucket.',
2491 'error_code' => 'upload_failed_to_S3_check_your_details_and_set_upload_delete_permissions_on_your_bucket',
2492 'partial' => 1
2493 );
2494 }
2495
2496 }catch (Exception $e){
2497 $err = $e->getMessage();
2498 if($err){
2499 return array(
2500 'error' => 'Failed to upload to AmazonS3 ('.$err.').',
2501 'error_code' => 'failed_upload_s3_with_error'
2502 );
2503 } else {
2504 return array(
2505 'error' => 'Failed to upload to Amazon S3.',
2506 'error_code' => 'failed_upload_s3'
2507 );
2508 }
2509 }
2510 } else {
2511 return array(
2512 'error' => 'You cannot use Amazon S3 on your server. Please enable curl first.',
2513 'error_code' => 'you_cannot_use_S3_on_your_server_enable_curl',
2514 'partial' => 1
2515 );
2516 }
2517 }
2518
2519 function google_drive_backup($args = '', $uploadid = null, $offset = 0)
2520 {
2521 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Client.php');
2522 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Http/MediaFileUpload.php');
2523 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Service/Drive.php');
2524
2525 //$this -> hisID = $historyID;
2526
2527 $upload_file_block_size = 1 *1024 *1024;
2528 $iwp_folder_id = '';
2529 $sub_folder_id = '';
2530 $create_sub_folder = $args['gdrive_site_folder'];
2531 $sub_folder_name = $this->site_name;
2532 //$task_result = $this->getRequiredData($historyID, "taskResults");
2533
2534 $fileSizeUploaded = 0;
2535 $resumeURI = false;
2536
2537 $client = new IWP_google_Client();
2538 $client->setClientId($args['clientID']);
2539 $client->setClientSecret($args['clientSecretKey']);
2540 $client->setRedirectUri($args['redirectURL']);
2541 $client->setScopes(array(
2542 'https://www.googleapis.com/auth/drive',
2543 'https://www.googleapis.com/auth/userinfo.email',
2544 'https://www.googleapis.com/auth/userinfo.profile'));
2545
2546
2547 $accessToken = $args['token'];
2548 $refreshToken = $accessToken['refresh_token'];
2549 $backup_file = $args['backup_file'];
2550
2551 try
2552 {
2553 $client->refreshToken($refreshToken);
2554 }
2555 catch(Exception $e)
2556 {
2557 echo 'google Error ', $e->getMessage(), "\n";
2558 return array("error" => $e->getMessage(), "error_code" => "google_error_refresh_token");
2559 }
2560
2561 $service = new IWP_google_Service_Drive($client);
2562
2563 //create folder if not present
2564 try
2565 {
2566 $parameters = array();
2567 $parameters['q'] = "title = 'infinitewp' and trashed = false and 'root' in parents and 'me' in owners and mimeType= 'application/vnd.google-apps.folder'";
2568 $files = $service->files->listFiles($parameters);
2569 $list_result = array();
2570 $list_result = array_merge($list_result, $files->getItems());
2571 $list_result = (array)$list_result;
2572
2573 if(empty($list_result))
2574 {
2575 $file = new IWP_google_Service_Drive_DriveFile();
2576 $file->setTitle('infinitewp');
2577 $file->setMimeType('application/vnd.google-apps.folder');
2578
2579 $createdFolder = $service->files->insert($file, array(
2580 'mimeType' => 'application/vnd.google-apps.folder',
2581 ));
2582 if($createdFolder)
2583 {
2584 $createdFolder = (array)$createdFolder;
2585 $iwp_folder_id = $createdFolder['id'];
2586 }
2587 }
2588 else
2589 {
2590 $list_result = (array)$list_result[0];
2591 $iwp_folder_id = $list_result['id'];
2592 }
2593 }catch (Exception $e){
2594 print "An error occurred: " . $e->getMessage();
2595 return array('error' => $e->getMessage());
2596 }
2597
2598 //create sub folder by site name
2599 if($create_sub_folder)
2600 {
2601 $parameters = array();
2602 $parameters['q'] = "title = '$sub_folder_name' and trashed = false and '$iwp_folder_id' in parents and 'me' in owners and mimeType = 'application/vnd.google-apps.folder'";
2603 $files = $service->files->listFiles($parameters);
2604 $list_result = array();
2605 $list_result = array_merge($list_result, $files->getItems());
2606 $list_result = (array)$list_result;
2607
2608 if(empty($list_result))
2609 {
2610 $file = new IWP_google_Service_Drive_DriveFile();
2611 $file->setTitle($sub_folder_name);
2612 $file->setMimeType('application/vnd.google-apps.folder');
2613
2614 //setting parent as infinitewpFolder
2615 $parent = new IWP_google_Service_Drive_ParentReference();
2616 $parent->setId($iwp_folder_id);
2617 $file->setParents(array($parent));
2618
2619 $createdFolder = $service->files->insert($file, array(
2620 'mimeType' => 'application/vnd.google-apps.folder',
2621 ));
2622 if($createdFolder)
2623 {
2624 $createdFolder = (array)$createdFolder;
2625 $sub_folder_id = $createdFolder['id'];
2626 }
2627 }
2628 else
2629 {
2630 $list_result = (array)$list_result[0];
2631 $sub_folder_id = $list_result['id'];
2632 }
2633 }
2634
2635
2636 //Insert a file
2637 $file = new IWP_google_Service_Drive_DriveFile();
2638 $file->setTitle(basename($backup_file));
2639 $file->setMimeType('binary/octet-stream');
2640
2641 // Set the Parent Folder on Google Drive
2642 $parent = new IWP_google_Service_Drive_ParentReference();
2643 if(empty($sub_folder_id))
2644 {
2645 $parent->setId($iwp_folder_id);
2646 }
2647 else
2648 {
2649 $parent->setId($sub_folder_id);
2650 }
2651 $file->setParents(array($parent));
2652
2653 $gDriveID = '';
2654 try
2655 {
2656 if(false)
2657 {
2658 //single upload
2659 $data = file_get_contents($backup_file);
2660 $createdFile = (array)$service->files->insert($file, array(
2661 'data' => $data,
2662 //'mimeType' => 'text/plain',
2663 ));
2664 $gDriveID = $createdFile['id'];
2665 }
2666
2667 //multipart upload
2668
2669 if(true)
2670 {
2671 // Call the API with the media upload, defer so it doesn't immediately return.
2672 $client->setDefer(true);
2673 $request = $service->files->insert($file);
2674
2675 // Create a media file upload to represent our upload process.
2676 $media = new IWP_google_Http_MediaFileUpload($client, $request, 'application/zip', null, true, $upload_file_block_size);
2677 $media->setFileSize(filesize($backup_file));
2678
2679
2680 $status = false;
2681 $handle = fopen($backup_file, "rb");
2682 fseek($handle, $fileSizeUploaded);
2683
2684 /* $resArray = array (
2685 'status' => 'completed',
2686 'backupParentHID' => $historyID,
2687 ); */
2688
2689 while (!$status && !feof($handle))
2690 {
2691 iwp_mmb_auto_print('gdrive_chucked_upload');
2692 $chunk = fread($handle, $upload_file_block_size);
2693 $statusArray = $media->nextChunk($chunk, $resumeURI, $fileSizeUploaded);
2694 $status = $statusArray['status'];
2695 if(isset($statusArray['resumeURI'])){
2696 $resumeURI = $statusArray['resumeURI'];
2697 }
2698 //$fileSizeUploaded = ftell($handle);
2699 $fileSizeUploaded = $statusArray['progress'];
2700 }
2701
2702 $result = false;
2703 if($status != false) {
2704 $result = $status;
2705 }
2706
2707 fclose($handle);
2708 $client->setDefer(false);
2709
2710 $completeBackupResult = (array)$status;
2711
2712 //$gDriveID = $createdFile['id'];
2713 $gDriveID = $completeBackupResult['id'];
2714 }
2715 }
2716 catch (Exception $e)
2717 {
2718 echo "An error occurred: " . $e->getMessage();
2719 return array("error" => "gDrive Error".$e->getMessage());
2720 }
2721
2722 /* if($del_host_file)
2723 {
2724 unset($task_result['task_results'][$historyID]['server']);
2725 @unlink($backup_file);
2726 } */
2727 $test_this_task = $this->get_this_tasks();
2728
2729 $tasksThere = unserialize($test_this_task['taskResults']);
2730
2731 return $gDriveID;
2732 }
2733
2734 function remove_amazons3_backup_bwd_comp($args)
2735 {
2736 if ($this->iwp_mmb_function_exists('curl_init')) {
2737 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3_bwd_comp/sdk.class.php');
2738 extract($args);
2739
2740 if(!is_array($backup_file))
2741 {
2742 $temp_backup_file = $backup_file;
2743 $backup_file = array();
2744 $backup_file[] = $temp_backup_file;
2745 }
2746
2747 if ($as3_site_folder == true)
2748 {
2749 if(!empty($as3_directory))
2750 {
2751 $as3_directory .= '/' . $this->site_name;
2752 }
2753 else
2754 {
2755 $as3_directory = $this->site_name;
2756 }
2757 }
2758 try{
2759 CFCredentials::set(array('development' => array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'default_cache_config' => '', 'certificate_authority' => true), '@default' => 'development'));
2760 $s3 = new AmazonS3();
2761 foreach($backup_file as $single_backup_file)
2762 {
2763 if(empty($as3_directory))
2764 {
2765 $single_as3_file = $single_backup_file;
2766 }
2767 else
2768 {
2769 $single_as3_file = $as3_directory . '/' . $single_backup_file;
2770 }
2771 $s3->delete_object($as3_bucket, $single_as3_file);
2772 }
2773
2774 } catch (Exception $e){
2775
2776 }
2777 }
2778 }
2779
2780 //IWP Remove ends here
2781
2782 function remove_google_drive_backup($args)
2783 {
2784 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Client.php');
2785 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Service/Drive.php');
2786
2787 $client = new IWP_google_Client();
2788 $client->setClientId($args['clientID']);
2789 $client->setClientSecret($args['clientSecretKey']);
2790 $client->setRedirectUri($args['redirectURL']);
2791 $client->setScopes(array(
2792 'https://www.googleapis.com/auth/drive',
2793 'https://www.googleapis.com/auth/userinfo.email',
2794 'https://www.googleapis.com/auth/userinfo.profile'));
2795
2796 //$client->setUseObjects(true);
2797
2798 $accessToken = $args['token'];
2799 $refreshToken = $accessToken['refresh_token'];
2800 $backup_file = $args['backup_file'];
2801 if(!is_array($backup_file))
2802 {
2803 $backup_file = array();
2804 $backup_file[0] = $args['backup_file'];
2805 }
2806
2807 try
2808 {
2809 $client->refreshToken($refreshToken);
2810 }
2811 catch(Exception $e)
2812 {
2813 echo 'google Error ', $e->getMessage(), "\n";
2814 return array("error" => $e->getMessage(), "error_code" => "google_error_remove_refresh_token");
2815 }
2816
2817 $service = new IWP_google_Service_Drive($client);
2818
2819 foreach($backup_file as $key => $value)
2820 {
2821 try
2822 {
2823 $service->files->delete($value);
2824 }
2825 catch (Exception $e)
2826 {
2827 echo "An error occurred: " . $e->getMessage();
2828 return array("error" => "gDrive Remove Error".$e->getMessage(), "error_code" => "google_error_delete");
2829 }
2830 }
2831 }
2832
2833 function schedule_next($type, $schedule)
2834 {
2835 $schedule = explode("|", $schedule);
2836 if (empty($schedule))
2837 return false;
2838 switch ($type) {
2839
2840 case 'daily':
2841
2842 if (isset($schedule[1]) && $schedule[1]) {
2843 $delay_time = $schedule[1] * 60;
2844 }
2845
2846 $current_hour = date("H");
2847 $schedule_hour = $schedule[0];
2848 if ($current_hour >= $schedule_hour){
2849 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 1, date("Y"));
2850 //$time ='0001#'.$current_hour.'|'.$schedule_hour;
2851
2852 }
2853
2854 else{
2855 $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2856 //$time ='0000#'.$current_hour.'|'.$schedule_hour;
2857 }
2858 $time = time() + 30;
2859
2860
2861 break;
2862
2863
2864 case 'weekly':
2865 if (isset($schedule[2]) && $schedule[2]) {
2866 $delay_time = $schedule[2] * 60;
2867 }
2868 $current_weekday = date('w');
2869 $schedule_weekday = $schedule[1];
2870 $current_hour = date("H");
2871 $schedule_hour = $schedule[0];
2872
2873 if ($current_weekday > $schedule_weekday)
2874 $weekday_offset = 7 - ($schedule_weekday - $schedule[1]);
2875 else
2876 $weekday_offset = $schedule_weekday - $current_weekday;
2877
2878
2879 if (!$weekday_offset) { //today is scheduled weekday
2880 if ($current_hour >= $schedule_hour)
2881 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 7, date("Y"));
2882 else
2883 $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2884 } else {
2885 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + $weekday_offset, date("Y"));
2886 }
2887
2888 break;
2889
2890 case 'monthly':
2891 if (isset($schedule[2]) && $schedule[2]) {
2892 $delay_time = $schedule[2] * 60;
2893 }
2894 $current_monthday = date('j');
2895 $schedule_monthday = $schedule[1];
2896 $current_hour = date("H");
2897 $schedule_hour = $schedule[0];
2898
2899 if ($current_monthday > $schedule_monthday) {
2900 $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2901 } else if ($current_monthday < $schedule_monthday) {
2902 $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2903 } else if ($current_monthday == $schedule_monthday) {
2904 if ($current_hour >= $schedule_hour)
2905 $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2906 else
2907 $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2908 break;
2909 }
2910
2911 break;
2912 default:
2913 break;
2914 }
2915
2916 if (isset($delay_time) && $delay_time) {
2917 $time += $delay_time;
2918 }
2919
2920 return $time;
2921 }
2922
2923
2924 //Parse task arguments for info on IWP Admin Panel
2925
2926 function get_all_tasks(){
2927 /*global $wpdb;
2928
2929 $stats = array();
2930 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2931
2932 $rows = $wpdb->get_col("SELECT taskResults FROM ".$table_name);
2933 $task_res = array();
2934 foreach($rows as $key => $value){
2935 $task_results = unserialize($value);
2936 if(is_array($task_results['task_results'])){
2937
2938 foreach($task_results['task_results'] as $key => $data){
2939 $task_res['task_results'][$key] = $data;
2940 }
2941 }
2942 }*/
2943
2944 global $wpdb;
2945
2946 $stats = array();
2947 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2948
2949 $rows = $wpdb->get_results("SELECT ID, taskName, taskResults FROM ".$table_name." ORDER BY ID DESC", ARRAY_A);
2950 $this->cleanup_failed_backups($rows);
2951 $task_res = array();
2952 foreach($rows as $key => $value){
2953 $task_results = unserialize($value['taskResults']);
2954 if (!empty($task_results['task_results']))
2955 foreach($task_results['task_results'] as $key => $data){
2956 $task_res[$value['taskName']]['task_results'][$key] = $data;
2957 }
2958 }
2959
2960 return $task_res;
2961 }
2962
2963 function cleanup_failed_backups($rows){
2964 $rowCount = 0;
2965 if (empty($rows) || !is_array($rows)) {
2966 return false;
2967 }
2968 foreach($rows as $key => $value){
2969 $task_results = unserialize($value['taskResults']);
2970 if(empty($task_results['task_results'])){
2971 if ($rowCount > 0) {
2972 $this->remove_failed_backups($value['ID']);
2973 }
2974 $rowCount++;
2975 continue;
2976 }
2977 $rowCount++;
2978 }
2979 }
2980
2981 function remove_failed_backups($ID){
2982 global $wpdb;
2983 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2984 $delete_query = $wpdb->prepare(
2985 "DELETE FROM {$table_name} WHERE ID = %d",
2986 absint($ID)
2987 );
2988 $deleteRes = $wpdb->query($delete_query);
2989 }
2990
2991 function remove_failed_backups_by_hisID($ID){
2992 global $wpdb;
2993 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2994 $ids = array_map('absint', (array)$ID);
2995 $ids = array_filter($ids, static function ($value) {
2996 return $value > 0;
2997 });
2998 if (empty($ids)) {
2999 return;
3000 }
3001 $placeholders = implode(', ', array_fill(0, count($ids), '%d'));
3002 $delete_query = $wpdb->prepare(
3003 "DELETE FROM {$table_name} WHERE historyID IN ({$placeholders})",
3004 $ids
3005 );
3006 $deleteRes = $wpdb->query($delete_query);
3007 }
3008
3009 function get_this_tasks($requestParams = ''){
3010 $this->wpdb_reconnect();
3011
3012 global $wpdb;
3013 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3014
3015 $rows = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$table_name." WHERE historyID = %d", $GLOBALS['IWP_CLIENT_HISTORY_ID']), ARRAY_A);
3016
3017 if($requestParams == 'requestParams'){
3018 $rows = unserialize($rows['requestParams']);
3019 }
3020
3021 return $rows;
3022
3023 }
3024
3025 function get_this_tasks_params(){
3026 $this->wpdb_reconnect();
3027
3028 global $wpdb;
3029 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3030
3031 $rows = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$table_name." WHERE historyID = %d", $GLOBALS['IWP_CLIENT_HISTORY_ID']), ARRAY_A);
3032
3033 return unserialize($rows['requestParams']);
3034 }
3035
3036 function get_requested_task($ID){
3037 global $wpdb;
3038 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3039
3040 $rows = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$table_name." WHERE historyID = %d ORDER BY ID DESC LIMIT 1", $ID), ARRAY_A);
3041
3042 $return = unserialize($rows['taskResults']);
3043
3044 return $return;
3045
3046 }
3047
3048 function get_backup_stats()
3049 {
3050 global $wpdb;
3051 $stats = array();
3052 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3053 $rows = $wpdb->get_results("select * from ".$table_name);
3054 $task_res = array();
3055 if(!empty($rows)){
3056 foreach($rows as $key => $value){
3057 $task_results = unserialize($value->taskResults);
3058 if(!empty($task_results['task_results'])){
3059 $task_res[$value->taskName][$value->historyID] = $task_results['task_results'][$value->historyID];
3060 $requestParams = unserialize($value->requestParams);
3061 $args = $requestParams['account_info'];
3062 if (!empty($args['iwp_ftp']['use_sftp'])) {
3063 $task_res[$value->taskName][$value->historyID]['sftp'] = true;
3064 }
3065 }
3066 if (!empty($task_results['backhack_status'])) {
3067 $task_res[$value->taskName][$value->historyID]['backhack_status'] = $task_results['backhack_status'];
3068 }
3069 }
3070 }
3071 $stats = $task_res;
3072 return $stats;
3073 /*foreach ($rows as $obj) {
3074
3075 echo $obj->name;
3076
3077 }*/
3078
3079 /*
3080 $stats = array();
3081 $tasks = $this->tasks;
3082 if (is_array($tasks) && !empty($tasks)) {
3083 foreach ($tasks as $task_name => $info) {
3084 if (is_array($info['task_results']) && !empty($info['task_results'])) {
3085 foreach ($info['task_results'] as $key => $result) {
3086 if (isset($result['server']) && !isset($result['error'])) {
3087 if (!file_exists($result['server']['file_path'])) {
3088 $info['task_results'][$key]['error'] = 'Backup created but manually removed from server.';
3089 }
3090 }
3091 }
3092 }
3093 if (is_array($info['task_results']))
3094 $stats[$task_name] = $info['task_results'];
3095 }
3096 }
3097 return $stats;
3098 */
3099 }
3100
3101
3102 function remove_old_backups($task_name)
3103 {
3104 global $wpdb;
3105
3106 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3107
3108 //Check for previous failed backups first
3109 $this->cleanup();
3110
3111 //Remove by limit
3112 $backups = $this->get_all_tasks();
3113
3114 $requestParams = $this->get_this_tasks("requestParams");
3115
3116 $limit = absint($requestParams['args']['limit']);
3117
3118 $other_method_backups = iwp_mmb_get_backup_ID_by_taskname('advanced', $task_name);
3119 $current_backups = $this->get_timestamp_by_label($task_name);
3120 $all_backups = array();
3121 $delete_backup = array();
3122 if (!empty($other_method_backups)) {
3123 $all_backups = array_merge($all_backups, $other_method_backups);
3124 if (!empty($current_backups)) {
3125 $all_backups = array_merge($all_backups, $current_backups);
3126 ksort($all_backups);
3127 ksort($current_backups);
3128 foreach ($other_method_backups as $timestamp => $historyID) {
3129 foreach ($current_backups as $time => $value) {
3130 if ($time > $timestamp) {
3131 $delete_backup[$timestamp] = $timestamp;
3132 }
3133 break;
3134 }
3135 }
3136 }
3137 }
3138 if (!empty($delete_backup)) {
3139 $total_backups = count($all_backups);
3140 if ($total_backups > $limit) {
3141 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/backup/backup.core.class.php');
3142 iwp_mmb_define_constant();
3143 $backup_instance = new IWP_MMB_Backup_Core();
3144 foreach ($delete_backup as $timestamp => $historyID) {
3145 $total_backups--;
3146 $backup_instance->delete_backup(array('result_id' => $historyID));
3147 if ($total_backups<= $limit) {
3148 return;
3149 }
3150 }
3151 }
3152 }
3153
3154 $select_prev_backup = $wpdb->prepare(
3155 "SELECT historyID, taskResults FROM {$table_name} WHERE taskName = %s ORDER BY ID DESC LIMIT %d, 100",
3156 $task_name,
3157 $limit
3158 );
3159
3160 $select_prev_backup_res = $wpdb->get_results($select_prev_backup, ARRAY_A);
3161
3162
3163 foreach ( $select_prev_backup_res as $backup_data )
3164 {
3165 $task_result = unserialize($backup_data['taskResults']);
3166 $thisRequestParams = $this->getRequiredData($backup_data['historyID'], "requestParams");
3167
3168 if (isset($task_result['task_results'][$backup_data['historyID']]['server'])) {
3169 $backup_file = $task_result['task_results'][$backup_data['historyID']]['server']['file_path'];
3170 if(!is_array($backup_file))
3171 {
3172 $temp_backup_file = $backup_file;
3173 $backup_file = array();
3174 $backup_file[0] = $temp_backup_file;
3175 }
3176 foreach($backup_file as $value)
3177 {
3178 @unlink($value);
3179 }
3180 }
3181
3182 if (isset($task_result['task_results'][$backup_data['historyID']]['ftp'])) {
3183 $ftp_file = $task_result['task_results'][$backup_data['historyID']]['ftp'];
3184 $args = $thisRequestParams['account_info']['iwp_ftp'];
3185 $args['backup_file'] = $ftp_file;
3186 $this->remove_ftp_backup($args);
3187 }
3188
3189 if (isset($task_result['task_results'][$backup_data['historyID']]['amazons3'])) {
3190 $amazons3_file = $task_result['task_results'][$backup_data['historyID']]['amazons3'];
3191 $args = $thisRequestParams['account_info']['iwp_amazon_s3'];
3192 $args['backup_file'] = $amazons3_file;
3193 if(is_new_s3_compatible()){
3194 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
3195 $new_s3_obj = new IWP_MMB_S3_SINGLECALL();
3196 $new_s3_obj->remove_amazons3_backup($args);
3197 }
3198 else{
3199 $this->remove_amazons3_backup_bwd_comp($args);
3200 }
3201 }
3202
3203 if (isset($task_result['task_results'][$backup_data['historyID']]['dropbox']) && isset($thisRequestParams['account_info']['iwp_dropbox'])) {
3204 //To do: dropbox remove
3205 $dropbox_file = $task_result['task_results'][$backup_data['historyID']]['dropbox'];
3206 $args = $thisRequestParams['account_info']['iwp_dropbox'];
3207 $args['backup_file'] = $dropbox_file;
3208 if(!empty($args['dropbox_access_token']) || (empty($args['dropbox_access_token']) && time() < 1498608000)){
3209 $this->remove_dropbox_backup($args);
3210 }
3211 }
3212
3213 if (isset($task_result['task_results'][$backup_data['historyID']]['gDrive'])) {
3214 $gdrive_file = $task_result['task_results'][$backup_data['historyID']]['gDrive'];
3215 $args = $thisRequestParams['account_info']['iwp_gdrive'];
3216 $args['backup_file'] = $gdrive_file;
3217 $this->remove_google_drive_backup($args);
3218 }
3219
3220 $delete_query = $wpdb->prepare(
3221 "DELETE FROM {$table_name} WHERE historyID = %d",
3222 absint($backup_data['historyID'])
3223 );
3224
3225 $deleteRes = $wpdb->query($delete_query);
3226 }
3227
3228 return true;
3229
3230 }
3231
3232 /**
3233 * Delete specified backup
3234 * Args: $task_name, $result_id
3235 */
3236
3237 function delete_backup($args)
3238 {
3239 if (empty($args))
3240 return false;
3241
3242 global $wpdb;
3243 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3244
3245 extract($args);
3246
3247 $tasks = $this->get_requested_task($result_id);
3248 $backup = $tasks['task_results'][$result_id];
3249
3250 //$requestParams = unserialize($tasks['requestParams']);
3251 $requestParams = $this->getRequiredData($result_id, 'requestParams');
3252
3253 if(!empty($requestParams['account_info'])){
3254 $args = $requestParams['account_info'];
3255 }
3256
3257 if (isset($backup['server'])) {
3258 $backup_file = $backup['server']['file_path'];
3259 if(is_array($backup_file))
3260 {
3261 foreach($backup_file as $value)
3262 {
3263 @unlink($value);
3264 }
3265 }
3266 else
3267 {
3268 if (file_exists($backup_file)) {
3269 @unlink($backup_file);
3270 }
3271 }
3272 }
3273
3274
3275 //Remove from ftp
3276 if (isset($backup['ftp'])) {
3277 $ftp_file = $backup['ftp'];
3278 $args = $args['iwp_ftp'];
3279 $args['backup_file'] = $ftp_file;
3280 $this->remove_ftp_backup($args);
3281 }
3282
3283 if (isset($backup['amazons3'])) {
3284 $amazons3_file = $backup['amazons3'];
3285 $args = $args['iwp_amazon_s3'];
3286 $args['backup_file'] = $amazons3_file;
3287 if(is_new_s3_compatible()){
3288 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
3289 $new_s3_obj = new IWP_MMB_S3_SINGLECALL();
3290 $new_s3_obj->remove_amazons3_backup($args);
3291 }
3292 else{
3293 $this->remove_amazons3_backup_bwd_comp($args);
3294 }
3295 }
3296
3297 if (isset($backup['dropbox'])) {
3298 $dropbox_file = $backup['dropbox'];
3299 $args = $args['iwp_dropbox'];
3300 $args['backup_file'] = $dropbox_file;
3301 $this->remove_dropbox_backup($args);
3302 }
3303
3304 if (isset($backup['gDrive'])) {
3305 $g_drive_file = $backup['gDrive'];
3306 $args = $args['iwp_gdrive'];
3307 $args['backup_file'] = $g_drive_file;
3308 $this->remove_google_drive_backup($args);
3309 }
3310
3311 $delete_query = $wpdb->prepare(
3312 "DELETE FROM {$table_name} WHERE historyID = %d",
3313 absint($result_id)
3314 );
3315
3316 $deleteRes = $wpdb->query($delete_query);
3317
3318 return true;
3319
3320 }
3321
3322 function getRequiredData($historyID, $field){
3323 global $wpdb;
3324
3325 $allowed_fields = array('requestParams', 'responseParams', 'taskResults', 'category');
3326 if (!in_array($field, $allowed_fields, true)) {
3327 return null;
3328 }
3329
3330 $backupData = $wpdb->get_row(
3331 $wpdb->prepare(
3332 "SELECT {$field} FROM {$wpdb->base_prefix}iwp_backup_status WHERE historyID = %d",
3333 $historyID
3334 )
3335 );
3336 if (($field == 'responseParams') || ($field == 'requestParams') || ($field == 'taskResults')) {
3337 $fieldParams = unserialize($backupData->$field);
3338 } else {
3339 $fieldParams = $backupData->$field;
3340 }
3341 return $fieldParams;
3342 }
3343
3344 function cleanup()
3345 {
3346 $tasks = $this->get_all_tasks(); //all backups task results array.
3347 $requestParams = $this->get_all_tasks(true);
3348 $thisTask = $this->get_this_tasks();
3349 $backup_folder = WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups/';
3350 $backup_folder_new = IWP_BACKUP_DIR . '/';
3351 $backup_temp_folder = IWP_PCLZIP_TEMPORARY_DIR;
3352 $files = glob($backup_folder . "*");
3353 $new = glob($backup_folder_new . "*");
3354 $new_temp = glob($backup_temp_folder . "*");
3355
3356 //Failed db files first
3357 $db_folder = IWP_DB_DIR . '/';
3358 $db_files = glob($db_folder . "*");
3359 if (is_array($db_files) && !empty($db_files)) {
3360 foreach ($db_files as $file) {
3361 @unlink($file);
3362 }
3363 @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
3364 @rmdir(IWP_DB_DIR);
3365 }
3366
3367
3368 //clean_old folder?
3369 if ((count($files) == 1 && basename($files[0]) == 'index.php') || (!empty($files))) { //USE (!empty($files)
3370 foreach ($files as $file) {
3371 @unlink($file);
3372 }
3373 @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups');
3374 @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client'));
3375 }
3376
3377 if (!empty($new)) {
3378 foreach ($new as $b) {
3379 $files[] = $b;
3380 }
3381 }
3382 if (!empty($new_temp)) {
3383 foreach ($new_temp as $c) {
3384 $files[] = $c;
3385 }
3386 }
3387 $deleted = array();
3388
3389 $results = array();
3390 if (is_array($files) && count($files)) {
3391 $cloudFailedBackup = array();
3392 $failedBackupHisID = array();
3393 if (!empty($tasks)) {
3394 foreach ((array) $tasks as $taskName => $task) {
3395 //if (isset($task) && count($task)) {
3396 // foreach ($task as $backup) {
3397 if (isset($task['task_results']) && count($task['task_results'])) {
3398 foreach ($task['task_results'] as $historyID => $backup) {
3399 if (isset($backup['server'])) {
3400 $this_backup_file = $backup['server']['file_path'];
3401 if(is_array($this_backup_file))
3402 {
3403 foreach($this_backup_file as $single_backup_file)
3404 { if (!empty($requestParams[$taskName]['requestParams'][$historyID]['account_info']) && $thisTask['historyID'] != $historyID) {
3405 $cloudFailedBackup[]= $single_backup_file;
3406 $failedBackupHisID[$historyID]=$historyID;
3407 }
3408 $results[] = $single_backup_file;
3409 }
3410 }
3411 else
3412 {
3413 if (!empty($requestParams[$taskName]['requestParams'][$historyID]['account_info']) && !empty($thisTask['historyID']) && $thisTask['historyID'] != $historyID) {
3414 $cloudFailedBackup[]= $this_backup_file;
3415 $failedBackupHisID[$historyID]=$historyID;
3416 }
3417 $results[] = $this_backup_file;
3418 }
3419 }
3420 }
3421 }
3422 }
3423 }
3424
3425 $pheonixBackup = $GLOBALS['iwp_backup_core']->get_backup_history();
3426 if (!empty($pheonixBackup)) {
3427 foreach ($pheonixBackup as $timestamp => $backup) {
3428 if (!empty($backup['plugins'])) {
3429 $results = array_merge($results, $backup['plugins']);
3430 }
3431 if (!empty($backup['themes'])) {
3432 $results = array_merge($results, $backup['themes']);
3433 }
3434 if (!empty($backup['uploads'])) {
3435 $results = array_merge($results, $backup['uploads']);
3436 }
3437 if (!empty($backup['others'])) {
3438 $results = array_merge($results, $backup['others']);
3439 }
3440 if (!empty($backup['more'])) {
3441 $results = array_merge($results, $backup['more']);
3442 }
3443 if (!empty($backup['db'])) {
3444 $results[] = $backup['db'];
3445 }
3446 if (!empty($backup['backup_file_basename'])) {
3447 $results[] = $backup['backup_file_basename'];
3448 }
3449 }
3450 }
3451
3452 $num_deleted = 0;
3453 foreach ($files as $file) {
3454 if (((!in_array($file, $results) && !in_array(basename($file), $results)) || in_array($file, $failedBackupHisID)) && basename($file) != 'index.php') {
3455 @unlink($file);
3456 // $deleted[] = basename($file);
3457 $deleted[] = $file;
3458 $num_deleted++;
3459 }
3460 }
3461
3462 if (!empty($failedBackupHisID)) {
3463 $this->remove_failed_backups_by_hisID($failedBackupHisID);
3464 }
3465 }
3466 return $deleted;
3467 }
3468
3469
3470
3471 function update_status($task_name, $status, $completed = false, $task_result='')
3472 {
3473 /* Statuses:
3474 0 - Backup started 1 - DB dump 2 - DB ZIP 3 - Files ZIP 4 - Amazon S3 5 - Dropbox 6 - FTP 7 - Email 100 - Finished
3475 */
3476
3477 //$tasks = $this->tasks;
3478
3479 $test_this_task = $this->get_this_tasks();
3480
3481 $tasks = unserialize($test_this_task['taskResults']);
3482
3483 $tasks['backhack_status']['adminHistoryID'] = $GLOBALS['IWP_CLIENT_HISTORY_ID'];
3484
3485 if (!$completed) {
3486
3487 $tasks['backhack_status'][$status]['start'] = microtime(true);
3488
3489 $test = $this->statusLog($GLOBALS['IWP_CLIENT_HISTORY_ID'], array('stage' => $status, 'status' => 'processing', 'statusMsg' => 'processing', 'task_result' => $tasks));
3490
3491 }
3492 else {
3493
3494 $tasks['backhack_status'][$status]['end'] = microtime(true);
3495
3496 if(!empty($task_result)){
3497 $tasks['task_results'][$GLOBALS['IWP_CLIENT_HISTORY_ID']] = $task_result;
3498 }
3499
3500 $test2 = $this->statusLog($GLOBALS['IWP_CLIENT_HISTORY_ID'], array('stage' => $status, 'status' => 'completed', 'statusMsg' => 'completed', 'task_result' => $tasks));
3501
3502 }
3503
3504 $this->update_tasks($tasks);
3505 }
3506
3507 function statusLog($historyID = '', $statusArray = array(), $params=array())
3508 {
3509 global $wpdb,$insertID;
3510 iwp_mmb_create_backup_status_table();
3511 if(empty($historyID))
3512 {
3513 $insert = $wpdb->insert($wpdb->base_prefix.'iwp_backup_status',array( 'stage' => $statusArray['stage'], 'status' => $statusArray['status'], 'action' => $params['args']['action'], 'type' => $params['args']['type'],'category' => $params['args']['what'],'historyID' => $GLOBALS['IWP_CLIENT_HISTORY_ID'],'finalStatus' => 'pending','startTime' => microtime(true),'lastUpdateTime' => microtime(true), 'endTime' => '','statusMsg' => $statusArray['statusMsg'],'requestParams' => serialize($params),'taskName' => $params['task_name']), array( '%s', '%s','%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s' ) );
3514 if($insert)
3515 {
3516 $insertID = $wpdb->insert_id;
3517 }
3518 }
3519 else if(isset($statusArray['responseParams']))
3520 {
3521
3522 $update = $wpdb->update($wpdb->base_prefix.'iwp_backup_status',array( 'responseParams' => serialize($statusArray['responseParams']),'stage' => $statusArray['stage'], 'status' => $statusArray['status'],'statusMsg' => $statusArray['statusMsg'], 'taskResults' => serialize($statusArray['task_result']), 'lastUpdateTime' => microtime(true)),array( 'historyID' => $historyID),array('%s','%s', '%s', '%s', '%s'),array('%d'));
3523
3524
3525 }
3526 else
3527 {
3528 $update = $wpdb->update($wpdb->base_prefix.'iwp_backup_status',array( 'stage' => $statusArray['stage'], 'status' => $statusArray['status'],'statusMsg' => $statusArray['statusMsg'], 'taskResults' => serialize($statusArray['task_result']), 'lastUpdateTime' => microtime(true)),array( 'historyID' => $historyID),array('%s', '%s', '%s', '%s'),array('%d'));
3529
3530 }
3531 if( (isset($update)&&(!$update)) || (isset($insert)&&(!$insert)) )
3532 {
3533 //return array('error'=> $statusArray['statusMsg']);
3534 iwp_mmb_response(array('error' => 'MySQL Error: '.$wpdb -> last_error, 'error_code' => 'status_log_my_sql_error'), false);
3535 }
3536
3537 if((isset($statusArray['sendResponse']) && $statusArray['sendResponse'] == true) || $statusArray['status'] == 'completed')
3538 {
3539 $returnParams = array();
3540 $returnParams['parentHID'] = $historyID;
3541 $returnParams['backupID'] = $insertID;
3542 $returnParams['stage'] = $statusArray['stage'] ;
3543 $returnParams['status'] = $statusArray['status'];
3544 $returnParams['nextFunc'] = isset($statusArray['nextFunc']) ? $statusArray['nextFunc']:NULL;
3545 return array('success' => $returnParams);
3546 }
3547 else
3548 {
3549 if($statusArray['status'] == 'error')
3550 {
3551 $returnParams = array();
3552 $returnParams['parentHID'] = $historyID;
3553 $returnParams['backupID'] = $insertID;
3554 $returnParams['stage'] = $statusArray['stage'] ;
3555 $returnParams['status'] = $statusArray['status'];
3556 $returnParams['statusMsg'] = $statusArray['statusMsg'];
3557
3558 return array('error'=> $returnParams);
3559 }
3560 }
3561 }
3562
3563 function update_tasks($tasks)
3564 {
3565 //$this->tasks = $tasks;
3566 update_option('iwp_client_backup_tasks', $tasks);
3567 }
3568
3569 function wpdb_reconnect(){
3570 if(version_compare(phpversion() , '8', '>=')){
3571 return;
3572 }
3573 global $wpdb;
3574 $old_wpdb = $wpdb;
3575 //Reconnect to avoid timeout problem after ZIP files
3576 if(class_exists('wpdb') && function_exists('wp_set_wpdb_vars')){
3577 if ($wpdb->use_mysqli) {
3578 @mysqli_close($wpdb->dbh);
3579 } else {
3580 if (function_exists('mysql_close')){
3581 @mysql_close($wpdb->dbh);
3582 }
3583 }
3584 $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
3585 wp_set_wpdb_vars();
3586 $wpdb->options = $old_wpdb->options;//fix for multi site full backup
3587 }
3588 }
3589
3590 function replace_htaccess($url, $remote_abspath)
3591 {
3592 global $wp_filesystem;
3593 //$file = @file_get_contents(ABSPATH.'.htaccess');
3594 $file = $wp_filesystem->get_contents($remote_abspath.'.htaccess');
3595 if ($file && strlen($file)) {
3596 $args = parse_url($url);
3597 $string = rtrim($args['path'], "/");
3598 $regex = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
3599 $replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
3600 $file = preg_replace($regex, $replace, $file);
3601 //@file_put_contents(ABSPATH.'.htaccess', $file);
3602 $wp_filesystem->put_contents($remote_abspath.'.htaccess', $file);
3603 }
3604 }
3605
3606 public function readd_tasks( $params = array() ){
3607 global $iwp_mmb_core;
3608
3609 if( empty($params) || !isset($params['backups']) )
3610 return $params;
3611
3612 $before = array();
3613 $tasks = $params['backups'];
3614 if( !empty($tasks) ){
3615
3616 if( function_exists( 'wp_next_scheduled' ) ){
3617 if ( !wp_next_scheduled('iwp_client_backup_tasks') ) {
3618 wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
3619 }
3620 }
3621
3622 foreach( $tasks as $task ){
3623 $before[$task['task_name']] = array();
3624
3625 if(isset($task['secure'])){
3626 if($decrypted = $iwp_mmb_core->_secure_data($task['secure'])){
3627 $decrypted = maybe_unserialize($decrypted);
3628 if(is_array($decrypted)){
3629 foreach($decrypted as $key => $val){
3630 if(!is_numeric($key))
3631 $task[$key] = $val;
3632 }
3633 unset($task['secure']);
3634 } else
3635 $task['secure'] = $decrypted;
3636 }
3637
3638 }
3639 if (isset($task['account_info']) && is_array($task['account_info'])) { //only if sends from panel first time(secure data)
3640 $task['args']['account_info'] = $task['account_info'];
3641 }
3642
3643 $before[$task['task_name']]['task_args'] = $task['args'];
3644 $before[$task['task_name']]['task_args']['next'] = $this->schedule_next($task['args']['type'], $task['args']['schedule']);
3645 }
3646 }
3647 update_option('iwp_client_backup_tasks', $before);
3648
3649 unset($params['backups']);
3650 return $params;
3651 }
3652
3653 function is_server_writable(){
3654 if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), ABSPATH) != 'direct'))
3655 return false;
3656 else
3657 return true;
3658 }
3659
3660 function get_timestamp_by_label($label){
3661 $new_backup_keys = array();
3662 global $wpdb;
3663 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3664 $select_prev_backup = $wpdb->prepare(
3665 "SELECT historyID, lastUpdateTime FROM {$table_name} WHERE taskName = %s ORDER BY ID DESC",
3666 $label
3667 );
3668 $select_prev_backup_res = $wpdb->get_results($select_prev_backup, ARRAY_A);
3669 foreach ($select_prev_backup_res as $key => $value) {
3670 $new_backup_keys[$value['lastUpdateTime']] = $value['historyID'];
3671 }
3672 return $new_backup_keys;
3673 }
3674 }
3675
3676 /*if( function_exists('add_filter') ){
3677 add_filter( 'iwp_website_add', 'IWP_MMB_Backup::readd_tasks' );
3678 }*/
3679
3680 if(!function_exists('get_all_files_from_dir')) {
3681 /**
3682 * Get all files in directory
3683 *
3684 * @param string $path Relative or absolute path to folder
3685 * @param array $exclude List of excluded files or folders, relative to $path
3686 * @return array List of all files in folder $path, exclude all files in $exclude array
3687 */
3688 function get_all_files_from_dir($path, $exclude = array()) {
3689
3690 if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
3691 global $directory_tree, $ignore_array;
3692 $directory_tree = array();
3693 if(!empty($exclude))
3694 {
3695 foreach ($exclude as $file) {
3696 if (!in_array($file, array('.', '..'))) {
3697 if (!empty($file[0]) && $file[0] === "/") $path = substr($file, 1);
3698 $ignore_array[] = "$path/$file";
3699 }
3700 }
3701 }
3702 get_all_files_from_dir_recursive($path);
3703
3704 return $directory_tree;
3705 }
3706 }
3707
3708 if (!function_exists('get_all_files_from_dir_recursive')) {
3709 /**
3710 * Get all files in directory,
3711 * wrapped function which writes in global variable
3712 * and exclued files or folders are read from global variable
3713 *
3714 * @param string $path Relative or absolute path to folder
3715 * @return void
3716 */
3717 function get_all_files_from_dir_recursive($path) {
3718 if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
3719 global $directory_tree, $ignore_array;
3720 if(empty($ignore_array))
3721 {
3722 $ignore_array = array();
3723 }
3724 $directory_tree_temp = array();
3725 $dh = @opendir($path);
3726 if($dh !== false){
3727 while (false !== ($file = @readdir($dh))) {
3728 if (!in_array($file, array('.', '..'))) {
3729 if (!in_array("$path/$file", $ignore_array)) {
3730 if (!is_dir("$path/$file")) {
3731 $directory_tree[] = "$path/$file";
3732 } else {
3733 get_all_files_from_dir_recursive("$path/$file");
3734 }
3735 }
3736 }
3737 }
3738 @closedir($dh);
3739 }
3740 else{
3741 //code to process openDir failure.
3742 }
3743 }
3744 }
3745
3746 if( !function_exists('is_new_s3_compatible') ){
3747 function is_new_s3_compatible(){
3748 if(phpversion() >= '5.3.3'){
3749 return true;
3750 }
3751 return false;
3752 }
3753 }
3754
3755 if( !function_exists('is_new_dropbox_compatible') ){
3756 function is_new_dropbox_compatible(){
3757 if(version_compare(phpversion() , '5.3.3', '>=')){
3758 return true;
3759 }
3760 return false;
3761 }
3762 }
3763
3764 if( !function_exists('upgradeOldDropBoxBackupList')){
3765 function upgradeOldDropBoxBackupList($dropBoxInfo){
3766 if (!isset($dropBoxInfo['dropbox_access_token']) && empty($dropBoxInfo['dropbox_access_token']) ) {
3767 return false;
3768 }
3769 global $wpdb;
3770 $table_name = $wpdb->base_prefix . "iwp_backup_status";
3771
3772 $rows = $wpdb->get_results("SELECT ID, taskName, taskResults, requestParams FROM ".$table_name." ORDER BY ID DESC", ARRAY_A);
3773 if (empty($rows)) {
3774 return false;
3775 }
3776 foreach ($rows as $ID => $taskArray) {
3777 $requestParams = unserialize($taskArray['requestParams']);
3778 $accountInfo = isset($requestParams['account_info']) ? $requestParams['account_info']:array();
3779 if (isset($accountInfo['iwp_dropbox']) && isset($accountInfo['iwp_dropbox']['oauth_token']) && !empty($accountInfo['iwp_dropbox']['oauth_token'])) {
3780 $requestParams['account_info']['iwp_dropbox']['consumer_key'] = '';
3781 $requestParams['account_info']['iwp_dropbox']['consumer_secret'] = '';
3782 $requestParams['account_info']['iwp_dropbox']['oauth_token'] = '';
3783 $requestParams['account_info']['iwp_dropbox']['oauth_token_secret'] = '';
3784 $requestParams['account_info']['iwp_dropbox']['dropbox_app_key'] = $dropBoxInfo['dropbox_app_key'];
3785 $requestParams['account_info']['iwp_dropbox']['dropbox_app_secure_key'] = $dropBoxInfo['dropbox_app_secure_key'];
3786 $requestParams['account_info']['iwp_dropbox']['dropbox_access_token'] = $dropBoxInfo['dropbox_access_token'];
3787 $update = $wpdb->update($table_name,array( 'requestParams' => serialize($requestParams)),array( 'ID' => $taskArray['ID']),array('%s'),array('%d'));
3788 }
3789 }
3790 }
3791 }
3792
3793 ?>