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.multicall.php

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

7,618 lines 283.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /************************************************************
3 * This plugin was modified by Revmakx *
4 * Copyright (c) 2012 Revmakx *
5 * www.revmakx.com *
6 * *
7 ************************************************************/
8 /*************************************************************
9 *
10 * backup.class.php
11 *
12 * Manage Backups
13 *
14 *
15 * Copyright (c) 2011 Prelovac Media
16 * www.prelovac.com
17 **************************************************************/
18 if ( ! defined('ABSPATH') )
19 die();
20
21 if(!defined('IWP_BACKUP_DIR')){
22 define('IWP_BACKUP_DIR', WP_CONTENT_DIR . '/infinitewp/backups');
23 }
24
25 if(!defined('IWP_DB_DIR')){
26 define('IWP_DB_DIR', IWP_BACKUP_DIR . '/iwp_db');
27 }
28
29 if(!defined('IWP_PCLZIP_TEMPORARY_DIR')){
30 define('IWP_PCLZIP_TEMPORARY_DIR', WP_CONTENT_DIR . '/infinitewp/temp/');
31 }
32
33 $zip_errors = array(
34 'No error',
35 'No error',
36 'Unexpected end of zip file',
37 'A generic error in the zipfile format was detected',
38 'zip was unable to allocate itself memory',
39 'A severe error in the zipfile format was detected',
40 'Entry too large to be split with zipsplit',
41 'Invalid comment format',
42 'zip -T failed or out of memory',
43 'The user aborted zip prematurely',
44 'zip encountered an error while using a temp file. Please check if this domain\'s account has enough disk space.',
45 'Read or seek error',
46 'zip has nothing to do',
47 'Missing or empty zip file',
48 'Error writing to a file. Please check if this domain\'s account has enough disk space.',
49 'zip was unable to create a file to write to',
50 'bad command line parameters',
51 'no error',
52 'zip could not open a specified file to read'
53 );
54 $unzip_errors = array(
55 'No error',
56 'One or more warning errors were encountered, but processing completed successfully anyway',
57 'A generic error in the zipfile format was detected',
58 'A severe error in the zipfile format was detected.',
59 'unzip was unable to allocate itself memory.',
60 'unzip was unable to allocate memory, or encountered an encryption error',
61 'unzip was unable to allocate memory during decompression to disk',
62 'unzip was unable allocate memory during in-memory decompression',
63 'unused',
64 'The specified zipfiles were not found',
65 'Bad command line parameters',
66 'No matching files were found',
67 50 => 'The disk is (or was) full during extraction',
68 51 => 'The end of the ZIP archive was encountered prematurely.',
69 80 => 'The user aborted unzip prematurely.',
70 81 => 'Testing or extraction of one or more files failed due to unsupported compression methods or unsupported decryption.',
71 82 => 'No files were found due to bad decryption password(s)'
72 );
73
74 class IWP_MMB_Backup_Multicall extends IWP_MMB_Core
75 {
76 var $site_name;
77 var $statuses;
78 var $tasks;
79 var $s3;
80 var $ftp;
81 var $dropbox;
82 var $statusLogVar;
83 var $hisID;
84 var $backup_url;
85 var $backup_settings_vals = array();
86 var $iwpScriptStartTime;
87
88 function __construct()
89 {
90
91 //require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.split.php';
92 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
93 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/iwp-file-iterator.php';
94 parent::__construct();
95 $this->site_name = str_replace(array(
96 "_",
97 "/",
98 "~"
99 ), array(
100 "",
101 "-",
102 "-"
103 ), rtrim($this->remove_http(get_bloginfo('url')), "/"));
104 $this->statuses = array(
105 'db_dump' => 1,
106 'db_zip' => 2,
107 'files_zip' => 3,
108 'finished' => 100
109 );
110 $this->tasks = get_option('iwp_client_multi_backup_temp_values');
111 if (!empty($GLOBALS['IWP_MMB_PROFILING']['ACTION_START'])) {
112 $this->iwpScriptStartTime = $GLOBALS['IWP_MMB_PROFILING']['ACTION_START'];
113 }else{
114 $this->iwpScriptStartTime = microtime(1);
115 }
116 }
117
118 function set_resource_limit()
119 {
120 $changed = array('execution_time' => 0, 'memory_limit' => 0, 'ini_memory_limit' => ini_get('memory_limit'), 'ini_execution_time' => ini_get('max_execution_time'));
121 @ignore_user_abort(true);
122
123
124 $mod_memory = (@ini_set('memory_limit', -1) == false) ? $changed['memory_limit'] = false : $changed['memory_limit'] = 1;
125
126 @ini_set('memory_limit', '-1');
127
128 if ( (int) @ini_get('max_execution_time') < 1200 ) {
129 $mod_exec = @ini_set('max_execution_time', 1200) == false ? $changed['execution_time'] = false : $changed['execution_time'] = 1; //twenty minutes
130 @set_time_limit(1200);
131
132 }
133
134 return $changed;
135
136 }
137
138
139 function trigger_check($datas)
140 {
141 global $iwp_multicall_hisID;
142 if(!empty($datas))
143 {
144 $this->set_resource_limit();
145 $responseParams = $this -> getRequiredData($datas['backupParentHID'],"responseParams");
146 if(empty($responseParams))
147 {
148 return $this->statusLog($datas['backupParentHID'], array('stage' => 'trigger_check', 'status' => 'error', 'statusMsg' => 'Error while fetching table data', 'statusCode' => 'error_while_fetching_table_data'));
149 }
150 $defaults = array (
151 'nextFunc' => NULL,
152 'status' => NULL
153 );
154 $responseParams = wp_parse_args( $responseParams, $defaults );
155 $action = $responseParams['nextFunc'];
156 $status = $responseParams['status'];
157 if(empty($action))
158 {
159 $iwp_multical_db_dump_flag = get_option('iwp_multical_db_dump_flag');
160 if ($iwp_multical_db_dump_flag) {
161 delete_option('iwp_multical_db_dump_flag');
162 $db_result = $this->backupDBPHP($datas['backupParentHID']);
163 return $db_result;
164 }
165 if (empty($datas['params']['success']['nextFunc'])) {
166 manual_debug('', 'triggerError');
167 return $this->statusLog($datas['backupParentHID'], array('stage' => 'trigger_check', 'status' => 'error', 'statusMsg' => 'Calling Next Function failed - Error while fetching table data', 'statusCode' => 'calling_next_function_failed_error_while_fetching_table_data'));
168 }
169 $action = $datas['params']['success']['nextFunc'];
170 }
171
172 unset($responseParams);
173
174 $is_s3 = false;
175 $is_s3 = $this->check_if_s3_backup($action, $datas['backupParentHID']);
176
177 $iwp_multicall_hisID = $datas['backupParentHID'];
178 if(method_exists('IWP_MMB_Backup_Multicall', $action) || !empty($is_s3)){
179 manual_debug('', 'triggerStart');
180 if(empty($is_s3)){
181 $result = self::$action($datas['backupParentHID']);
182 }
183 else{
184 $result = $is_s3;
185 }
186 manual_debug('', 'triggerEnd');
187 return $result;
188 }else{
189 if ($action == 'backupFilesZIPOver' && $status == 'completed') {
190 $result = array('status' => 'completed');
191 return $result;
192 }
193 }
194 }
195 }
196
197 function check_if_s3_backup($action, $h_id){
198 $amazons3_result = false;
199 if($action == 'amazons3_backup'){
200 if(is_new_s3_compatible()){
201 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
202 $new_s3_obj = new IWP_MMB_S3_MULTICALL();
203 $amazons3_result = $new_s3_obj->amazons3_backup($h_id);
204 }
205 else{
206 $action = 'amazons3_backup_bwd_comp';
207 $amazons3_result = self::$action($h_id);
208 }
209 }
210 return $amazons3_result;
211 }
212
213 function set_backup_task($params)
214 {
215 global $iwp_mmb_activities_log, $iwp_multicall_hisID;
216
217 if(!empty($params))
218 {
219 // $disk_space = iwp_mmb_check_disk_space();
220 // if ($disk_space != false) {
221 // iwp_mmb_response(array('error' => 'Your disk space is very low available space: '.$disk_space.'MB'), false);
222 // }
223 $this->cleanup();
224 $initialize_result = refresh_iwp_files_db();
225 if(is_array($initialize_result) && isset($initialize_result['error'])){
226 return $initialize_result;
227 }
228
229
230 //darkCode testing purpose static values
231 if((empty($params['args']['file_block_size']))||($params['args']['file_block_size'] < 1))
232 {
233 $params['args']['file_block_size'] = 5; //MB
234 }
235 if($params['args']['disable_comp'] == '')
236 {
237 $params['args']['is_compressed'] = true;
238 }
239 else
240 {
241 $params['args']['is_compressed'] = false;
242 }
243 if((empty($params['args']['file_loop_break_time']))||($params['args']['file_loop_break_time'] < 6))
244 {
245 $params['args']['file_loop_break_time'] = 15;
246 }
247 if((empty($params['args']['db_loop_break_time']))||($params['args']['db_loop_break_time'] < 6))
248 {
249 $params['args']['db_loop_break_time'] = 23;
250 }
251 if($params['account_info'])
252 {
253 if((empty($params['account_info']['upload_loop_break_time']))||($params['account_info']['upload_loop_break_time'] < 6))
254 {
255 $params['account_info']['upload_loop_break_time'] = 23;
256 }
257 if((empty($params['account_info']['upload_file_block_size']))||($params['account_info']['upload_file_block_size'] < 1))
258 {
259 $params['account_info']['upload_file_block_size'] = (5*1024*1024)+1;
260 }
261 else
262 {
263 $params['account_info']['upload_file_block_size'] = ($params['account_info']['upload_file_block_size']*1024*1024)+1;
264 }
265 $params['account_info']['actual_file_size'] = 0;
266
267 }
268 $historyID = '';
269
270 $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'processing', 'statusMsg' => 'verificationInitiated'),$params);
271 $historyID = $params['args']['parentHID'];
272
273 $this->hisID = $historyID;
274 $iwp_multicall_hisID = $historyID;
275
276 initialize_manual_debug();
277
278 $setMemory = $this->set_resource_limit();
279
280 if(!empty($params['account_info']) && !empty($params['account_info']['iwp_dropbox'])){
281 if(empty($params['account_info']['iwp_dropbox']['dropbox_access_token']) && time() > 1506556800){
282 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => 'Please update your cloud backup addon to v1.2.0 or above to use Dropbox API V2', 'statusCode' => 'drop_box_update'));
283 }elseif(!is_new_dropbox_compatible()){
284 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => 'Please upgrade your PHP version to 5.3.3 or above to use Dropbox V2 API', 'statusCode' => 'drop_box_version_incompitability'));
285 }
286 upgradeOldDropBoxBackupList($params['account_info']['iwp_dropbox']);
287 }
288
289 if (!empty($params['account_info']['iwp_dropbox'])) {
290 set_iwp_dropbox_auth_setting($params['account_info']['iwp_dropbox']);
291 }
292
293 if(file_exists(IWP_BACKUP_DIR) && is_dir(IWP_BACKUP_DIR)){
294 $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'processing', 'statusMsg' => 'Directory Writable'));
295 }else{
296 $mkdir = @mkdir(IWP_BACKUP_DIR, 0755, true);
297 if(!$mkdir){
298 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => 'Permission denied; Make sure you have write permission for the wp-content folder.', 'statusCode' => 'permission_denied_make_sure_you_have_write_permission_for_the_wp_content_folder'));
299 }
300 }
301 if(is_writable(IWP_BACKUP_DIR)){
302 @file_put_contents(IWP_BACKUP_DIR . '/index.php', ''); //safe
303
304 }else{
305 $chmod = chmod(IWP_BACKUP_DIR, 777);
306 if(!is_writable(IWP_BACKUP_DIR)){
307 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => IWP_BACKUP_DIR.' directory is not writable. Please set 755 or 777 file permission and try again.', 'statusCode' => 'backup_dir_is_not_writable'));
308 }
309 }
310
311 //pclzip temp folder creation
312
313 if(file_exists(IWP_PCLZIP_TEMPORARY_DIR) && is_dir(IWP_PCLZIP_TEMPORARY_DIR))
314 {
315 $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'processing', 'statusMsg' => 'Directorywritable'));
316 }
317 else
318 {
319 $mkdir = @mkdir(IWP_PCLZIP_TEMPORARY_DIR, 0755, true);
320 if(!$mkdir){
321 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => 'Error creating database backup folder (' . IWP_PCLZIP_TEMPORARY_DIR . '). Make sure you have corrrect write permissions.', 'statusCode' => 'error_creating_database_backup_folder'));
322 }
323 }
324 if(is_writable(IWP_PCLZIP_TEMPORARY_DIR))
325 {
326 @file_put_contents(IWP_PCLZIP_TEMPORARY_DIR . '/index.php', ''); //safe
327 }
328 else
329 {
330 $chmod = chmod(IWP_PCLZIP_TEMPORARY_DIR, 777);
331 if(!is_writable(IWP_PCLZIP_TEMPORARY_DIR)){
332 //$this->statusLog($historyID, "verification", false, "can't set 777");
333 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => IWP_PCLZIP_TEMPORARY_DIR.' directory is not writable. Please set 755 or 777 file permission and try again.', 'statusCode' => 'pclzip_dir_not_writable'));
334 }
335 }
336 if ((!defined('DISABLE_IWP_CLOUD_VERIFICATION')) && (empty($params['args']['disable_iwp_cloud_verification']))) {
337 $backup_repo_test_obj = new IWP_BACKUP_REPO_TEST();
338 $backup_repo_test_result = $backup_repo_test_obj->repositoryTestConnection($params['account_info']);
339 if (!empty($backup_repo_test_result['error']) && $backup_repo_test_result['status'] != 'success') {
340 return $this->statusLog($historyID, array('stage' => 'backup_repo_test', 'status' => 'error', 'statusMsg' => $backup_repo_test_result['error'], 'statusCode' => $backup_repo_test_result['error_code']));
341 }
342 }
343 //if verification is ok then store the settings in the options table
344 $backup_settings_values = array();
345 $backup_settings_values['file_block_size'] = $params['args']['file_block_size'];
346 $backup_settings_values['is_compressed'] = $params['args']['is_compressed'];
347 $backup_settings_values['file_loop_break_time'] = $params['args']['file_loop_break_time'];
348 $backup_settings_values['del_host_file'] = $params['args']['del_host_file'];
349 $backup_settings_values['task_name'] = $params['args']['backup_name'];
350 if($params['account_info'])
351 {
352 $backup_settings_values['upload_loop_break_time'] = $params['account_info']['upload_loop_break_time'];
353 $backup_settings_values['upload_file_block_size'] = $params['account_info']['upload_file_block_size'];
354 }
355 if($params['args']['what'] != 'files')
356 {
357 $backup_settings_values['db_loop_break_time'] = $params['args']['db_loop_break_time'];
358 }
359
360 //Remove the old backups (limit)
361 $removed = $this->remove_old_backups($params['task_name']);
362 if (is_array($removed) && isset($removed['error']))
363 {
364 $result_arr = array();
365 return $this->statusLog($this -> hisID, array('stage' => 'removingBackupFiles', 'status' => 'error', 'statusMsg' => 'Error while removing old backups. ('.$removed['error'].')', 'statusCode' => 'error_while_removing_old_backups', 'responseParams' => $result_arr));
366 }
367 if (!empty($params['account_info']['iwp_dropbox'])) {
368 set_iwp_dropbox_auth_setting($params['account_info']['iwp_dropbox']);
369 }
370
371 update_option('iwp_client_multi_backup_temp_values', $backup_settings_values);
372 $responseParams = array();
373 $responseParams['nextFunc'] = 'backup';
374 $responseParams['mechanism'] = 'multiCall';
375
376 $iwp_mmb_activities_log->iwp_mmb_collect_backup_details($params);
377 iwp_mmb_create_processed_iterator();
378 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'completed', 'statusMsg' => 'verified', 'nextFunc' => 'backup', 'responseParams' => $responseParams));
379 }
380 }
381
382 function backup($historyID)
383 {
384 $this -> hisID = $historyID;
385 $args = $this->getRequiredData($historyID, "requestParams"); //format available - $args
386
387 $backup_file_details = $this->prepareBackupFileDetails($args);
388 extract($backup_file_details);
389 if($what == 'db')
390 {
391 //DB alone funcion
392 $result = $this->backupDB($historyID,$backup_file,$account_info);
393 return $result;
394 }
395 elseif($what == 'files')
396 {
397 //FIle alone
398 $result = $this->backupFiles($historyID,$backup_file,$account_info);
399 return $result;
400 }
401 elseif($what == 'full')
402 {
403 //both files and db.
404
405 $result = $this->backupDB($historyID,$backup_file,$account_info);
406 return $result;
407 }
408
409
410 }
411
412 function backup_db_dump_multi($historyID)
413 {
414 $requestParams = $this->getRequiredData($historyID, "requestParams");
415 $db_loop_break_time = $requestParams['args']['db_loop_break_time'];
416 $exclude_tables =$requestParams['args']['exclude_tables'];
417 $responseParams = $this -> getRequiredData($historyID,"responseParams");
418 $file = $responseParams['file_name'];
419
420 if(!$file)
421 {
422 $file = '';
423 }
424 $db_folder = IWP_DB_DIR . '/';
425 $temp_sql_file_name = '';
426 $db_final_response = array();
427 $db_final_response['success'] = array ();
428 $db_final_response['success']['type'] = 'db';
429 if($file == '')
430 {
431 $file = DB_NAME;
432 $file .='_'.$this->generate_hash();
433 }
434 $db_final_response['success']['file_name'] = $file;
435 //$temp_sql_file_name = $file."-".$callCount.".sql"; //old method
436 $temp_sql_file_name = $file.".sql";
437 $file = $db_folder . $temp_sql_file_name;
438 global $wpdb;
439 if(empty($responseParams['mysqldump'])){
440 $paths = $this->getMySQLPath();
441 }else{
442 $paths['mysqldump'] = $responseParams['mysqldump'];
443 }
444 if(empty($paths['mysqldump'])){
445 // Fallback to php
446 return false;
447 }
448 $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
449 //$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;
450 if(empty($responseParams['full_table'])){
451 // Avoid getting exclude_table on mysqlDump retry call
452 $this_prefix = $wpdb->esc_like($wpdb->base_prefix);
453 $command0 = $wpdb->get_col('SHOW TABLES LIKE "'.$this_prefix.'%"');
454 $full_table = array();
455 $structure_only_table = array();
456 if (!empty($exclude_tables)) {
457 foreach ($command0 as $tk => $table) {
458 foreach ($exclude_tables as $ke => $exclude_table) {
459 $structure = false;
460 if (!empty($exclude_table) && strpos($table, $exclude_table)) {
461 $structure = true;
462 break;
463 }
464 }
465 if ($structure) {
466 $structure_only_table [] = $table;
467 }else{
468 $full_table [] = $table;
469 }
470 }
471 }else{
472 $full_table = $command0;
473 }
474 $wp_tables = join("\" \"",$full_table);
475 if(!empty($structure_only_table)){
476 $structure_only_table = join("\" \"",$structure_only_table);
477 }
478
479 }else{
480 $wp_tables = $responseParams['full_table'];
481 if(!empty($responseParams['structure_only_table'])){
482 $structure_only_table = $responseParams['structure_only_table'];
483 }
484 }
485 $skipThisTable = false;
486 $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';
487 if(!empty($responseParams['max_allowed_packet'])){
488 $msqld_max_allowed_packet = $responseParams['max_allowed_packet'];
489 }
490 $host_string = '--host="' . DB_HOST . '"';
491 $parsed_db = $wpdb->parse_db_host(DB_HOST);
492 if (!empty($parsed_db[0])) {
493 $host_string = '--host="' . $parsed_db[0] . '"';
494 if(!empty($parsed_db[1])){
495 $host_string .= ' --port=' . $parsed_db[1];
496 }
497 }
498
499 $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;
500
501 iwp_mmb_print_flush('DB DUMP CMD: Start');
502 ob_start();
503 update_option('iwp_multical_db_dump_flag', 1);
504 if (!empty($structure_only_table)) {
505 $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_table.'" >> ' . $brace . $file . $brace;
506 // $result = $this->iwp_mmb_exec($structure_command);
507 $command.=' && '.$structure_command;
508
509 }
510 $result = $this->iwp_mmb_exec($command);
511 ob_get_clean();
512 iwp_mmb_print_flush('DB DUMP CMD: End');
513 $time = microtime(true);
514 $finish_part = $time;
515 $total_time_part = $finish_part - $this->iwpScriptStartTime;
516 if(!$result && !defined('IWP_MYSQLDUMP_MAX_ALLOWED_PACKET')){
517 // 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
518 // the call triggered from trigger_check via nextFunc
519 if(!empty($responseParams['max_allowed_packet'])){
520 delete_option('iwp_multical_db_dump_flag');
521 return $this->backupDBPHP($historyID);
522 }
523 if(empty($responseParams['max_allowed_packet'])){
524 global $iwp_mmb_core;
525 $db_final_response['success']['max_allowed_packet'] = $iwp_mmb_core->get_max_allowed_packet();
526
527 }
528 $db_final_response['success']['response_data'] = array();
529 $db_final_response['success']['backup_file'] = $responseParams['backup_file'];
530 $db_final_response['success']['backup_url'] = $responseParams['backup_url'];
531 $db_final_response['success']['parentHID'] = $historyID;
532 $db_final_response['success']['backupParentHID'] = $historyID;
533 $db_final_response['success']['nextFunc'] = 'backup_db_dump_multi';
534 $db_final_response['success']['account_info'] = $responseParams['account_info'];
535 $db_final_response['success']['status'] = 'partiallyCompleted';
536 $db_final_response['success']['full_table'] = $wp_tables;
537 $db_final_response['success']['mysqldump'] = $paths['mysqldump'];
538 if(!empty($structure_only_table)){
539 $db_final_response['success']['structure_only_table'] = $structure_only_table;
540 }
541
542 $backupStage = 'backupDBMultiCall';
543 $this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'partiallyCompleted', 'statusMsg' => 'backupDBMultiCallRetry','nextFunc' => 'backup_db_dump_multi', 'responseParams' => $db_final_response['success']));
544
545 $db_res_array = array();
546 $db_res_array['status'] = 'partiallyCompleted';
547 $db_res_array['statusMsg'] = 'backupDBMultiCallRetry';
548 $db_res_array['backupParentHID'] = $historyID;
549 $db_res_array['parentHID'] = $historyID;
550 $db_res_array['max_allowed_packet'] = $db_final_response['success']['max_allowed_packet'];
551 return $db_res_array;
552 }
553
554 if (!$result) { // Fallback to php
555 // $result = $this->backup_db_php($file);
556 @unlink($file);
557 return $result;
558 }
559
560 if (iwp_mmb_get_file_size($file) == 0 || !is_file($file) || !$result) {
561 @unlink($file);
562 return false;
563 } else {
564 $db_final_response['success']['backup_file'] = $responseParams['backup_file'];
565 $db_final_response['success']['backup_url'] = $responseParams['backup_url'];
566 $db_final_response['success']['parentHID'] = $historyID;
567 $db_final_response['success']['backupParentHID'] = $historyID;
568 $db_final_response['success']['nextFunc'] = 'backupDBZip';
569 $db_final_response['success']['account_info'] = $responseParams['account_info'];
570 //$this->statusLog($historyID, "backupDB", true, "completed", $params, true);
571 //$this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'completed', 'statusMsg' => 'backupDBCompleted'));
572 $db_final_response['success']['status'] = 'partiallyCompleted';
573 $backupStage = 'backupDBMultiCall';
574 $this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'completed', 'statusMsg' => 'backupDBCompleted','nextFunc' => 'backupDBZip', 'responseParams' => $db_final_response['success']));
575 unset($db_final_response['success']['response_data']);
576 delete_option('iwp_multical_db_dump_flag');
577 //to continue in the same call
578 if(($db_loop_break_time - $total_time_part) > 5)
579 {
580 return $this->backupDBZip($historyID);
581 }
582 else
583 {
584 delete_option('iwp_multical_db_dump_flag');
585 $db_res_array = array();
586 $db_res_array['status'] = $db_final_response['success']['status'];
587 $db_res_array['backupParentHID'] = $db_final_response['success']['backupParentHID'];
588 $db_res_array['parentHID'] = $db_final_response['success']['parentHID'];
589 return $db_res_array;
590 }
591 }
592 }
593
594 function check_mysql_paths()
595 {
596 global $wpdb;
597 $paths = array(
598 'mysql' => '',
599 'mysqldump' => ''
600 );
601 if (substr(PHP_OS, 0, 3) == 'WIN') {
602 $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
603 if ($mysql_install) {
604 $install_path = str_replace('\\', '/', $mysql_install->Value);
605 $paths['mysql'] = $install_path . '/bin/mysql.exe';
606 $paths['mysqldump'] = $install_path . '/bin/mysqldump.exe';
607 } else {
608 $paths['mysql'] = 'mysql.exe';
609 $paths['mysqldump'] = 'mysqldump.exe';
610 }
611 } else {
612 $paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
613 if (empty($paths['mysql']))
614 $paths['mysql'] = 'mysql'; // try anyway
615
616 $paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
617 if (empty($paths['mysqldump']))
618 $paths['mysqldump'] = 'mysqldump'; // try anyway
619
620 }
621
622
623 return $paths;
624 }
625
626 public function getMySQLPath(){
627 global $wpdb;
628 $paths = array(
629 'mysql' => '',
630 'mysqldump' => ''
631 );
632 if (substr(PHP_OS, 0, 3) == 'WIN') {
633 $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
634 if ($mysql_install) {
635 $install_path = str_replace('\\', '/', $mysql_install->Value);
636 $paths['mysql'] = $install_path . '/bin/mysql.exe';
637 $paths['mysqldump'] = $install_path . '/bin/mysqldump.exe';
638 } else {
639 $paths['mysql'] = 'mysql.exe';
640 $paths['mysqldump'] = 'mysqldump.exe';
641 }
642 } else{
643 if(defined('IWP_MYSQLDUMP_EXECUTABLE') && IWP_MYSQLDUMP_EXECUTABLE){
644 $mysqlPath = IWP_MYSQLDUMP_EXECUTABLE;
645 }else{
646 $mysqlPath = iwp_mmb_build_mysqldump_list();
647 }
648
649 $bin = explode(',' , $mysqlPath);
650 $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
651 $db_folder = IWP_DB_DIR . '/';
652 $temp_sql_file_name = "iwp_temp.sql";
653 $file = $db_folder . $temp_sql_file_name;
654 $host_string = '--host="' . DB_HOST . '"';
655 $parsed_db = $wpdb->parse_db_host(DB_HOST);
656 if (!empty($parsed_db[0])) {
657 $host_string = '--host="' . $parsed_db[0] . '"';
658 if(!empty($parsed_db[1])){
659 $host_string .= ' --port=' . $parsed_db[1];
660 }
661 }
662 foreach ($bin as $key => $value) {
663 $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;
664 $result = $this->iwp_mmb_exec($command);
665 if (!$result) {
666 continue;
667 }
668
669 if (iwp_mmb_get_file_size($file) == 0 || !is_file($file) || !$result) {
670 continue;
671 }
672 unlink($file);
673 $paths = array(
674 'mysql' => $value,
675 'mysqldump' => $value
676 );
677
678 return $paths;
679 }
680 unlink($file);
681 }
682
683 if (empty($paths['mysql'])){
684 $paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
685 }
686
687 if (empty($paths['mysqldump'])){
688 $paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
689 }
690 return $paths;
691 }
692
693 function backup_uploads($historyID)
694 {
695 //after creating the backup file dont forget to include it in the account_info array
696 $this -> hisID = $historyID;
697 $responseParams = $this -> getRequiredData($historyID,"responseParams");
698 $account_info = $responseParams['response_data']['account_info'];
699 $backup_file = $responseParams['response_data']['backup_file'];
700 //storing the filesize value into settings array - first get the values and then append the value of filesize to it
701 $this -> backup_settings_vals = get_option('iwp_client_multi_backup_temp_values');
702 $backup_settings_values = $this -> backup_settings_vals;
703 $backup_settings_values['actual_file_size'] = iwp_mmb_get_file_size($backup_file);
704 update_option('iwp_client_multi_backup_temp_values', $backup_settings_values);
705 if (isset($account_info['iwp_ftp']) && !empty($account_info['iwp_ftp']) && $account_info['iwp_ftp']['use_sftp'] != '1' ) {
706 $account_info['iwp_ftp']['backup_file'] = $backup_file;
707 iwp_mmb_print_flush('FTP upload: Start');
708 $ftp_result = $this->ftp_backup($historyID, $account_info['iwp_ftp']);
709 if(!$ftp_result)
710 {
711 if(!empty($backup_settings_values['del_host_file']) && $backup_settings_values['del_host_file']){
712 $this->unlinkBackupFiles($backup_file);
713 }
714 return array('error' => "Unexpected Error", 'error_code' => "unexpected_error");
715 }
716 else if(is_array($ftp_result) && isset($ftp_result['error'])){
717 if(!empty($backup_settings_values['del_host_file']) && $backup_settings_values['del_host_file']){
718 if($ftp_result['error_code'] !== 'ftp_nb_fput_not_permitted_error'){
719
720 $this->unlinkBackupFiles($backup_file);
721 }
722 }
723 return $ftp_result;
724 }
725 else
726 {
727 return $ftp_result;
728 }
729 }
730
731 if (isset($account_info['iwp_ftp']) && !empty($account_info['iwp_ftp']) && $account_info['iwp_ftp']['use_sftp'] == '1' ) {
732 $account_info['iwp_ftp']['backup_file'] = $backup_file;
733 iwp_mmb_print_flush('SFTP upload: Start');
734
735 $sftp_result = $this->sftp_backup($historyID, $account_info['iwp_ftp']);
736
737 if(!$sftp_result)
738 {
739 if(!empty($backup_settings_values['del_host_file']) && $backup_settings_values['del_host_file']){
740 $this->unlinkBackupFiles($backup_file);
741 }
742 return array('error' => "Unexpected Error", 'error_code' => "unexpected_error");
743 }
744 else if(is_array($sftp_result) && isset($sftp_result['error'])){
745 if(!empty($backup_settings_values['del_host_file']) && $backup_settings_values['del_host_file']){
746 if($sftp_result['error_code'] !== 'ftp_nb_fput_not_permitted_error'){
747
748 $this->unlinkBackupFiles($backup_file);
749 }
750 }
751 return $sftp_result;
752 }
753 else
754 {
755 return $sftp_result;
756 }
757 }
758
759
760 if (isset($account_info['iwp_amazon_s3']) && !empty($account_info['iwp_amazon_s3'])) {
761 $account_info['iwp_amazon_s3']['backup_file'] = $backup_file;
762 iwp_mmb_print_flush('Amazon S3 upload: Start');
763 if(is_new_s3_compatible()){
764 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
765 $new_s3_obj = new IWP_MMB_S3_MULTICALL();
766 $amazons3_result = $new_s3_obj->amazons3_backup($historyID,$account_info['iwp_amazon_s3']);
767 }
768 else{
769 $amazons3_result = $this->amazons3_backup_bwd_comp($historyID,$account_info['iwp_amazon_s3']);
770 }
771 iwp_mmb_print_flush('Amazon S3 upload: End');
772 if (is_array($amazons3_result) && isset($amazons3_result['error'])) {
773 $this->unlinkBackupFiles($backup_file);
774 }
775 return $amazons3_result;
776
777 }
778
779 if (isset($account_info['iwp_gdrive']) && !empty($account_info['iwp_gdrive'])) {
780 $account_info['iwp_gdrive']['backup_file'] = $backup_file;
781 iwp_mmb_print_flush('google Drive upload: Start');
782 $gdrive_result = $this->google_drive_backup($historyID, $account_info['iwp_gdrive']);
783 iwp_mmb_print_flush('google Drive upload: End');
784 if (is_array($gdrive_result) && isset($gdrive_result['error'])){
785 if($del_host_file){
786 $this->unlinkBackupFiles($backup_file);
787 }
788 }
789
790 return $gdrive_result;
791
792 }
793
794 if (isset($account_info['iwp_dropbox']) && !empty($account_info['iwp_dropbox'])) {
795 $this->statusLog($historyID, array('stage' => 'uploadDrobox', 'status' => 'processing', 'statusMsg' => 'tempDirectorywritable'));
796
797 $account_info['iwp_dropbox']['backup_file'] = $backup_file;
798 iwp_mmb_print_flush('Dropbox upload: Start');
799 $dropbox_result = $this->dropbox_backup($historyID, $account_info['iwp_dropbox']);
800 iwp_mmb_print_flush('Dropbox upload: End');
801
802 if (empty($dropbox_result) && $del_host_file) {
803 $this->unlinkBackupFiles($backup_file);
804 }
805
806 $dropbox_skip_errors = array('Failed to connect to content.dropboxapi.com port 443: Connection timed out',
807 'Could not resolve host: api.dropboxapi.com'
808 );
809 if (is_array($dropbox_result) && isset($dropbox_result['error']) && !in_array($dropbox_result['error'], $dropbox_skip_errors)) {
810 $this->unlinkBackupFiles($backup_file);
811 }
812 if($dropbox_result['status'] == 'partiallyCompleted')
813 {
814 return $dropbox_result;
815 }
816
817 $this->wpdb_reconnect();
818 return $dropbox_result;
819 }
820
821 if ($del_host_file) {
822 //@unlink($backup_file); //darkCode testing purpose
823 }
824
825
826 }
827
828 function unlinkBackupFiles($this_files){
829 if(is_array($this_files)){
830 if(!empty($this_files)){
831 foreach($this_files as $this_key => $this_file){
832 @unlink($this_file);
833 }
834 }
835 }
836 else{
837 @unlink($this_files);
838 }
839 }
840
841 function backupDB($historyID,$backup_file,$account_info = array())
842 {
843 manual_debug('', 'backupDBStart');
844 $this->statusLog($historyID, array('stage' => 'backupDB', 'status' => 'processing', 'statusMsg' => 'backupDBInitiated'));
845 clearstatcache();
846 if(file_exists(IWP_DB_DIR) && is_dir(IWP_DB_DIR))
847 {
848 $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'processing', 'statusMsg' => 'Directorywritable'));
849 }
850 else
851 {
852 $mkdir = mkdir(IWP_DB_DIR, 0755, true);
853 if(!$mkdir){
854 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => 'Error creating database backup folder (' . IWP_DB_DIR . '). Make sure you have corrrect write permissions.', 'statusCode' => 'error_creating_database_backup_folder'));
855 }
856 }
857 if(is_writable(IWP_DB_DIR))
858 {
859 @file_put_contents(IWP_DB_DIR . '/index.php', ''); //safe
860 }
861 else
862 {
863 $chmod = chmod(IWP_DB_DIR, 777);
864 if(!is_writable(IWP_DB_DIR)){
865 //$this->statusLog($historyID, "verification", false, "can't set 777");
866 return $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'error', 'statusMsg' => IWP_DB_DIR.' directory is not writable. Please set 755 or 777 file permission and try again.', 'statusCode' => 'db_dir_not_writable'));
867 }
868 }
869
870 $db_index_file = '<?php
871 global $old_url, $old_file_path;
872 $old_url = \''.get_option('siteurl').'\';
873 $old_file_path = \''.ABSPATH.'\';
874 ';
875
876 @file_put_contents(IWP_DB_DIR . '/index.php', $db_index_file); //safe
877
878 //$this->statusLog($historyID, "verification", true, "Backup DB directory Created and writable");
879 $this->statusLog($historyID, array('stage' => 'verification', 'status' => 'processing', 'statusMsg' => 'BackupDBDirectoryCreatedAndWritable'));
880 $res_arr = array();
881 $res_arr['response_data'] = array();
882 $file = DB_NAME;
883 $file .='_'.$this->generate_hash();
884 $res_arr['file_name'] = $file;
885 $res_arr['backup_file'] = $backup_file;
886 $res_arr['backup_url'] = $this -> backup_url;
887 $res_arr['account_info'] = $account_info;
888 $this->statusLog($historyID, array('stage' => 'backupDB', 'status' => 'initiating', 'statusMsg' => 'createdFileNameAndSent','responseParams' => $res_arr));
889 $func = $this->check_sys();
890 $db_result = true;
891 if($func == false){
892 $db_result = false;
893 }
894 if ($db_result) {
895 $db_result = $this->backup_db_dump_multi($historyID);
896 }
897 if ($db_result === true) {
898 delete_option('iwp_multical_db_dump_flag');
899 }
900 if ($db_result == false) {
901 delete_option('iwp_multical_db_dump_flag');
902 $db_result = $this->backupDBPHP($historyID);
903 }
904
905 //arguments format - dbresult_before_zip
906 //$result = $this->backupDBZip($historyID,$db_result,$backup_url); //if DB is succsessful do the DB zip
907
908
909 return $db_result;
910 }
911
912 function backupDBZip($historyID)
913 {
914 manual_debug('', 'backupDBZipStart');
915 // if the DB backup is successful do the zip operations
916 $responseParams = $this -> getRequiredData($historyID,"responseParams");
917 $responseParams['category'] = 'dbZip';
918 $backup_file = $responseParams['backup_file'];
919 $backup_url = $responseParams['backup_url'];
920 $responseParams['response_data']['backup_file'] = $backup_file;
921 $responseParams['response_data']['backup_url'] = $backup_url;
922 $responseParams['response_data']['account_info'] = $responseParams['account_info'];
923 $db_result = $responseParams['response_data'];
924 $this->statusLog($historyID, array('stage' => 'backupDBZip', 'status' => 'processing', 'statusMsg' => 'backupZipInitiated','responseParams' => $responseParams));
925 if ($db_result == false) {
926 return array(
927 'error' => 'Failed to backup database.'
928 );
929 }
930 else if (is_array($db_result) && isset($db_result['error'])) {
931 return array(
932 'error' => $db_result['error']
933 );
934 }
935 else
936 {
937 unset($responseParams);
938 unset($db_result);
939 //perform the zip operations here ..... for DB
940 iwp_mmb_print_flush('DB ZIP PCL: Start');
941 // fallback to pclzip
942 //define('IWP_PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
943 /* require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
944 $archive = new IWPPclZip($backup_file);
945 $result = $archive->add(IWP_DB_DIR, IWP_PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR); */
946 $result = $this -> backupFilesZIP($historyID);
947 iwp_mmb_print_flush('DB ZIP PCL: End');
948 /* @unlink($db_result);
949 @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php'); //dark comment
950 @rmdir(IWP_DB_DIR); */
951 if (!$result) {
952 return $this->statusLog($historyID, array('stage' => 'backupDBZip', 'status' => 'error', 'statusMsg' => 'Database zip failed', 'statusCode' => 'database_zip_failed'));
953 }
954
955 }
956 //$this->statusLog($historyID, array('stage' => 'backupDBZip', 'status' => 'completed', 'statusMsg' => 'backupZipCompleted'));
957 manual_debug('', 'backupDBZipEnd');
958 return $result;
959 }
960
961 function backupDBPHP($historyID) //file must be db name alone ; $response_array should be table_name and its fields and callCount
962 {
963 //getting the settings first
964 $this -> backup_settings_vals = get_option('iwp_client_multi_backup_temp_values');
965 $backup_settings_values = $this -> backup_settings_vals;
966
967 //$file_block_size = $backup_settings_values['file_block_size'];
968 //$is_compressed = $backup_settings_values['is_compressed'];
969 //$file_loop_break_time = $backup_settings_values['file_loop_break_time'];
970 //$db_loop_break_time = $backup_settings_values['db_loop_break_time'];
971
972 //getting the settings by other method
973 $requestParams = $this->getRequiredData($historyID, "requestParams");
974 $file_block_size = $requestParams['args']['file_block_size']; //darkcode changed
975 $is_compressed = $requestParams['args']['is_compressed'];
976 $file_loop_break_time = $requestParams['args']['file_loop_break_time'];
977 $db_loop_break_time = $requestParams['args']['db_loop_break_time'];
978 $zip_split_size = $requestParams['args']['zip_split_size'];
979 $exclude_tables =$requestParams['args']['exclude_tables'];
980 $responseParams = $this -> getRequiredData($historyID,"responseParams");
981 $file = $responseParams['file_name'];
982 $total_time_part = 0;
983
984 if(!$file)
985 {
986 $file = '';
987 }
988 $backup_file = $responseParams['backup_file'];
989 $backup_url = $responseParams['backup_url'];
990 $response_array = $responseParams['response_data'];
991 $account_info = $responseParams['account_info'];
992 $backupStage = '';
993 if(empty($response_array))
994 {
995 $backupStage = 'backupDB';
996 $callCount = 0;
997 }
998 else
999 {
1000 iwp_mmb_print_flush('DB DUMP PHP CALL COUNT :' . $response_array['callCount']);
1001 $callCount = $response_array['callCount'];
1002 $backupStage = 'backupDBMultiCall';
1003 }
1004 //$this->statusLog($historyID, "backupDB", true, "processing", $params, true);
1005 $this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'processing', 'statusMsg' => 'backupDBInitiated', 'responseParams' => $responseParams));
1006 global $wpdb;
1007 $db_folder = IWP_DB_DIR . '/';
1008 $time = microtime(true);
1009 $start = $time;
1010 $break_flag = '';
1011 $is_continue = '';
1012 $break_flag_first_key = '';
1013 $temp_sql_file_name = '';
1014 iwp_mmb_print_flush('DB DUMP PHP Fail-safe: Start');
1015 $dump_data = '';
1016 //$response_array = array();
1017 //$response_array['db_response'] = array();
1018 //$response_array['status'] = '';
1019 //$response_array['callCount'] = 0;
1020 $left_out_array = array();
1021 $left_out_table = '';
1022 $left_out_count = '';
1023 $db_final_response = array();
1024 $db_final_response['success'] = array ();
1025 $db_final_response['success']['type'] = 'db';
1026 /* $response_array = array (
1027 'callCount' => 5,
1028 'wp_commentmeta' => 0,
1029 'wp_comments' => 16,
1030 'wp_links' => 92,
1031 'wp_options' => 1149,
1032 'wp_postmeta' => 109,
1033 'wp_posts' => 116,
1034 'wp_term_relationships' => 28,
1035 'wp_term_taxonomy' => 79,
1036 'wp_terms' => 22,
1037 );*/
1038
1039 $left_out_array = array_slice($response_array,-1,1);
1040 array_pop($response_array);
1041 $response_array['callCount'] = $callCount;
1042 if($file == '')
1043 {
1044 $file = DB_NAME;
1045 $file .='_'.$this->generate_hash();
1046 }
1047 $db_final_response['success']['file_name'] = $file;
1048 //$temp_sql_file_name = $file."-".$callCount.".sql"; //old method
1049 $temp_sql_file_name = $file.".sql";
1050 $file = $db_folder . $temp_sql_file_name;
1051 //file_put_contents($file, '');//safe to reset any old data
1052 /* if($callCount == 0) //used in old method
1053 {
1054 $db_final_response['success']['file'] = $file;
1055 file_put_contents($file, '');//safe to reset any old data
1056 } */
1057 //$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
1058 $this_prefix = $wpdb->esc_like($wpdb->base_prefix);
1059 $tables = $wpdb->get_results('SHOW TABLES LIKE "'.$this_prefix.'%"', ARRAY_N);
1060
1061 $max_row_limit = 150;
1062 if(defined('IWP_PHP_DB_ROWS') && (is_int(IWP_PHP_DB_ROWS) || is_string(IWP_PHP_DB_ROWS))){
1063 if(IWP_PHP_DB_ROWS > $max_row_limit ){
1064 $max_row_limit = IWP_PHP_DB_ROWS;
1065 }
1066 }
1067 foreach ($tables as $table) {
1068 $is_continue = '';
1069 foreach($response_array as $k => $v)
1070 {
1071 if($k == $table[0])
1072 {
1073 $is_continue = 'set';
1074 break;
1075 }
1076 else
1077 {
1078 $is_continue = '';
1079 }
1080 }
1081 if($is_continue == 'set')
1082 {
1083 continue;
1084 }
1085
1086 foreach ($left_out_array as $key => $val)
1087 {
1088 $left_out_table = $key;
1089 $left_out_count = $val;
1090 }
1091 if($left_out_table != $table[0])
1092 {
1093 //drop existing table
1094 $dump_data = "DROP TABLE IF EXISTS `$table[0]`;";
1095 file_put_contents($file, $dump_data, FILE_APPEND);
1096 //create table
1097 $create_table = $wpdb->get_row("SHOW CREATE TABLE `$table[0]`", ARRAY_N);
1098 $dump_data = "\n\n" . $create_table[1] . ";\n\n";
1099 $response_array[$table[0]] = 0;
1100 file_put_contents($file, $dump_data, FILE_APPEND);
1101 //$left_out_count = '';
1102 }
1103 //Skip log tables
1104 $skipThisTable = false;
1105 if (!empty($exclude_tables)) {
1106 foreach ($exclude_tables as $ke => $exclude_table) {
1107 if (strpos($table[0], $exclude_table)) {
1108 $skipThisTable = true;
1109 break;
1110 }
1111 }
1112 }
1113 if ($skipThisTable) {
1114 continue;
1115 }
1116 $count = $wpdb->get_var("SELECT count(*) FROM `".$table[0]."`");
1117 $count_field = 1;
1118
1119 $table_fields = $wpdb->get_results("SHOW COLUMNS FROM `$table[0]`", ARRAY_A);
1120 $no_of_cols = count($table_fields);
1121 $initialCount = 0;
1122 $done_count = 0;
1123 if($left_out_table == $table[0]){
1124 $breakingCount = isset($responseParams['breakingCount']) ? $responseParams['breakingCount'] : 0; //new changes
1125 }
1126 else{
1127 $breakingCount = 0;
1128 }
1129
1130 if(!$breakingCount)
1131 {
1132 $breakingCount = 0;
1133 }
1134 if ($count > $max_row_limit)
1135 {
1136 $count = ceil($count / $max_row_limit);
1137 if($left_out_count > 0)
1138 {
1139 $temp_left_count = $left_out_count;
1140 //$done_count = floor($temp_left_count / (100*$no_of_cols));
1141 $done_count = $breakingCount;
1142 }
1143 }
1144 else if ($count > 0)
1145 {
1146 $count = 1;
1147 }
1148 $table_structure = $wpdb->get_results("DESCRIBE `$table[0]`");
1149 $search = array("\x00", "\x0a", "\x0d", "\x1a");
1150 $replace = array('\0', '\n', '\r', '\Z');
1151 $defs = array();
1152 $integer_fields = array();
1153 foreach ($table_structure as $struct) {
1154 if ( (0 === strpos($struct->Type, 'tinyint')) || (0 === strpos(strtolower($struct->Type), 'smallint')) ||
1155 (0 === strpos(strtolower($struct->Type), 'mediumint')) || (0 === strpos(strtolower($struct->Type), 'int')) || (0 === strpos(strtolower($struct->Type), 'bigint')) ) {
1156 $defs[strtolower($struct->Field)] = ( null === $struct->Default ) ? 'NULL' : $struct->Default;
1157 $integer_fields[strtolower($struct->Field)] = "1";
1158 }
1159 }
1160 for($i = 0; $i < $count; $i++){
1161 if($done_count > 0)
1162 {
1163 if($done_count > ($i))
1164 {
1165 $count_field += $max_row_limit * $no_of_cols;
1166 continue;
1167 }
1168 }
1169
1170 iwp_mmb_auto_print('backup_db_php_fail_safe');
1171 $low_limit = $i * $max_row_limit;
1172 $qry = "SELECT * FROM `$table[0]` LIMIT $low_limit, $max_row_limit";
1173 $rows = $wpdb->get_results($qry, ARRAY_A);
1174
1175 $number_data_types = 'tinyint, smallint, mediumint, bigint, int, decimal, numeric, real, float, double';
1176 if (is_array($rows)) {
1177 foreach ($rows as $row) {
1178 manual_debug('', 'eachRow', 1000);
1179 //insert single row
1180 if(($table[0] != $left_out_table))
1181 $dump_data = "INSERT INTO `$table[0]` VALUES(";
1182 if(($table[0] == $left_out_table)&&($left_out_count <= $count_field))
1183 $dump_data = "INSERT INTO `$table[0]` VALUES(";
1184 $num_values = count($row);
1185 $j = 1;
1186 foreach ($row as $key => $value) {
1187 $count_field++;
1188 $response_array[$table[0]] = $count_field;
1189 if(($left_out_table == $table[0])&&($count_field <= $left_out_count))
1190 {
1191 $j++;
1192 continue;
1193 }
1194 $time = microtime(true);
1195 $finish_part = $time;
1196 $total_time_part = $finish_part - $this->iwpScriptStartTime;
1197
1198 //$dump_data .= $count_field;
1199 /****************New method starts here********************/
1200 // if (empty($value) && $value != 0 || $value == '') {
1201 // $default_value = isset($table_description[$key]['Default']) ? $table_description[$key]['Default']: NULL;
1202 // if (@strstr(strtolower($number_data_types), substr($table_description[$key]['Type'], 0, strpos($table_description[$key]['Type'], '('))) !== false && ($default_value === NULL && $default_value != '') ) {
1203 // if ($default_value === NULL) {
1204 // $num_values == $j ? $dump_data .= "NULL " : $dump_data .= "NULL, ";
1205 // } else {
1206 // $num_values == $j ? $dump_data .= "'$default_value'" : $dump_data .= "'$default_value', ";
1207 // }
1208 // } else if($default_value === NULL){
1209 // $num_values == $j ? $dump_data .= "NULL " : $dump_data .= "NULL, ";
1210 // } else {
1211 // $num_values == $j ? $dump_data .= "$default_value" : $dump_data .= "$default_value,";
1212 // }
1213 // } else if (@strstr(strtolower($number_data_types), substr($table_description[$key]['Type'], 0, strpos($table_description[$key]['Type'], '('))) !== false) {
1214 // $num_values == $j ? $dump_data .= "'$value'" : $dump_data .= "'$value',";
1215 // } else {
1216 // $value = addslashes($value);
1217 // $value = str_replace("\n", "\\n", $value);
1218 // $value = str_replace("\r", "\\r", $value);
1219 // $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
1220 // }
1221 //$num_values = $dump_data;
1222 /*********New Method ends Here******************/
1223
1224 /**********Old Method start here ************/
1225 // $value2 = $value;
1226 // $value = addslashes($value);
1227 // $value = preg_replace("/\n/Ui", "\\n", $value);
1228 // $value = str_replace("\n", "\\n", $value);
1229 // $value = str_replace("\r", "\\r", $value);
1230 // $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
1231 /*************** Old Method ends here ********/
1232
1233 /**********Phoenix Method start here ************/
1234 if (isset($integer_fields[strtolower($key)])) {
1235 // make sure there are no blank spots in the insert syntax,
1236 // yet try to avoid quotation marks around integers
1237 $value = ( null === $value || '' === $value) ? $defs[strtolower($key)] : $value;
1238 $value = ( '' === $value ) ? "''" : $value;
1239 } else {
1240 $value = (null === $value) ? 'NULL' : "'" . str_replace($search, $replace, str_replace('\'', '\\\'', str_replace('\\', '\\\\', $value))) . "'";
1241 }
1242
1243 /**********Phoenix Method end here ************/
1244
1245 $num_values == $j ? $dump_data .= $value: $dump_data .= $value . ", ";
1246
1247
1248 $j++;
1249 unset($value);
1250 if($total_time_part > $db_loop_break_time)
1251 {
1252 $break_flag = 'set';
1253 $break_flag_first_key = 'set';
1254 //$this -> sendNextCallFlag = '';
1255 break;
1256 }
1257 else
1258 {
1259 $break_flag == '';
1260 }
1261 }
1262 if(($left_out_table == $table[0])&&(($count_field <= $left_out_count-1)&&(!empty($count_field))))
1263 {
1264 continue;
1265 }
1266 //if(($break_flag == '')&&($count_field > $left_out_count))
1267 if(($break_flag == ''))
1268 {
1269 $dump_data .= ");\n";
1270 }
1271 else
1272 {
1273 break;
1274 }
1275 /* if($count_field != $left_out_count)
1276 {
1277 } */
1278 file_put_contents($file, $dump_data, FILE_APPEND);
1279 }
1280 }
1281 if($break_flag == 'set')
1282 {
1283 break;
1284 }
1285 }
1286
1287
1288 if($break_flag == '')
1289 {
1290 $dump_data = "\n\n\n";
1291 file_put_contents($file, $dump_data, FILE_APPEND);
1292 //manual_debug('', 'endingTableSingle');
1293 }
1294 else
1295 {
1296 //$temp_sql_file_name = "DE_dbFailsafeCont"."-".$callCount.".sql";
1297 file_put_contents($file, $dump_data, FILE_APPEND);
1298 $callCount++;
1299 //$response_array['status'] = 'partiallyCompleted';
1300 $response_array['callCount'] = $callCount;
1301 $db_final_response['success']['response_data'] = $response_array;
1302 $db_final_response['success']['breakingCount'] = $i;
1303 $db_final_response['success']['status'] = 'partiallyCompleted';
1304 $db_final_response['success']['parentHID'] = $historyID;
1305 $db_final_response['success']['backupParentHID'] = $historyID;
1306 $db_final_response['success']['nextFunc'] = 'backupDBPHP';
1307 $db_final_response['success']['file'] = $file;
1308 $db_final_response['success']['backup_file'] = $backup_file;
1309 $db_final_response['success']['backup_url'] = $backup_url;
1310 $db_final_response['success']['account_info'] = $account_info;
1311
1312 //$this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'completed', 'statusMsg' => 'singleCallCompleted'));
1313 $this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'completed', 'statusMsg' => 'singleDBCallPartiallyCompleted','nextFunc' => 'backupDBPHP', 'responseParams' => $db_final_response['success']));
1314 $db_res_array = array();
1315 $db_res_array['status'] = $db_final_response['success']['status'];
1316 $db_res_array['backupParentHID'] = $db_final_response['success']['backupParentHID'];
1317 $db_res_array['parentHID'] = $db_final_response['success']['parentHID'];
1318 //manual_debug('', 'endingTableMulti');
1319 return $db_res_array;
1320
1321 break;
1322 }
1323
1324 unset($rows);
1325 unset($dump_data);
1326 }
1327
1328 unset($tables);
1329 iwp_mmb_print_flush('DB DUMP PHP Fail-safe: End');
1330
1331
1332 if (iwp_mmb_get_file_size($file) == 0 || !is_file($file))
1333 {
1334 //@unlink($file);
1335 $this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'error', 'statusMsg' => 'DatabaseBackupFailed', 'statusCode' => 'database_backup_failed'));
1336 return array(
1337 'error' => 'Database backup failed. Try to enable MySQL dump on your server.', 'error_code' => 'database_backup_failed_try_to_enable_mysql_dump_on_your_server' //returning here may not be necessary
1338 );
1339 }
1340 $db_final_response['success']['response_data'] = $response_array;
1341 $db_final_response['success']['backup_file'] = $backup_file;
1342 $db_final_response['success']['backup_url'] = $backup_url;
1343 $db_final_response['success']['parentHID'] = $historyID;
1344 $db_final_response['success']['backupParentHID'] = $historyID;
1345 $db_final_response['success']['nextFunc'] = 'backupDBZip';
1346 $db_final_response['success']['account_info'] = $account_info;
1347 //$this->statusLog($historyID, "backupDB", true, "completed", $params, true);
1348 //$this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'completed', 'statusMsg' => 'backupDBCompleted'));
1349 $db_final_response['success']['status'] = 'partiallyCompleted';
1350 unset($response_array);
1351 $this->statusLog($historyID, array('stage' => $backupStage, 'status' => 'completed', 'statusMsg' => 'backupDBCompleted','nextFunc' => 'backupDBZip', 'responseParams' => $db_final_response['success']));
1352 unset($db_final_response['success']['response_data']);
1353 //to continue in the same call
1354 if(($db_loop_break_time - $total_time_part) > 5)
1355 {
1356 return $this->backupDBZip($historyID);
1357 }
1358 else
1359 {
1360 $db_res_array = array();
1361 $db_res_array['status'] = $db_final_response['success']['status'];
1362 $db_res_array['backupParentHID'] = $db_final_response['success']['backupParentHID'];
1363 $db_res_array['parentHID'] = $db_final_response['success']['parentHID'];
1364 return $db_res_array;
1365 }
1366
1367 }
1368
1369 function backupFiles($historyID, $backup_file='', $account_info = array(), $exclude = array(), $include = array())
1370 {
1371 iwp_mmb_auto_print("backupFiles");
1372 $this -> hisID = $historyID;
1373
1374 $initialize_result = refresh_iwp_files_db();
1375 if(is_array($initialize_result) && isset($initialize_result['error'])){
1376 return $initialize_result;
1377 }
1378 //for exclude and include
1379 $requestParams = $this->getRequiredData($historyID, "requestParams");
1380 $exclude = $requestParams['args']['exclude'];
1381 $include = $requestParams['args']['include'];
1382 $exclude_extensions = $requestParams['args']['exclude_extensions'];
1383 $exclude_file_size = $requestParams['args']['exclude_file_size'];
1384 $category = '';
1385 if(empty($exclude_extensions))
1386 {
1387 $exclude_extensions = array();
1388 }
1389 else if($exclude_extensions == 'eg. .zip,.mp4')
1390 {
1391 $exclude_extensions = array();
1392 }
1393 else
1394 {
1395 $exclude_extensions_array = explode(",",$exclude_extensions);
1396 $exclude_extensions = array();
1397 $exclude_extensions = $exclude_extensions_array;
1398 }
1399 if($backup_file != '')
1400 {
1401 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'processing', 'statusMsg' => 'backupFilesInitiated'));
1402 }
1403 $backup_url = $this -> backup_url;
1404 $zip_split_part = 0;
1405 if($backup_file == '')
1406 {
1407 $responseParams = $this -> getRequiredData($this -> hisID, "responseParams");
1408 $backup_file = $responseParams['response_data']['backup_file'];
1409 $backup_url = $responseParams['response_data']['backup_url'];
1410 $category = $responseParams['category'];
1411 $account_info = $responseParams['response_data']['account_info'];
1412 $zip_split_part = $responseParams['response_data']['zip_split_part'];
1413 if(empty($zip_split_part))
1414 {
1415 $zip_split_part = 0;
1416 }
1417 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'processing', 'statusMsg' => 'backupFilesInitiated','responseParams' => $responseParams));
1418 }
1419 /* if($category == "fileZipAfterDBZip")
1420 {
1421 $account_info = $responseParams['account_info'];
1422 } */
1423
1424
1425
1426 //Always remove backup folders
1427 $remove = array(
1428 trim(basename(WP_CONTENT_DIR)) . "/infinitewp/backups",
1429 trim(basename(WP_CONTENT_DIR)) . "/" . md5('iwp_mmb-client') . "/iwp_backups",
1430 trim(basename(WP_CONTENT_DIR)) . "/cache",
1431 trim(basename(WP_CONTENT_DIR)) . "/managewp/backups",
1432 trim(basename(WP_CONTENT_DIR)) . "/backupwordpress",
1433 trim(basename(WP_CONTENT_DIR)) . "/contents/cache",
1434 trim(basename(WP_CONTENT_DIR)) . "/content/cache",
1435 trim(basename(WP_CONTENT_DIR)) . "/old-cache",
1436 trim(basename(WP_CONTENT_DIR)) . "/cmscommander/backups",
1437 trim(basename(WP_CONTENT_DIR)) . "/gt-cache",
1438 trim(basename(WP_CONTENT_DIR)) . "/wfcache",
1439 trim(basename(WP_CONTENT_DIR)) . "/bps-backup",
1440 trim(basename(WP_CONTENT_DIR)) . "/old-cache",
1441 trim(basename(WP_CONTENT_DIR)) . "/nfwlog",
1442 trim(basename(WP_CONTENT_DIR)) . "/upgrade",
1443 trim(basename(WP_CONTENT_DIR)) . "/nfwlog",
1444 trim(basename(WP_CONTENT_DIR)) . "/wflogs",
1445 trim(basename(WP_CONTENT_DIR)) . "/debug.log",
1446 trim(basename(WP_CONTENT_DIR)) . "/wptouch-data/infinity-cache/",
1447 trim(basename(WP_CONTENT_DIR)) . "/mysql.sql",
1448 trim(basename(WP_CONTENT_DIR)) . "/wishlist-backup",
1449 trim(basename(WP_CONTENT_DIR)) . "/w3tc",
1450 trim(basename(WP_CONTENT_DIR)) . "/logs",
1451 trim(basename(WP_CONTENT_DIR)) . "/widget_cache",
1452 trim(basename(WP_CONTENT_DIR)) . "/tmp",
1453 trim(basename(WP_CONTENT_DIR)) . "/updraft",
1454 trim(basename(WP_CONTENT_DIR)) . "/updraftplus",
1455 trim(basename(WP_CONTENT_DIR)) . "/backups",
1456 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp-clone",
1457 trim(basename(WP_CONTENT_DIR)) . "/uploads/uploads/db-backup",
1458 trim(basename(WP_CONTENT_DIR)) . "/uploads/ithemes-security/backups",
1459 trim(basename(WP_CONTENT_DIR)) . "/uploads/mainwp/backup",
1460 trim(basename(WP_CONTENT_DIR)) . "/uploads/backupbuddy_backups",
1461 trim(basename(WP_CONTENT_DIR)) . "/uploads/vcf",
1462 trim(basename(WP_CONTENT_DIR)) . "/uploads/pb_backupbuddy",
1463 trim(basename(WP_CONTENT_DIR)) . "/uploads/sucuri",
1464 trim(basename(WP_CONTENT_DIR)) . "/uploads/aiowps_backups",
1465 trim(basename(WP_CONTENT_DIR)) . "/uploads/mainwp",
1466 trim(basename(WP_CONTENT_DIR)) . "/uploads/snapshots",
1467 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp_system",
1468 trim(basename(WP_CONTENT_DIR)) . "/uploads/wpcf7_captcha",
1469 trim(basename(WP_CONTENT_DIR)) . "/uploads/wc-logs",
1470 trim(basename(WP_CONTENT_DIR)) . "/uploads/siteorigin-widgets",
1471 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp-hummingbird-cache",
1472 trim(basename(WP_CONTENT_DIR)) . "/uploads/wp-security-audit-log",
1473 trim(basename(WP_CONTENT_DIR)) . "/uploads/backwpup-12b462-backups",
1474 trim(basename(WP_CONTENT_DIR)) . "/uploads/backwpup-12b462-logs",
1475 trim(basename(WP_CONTENT_DIR)) . "/uploads/wpallimport",
1476 trim(basename(WP_CONTENT_DIR)) . "/uploads/backwpup-12b462-temp",
1477 trim(basename(WP_CONTENT_DIR)) . "/Dropbox_Backup",
1478 trim(basename(WP_PLUGIN_DIR)) . "/cache",
1479 "wp-admin/error_log",
1480 "wp-admin/php_errorlog",
1481 "error_log",
1482 "error.log",
1483 "debug.log",
1484 "WS_FTP.LOG",
1485 "security.log",
1486 "wp-tcapsule-bridge.zip",
1487 "dbcache",
1488 "pgcache",
1489 "objectcache",
1490 "wp-snapshots",
1491 "site_map.xml",
1492 "iwp-clone-log.txt",
1493 "iwp-restore-log.txt",
1494 "wp-content/wpmerge-temp"
1495 );
1496 manual_debug('', 'beforeExclude', 0);
1497 if((!empty($exclude_file_size))||(!empty($exclude_extensions)))
1498 {
1499 /* //removing files which are larger than the specified size
1500 $total_files_array = get_all_files_from_dir(ABSPATH, $remove);
1501 $files_excluded_by_size = array();
1502 foreach($total_files_array as $key => $value)
1503 {
1504 $this_base_name = basename($value);
1505 $skip_after_ext = false;
1506 //file extension based exclude
1507 if(is_array($exclude_extensions) && (!empty($exclude_extensions)))
1508 {
1509 foreach($exclude_extensions as $ext)
1510 {
1511 $this_pos = strrpos($this_base_name, $ext);
1512 if($this_pos !== false)
1513 {
1514 if(substr($this_base_name, $this_pos) == $ext)
1515 {
1516 $files_excluded_by_size[] = substr($value, strlen(ABSPATH));
1517 $skip_after_ext = true; //to skip the file exclude by size
1518 break;
1519 }
1520 }
1521 }
1522 }
1523 if($skip_after_ext)
1524 {
1525 continue;
1526 }
1527 //file size based exclude
1528 if(!empty($exclude_file_size))
1529 {
1530 if(iwp_mmb_get_file_size($value) >= $exclude_file_size*1024*1024)
1531 {
1532 $files_excluded_by_size[] = substr($value, strlen(ABSPATH));
1533 }
1534 }
1535 }
1536 $remove = array_merge($remove, $files_excluded_by_size); */
1537 }
1538 $exclude = array_merge($exclude, $remove);
1539 manual_debug('', 'afterExclude', 0);
1540 //Exclude paths
1541
1542
1543 //Include paths by default
1544 $add = array(
1545 trim(WPINC),
1546 trim(basename(WP_CONTENT_DIR)),
1547 "wp-admin"
1548 );
1549 $normalized_abspath = wp_normalize_path(ABSPATH);
1550 chdir($normalized_abspath);
1551 $include_data = array();
1552 if (!empty($include) && is_array($include)) {
1553 foreach ($include as $data) {
1554 if ($data && file_exists($normalized_abspath . $data))
1555 $include_data[] = $normalized_abspath . $data . '/';
1556 }
1557 }
1558
1559 foreach ($add as $data) {
1560 if (file_exists($normalized_abspath . $data))
1561 $include_data[] = $normalized_abspath . $data . '/';
1562 }
1563 $os_name = '';
1564 if(function_exists('php_uname')){
1565 $os_name = php_uname();
1566 }elseif (defined('PHP_OS')) {
1567 $os_name = PHP_OS;
1568 }
1569 //Include root files
1570 if ($handle = @opendir($normalized_abspath)) {
1571 while (false !== ($file = readdir($handle))) {
1572 if ($file != "." && $file != ".." && !is_dir($file) && file_exists($normalized_abspath . $file)) {
1573 $include_data[] = $normalized_abspath . $file;
1574 }
1575 }
1576 closedir($handle);
1577 }elseif (stristr($os_name, 'windows')) {
1578 $windows_normalized_abspath = $normalized_abspath.'wp-admin/../';
1579 if ($handle = @opendir($windows_normalized_abspath)) {
1580 while (false !== ($file = readdir($handle))) {
1581 if ($file != "." && $file != ".." && !is_dir($file) && file_exists($windows_normalized_abspath . $file)) {
1582 $include_data[] = $windows_normalized_abspath . $file;
1583 }
1584 }
1585 closedir($handle);
1586 }else{
1587 return $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'Unable to list root directories', 'statusCode' => 'backup_of_files_failed_unable_to_list_root_directories'));
1588 }
1589
1590 }
1591
1592 //exclude paths
1593 $exclude_data = array();
1594 if (!empty($exclude) && is_array($exclude)) {
1595 foreach ($exclude as $data) {
1596 if (is_dir($normalized_abspath . $data))
1597 $exclude_data[] = $data . '/';
1598 else
1599 $exclude_data[] = $data;
1600 }
1601 }
1602
1603 foreach ($remove as $rem) {
1604 $exclude_data[] = $rem . '/';
1605 }
1606
1607 iwp_mmb_print_flush('Exclude Include Time Taken');
1608
1609 $result_arr = array();
1610 $result_arr['response_data']['nextCount'] = 0;
1611 $result_arr['status'] = 'processing';
1612 $result_arr['category'] = $category;
1613 /* $include_data = array (
1614 0 => 'F:\\wamp\\www\\plugin_for_bugs/wp-new-dark/',
1615 ); */
1616 /* $include_data = array (
1617 0 => '/mnt/weba/e2/89/53672689/htdocs/wordpress_v2/wp-content/uploads/2015/03/',
1618 ); */
1619 $result_arr['response_data']['include_data'] = $include_data;
1620 $result_arr['response_data']['exclude_data'] = $exclude_data;
1621 $result_arr['response_data']['backup_file'] = $backup_file;
1622 $result_arr['response_data']['backup_url'] = $backup_url;
1623 $result_arr['response_data']['account_info'] = $account_info;
1624 $result_arr['response_data']['zip_split_part'] = $zip_split_part;
1625 //$result_arr['response_data']['files_excluded_by_size'] = $files_excluded_by_size;
1626
1627 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'processing', 'statusMsg' => 'backupFileSingleCallStage1Complete','responseParams' => $result_arr));
1628 unset($result_arr);
1629 $result = $this->backupFilesZIP($this -> hisID);
1630 return $result;
1631 }
1632
1633 function backupFilesZIP($historyID)
1634 {
1635 $this -> hisID = $historyID;
1636 $files_with_error = array();
1637 $files_excluded_by_size = array();
1638 //get the backup settings values from options table
1639 $this -> backup_settings_vals = get_option('iwp_client_multi_backup_temp_values');
1640 $backup_settings_values = $this -> backup_settings_vals;
1641 //$file_block_size = $backup_settings_values['file_block_size'];
1642 //$is_compressed = $backup_settings_values['is_compressed'];
1643 //$file_loop_break_time = $backup_settings_values['file_loop_break_time'];
1644 //$task_name = $backup_settings_values['task_name'];
1645
1646 //get the settings by other method
1647 $requestParams = $this->getRequiredData($historyID, "requestParams");
1648 $file_block_size = $requestParams['args']['file_block_size']; //darkcode changed
1649 $is_compressed = $requestParams['args']['is_compressed'];
1650 $file_loop_break_time = $requestParams['args']['file_loop_break_time'];
1651 $task_name = $requestParams['args']['backup_name'];
1652 $exclude_file_size = $requestParams['args']['exclude_file_size'];
1653 $exclude_extensions = explode(",",$requestParams['args']['exclude_extensions']);
1654 $zip_split_size = $requestParams['args']['zip_split_size'];
1655 $v_offset = 0;
1656 if(isset($backup_settings_values['dbFileHashValue']) && !empty($backup_settings_values['dbFileHashValue'][$historyID]))
1657 {
1658 $dbFileHashValue = $backup_settings_values['dbFileHashValue'][$historyID];
1659 }
1660 else
1661 {
1662 $dbFileHashValue = array();
1663 }
1664 $responseParams = $this -> getRequiredData($historyID,"responseParams");
1665 $category = $responseParams['category']; //Am getting the category to perform the dbZip actions
1666
1667 if(!$responseParams)
1668 {
1669 return $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'Backup of files failed - Error while fetching table data', 'statusCode' => 'backup_of_files_failed_error_while_fetching_table_data'));
1670 }
1671
1672 $include_data = isset($responseParams['response_data']['include_data']) ? $responseParams['response_data']['include_data'] : array();
1673 $exclude_data = isset($responseParams['response_data']['exclude_data']) ? $responseParams['response_data']['exclude_data'] : array();
1674 $backup_file = $responseParams['response_data']['backup_file'];
1675 $backup_url = $responseParams['response_data']['backup_url'];
1676 $nextCount = isset($responseParams['response_data']['nextCount']) ? $responseParams['response_data']['nextCount'] : 0;
1677 $account_info = $responseParams['response_data']['account_info'];
1678 $files_with_error = isset($responseParams['response_data']['files_with_error']) ? $responseParams['response_data']['files_with_error'] : array();
1679 $files_excluded_by_size = isset($responseParams['response_data']['files_excluded_by_size']) ? $responseParams['response_data']['files_excluded_by_size'] : array();
1680 $p_filedescr_list = isset($responseParams['response_data']['p_filedescr_list']) ? $responseParams['response_data']['p_filedescr_list'] : array();
1681 $zip_split_part = isset($responseParams['response_data']['zip_split_part']) ? $responseParams['response_data']['zip_split_part'] : 0;
1682 $is_new_zip = isset($responseParams['response_data']['is_new_zip']) ? $responseParams['response_data']['is_new_zip'] : 0;
1683 $get_file_list = isset($responseParams['response_data']['get_file_list']) ? $responseParams['response_data']['get_file_list'] : '';
1684 $next_file_index = isset($responseParams['response_data']['next_file_index']) ? $responseParams['response_data']['next_file_index'] : 0;
1685 /* if(empty($zip_split_part))
1686 {
1687 $zip_split_part = 1;
1688 } */
1689 //If the zip file exceeds ~1.6 GB we are splitting the zip file into many parts.
1690 if((!empty($zip_split_part))&&(!empty($is_new_zip)))
1691 {
1692 if(strpos($backup_file, '_iwp_part_'))
1693 {
1694 $backup_file = substr($backup_file, 0, strpos($backup_file, '_iwp_part_')).'_iwp_part_'.$zip_split_part.'.zip';
1695 $backup_url = substr($backup_url, 0, strpos($backup_url, '_iwp_part_')).'_iwp_part_'.$zip_split_part.'.zip';
1696 }
1697 else
1698 {
1699 $backup_file = substr($backup_file, 0, strpos($backup_file, '.zip')).'_iwp_part_'.$zip_split_part.'.zip';
1700 $backup_url = substr($backup_url, 0, strpos($backup_url, '.zip')).'_iwp_part_'.$zip_split_part.'.zip';
1701 }
1702 }
1703 if(empty($zip_split_part))
1704 {
1705 $zip_split_part = 0;
1706 }
1707
1708 include_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
1709 include_once $GLOBALS['iwp_mmb_plugin_dir'].'/iwp-file-iterator.php';
1710 $returnArr = array();
1711 if((($nextCount != 0)||($category == 'fileZipAfterDBZip'))&&(empty($is_new_zip)))
1712 {
1713 unset($responseParams);
1714 $initialFileSize = iwp_mmb_get_file_size($backup_file)/1024/1024;
1715 $returnArr = $this->backupFilesNext($include_data, $exclude_data, $backup_file, $backup_url, $nextCount, $p_filedescr_list, $account_info, $files_with_error, $files_excluded_by_size, $zip_split_part);
1716 $fileNextTimeTaken = microtime(true) - $this->iwpScriptStartTime;
1717 echo "<br>iwpmsg Total file size".(iwp_mmb_get_file_size($backup_file)/1024/1024);
1718 $file_size_in_this_call = (iwp_mmb_get_file_size($backup_file)/1024/1024) - $initialFileSize;
1719 echo "<br>iwpmsg file size in this call".$file_size_in_this_call;
1720 echo "<br>iwpmsg Time taken in this call ".$fileNextTimeTaken."<br>";
1721 /*
1722 //Some times the difference between intitial and this call may equal to 0
1723 if( !(($file_size_in_this_call == 0) && is_array($returnArr) && !empty($returnArr['error'])) && !(is_array($returnArr) && !empty($returnArr['isGetFileList'])))
1724 {
1725 return array( 'error' => 'Zip-error: Unable to zip', 'error_code' => 'zip_error_unable_to_zip');
1726 }
1727 */
1728 return $returnArr;
1729 }
1730 else
1731 {
1732 //$nextCount = 0;
1733 $this->statusLog($this->hisID, array('stage' => 'backupFiles', 'status' => 'processing', 'statusMsg' => 'backupSingleCallInitiated','responseParams' => $responseParams));
1734
1735 $time = microtime(true);
1736 $start = $time;
1737 //$archive = new IWPPclZip('../archive.zip');
1738 global $archive;
1739 $archive = new IWPPclZip($backup_file);
1740 if($category == 'dbZip')
1741 {
1742 if(empty($get_file_list))
1743 {
1744 manual_debug('', 'beforeGettingFileList', 0);
1745 //define('IWP_PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
1746 $p_filedescr_list_array = $archive->getFileList(IWP_DB_DIR, IWP_PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, IWP_PCLZIP_OPT_CHUNK_BLOCK_SIZE, $file_block_size, IWP_PCLZIP_OPT_HISTORY_ID, $historyID); //darkCode set the file block size here .. static values
1747 //$p_filedescr_list = $p_filedescr_list_array['p_filedescr_list'];
1748 //unset($p_filedescr_list_array['p_filedescr_list']);
1749 $next_file_index = $p_filedescr_list_array['next_file_index'];
1750 manual_debug('', 'afterGettingFileList', 0);
1751 if($p_filedescr_list_array['status'] == 'partiallyCompleted')
1752 {
1753 echo('iwpmsg fileListDBInMultiPart');
1754 $result_arr = array();
1755 $result_arr = $responseParams;
1756 $result_arr['nextFunc'] = 'backupFilesZIP';
1757 $result_arr['response_data']['p_filedescr_list'] = $p_filedescr_list;
1758 unset($p_filedescr_list);
1759 $result_arr['response_data']['next_file_index'] = $next_file_index;
1760 if (isset($p_filedescr_list_array['complete_folder_list'])) {
1761 $result_arr['response_data']['complete_folder_list'] = $p_filedescr_list_array['complete_folder_list'];
1762 }else{
1763 $result_arr['response_data']['complete_folder_list'] = array();
1764 }
1765 unset($p_filedescr_list_array);
1766 $this->statusLog($this -> hisID, array('stage' => 'gettingFileList', 'status' => 'processing', 'statusMsg' => 'gettingFileListInMultiCall','responseParams' => $result_arr));
1767 $resArray = array();
1768 $resArray['status'] = 'partiallyCompleted';
1769 $resArray['backupParentHID'] = $historyID;
1770 return $resArray;
1771 }
1772 elseif(($p_filedescr_list_array['status'] == 'error')||(!$p_filedescr_list_array))
1773 {
1774 return $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'Backup of files failed - Error while preparing file list', 'statusCode' => 'dbZip_backup_of_files_failed_error_while_preparing_file_list'));
1775 }
1776 elseif($p_filedescr_list_array['status'] == 'completed')
1777 {
1778
1779 }
1780 }
1781 }
1782 else
1783 {
1784 if(empty($get_file_list))
1785 {
1786 manual_debug('', 'beforeGettingFileList', 0);
1787
1788 //$p_filedescr_list_array = $archive->getFileList($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, IWP_PCLZIP_OPT_CHUNK_BLOCK_SIZE, $file_block_size, IWP_PCLZIP_OPT_HISTORY_ID, $historyID); //testing darkCode set the file block size here .. static values
1789
1790 $p_filedescr_list_array = $archive->getFileList($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_FILE_EXCLUDE_SIZE, $exclude_file_size, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, IWP_PCLZIP_OPT_IWP_EXCLUDE_EXT, $exclude_extensions, IWP_PCLZIP_OPT_CHUNK_BLOCK_SIZE, $file_block_size, IWP_PCLZIP_OPT_HISTORY_ID, $historyID);
1791
1792 manual_debug('', 'afterGettingFileList', 0);
1793 //$p_filedescr_list = $p_filedescr_list_array['p_filedescr_list'];
1794 //unset($p_filedescr_list_array['p_filedescr_list']);
1795 $next_file_index = $p_filedescr_list_array['next_file_index'];
1796
1797 if($p_filedescr_list_array['status'] == 'partiallyCompleted')
1798 {
1799 echo('iwpmsg fileListInMultiPart');
1800 $result_arr = array();
1801 $result_arr = $responseParams;
1802 $result_arr['nextFunc'] = 'backupFilesZIP';
1803 $result_arr['response_data']['p_filedescr_list'] = $p_filedescr_list;
1804 unset($p_filedescr_list);
1805 $result_arr['response_data']['next_file_index'] = $next_file_index;
1806 $result_arr['response_data']['complete_folder_list'] = $p_filedescr_list_array['complete_folder_list'];
1807 unset($p_filedescr_list_array);
1808 $this->statusLog($this -> hisID, array('stage' => 'gettingFileList', 'status' => 'processing', 'statusMsg' => 'gettingFileListInMultiCall','responseParams' => $result_arr));
1809
1810 $resArray = array();
1811 $resArray['status'] = 'partiallyCompleted';
1812 $resArray['backupParentHID'] = $historyID;
1813 return $resArray;
1814 }
1815 elseif(($p_filedescr_list_array['status'] == 'error')||(!$p_filedescr_list_array))
1816 {
1817 return $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'Backup of files failed - Error while preparing file list', 'statusCode' => 'backup_of_files_failed_error_while_preparing_file_list'));
1818 }
1819 elseif($p_filedescr_list_array['status'] == 'completed')
1820 {
1821
1822 }
1823 }
1824 }
1825 //usort($p_filedescr_list, "cmp");
1826 $p_options = array ( //darkCode static values
1827 77021 => true, //tempFile ON
1828 77007 => !($is_compressed), //if we dont need to compress .. set as true
1829 77020 => 63082332, //setting tempFIle threshold value here
1830 78999 => $file_block_size,
1831 );
1832 $v_result = 1;
1833 $v_header = array();
1834 $v_header_list = array();
1835 $v_nb = get_iwp_files_db_count('headers');
1836 $v_nb_initial = get_iwp_files_db_count('headers');
1837 $p_result_list = array();
1838 //$nextCount = 0;
1839 $archive->privOpenFd('wb');
1840 $p_filedescr_list_omitted = array();
1841 $omitted_flag = '';
1842 //$p_filedescr_list_size = sizeof($p_filedescr_list);
1843 //$p_filedescr_list_size = $p_filedescr_list_array['total_FL_count'];
1844 $p_filedescr_list_size = get_iwp_files_db_count('files');
1845 echo "iwpmsg loopStarted";
1846 echo "iwpmsg ". $p_filedescr_list_size;
1847 manual_debug('', 'beforeStartingLoop', 0);
1848 for ($j=$nextCount; ($j<$p_filedescr_list_size) && ($v_result==1); $j++) {
1849
1850 //new method of getting fileList
1851 $p_filedescr_list[$j] = get_from_iwp_files_db($j);
1852
1853 // ----- Format the filename
1854 $p_filedescr_list[$j]['filename'] = IWPPclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
1855
1856 // ----- Skip empty file names
1857
1858 // TBC : Can this be possible ? not checked in DescrParseAtt ?
1859 if ($p_filedescr_list[$j]['filename'] == "") {
1860 continue;
1861 }
1862
1863 // ----- Check the filename
1864 if ( ($p_filedescr_list[$j]['type'] != 'virtual_file')
1865 && (!file_exists($p_filedescr_list[$j]['filename']))) {
1866 echo 'iwpmsg FILE DOESNT EXIST';
1867 continue;
1868 }
1869
1870 // ----- Look if it is a file or a dir with no all path remove option
1871 // or a dir with all its path removed
1872 // if ( (is_file($p_filedescr_list[$j]['filename']))
1873 // || ( is_dir($p_filedescr_list[$j]['filename'])
1874 if ( ($p_filedescr_list[$j]['type'] == 'file')
1875 || ($p_filedescr_list[$j]['type'] == 'virtual_file')
1876 || ( ($p_filedescr_list[$j]['type'] == 'folder')
1877 && ( !isset($p_options[IWP_PCLZIP_OPT_REMOVE_ALL_PATH])
1878 || !$p_options[IWP_PCLZIP_OPT_REMOVE_ALL_PATH]))
1879 ) {
1880
1881 // ----- Add the file
1882 $v_result = $archive->privAddFile($p_filedescr_list[$j], $v_header, $p_options);
1883 //saving the header in DB
1884 $cur_file = $p_filedescr_list[$j]['filename'];
1885 if($v_result == 1){
1886 $header_save_result = save_in_iwp_files_db(0, array(), $v_header, 'update', $v_nb);
1887 }
1888 else{
1889 $header_save_result = save_in_iwp_files_db(0, array(), array('error' => 1), 'update', $v_nb);
1890 $files_with_error[] = $cur_file;
1891 }
1892 if(is_array($header_save_result) && isset($header_save_result['error'])){
1893 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Zip-error: Error while updating the file "'.$cur_file.'" in the file list table.', 'statusCode' => 'zip_error_while_updating_file_list_table'));
1894 }
1895 $v_nb++;
1896 unset($p_filedescr_list);
1897
1898 // ----- Store the file infos
1899 //$v_header_list[$v_nb++] = $v_header;
1900 $nextCount = $j+1;
1901
1902 //unset($v_header_list[$v_nb++]);
1903
1904 if ($v_result != 1) {
1905 echo 'iwpmsg Error zipping this file'.$cur_file;
1906 $files_with_error[] = $cur_file;
1907 if($v_result == -10)
1908 {
1909 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Zip-error: Error compressing the file "'.$cur_file.'".Try excluding this file and try again.', 'statusCode' => 'zip_error_while_compressing_file'));
1910 }
1911 continue;
1912 //return $v_result;
1913 }
1914 }
1915
1916 $total_time = microtime(true) - $this->iwpScriptStartTime;
1917 //if(($total_time > $file_loop_break_time)||) //darkCode static Values
1918 $buffer_size = $zip_split_size*1024*1024 - 3*1024*1024*$file_block_size;
1919 $is_new_zip = false;
1920 if(($total_time > $file_loop_break_time)||(iwp_mmb_get_file_size($backup_file) >= $buffer_size))
1921 {
1922 if(iwp_mmb_get_file_size($backup_file) >= $buffer_size)
1923 {
1924 $zip_split_part += 1;
1925 $is_new_zip = true;
1926 }
1927 break;
1928 }
1929 //iwp_mmb_print_flush("|");
1930 iwp_mmb_auto_print("multiCallZip");
1931 echo("|");
1932 manual_debug('', "zipLoop", 1000);
1933 }
1934 echo "iwpmsg loopEnded";
1935 manual_debug('', 'afterEndingLoop', 0);
1936 $v_offset = @ftell($archive->zip_fd);
1937 $size_of_v_header_list = 0;
1938 //$v_header_list = $p_result_list;
1939 //$nextCount = sizeof($p_result_list);
1940 manual_debug('', 'beforeStartingHeaderWrite', 0);
1941 $total_header_count = get_iwp_files_db_count('headers');
1942 //for ($i=$v_nb_initial, $v_count=$v_nb_initial; $i<sizeof($v_header_list); $i++)
1943 for ($i=$v_nb_initial, $v_count=0; $i<$total_header_count; $i++)
1944 {
1945 //getting header list from db
1946 $v_header_list[$i] = get_from_iwp_files_db($i, 'thisFileHeader');
1947
1948 // ----- Create the file header
1949 if ($v_header_list[$i]['status'] == 'ok') {
1950 if (($v_result = $archive->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
1951 // ----- Return
1952 echo 'error writing header';
1953 //return $v_result;
1954 }
1955 $v_count++;
1956 }
1957
1958 // ----- Transform the header to a 'usable' info
1959 $archive->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
1960 unset($v_header_list);
1961 unset($p_result_list);
1962
1963 //manual_debug('', "duringEachHeaderWrite", 100);
1964 }
1965 manual_debug('', 'afterHeaderWrite', 0);
1966 $v_size = @ftell($archive->zip_fd)-$v_offset;
1967 if(empty($v_comment)){
1968 $v_comment = '';
1969 }
1970 $archive->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment);
1971 $archive->privCloseFd();
1972 echo 'iwpmsg next Count -'.$nextCount;
1973 //if(($nextCount == sizeof($p_filedescr_list)+1)||($nextCount == sizeof($p_filedescr_list)))
1974 if(($nextCount == get_iwp_files_db_count('files')+1)||($nextCount == get_iwp_files_db_count('files')))
1975 {
1976 $nextCount = "completed";
1977 $status = "completed";
1978 }
1979 else
1980 {
1981 $status = "partiallyCompleted";
1982 }
1983 manual_debug('', 'afterWholeHeaderWrite', 0);
1984 $result_arr = array();
1985
1986 //return $p_result_list;
1987 $result_arr['response_data']['nextCount'] = $nextCount;
1988 $result_arr['status'] = $status;
1989 $result_arr['category'] = $category;
1990 $result_arr['nextFunc'] = 'backupFilesZIP';
1991 $result_arr['response_data']['include_data'] = $include_data;
1992 $result_arr['response_data']['exclude_data'] = $exclude_data;
1993 $result_arr['response_data']['backup_file'] = $backup_file;
1994 $result_arr['response_data']['backup_url'] = $backup_url;
1995 $result_arr['response_data']['account_info'] = $account_info;
1996 $result_arr['response_data']['files_with_error'] = $files_with_error;
1997 $result_arr['response_data']['files_excluded_by_size'] = $files_excluded_by_size;
1998 $result_arr['response_data']['is_new_zip'] = $is_new_zip;
1999 $result_arr['response_data']['get_file_list'] = 'completed';
2000 //$result_arr['response_data']['p_filedescr_list'] = $p_filedescr_list;
2001 $result_arr['response_data']['zip_split_part'] = $zip_split_part;
2002 $resArray = array (
2003 'responseData' =>
2004 array (
2005 'stage' => 'backupFiles',
2006 'status' => 'completed',
2007
2008 ),
2009 'parentHID' => $this -> hisID,
2010 'nextFunc' => 'backupFilesZIP',
2011 'status' => $status,
2012 'backupParentHID' => $this -> hisID,
2013 'category' => $category,
2014 );
2015 if(($nextCount == 0)&&($nextCount != 'completed'))
2016 {
2017 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'backupFileSingleCall'.$status, 'statusCode' => 'backup_file_single_call_error', 'responseParams' => $result_arr));
2018 $nextFunc = 'error';
2019 $status = 'error';
2020 return array('error' => 'Must be error');
2021 }
2022 if(!isset($p_filedescr_list)){
2023 $p_filedescr_list = array();
2024 }
2025 if($status == 'partiallyCompleted')
2026 {
2027 echo 'iwpmsg filesNextCount: '.$nextCount;
2028 echo 'iwpmsg totalFilesCount: '.get_iwp_files_db_count('files');
2029 $result_arr['response_data']['p_filedescr_list'] = $p_filedescr_list;
2030 unset($p_filedescr_list);
2031 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'completed', 'statusMsg' => 'backupFileSingleCall'.$status,'nextFunc' => 'backupFilesZIP', 'responseParams' => $result_arr));
2032 unset($result_arr);
2033 }
2034 else
2035 {
2036 $main_category = $this -> getRequiredData($historyID,"category");
2037 if(($main_category == 'full')&&($category != 'fileZipAfterDBZip'))
2038 {
2039 //storing hash values of db-file if any
2040 $backup_settings_values['dbFileHashValue'][$historyID] = $this -> getHashValuesArray($p_filedescr_list);
2041 update_option('iwp_client_multi_backup_temp_values', $backup_settings_values);
2042
2043 $result_arr['category'] = 'fileZipAfterDBZip';
2044 $result_arr['nextFunc'] = 'backupFiles';
2045 $resArray['response_data']['backup_file'] = $backup_file;
2046 $resArray['status'] = 'partiallyCompleted'; //Here am setting partiallyCompleted to continue the loop for the full(both db and files) method
2047 $result_arr['status'] = 'partiallyCompleted';
2048 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'partiallyCompleted', 'statusMsg' => 'backupFileSingleCall'.$status,'nextFunc' => 'backupFiles', 'responseParams' => $result_arr));
2049 }
2050 else
2051 {
2052 refresh_iwp_files_db(); //truncating table on final call.
2053 $paths = array();
2054 $tempPaths = array();
2055
2056 $backup_files_array = $this->get_files_array_from_iwp_part($backup_file);
2057 $backup_file = array();
2058 $backup_file = $backup_files_array;
2059
2060 $backup_url_array = $this->get_files_array_from_iwp_part($backup_url);
2061 $backup_url = array();
2062 $backup_url = $backup_url_array;
2063
2064 $size = round($this->get_total_files_size($backup_file) / 1024, 2);
2065 if ($size > 1000) {
2066 $paths['size'] = round($size / 1024, 2) . " MB"; //Modified by IWP //Mb => MB
2067 } else {
2068 $paths['size'] = $size . 'KB'; //Modified by IWP //Kb => KB
2069 }
2070 $paths['backup_name'] = $task_name;
2071 $paths['mechanism'] = 'multicall';
2072 $paths['server'] = array(
2073 'file_path' => $backup_file,
2074 'file_url' => $backup_url);
2075
2076 $paths['time'] = time();
2077 $paths['adminHistoryID'] = $historyID;
2078 $paths['files_with_error'] = $files_with_error;
2079 $paths['files_excluded_by_size'] = $files_excluded_by_size;
2080 //$paths['hashValues'] = $this -> getHashValuesArray($p_filedescr_list);
2081 //$paths['hashValues'] = array_merge($dbFileHashValue, $paths['hashValues']);
2082 unset($p_filedescr_list);
2083 $tempPath = $paths;
2084 $paths['task_results'][$historyID] = $tempPath;
2085 if(empty($account_info))
2086 {
2087 $tempPath['server']['dbHost'] = DB_HOST;
2088 $tempPath['server']['dbName'] = DB_NAME;
2089 $tempPath['server']['dbUser'] = DB_USER;
2090 $tempPath['server']['dbPassword'] = DB_PASSWORD;
2091 $resArray['task_results'][$historyID] = $tempPath;
2092
2093 $result_arr['nextFunc'] = 'backupFilesZIPOver';
2094 }
2095 else
2096 {
2097 $resArray['status'] = 'partiallyCompleted'; //continuing the flow to backup_uploads
2098
2099 $result_arr['nextFunc'] = 'backup_uploads';
2100 $result_arr['status'] = 'partiallyCompleted';
2101 $result_arr['response_data']['backup_file'] = $backup_file;
2102 }
2103
2104 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'completed', 'statusMsg' => 'backupFileSingleCall'.$status, 'responseParams' => $result_arr,'task_result' => $paths));
2105
2106 if((($main_category != 'files')&&($category == 'dbZip')) || ($main_category == 'db'))
2107 {
2108 @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
2109 @unlink(DB_NAME);
2110 @rmdir(IWP_DB_DIR);
2111 }
2112
2113 //verification
2114 if(is_array($backup_file))
2115 {
2116 foreach($backup_file as $key => $single_backup_file)
2117 {
2118 $verification_result = $this -> postBackupVerification($archive, $single_backup_file);
2119 if(!$verification_result)
2120 {
2121 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'The zip file was corrupted while zipping', 'responseParams' => $result_arr));
2122 }
2123 }
2124 }
2125 //Remove the old backups (limit)
2126 $removed = $this->remove_old_backups($requestParams['task_name']);
2127 if (is_array($removed) && isset($removed['error'])) {
2128 //$error_message = $removed['error'];
2129 return $this->statusLog($this -> hisID, array('stage' => 'removingBackupFiles', 'status' => 'error', 'statusMsg' => 'Error while removing old backups. ('.$removed['error'].')', 'statusCode' => 'remove_old_backups_error_while_removing_old_backups', 'responseParams' => $result_arr));
2130 }
2131
2132 }
2133
2134 }
2135
2136 return $resArray;
2137
2138 }
2139 }
2140
2141 function get_total_files_size($backup_files)
2142 {
2143 if(is_array($backup_files))
2144 {
2145 $total_size = 0;
2146 foreach($backup_files as $key => $value)
2147 {
2148 $total_size += iwp_mmb_get_file_size($value);
2149 }
2150 return $total_size;
2151 }
2152 else
2153 {
2154 return iwp_mmb_get_file_size($backup_files);
2155 }
2156 }
2157
2158 function backupFilesNext($include_data, $exclude_data, $backup_file, $backup_url, $nextCount, $p_filedescr_list = array(), $account_info = array(), $files_with_error = array(), $files_excluded_by_size = array(), $zip_split_part = 0)
2159 {
2160 $historyID = $this -> hisID;
2161 $is_new_zip = false;
2162 $backup_settings_values = $this -> backup_settings_vals;
2163 //$file_block_size = $backup_settings_values['file_block_size'];
2164 //$is_compressed = $backup_settings_values['is_compressed'];
2165 //$file_loop_break_time = $backup_settings_values['file_loop_break_time'];
2166 //$task_name = $backup_settings_values['task_name'];
2167
2168 //get the settings by other method
2169 $requestParams = $this->getRequiredData($historyID, "requestParams");
2170 $file_block_size = $requestParams['args']['file_block_size']; //darkcode changed
2171 $is_compressed = $requestParams['args']['is_compressed'];
2172 $file_loop_break_time = $requestParams['args']['file_loop_break_time'];
2173 $task_name = $requestParams['args']['backup_name'];
2174 $exclude_file_size = $requestParams['args']['exclude_file_size'];
2175 $exclude_extensions = explode(",",$requestParams['args']['exclude_extensions']);
2176 $zip_split_size = $requestParams['args']['zip_split_size'];
2177
2178 if(isset($backup_settings_values['dbFileHashValue']) && $backup_settings_values['dbFileHashValue'][$historyID])
2179 $dbFileHashValue = $backup_settings_values['dbFileHashValue'][$historyID];
2180 else
2181 $dbFileHashValue = array();
2182
2183 $responseParams = $this -> getRequiredData($historyID,"responseParams");
2184 $category = $responseParams['category']; //Am getting the category to perform the dbZip actions
2185
2186 $get_file_list = isset($responseParams['response_data']['get_file_list']) ? $responseParams['response_data']['get_file_list'] : '';
2187
2188
2189 $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'processing', 'statusMsg' => 'backupMultiCallInitiated', 'responseParams' => $responseParams));
2190
2191 $time = microtime(true);
2192 $start = $time;
2193 //include_once 'pclzip.class.php';
2194 //include_once 'pclzip.class.split.php';
2195 global $archive;
2196 $archive = new IWPPclZip($backup_file);
2197 if($category == 'dbZip')
2198 {
2199 if(empty($p_filedescr_list)||($nextCount == 0))
2200 {
2201 if($get_file_list != 'completed'){
2202 $p_filedescr_list_array = $archive->getFileList(IWP_DB_DIR, IWP_PCLZIP_OPT_REMOVE_PATH, IWP_BACKUP_DIR, IWP_PCLZIP_OPT_CHUNK_BLOCK_SIZE, $file_block_size, IWP_PCLZIP_OPT_HISTORY_ID, $historyID);//darkCode set the file block size here .. static values
2203 $p_filedescr_list = $p_filedescr_list_array['p_filedescr_list'];
2204 $next_file_index = $p_filedescr_list_array['next_file_index'];
2205
2206 if($p_filedescr_list_array['status'] == 'partiallyCompleted')
2207 {
2208 $result_arr = array();
2209 $result_arr = $responseParams;
2210 $result_arr['nextFunc'] = 'backupFilesZIP';
2211 $result_arr['response_data']['p_filedescr_list'] = $p_filedescr_list;
2212 $result_arr['response_data']['next_file_index'] = $p_filedescr_list_array['next_file_index'];
2213 $result_arr['response_data']['complete_folder_list'] = $p_filedescr_list_array['complete_folder_list'];
2214 unset($p_filedescr_list_array);
2215 $this->statusLog($this -> hisID, array('stage' => 'gettingFileList', 'status' => 'processing', 'statusMsg' => 'gettingFileListInMultiCall','responseParams' => $result_arr));
2216
2217 $resArray = array();
2218 $resArray['status'] = 'partiallyCompleted';
2219 $resArray['backupParentHID'] = $historyID;
2220 return $resArray;
2221 }
2222 elseif(($p_filedescr_list_array['status'] == 'error')||(!$p_filedescr_list_array))
2223 {
2224 return $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'Backup of files failed - Error while preparing file list', 'statusCode' => 'backup_files_next_dbZip_backup_of_files_failed_error_while_preparing_file_list'));
2225 }
2226 elseif($p_filedescr_list_array['status'] == 'completed')
2227 {
2228
2229 }
2230 }
2231 }
2232 }
2233 else
2234 {
2235 if(empty($p_filedescr_list)||($nextCount == 0))
2236 {
2237 if($get_file_list != 'completed'){
2238 //$p_filedescr_list_array = $archive->getFileList($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, IWP_PCLZIP_OPT_CHUNK_BLOCK_SIZE, $file_block_size, IWP_PCLZIP_OPT_HISTORY_ID, $historyID); //testing darkCode set the file block size here .. static values
2239
2240 $p_filedescr_list_array = $archive->getFileList($include_data, IWP_PCLZIP_OPT_REMOVE_PATH, ABSPATH, IWP_PCLZIP_OPT_FILE_EXCLUDE_SIZE, $exclude_file_size, IWP_PCLZIP_OPT_IWP_EXCLUDE, $exclude_data, IWP_PCLZIP_OPT_IWP_EXCLUDE_EXT, $exclude_extensions, IWP_PCLZIP_OPT_CHUNK_BLOCK_SIZE, $file_block_size, IWP_PCLZIP_OPT_HISTORY_ID, $historyID);
2241
2242 $p_filedescr_list = $p_filedescr_list_array['p_filedescr_list'];
2243
2244 if($p_filedescr_list_array['status'] == 'partiallyCompleted')
2245 {
2246 $result_arr = array();
2247 $result_arr = $responseParams;
2248 $result_arr['nextFunc'] = 'backupFilesZIP';
2249 $result_arr['response_data']['p_filedescr_list'] = $p_filedescr_list;
2250 unset($p_filedescr_list);
2251 unset($p_filedescr_list_array['p_filedescr_list']);
2252 $result_arr['response_data']['next_file_index'] = $p_filedescr_list_array['next_file_index'];
2253 $result_arr['response_data']['complete_folder_list'] = isset($p_filedescr_list_array['complete_folder_list']) ? $p_filedescr_list_array['complete_folder_list'] : array();
2254
2255 $this->statusLog($this -> hisID, array('stage' => 'gettingFileList', 'status' => 'processing', 'statusMsg' => 'gettingFileListInMultiCall','responseParams' => $result_arr));
2256 unset($p_filedescr_list_array);
2257 $resArray = array();
2258 $resArray['status'] = 'partiallyCompleted';
2259 $resArray['backupParentHID'] = $historyID;
2260 $resArray['isGetFileList'] = true;
2261 return $resArray;
2262 }
2263 elseif(($p_filedescr_list_array['status'] == 'error')||(!$p_filedescr_list_array))
2264 {
2265 return $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'Backup of files failed - Error while preparing file list', 'statusCode' => 'backup_files_next_p_filedescr_list_array_dbZip_backup_of_files_failed_Error_while_preparing_file_list'));
2266 }
2267 elseif($p_filedescr_list_array['status'] == 'completed')
2268 {
2269
2270 }
2271 }
2272 }
2273 }
2274 $archive->privDisableMagicQuotes();
2275 if (($v_result=$archive->privOpenFd('rb+')) != 1)
2276 {
2277 $archive->privSwapBackMagicQuotes();
2278 $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'openingFileError', 'statusCode' => 'opening_file_error'));
2279 return array( 'error' => 'Zip-error: Error opening file', 'error_code' => 'zip_error_opening_file');
2280 //return $v_result;
2281 }
2282 clearstatcache();
2283 // ----- Read the central directory informations
2284 $v_central_dir = array();
2285 if (($v_result = $archive->privReadEndCentralDir($v_central_dir)) != 1)
2286 {
2287 echo 'iwpmsg error2';
2288 $archive->privCloseFd();
2289 $archive->privSwapBackMagicQuotes();
2290 if(is_array($v_result) && !empty($v_result['error']))
2291 {
2292 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => $v_result['error'], 'statusCode' => 'priv_read_end_central_dir_error'));
2293 }
2294 else
2295 {
2296 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Zip-error: Error reading end directory', 'statusCode' => 'zip_error_error_reading_end_directory'));
2297 }
2298 }
2299
2300 // ----- Go to beginning of File
2301 @rewind($archive->zip_fd);
2302
2303 // ----- Creates a temporay file
2304 $v_zip_temp_name = IWP_PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
2305
2306 // ----- Open the temporary file in write mode
2307 if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb+')) == 0)
2308 {
2309 $archive->privCloseFd();
2310 $archive->privSwapBackMagicQuotes();
2311 echo 'iwpmsg error3';
2312 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Unable to open temporary file', 'statusCode' => 'unable_to_open_temporary_file')); // ----- Return
2313
2314 }
2315
2316 // ----- Copy the files from the archive to the temporary file
2317 // TBC : Here I should better append the file and go back to erase the central dir
2318 $v_size = $v_central_dir['offset'];
2319
2320 fseek($archive->zip_fd, $v_size, SEEK_SET);
2321 $actualFileSize = iwp_mmb_get_file_size($backup_file);
2322
2323 while ($actualFileSize != 0)
2324 {
2325 $v_read_size = ($actualFileSize < IWP_PCLZIP_READ_BLOCK_SIZE ? $actualFileSize : IWP_PCLZIP_READ_BLOCK_SIZE);
2326 $v_buffer = fread($archive->zip_fd, $v_read_size);
2327 if (empty($v_buffer)) {
2328 break;
2329 }
2330 @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
2331 $actualFileSize -= $v_read_size;
2332 }
2333
2334 // ----- Swap the file descriptor
2335 // Here is a trick : I swap the temporary fd with the zip fd, in order to use
2336 // the following methods on the temporary fil and not the real archive
2337 /* $v_swap = $archive->zip_fd;
2338 $archive->zip_fd = $v_zip_temp_fd;
2339 $v_zip_temp_fd = $v_swap; */
2340 //usort($p_filedescr_list, "cmp");
2341
2342
2343 //truncate the file after just at the begining of central header
2344 fseek($archive->zip_fd, $v_size, SEEK_SET);
2345 $truncateResult = ftruncate($archive->zip_fd, $v_size);
2346 clearstatcache();
2347
2348
2349 $p_options = array ( //darkCode static values
2350 77021 => true, //using temp method
2351 77007 => !($is_compressed), //if no compression is needed set as true
2352 77020 => 63082332,
2353 );
2354 $v_result = 1;
2355 $v_header = array();
2356 $p_result_list = array();
2357 $v_header_list = array();
2358 $v_nb = $v_nb_initial = get_iwp_files_db_count('headers');
2359 $v_comment = '';
2360 //$nextCount = $_REQUEST['nextCount'];
2361 $omitted_flag = '';
2362 $nextCountHere = 0;
2363 $p_filedescr_list_size = get_iwp_files_db_count('files');
2364 iwp_mmb_print_flush("loopStarted");
2365 echo $p_filedescr_list_size;
2366 manual_debug('', 'beforeStartingNextLoop', 0);
2367 $p_filedescr_list = array();
2368 for ($j=($nextCount); ($j<$p_filedescr_list_size) && ($v_result==1); $j++) {
2369
2370 //new method of getting fileList
2371 $p_filedescr_list[$j] = get_from_iwp_files_db($j);
2372
2373 // ----- Format the filename
2374 $p_filedescr_list[$j]['filename'] = IWPPclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
2375
2376 // ----- Skip empty file names
2377 // TBC : Can this be possible ? not checked in DescrParseAtt ?
2378 if ($p_filedescr_list[$j]['filename'] == "") {
2379 continue;
2380 }
2381
2382 // ----- Check the filename
2383 if ( ($p_filedescr_list[$j]['type'] != 'virtual_file')
2384 && (!file_exists($p_filedescr_list[$j]['filename']))) {
2385 echo 'FILE DOESNT EXIST';
2386 continue;
2387 }
2388
2389 // ----- Look if it is a file or a dir with no all path remove option
2390 // or a dir with all its path removed
2391 // if ( (is_file($p_filedescr_list[$j]['filename']))
2392 // || ( is_dir($p_filedescr_list[$j]['filename'])
2393 if ( ($p_filedescr_list[$j]['type'] == 'file')
2394 || ($p_filedescr_list[$j]['type'] == 'virtual_file')
2395 || ( ($p_filedescr_list[$j]['type'] == 'folder')
2396 && ( !isset($p_options[IWP_PCLZIP_OPT_REMOVE_ALL_PATH])
2397 || !$p_options[IWP_PCLZIP_OPT_REMOVE_ALL_PATH]))
2398 ) {
2399 $time = microtime(true);
2400 $finish_part = $time;
2401 $total_time_part = $finish_part - $start;
2402 $nextCountHere = $j+1;
2403 /* if(($total_time_part > 2)&&($p_filedescr_list[$j]['size'] > 5000000))
2404 {
2405 $p_filedescr_list_omitted[$j] = $p_filedescr_list[$j];
2406 $v_nb++;
2407 $nextCount = $v_nb;
2408 $omitted_flag = 'set';
2409 continue;
2410
2411 } */
2412
2413 // ----- Add the file
2414 echo "|";
2415 //global $cur_file;
2416 $cur_file = $p_filedescr_list[$j]['filename'];
2417 $v_result = $archive->privAddFile($p_filedescr_list[$j], $v_header, $p_options);
2418 //saving the header in DB
2419 if($v_result == 1){
2420 $header_save_result = save_in_iwp_files_db(0, array(), $v_header, 'update', $v_nb);
2421 }
2422 else{
2423 $header_save_result = save_in_iwp_files_db(0, array(), array('error' => 1), 'update', $v_nb);
2424 }
2425 if(is_array($header_save_result) && isset($header_save_result['error'])){
2426 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Zip-error: Error while updating the file "'.$cur_file.'" in the file list table.', 'statusCode' => 'zip_error_while_updating_file_list_table'));
2427 }
2428 $v_nb++;
2429 unset($p_filedescr_list);
2430 // ----- Store the file infos
2431 //$v_header_list[$v_nb++] = $v_header;
2432
2433 if ($v_result != 1) {
2434 //$this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'SomeError1'));
2435 echo "iwpmsg error zipping this file:".$cur_file;
2436 echo 'iwpmsg errorCode - '.$v_result;
2437 $files_with_error[] = $cur_file;
2438 if($v_result == -10)
2439 {
2440 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Zip-error: Error compressing the file "'.$cur_file.'".Try excluding this file and try again.', 'statusCode' => 'zip_error_while_compressing_file'));
2441 }
2442 continue;
2443 //return $v_result;
2444 }
2445 }
2446
2447 $time = microtime(true);
2448 $finish = $time;
2449 $total_time = $finish - $this->iwpScriptStartTime;
2450 $buffer_size = $zip_split_size*1024*1024 - 3*1024*1024*$file_block_size;
2451 if(($total_time > $file_loop_break_time)||(iwp_mmb_get_file_size($backup_file) >= $buffer_size)) //darkCode static values
2452 {
2453 if(iwp_mmb_get_file_size($backup_file) >= $buffer_size)
2454 {
2455 $zip_split_part += 1;
2456 $is_new_zip = true;
2457 echo "iwpmsg splitting into new zip";
2458 }
2459 break;
2460 }
2461 //iwp_mmb_print_flush("|");
2462 iwp_mmb_auto_print("multiCallZip");
2463 //echo "|";
2464 manual_debug('', "zipLoop", 1000);
2465 }
2466 echo "iwpmsg loopEnded";
2467 manual_debug('', 'afterNextLoop', 0);
2468 $v_offset = @ftell($archive->zip_fd);
2469 $v_size = $v_central_dir['size'];
2470 /* while ($v_size != 0)
2471 {
2472 $v_read_size = ($v_size < IWP_PCLZIP_READ_BLOCK_SIZE ? $v_size : IWP_PCLZIP_READ_BLOCK_SIZE);
2473 $v_buffer = @fread($v_zip_temp_fd, $v_read_size);
2474 @fwrite($archive->zip_fd, $v_buffer, $v_read_size);
2475 $v_size -= $v_read_size;
2476 }
2477 */
2478 clearstatcache();
2479 $endOfFile = iwp_mmb_get_file_size($backup_file);
2480
2481
2482
2483 //writing the header which is stored in temp file
2484
2485 fseek($archive->zip_fd, $endOfFile, SEEK_SET);
2486 fseek($v_zip_temp_fd, 0, SEEK_SET);
2487
2488 if ($v_central_dir['size'] > 0) {
2489 $v_buffer = fread($v_zip_temp_fd, $v_central_dir['size']);
2490 $writeResult = fwrite($archive->zip_fd, $v_buffer);
2491 }
2492
2493 manual_debug('', 'beforeStartingNextHeaderWrite', 0);
2494
2495 $v_header_list = array();
2496 //array_pop($v_header_list);
2497 //$v_header_list = $p_result_list;
2498 // ----- Create the Central Dir files header
2499 $total_header_count = get_iwp_files_db_count('headers');
2500 for ($i=$v_nb_initial, $v_count=0; $i<$total_header_count; $i++)
2501 {
2502 //getting header list from db
2503 $v_header_list[$i] = get_from_iwp_files_db($i, 'thisFileHeader');
2504
2505 // ----- Create the file header
2506 if ($v_header_list[$i]['status'] == 'ok') {
2507 if (($v_result = $archive->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
2508 echo 'iwpmsg error4';
2509 fclose($v_zip_temp_fd);
2510 $archive->privCloseFd();
2511 @unlink($v_zip_temp_name);
2512 $archive->privSwapBackMagicQuotes();// ----- Return
2513 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Zip-error: Error while writing header', 'statusCode' => 'zip_error_while_writing_header'));
2514 //return $v_result;
2515 }
2516 $v_count++;
2517 }
2518
2519 // ----- Transform the header to a 'usable' info
2520 $archive->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
2521 unset($v_header_list);
2522 unset($p_result_list);
2523 }
2524 manual_debug('', 'afterNextHeaderWrite', 0);
2525 // ----- Calculate the size of the central header
2526 $v_size = @ftell($archive->zip_fd)-$v_offset;
2527
2528 // ----- Create the central dir footer
2529 if (($v_result = $archive->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1)
2530 {
2531 // ----- Reset the file list
2532 echo 'iwpmsg error5';
2533 unset($v_header_list);
2534 $archive->privSwapBackMagicQuotes();
2535 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'Zip-Error: Error while writing footer', 'statusCode' => 'zip_error_while_writing_footer'));
2536 }
2537
2538 // ----- Swap back the file descriptor
2539 /* $v_swap = $archive->zip_fd;
2540 $archive->zip_fd = $v_zip_temp_fd;
2541 $v_zip_temp_fd = $v_swap; */
2542
2543 // ----- Close
2544 $archive->privCloseFd();
2545
2546 // ----- Close the temporary file
2547 @fclose($v_zip_temp_fd);
2548
2549 // ----- Magic quotes trick
2550 $archive->privSwapBackMagicQuotes();
2551
2552 // ----- Delete the zip file
2553 // TBC : I should test the result ...
2554 //@unlink($archive->zipname);
2555 @unlink($v_zip_temp_name);
2556
2557 // ----- Rename the temporary file
2558 // TBC : I should test the result ...
2559 //@rename($v_zip_temp_name, $archive->zipname);
2560 //IWPPclZipUtilRename($v_zip_temp_name, $archive->zipname);
2561
2562 $nextCount = $nextCountHere;
2563
2564 $size_file_des = get_iwp_files_db_count('files');
2565 if($nextCount == $size_file_des)
2566 //if(true)
2567 {
2568 $nextCount = "completed";
2569 $status = "completed";
2570
2571 }
2572 else{
2573 $status = "partiallyCompleted";
2574 }
2575 manual_debug('', 'afterWholeHeaderWrite', 0);
2576 $result_arr = array();
2577 $result_arr['response_data']['nextCount'] = $nextCount;
2578 $result_arr['status'] = $status;
2579 $result_arr['category'] = $category;
2580 $result_arr['nextFunc'] = 'backupFilesZIP';
2581 $result_arr['response_data']['include_data'] = $include_data;
2582 $result_arr['response_data']['exclude_data'] = $exclude_data;
2583 $result_arr['response_data']['backup_file'] = $backup_file;
2584 $result_arr['response_data']['backup_url'] = $backup_url;
2585 $result_arr['response_data']['account_info'] = $account_info;
2586 $result_arr['response_data']['zip_split_part'] = $zip_split_part;
2587 $result_arr['response_data']['is_new_zip'] = $is_new_zip;
2588 $result_arr['response_data']['files_with_error'] = $files_with_error;
2589 $result_arr['response_data']['files_excluded_by_size'] = $files_excluded_by_size;
2590 $result_arr['response_data']['get_file_list'] = 'completed';
2591
2592 //$result_arr['response_data']['p_filedescr_list'] = $p_filedescr_list;
2593 $resArray = array (
2594 'responseData' =>
2595 array (
2596 'stage' => 'backupFilesNext',
2597 'status' => 'completed',
2598 ),
2599 'parentHID' => $this -> hisID,
2600 'nextFunc' => 'backupFilesZIP',
2601 'status' => $status,
2602 'backupParentHID' => $this -> hisID,
2603 );
2604 if(($nextCount == 0)&&($nextCount != 'completed'))
2605 {
2606 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'backupFileNextCallError'.$status, 'responseParams' => $result_arr, 'statusCode' => 'backup_file_next_call_error'));
2607 $nextFunc = 'error';
2608 $status = 'error';
2609 return array('error' => 'Must be error', 'error_code' => 'backup_file_next_call_error');
2610 }
2611 if($status == "partiallyCompleted")
2612 {
2613 echo 'iwpmsg filesNextCount: '.$nextCount;
2614 echo 'iwpmsg totalFilesCount: '.$p_filedescr_list_size;
2615 $result_arr['response_data']['p_filedescr_list'] = array();
2616 unset($p_filedescr_list);
2617 $this->statusLog($this -> hisID, array('stage' => 'backupFilesMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall'.$status,'nextFunc' => 'backupFilesZIP', 'responseParams' => $result_arr));
2618 unset($result_arr);
2619 }
2620 else
2621 {
2622 $main_category = $this -> getRequiredData($historyID,"category");
2623
2624 //this is where the call goes to backupFiles after DB complete
2625 if(($main_category == 'full')&&($category != 'fileZipAfterDBZip'))
2626 {
2627 //storing hash values of db-file if any
2628 $backup_settings_values['dbFileHashValue'][$historyID] = $this -> getHashValuesArray($p_filedescr_list);
2629 update_option('iwp_client_multi_backup_temp_values', $backup_settings_values);
2630
2631 $result_arr['category'] = 'fileZipAfterDBZip';
2632 $resArray['status'] = 'partiallyCompleted';
2633 $result_arr['nextFunc'] = 'backupFiles';
2634 $result_arr['status'] = 'partiallyCompleted';
2635 $result_arr['response_data']['get_file_list'] = '';
2636 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'completed', 'statusMsg' => 'nextCall'.$status,'nextFunc' => 'backupFiles', 'responseParams' => $result_arr));
2637 }
2638 else
2639 {
2640
2641 //$this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'completed', 'statusMsg' => 'nextCall'.$status, 'responseParams' => $result_arr));
2642 refresh_iwp_files_db(); //truncating table on final call.
2643 $paths = array();
2644 $tempPaths = array();
2645
2646 $backup_files_array = $this->get_files_array_from_iwp_part($backup_file);
2647 $backup_file = array();
2648 $backup_file = $backup_files_array;
2649
2650 $backup_url_array = $this->get_files_array_from_iwp_part($backup_url);
2651 $backup_url = array();
2652 $backup_url = $backup_url_array;
2653
2654 $size = round($this->get_total_files_size($backup_file) / 1024, 2);
2655 if ($size > 1000) {
2656 $paths['size'] = round($size / 1024, 2) . " MB"; //Modified by IWP //Mb => MB
2657 } else {
2658 $paths['size'] = $size . 'KB'; //Modified by IWP //Kb => KB
2659 }
2660 $paths['backup_name'] = $task_name;
2661 $paths['mechanism'] = 'multicall';
2662 $paths['server'] = array(
2663 'file_path' => $backup_file,
2664 'file_url' => $backup_url,
2665 );
2666
2667 $paths['time'] = time();
2668 $paths['adminHistoryID'] = $historyID;
2669 $paths['files_with_error'] = $files_with_error;
2670 $paths['files_excluded_by_size'] = $files_excluded_by_size;
2671 //$paths['hashValues'] = $this -> getHashValuesArray($p_filedescr_list);
2672 //$paths['hashValues'] = array_merge($dbFileHashValue, $paths['hashValues']);
2673 unset($p_filedescr_list);
2674 $tempPath = $paths;
2675 $paths['task_results'][$historyID] = $tempPath;
2676
2677 if(empty($account_info))
2678 {
2679 //this is where the call goes to upload after backup zip completion ..
2680 $resArray['status'] = 'completed';
2681
2682 $tempPath['server']['dbHost'] = DB_HOST;
2683 $tempPath['server']['dbName'] = DB_NAME;
2684 $tempPath['server']['dbUser'] = DB_USER;
2685 $tempPath['server']['dbPassword'] = DB_PASSWORD;
2686
2687 $resArray['task_results'][$historyID] = $tempPath;
2688
2689 $result_arr['nextFunc'] = 'backupFilesZIPOver';
2690 $result_arr['status'] = 'completed';
2691 }
2692 else
2693 {
2694 $resArray['actual_file_size'] = $size; //necessary for dropbox function
2695 $resArray['status'] = 'partiallyCompleted';
2696 $result_arr['nextFunc'] = 'backup_uploads';
2697 $result_arr['status'] = 'partiallyCompleted';
2698 $result_arr['actual_file_size'] = $size;
2699 $result_arr['response_data']['backup_file'] = $backup_file;
2700 }
2701
2702 $this->statusLog($this -> hisID, array('stage' => 'backupFiles', 'status' => 'completed', 'statusMsg' => 'nextCall'.$status, 'responseParams' => $result_arr,'task_result' => $paths));
2703
2704 if((($main_category != 'files')&&($category == 'dbZip')) || ($main_category == 'db'))
2705 {
2706 @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
2707 @unlink(DB_NAME);
2708 @rmdir(IWP_DB_DIR);
2709 }
2710
2711 //checking zip corruption
2712 if(is_array($backup_file))
2713 {
2714 foreach($backup_file as $key => $single_backup_file)
2715 {
2716 $verification_result = $this -> postBackupVerification($archive, $single_backup_file);
2717 if(!$verification_result)
2718 {
2719 return $this->statusLog($historyID, array('stage' => 'backupFilesMultiCall', 'status' => 'error', 'statusMsg' => 'The zip file was corrupted while zipping', 'responseParams' => $result_arr));
2720 }
2721 }
2722 }
2723
2724 //Remove the old backups (limit)
2725 $removed = $this->remove_old_backups($requestParams['task_name']);
2726
2727 if (is_array($removed) && isset($removed['error'])) {
2728 return $this->statusLog($this -> hisID, array('stage' => 'removingBackupFiles', 'status' => 'error', 'statusMsg' => 'Error while removing old backups. ('.$removed['error'].')', 'responseParams' => $result_arr, 'statusCode' => 'error_while_removing_old_backups'));
2729 }
2730
2731 }
2732 }
2733 return $resArray;
2734
2735 }
2736
2737 function get_files_array_from_iwp_part($backup_file)
2738 {
2739 $backup_files_array = array();
2740 if(strpos($backup_file, '_iwp_part') !== false)
2741 {
2742 $orgName = substr($backup_file, 0, strpos($backup_file, '_iwp_part_'));
2743 $totalParts = substr($backup_file, strpos($backup_file, '_iwp_part_')+10);
2744 $totalParts = substr($totalParts, 0, strlen($totalParts)-4);
2745 for($i=0; $i<=$totalParts; $i++)
2746 {
2747 if($i == 0)
2748 {
2749 $backup_files_array[] = $orgName.'.zip';
2750 }
2751 else
2752 {
2753 $backup_files_array[] = $orgName.'_iwp_part_'.$i.'.zip';
2754 }
2755 }
2756 return $backup_files_array;
2757 }
2758 else
2759 {
2760 $backup_files_array[] = $backup_file;
2761 return $backup_file;
2762 }
2763 }
2764
2765 function postBackupVerification(&$obj, $backup_file)
2766 {
2767 $file_size = iwp_mmb_get_file_size($backup_file);
2768 if($file_size > 0)
2769 {
2770 $list = $obj->listContent();
2771 if ($list == 0)
2772 {
2773 return false;
2774 }
2775 else
2776 {
2777 return true;
2778 }
2779 }
2780 else
2781 {
2782 return false;
2783 }
2784 }
2785
2786 function getHashValuesArray($p_filedescr_list)
2787 {
2788 $hashValues = array();
2789 if(is_array($p_filedescr_list))
2790 {
2791 foreach($p_filedescr_list as $key => $value)
2792 {
2793 if($value['fileHash'])
2794 {
2795 if($value['fileHash'] !== '')
2796 {
2797 $hashValues[$value['stored_filename']] = $value['fileHash'];
2798 }
2799 }
2800 }
2801 }
2802 return $hashValues;
2803 }
2804
2805 function maybe_serialize_compress($value){
2806 $value = serialize($value);
2807 if(!function_exists('gzdeflate') || !function_exists('gzinflate')){
2808 return $value;
2809 }
2810 $value = gzdeflate($value);
2811 $value = '**ZIP**'.base64_encode($value);
2812 return $value;
2813 }
2814
2815 function maybe_unserialize_uncompress($value){
2816 if(strpos($value, '**ZIP**') !== false){
2817 $value = gzinflate (base64_decode(str_replace('**ZIP**', '', $value)));
2818 }
2819 return unserialize($value);
2820 }
2821
2822 function getRequiredData($historyID, $field){
2823 global $wpdb;
2824
2825 $allowed_fields = array('requestParams', 'responseParams', 'taskResults', 'category');
2826 if (!in_array($field, $allowed_fields, true)) {
2827 return null;
2828 }
2829
2830 $backupData = $wpdb->get_row(
2831 $wpdb->prepare(
2832 "SELECT {$field} FROM {$wpdb->base_prefix}iwp_backup_status WHERE historyID = %d",
2833 absint($historyID)
2834 )
2835 );
2836 if (($field == 'responseParams') || ($field == 'requestParams') || ($field == 'taskResults')) {
2837 $fieldParams = $this->maybe_unserialize_uncompress($backupData->$field);
2838 } else {
2839 $fieldParams = $backupData->$field;
2840 }
2841 return $fieldParams;
2842 }
2843
2844 function get_all_tasks($isNeedRequestParams =false){
2845 /*global $wpdb;
2846
2847 $stats = array();
2848 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2849
2850 $rows = $wpdb->get_col("SELECT taskResults FROM ".$table_name);
2851 $task_res = array();
2852 foreach($rows as $key => $value){
2853 $task_results = unserialize($value);
2854 if(is_array($task_results['task_results'])){
2855
2856 foreach($task_results['task_results'] as $key => $data){
2857 $task_res['task_results'][$key] = $data;
2858 }
2859 }
2860 }*/
2861
2862 global $wpdb;
2863
2864 $stats = array();
2865 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2866
2867 $rows = $wpdb->get_results("SELECT ID, taskName, taskResults, requestParams FROM ".$table_name." ORDER BY ID DESC", ARRAY_A);
2868 $this->cleanup_failed_backups($rows);
2869 $task_res = array();
2870 foreach($rows as $key => $value){
2871 $task_results = (!empty($value['taskResults']))?unserialize($value['taskResults']):array();
2872 $requestParams = unserialize($value['requestParams']);
2873 if(!empty($task_results['task_results'])){
2874 foreach($task_results['task_results'] as $key => $data){
2875 if ($isNeedRequestParams===true && !empty($requestParams)) {
2876 $task_res[$value['taskName']]['requestParams'][$key] = $requestParams;
2877 }else{
2878 $task_res[$value['taskName']]['task_results'][$key] = $data;
2879 }
2880 }
2881 }
2882 }
2883
2884 return $task_res;
2885 }
2886
2887 function cleanup_failed_backups($rows){
2888 $rowCount = 0;
2889 if (empty($rows) || !is_array($rows)) {
2890 return false;
2891 }
2892 foreach($rows as $key => $value){
2893 $task_results = (!empty($value['taskResults']))?unserialize($value['taskResults']):array();
2894 if(empty($task_results['task_results'])){
2895 if ($rowCount > 0) {
2896 $this->remove_failed_backups($value['ID']);
2897 }
2898 $rowCount++;
2899 continue;
2900 }
2901 $rowCount++;
2902 }
2903 }
2904
2905 function remove_failed_backups($ID){
2906 global $wpdb;
2907 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2908 $delete_query = $wpdb->prepare(
2909 "DELETE FROM {$table_name} WHERE ID = %d",
2910 absint($ID)
2911 );
2912 $deleteRes = $wpdb->query($delete_query);
2913 }
2914
2915 function remove_failed_backups_by_hisID($ID){
2916 global $wpdb;
2917 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2918 $ids = array_map('absint', (array)$ID);
2919 $ids = array_filter($ids, static function ($value) {
2920 return $value > 0;
2921 });
2922 if (empty($ids)) {
2923 return;
2924 }
2925 $placeholders = implode(', ', array_fill(0, count($ids), '%d'));
2926 $delete_query = $wpdb->prepare(
2927 "DELETE FROM {$table_name} WHERE historyID IN ({$placeholders})",
2928 $ids
2929 );
2930 $deleteRes = $wpdb->query($delete_query);
2931 }
2932
2933 function get_this_tasks(){
2934 $this->wpdb_reconnect();
2935
2936 global $wpdb;
2937 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2938 if($GLOBALS['IWP_CLIENT_HISTORY_ID'] != $this -> hisID)
2939 {
2940 $rows = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$table_name." WHERE historyID = %d", $this -> hisID), ARRAY_A);
2941 }
2942 else
2943 {
2944 $rows = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$table_name." WHERE historyID = %d", $GLOBALS['IWP_CLIENT_HISTORY_ID']), ARRAY_A);
2945 }
2946
2947 return $rows;
2948
2949 }
2950
2951 function get_requested_task($ID){
2952 global $wpdb;
2953 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2954
2955 $rows = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$table_name." WHERE historyID = %d ORDER BY ID DESC LIMIT 1", $ID), ARRAY_A);
2956
2957 return $rows;
2958
2959 }
2960
2961 function get_backup_stats()
2962 {
2963 global $wpdb;
2964
2965 $stats = array();
2966 $table_name = $wpdb->base_prefix . "iwp_backup_status";
2967
2968 $rows = $wpdb->get_results("select * from ".$table_name);
2969
2970 $task_res = array();
2971 foreach($rows as $key => $value){
2972 $task_results = unserialize($value->taskResults);
2973 $task_res[$value->taskName][$value->historyID] = $task_results['task_results'][$value->historyID];
2974 $task_res[$value->taskName][$value->historyID]['backhack_status'] = $task_results['backhack_status'];
2975 }
2976
2977
2978 $stats = $task_res;
2979
2980 return $stats;
2981
2982 }
2983
2984
2985 function storeRequestParams($historyID, $requestParams)
2986 {
2987 global $wpdb;
2988 $update = $wpdb->update($wpdb->base_prefix.'iwp_backup_status',array( 'requestParams' => serialize($requestParams), ),array( 'historyID' => $historyID),array('%s'),array('%d'));
2989
2990 }
2991
2992 function statusLog($historyID = '', $statusArray = array(), $params=array())
2993 {
2994 global $wpdb,$insertID;
2995 $this->wpdb_reconnect();
2996 iwp_mmb_create_backup_status_table();
2997 if(empty($historyID))
2998 {
2999 $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' => $params['args']['parentHID'],'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' ) );
3000 if($insert)
3001 {
3002 $insertID = $wpdb->insert_id;
3003 }
3004 }
3005 else if((isset($statusArray['responseParams']))||(isset($statusArray['task_result'])))
3006 {
3007 $update = $wpdb->update($wpdb->base_prefix.'iwp_backup_status',array( 'responseParams' => $this->maybe_serialize_compress($statusArray['responseParams']),'stage' => $statusArray['stage'], 'status' => $statusArray['status'],'statusMsg' => $statusArray['statusMsg'],'taskResults' => isset($statusArray['task_result']) ? serialize($statusArray['task_result']) : serialize(array()), 'lastUpdateTime' => microtime(true)),array( 'historyID' => $historyID),array('%s','%s', '%s', '%s','%s'),array('%d'));
3008 }
3009 else
3010 {
3011 //$responseParams = $this -> getRequiredData($historyID,"responseParams");
3012 $update = $wpdb->update($wpdb->base_prefix.'iwp_backup_status',array('stage' => $statusArray['stage'], 'status' => $statusArray['status'],'statusMsg' => $statusArray['statusMsg'], 'lastUpdateTime' => microtime(true)),array( 'historyID' => $historyID),array( '%s', '%s', '%s'),array('%d'));
3013 }
3014 if( (isset($update)&&($update === false)) || (isset($insert)&&($insert === false)) )
3015 {
3016 //return array('error'=> $statusArray['statusMsg']);
3017 iwp_mmb_response(array('error' => 'MySQL Error: '.$wpdb -> last_error, 'error_code' => 'mysql_error_status_log'), false);
3018 }
3019 if((isset($statusArray['sendResponse']) && $statusArray['sendResponse'] == true) || $statusArray['status'] == 'completed')
3020 {
3021 $returnParams = array();
3022 $returnParams['parentHID'] = $historyID;
3023 $returnParams['backupRowID'] = $insertID;
3024 $returnParams['stage'] = $statusArray['stage'] ;
3025 $returnParams['status'] = $statusArray['status'];
3026 $returnParams['nextFunc'] = isset($statusArray['nextFunc']) ? $statusArray['nextFunc'] : '';
3027 return array('success' => $returnParams);
3028 }
3029 else
3030 {
3031 if($statusArray['status'] == 'error')
3032 {
3033 refresh_iwp_files_db(); //truncating the file list table on error
3034
3035 $returnParams = array();
3036 $returnParams['parentHID'] = $historyID;
3037 $returnParams['backupRowID'] = $insertID;
3038 $returnParams['stage'] = $statusArray['stage'] ;
3039 $returnParams['status'] = $statusArray['status'];
3040 $returnParams['statusMsg'] = $statusArray['statusMsg'];
3041
3042 return array('error'=> $statusArray['statusMsg'], 'error_code' => $statusArray['statusCode']);
3043 }
3044 }
3045 }
3046
3047
3048 function get_backup_settings()
3049 {
3050 $backup_settings = get_option('iwp_client_multi_backup_temp_values');
3051 if (!empty($backup_settings))
3052 return $backup_settings;
3053 else
3054 return false;
3055 }
3056
3057
3058
3059 function cmp($a, $b) {
3060 /* if ($a['size'] == $b['size']) {
3061 return 0;
3062 }
3063 return ($a['size'] < $b['size']) ? -1 : 1; */
3064 return $a['size'] - $b['size'];
3065 }
3066
3067
3068 function task_now($task_name){
3069
3070 $settings = $this->tasks;
3071 if(!array_key_exists($task_name,$settings)){
3072 return array('error' => $task_name." does not exist.", 'error_code' => 'task_name_doesnt_exists');
3073 } else {
3074 $setting = $settings[$task_name];
3075 }
3076
3077 $this->set_backup_task(array(
3078 'task_name' => $task_name,
3079 'args' => $settings[$task_name]['task_args'],
3080 'time' => time()
3081 ));
3082
3083 //Run backup
3084 $result = $this->backup($setting['task_args'], $task_name);
3085
3086 //Check for error
3087 if (is_array($result) && array_key_exists('error', $result)) {
3088 $this->set_backup_task(array(
3089 'task_name' => $task_name,
3090 'args' => $settings[$task_name]['task_args'],
3091 'error' => $result['error']
3092 ));
3093 return $result;
3094 } else {
3095 return $this->get_backup_stats();
3096 }
3097
3098 }
3099
3100
3101 /**
3102 * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
3103 * Assumes that WP_Filesystem() has already been called and setup.
3104 *
3105 * @since 2.5.0
3106 *
3107 * @param string $from source directory
3108 * @param string $to destination directory
3109 * @param array $skip_list a list of files/folders to skip copying
3110 * @return mixed WP_Error on failure, True on success.
3111 */
3112 function iwp_mmb_direct_to_any_copy_dir($from, $to, $skip_list = array() ) {//$from => direct file system, $to => automatic filesystem
3113 global $wp_filesystem;
3114
3115 $wp_temp_direct = new WP_Filesystem_Direct('');
3116
3117
3118 $dirlist = $wp_temp_direct->dirlist($from);
3119
3120 $from = trailingslashit($from);
3121 $to = trailingslashit($to);
3122
3123 $skip_regex = '';
3124 foreach ( (array)$skip_list as $key => $skip_file )
3125 $skip_regex .= preg_quote($skip_file, '!') . '|';
3126
3127 if ( !empty($skip_regex) )
3128 $skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i';
3129
3130 foreach ( (array) $dirlist as $filename => $fileinfo ) {
3131 if ( !empty($skip_regex) )
3132 if ( preg_match($skip_regex, $from . $filename) )
3133 continue;
3134
3135 if ( 'f' == $fileinfo['type'] ) {
3136 if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
3137 // If copy failed, chmod file to 0644 and try again.
3138 $wp_filesystem->chmod($to . $filename, 0644);
3139 if ( ! $this->iwp_mmb_direct_to_any_copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
3140 {
3141 continue;
3142 return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename);
3143 }
3144 }
3145 } elseif ( 'd' == $fileinfo['type'] ) {
3146 if ( !$wp_filesystem->is_dir($to . $filename) ) {
3147 if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
3148 return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename);
3149 }
3150 $result = $this->iwp_mmb_direct_to_any_copy_dir($from . $filename, $to . $filename, $skip_list);
3151 if ( is_wp_error($result) )
3152 return $result;
3153 }
3154 }
3155 return true;
3156 }
3157
3158 function iwp_mmb_direct_to_any_copy($source, $destination, $overwrite = false, $mode = false){
3159 global $wp_filesystem;
3160 if($wp_filesystem->method == 'direct'){
3161 return $wp_filesystem->copy($source, $destination, $overwrite, $mode);
3162 }
3163 elseif($wp_filesystem->method == 'ftpext' || $wp_filesystem->method == 'ftpsockets'){
3164 if ( ! $overwrite && $wp_filesystem->exists($destination) )
3165 return false;
3166 //$content = $this->get_contents($source);
3167 // if ( false === $content)
3168 // return false;
3169
3170 //put content
3171 //$tempfile = wp_tempnam($file);
3172 $source_handle = fopen($source, 'r');
3173 if ( ! $source_handle )
3174 return false;
3175
3176 //fwrite($temp, $contents);
3177 //fseek($temp, 0); //Skip back to the start of the file being written to
3178
3179 $sample_content = fread($source_handle, (1024 * 1024 * 2));//1024 * 1024 * 2 => 2MB
3180 fseek($source_handle, 0); //Skip back to the start of the file being written to
3181
3182 $type = $wp_filesystem->is_binary($sample_content) ? FTP_BINARY : FTP_ASCII;
3183 unset($sample_content);
3184 if($wp_filesystem->method == 'ftpext'){
3185 $ret = @ftp_fput($wp_filesystem->link, $destination, $source_handle, $type);
3186 }
3187 elseif($wp_filesystem->method == 'ftpsockets'){
3188 $wp_filesystem->ftp->SetType($type);
3189 $ret = $wp_filesystem->ftp->fput($destination, $source_handle);
3190 }
3191
3192 fclose($source_handle);
3193 unlink($source);//to immediately save system space
3194 //unlink($tempfile);
3195
3196 $wp_filesystem->chmod($destination, $mode);
3197
3198 return $ret;
3199
3200 //return $this->put_contents($destination, $content, $mode);
3201 }
3202 }
3203
3204
3205
3206 function restore($args)
3207 {
3208 global $wpdb, $wp_filesystem;
3209 if (empty($args)) {
3210 return false;
3211 }
3212
3213 extract($args);
3214 $this->set_resource_limit();
3215
3216 $unlink_file = true; //Delete file after restore
3217
3218 include_once ABSPATH . 'wp-admin/includes/file.php';
3219
3220 //Detect source
3221 if ($backup_url || (isset($manualBackupFile) && !empty($manualBackupFile))) {
3222 //This is for clone (overwrite)
3223 $backup_file = array();
3224 if(!$backup_url) {
3225 $site_url = site_url();
3226 $backup_url = $site_url."/".$manualBackupFile;
3227 }
3228 $backup_url_array = $this->get_files_array_from_iwp_part($backup_url);
3229 if(!is_array($backup_url_array))
3230 {
3231 echo "this backup backup_url - ".$backup_url_array;
3232 $temp_backup_url = $backup_url_array;
3233 $backup_url_array = array();
3234 $backup_url_array[] = $temp_backup_url;
3235 }
3236 foreach($backup_url_array as $key => $single_backup_url)
3237 {
3238 $backup_file[] = download_url($single_backup_url);
3239 if (is_wp_error($backup_file[$key])) {
3240 return array(
3241 'error' => 'Unable to download backup file ('.$backup_file[$key]->get_error_message().')', 'error_code' => 'unable_to_download_backup_file'
3242 );
3243 }
3244 }
3245 $what = 'full';
3246 } else {
3247 //manual restore darkPrince
3248
3249 $tasks = array();
3250 $task = array();
3251
3252 $tasks = $this->get_requested_task($result_id);
3253 $tasks['taskResults'] = unserialize($tasks['taskResults']);
3254
3255 $backup = $tasks['taskResults']['task_results'][$result_id]; //darkCode testing purpose
3256 $hashValues = $backup['hashValues'];
3257 //$backup = $tasks['taskResults'];
3258 $requestParams = unserialize($tasks['requestParams']);
3259 $args = $requestParams['account_info'];
3260 //$task = $tasks['Backup Now'];
3261 if (isset($backup['server'])) {
3262 $backup_file = $backup['server']['file_path'];
3263 $unlink_file = false; //Don't delete file if stored on server
3264 }
3265 elseif (isset($backup['ftp'])) {
3266 $ftp_file = $backup['ftp'];
3267 $args = $args['iwp_ftp'];
3268 if(!is_array($ftp_file))
3269 {
3270 $ftp_file = array();
3271 $ftp_file[0] = $backup['ftp'];
3272 $backup_file = array();
3273 }
3274 foreach($ftp_file as $key => $value)
3275 {
3276 $args['backup_file'] = $value;
3277 iwp_mmb_print_flush('FTP download: Start '.$key);
3278 $backup_file[] = $this->get_ftp_backup($args);
3279 iwp_mmb_print_flush('FTP download: End '.$key);
3280 if ($backup_file[$key] == false) {
3281 return array(
3282 'error' => 'Failed to download file from FTP.', 'error_code' => 'failed_to_download_file_from_ftp'
3283 );
3284 }
3285 }
3286 }
3287 elseif (isset($backup['amazons3'])) {
3288 $amazons3_file = $backup['amazons3'];
3289 $args = $args['iwp_amazon_s3'];
3290 if(!is_array($amazons3_file))
3291 {
3292 $amazons3_file = array();
3293 $amazons3_file[0] = $backup['amazons3'];
3294 $backup_file = array();
3295 }
3296 foreach($amazons3_file as $key => $value)
3297 {
3298 $args['backup_file'] = $value;
3299 iwp_mmb_print_flush('Amazon S3 download: Start '.$key);
3300 if(is_new_s3_compatible()){
3301 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
3302 $new_s3_obj = new IWP_MMB_S3_MULTICALL();
3303 $backup_file[] = $new_s3_obj->get_amazons3_backup($args);
3304 }
3305 else{
3306 $backup_file[] = $this->get_amazons3_backup_bwd_comp($args);
3307 }
3308 iwp_mmb_print_flush('Amazon S3 download: End '.$key);
3309 if ($backup_file[$key] == false) {
3310 return array(
3311 'error' => 'Failed to download file from Amazon S3.', 'error_code' => 'failed_to_download_file_from_s3'
3312 );
3313 }
3314 else if(is_array($backup_file[$key]) && isset($backup_file[$key]['error'])){
3315 return array(
3316 'error' => 'Failed to download file from Amazon S3. Please enable curl first.', 'error_code' => 'failed_to_download_file_from_s3_enable_curl'
3317 );
3318 }
3319 }
3320 }
3321 elseif(isset($backup['dropbox'])){
3322 $dropbox_file = $backup['dropbox'];
3323 $args = $args['iwp_dropbox'];
3324 if(!is_array($dropbox_file))
3325 {
3326 $dropbox_file = array();
3327 $dropbox_file[0] = $backup['dropbox'];
3328 $backup_file = array();
3329 }
3330 foreach($dropbox_file as $key => $value)
3331 {
3332 $args['backup_file'] = $value;
3333 iwp_mmb_print_flush('Dropbox download: Start '.$key);
3334 $backup_file[] = $this->get_dropbox_backup($args);
3335 iwp_mmb_print_flush('Dropbox download: End '.$key);
3336 if ($backup_file[$key] == false) {
3337 return array(
3338 'error' => 'Failed to download file from Dropbox.', 'error_code' => 'failed_to_download_file_from_dropbox'
3339 );
3340 }
3341 else if(is_array($backup_file[$key]) && isset($backup_file[$key]['error'])){
3342 return array(
3343 'error' => 'Failed to download file from Dropbox. Please enable curl first.', 'error_code' => 'failed_to_download_file_from_dbox_enable_curl'
3344 );
3345 }
3346 }
3347
3348 }
3349 elseif(isset($backup['gDrive'])){
3350 $gdrive_file = $backup['gDrive'];
3351 $args = $args['iwp_gdrive'];
3352
3353 if(!is_array($gdrive_file))
3354 {
3355 $gdrive_file = array();
3356 $gdrive_file[0] = $backup['gDrive'];
3357 $backup_file = array();
3358 }
3359 foreach($gdrive_file as $key => $value)
3360 {
3361 $args['backup_file'] = $value;
3362 iwp_mmb_print_flush('gDrive download: Start');
3363 $backup_file[] = $this->get_google_drive_backup($args);
3364 iwp_mmb_print_flush('gDrive download: End');
3365
3366 if(is_array($backup_file[$key]) && array_key_exists('error', $backup_file[$key]))
3367 {
3368 return $backup_file[$key];
3369 }
3370
3371 if ($backup_file[$key] == false) {
3372 return array(
3373 'error' => 'Failed to download file from gDrive.'
3374 );
3375 }
3376 }
3377 }
3378
3379 //$what = $tasks[$task_name]['task_args']['what'];
3380 $what = $requestParams['args']['what'];
3381 }
3382
3383
3384
3385 $this->wpdb_reconnect();
3386
3387 /////////////////// dev ////////////////////////
3388
3389 if (!$this->is_server_writable()) {
3390 return array(
3391 'error' => 'Failed, please add FTP details', 'error_code' => 'failed_please_add_ftp_details'
3392 );
3393 }
3394
3395 $url = wp_nonce_url('index.php?page=iwp_no_page','iwp_fs_cred');
3396 ob_start();
3397 if (false === ($creds = request_filesystem_credentials($url, '', false, ABSPATH, null) ) ) {
3398 return array(
3399 'error' => 'Unable to get file system credentials', 'error_code' => 'unable_to_get_file_system_credentials'
3400 ); // stop processing here
3401 }
3402 ob_end_clean();
3403
3404 if ( ! WP_Filesystem($creds, ABSPATH) ) {
3405 //request_filesystem_credentials($url, '', true, false, null);
3406 return array(
3407 'error' => 'Unable to initiate file system. Please check you have entered valid FTP credentials.', 'error_code' => 'unable_to_initiate_file_system'
3408 ); // stop processing here
3409 //return;
3410 }
3411
3412 require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');//will be used to copy from temp directory
3413
3414 // do process
3415 //$temp_dir = get_temp_dir();
3416 $temp_dir = IWP_PCLZIP_TEMPORARY_DIR;
3417
3418
3419
3420 if(file_exists(IWP_PCLZIP_TEMPORARY_DIR) && is_dir(IWP_PCLZIP_TEMPORARY_DIR))
3421 {
3422 //
3423 }
3424 else
3425 {
3426 if(file_exists(dirname(IWP_PCLZIP_TEMPORARY_DIR)) && is_dir(dirname(IWP_PCLZIP_TEMPORARY_DIR))){
3427 @mkdir(IWP_PCLZIP_TEMPORARY_DIR, 0755, true);
3428 }
3429 else{
3430 @mkdir(dirname(IWP_PCLZIP_TEMPORARY_DIR), 0755, true);
3431 @mkdir(IWP_PCLZIP_TEMPORARY_DIR, 0755, true);
3432 }
3433
3434 }
3435 if(is_writable(IWP_PCLZIP_TEMPORARY_DIR))
3436 {
3437 @file_put_contents(IWP_PCLZIP_TEMPORARY_DIR . '/index.php', ''); //safe
3438 }
3439 else
3440 {
3441 $chmod = chmod(IWP_PCLZIP_TEMPORARY_DIR, 777);
3442 if(is_writable(IWP_PCLZIP_TEMPORARY_DIR)){
3443 @file_put_contents(IWP_PCLZIP_TEMPORARY_DIR . '/index.php', ''); //safe
3444 }
3445
3446 }
3447
3448 if(is_writable(IWP_PCLZIP_TEMPORARY_DIR))
3449 {
3450 $temp_dir = IWP_PCLZIP_TEMPORARY_DIR;
3451 }
3452 else{
3453 $temp_dir = get_temp_dir();
3454 if(!is_writable($temp_dir)){
3455 return array(
3456 'error' => 'Temporary directory is not writable. Please set 777 permission for '.IWP_PCLZIP_TEMPORARY_DIR.' and try again.', 'error_code' => 'pclzip_temp_dir_not_writable_please_set_777'
3457 );
3458 }
3459 }
3460
3461
3462
3463 $new_temp_folder = untrailingslashit($temp_dir);
3464 $temp_uniq = md5(microtime(1));//should be random
3465 while (is_dir($new_temp_folder .'/'. $temp_uniq )) {
3466 $temp_uniq = md5(microtime(1));
3467 }
3468 $new_temp_folder = trailingslashit($new_temp_folder .'/'. $temp_uniq);
3469 $is_dir_created = mkdir($new_temp_folder);// new folder should be empty
3470 if(!$is_dir_created){
3471 return array(
3472 'error' => 'Unable to create a temporary directory.', 'error_code' => 'unable_to_create_temporary_directory'
3473 );
3474 }
3475
3476
3477 $remote_abspath = $wp_filesystem->abspath();
3478 if(!empty($remote_abspath)){
3479 $remote_abspath = trailingslashit($remote_abspath);
3480 }else{
3481 return array(
3482 'error' => 'Unable to locate WP root directory using file system.', 'error_code' => 'unable_to_locate_wp_root_directory_using_file_system'
3483 );
3484 }
3485
3486 //global $wp_filesystem;
3487 // $wp_filesystem->put_contents(
3488 // '/tmp/example.txt',
3489 // 'Example contents of a file',
3490 // FS_CHMOD_FILE // predefined mode settings for WP files
3491 // );
3492
3493 /////////////////// dev ////////////////////////
3494
3495 //if ($backup_file && file_exists($backup_file)) {
3496 if ($backup_file) {
3497 if ($overwrite)
3498 { //clone only fresh or existing to existing
3499 //Keep old db credentials before overwrite
3500 if (!$wp_filesystem->copy($remote_abspath . 'wp-config.php', $remote_abspath . 'iwp-temp-wp-config.php', true)) {
3501 if($unlink_file)
3502 {
3503 if(!is_array($backup_file))
3504 {
3505 $temp_backup_file = $backup_file;
3506 $backup_file = array();
3507 $backup_file = $temp_backup_file;
3508 }
3509 foreach($backup_file as $k => $value)
3510 {
3511 @unlink($value);
3512 }
3513 }
3514 return array(
3515 'error' => 'Error creating wp-config. Please check your write permissions.', 'error_code' => 'error_creating_wp_config'
3516 );
3517 }
3518
3519 $db_host = DB_HOST;
3520 $db_user = DB_USER;
3521 $db_password = DB_PASSWORD;
3522 $home = rtrim(get_option('home'), "/");
3523 $site_url = get_option('site_url');
3524
3525 $clone_options = array();
3526 if (trim($clone_from_url) || trim($iwp_clone) || trim($maintain_old_key)) {
3527
3528 $clone_options['iwp_client_nossl_key'] = get_option('iwp_client_nossl_key');
3529 $clone_options['iwp_client_public_key'] = get_option('iwp_client_public_key');
3530 $clone_options['iwp_client_action_message_id'] = get_option('iwp_client_action_message_id');
3531
3532 }
3533
3534 //$clone_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_multi_backup_temp_values'));
3535 $clone_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
3536 $clone_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
3537
3538 $qry = "SELECT * FROM ".$wpdb->base_prefix."iwp_backup_status";
3539 $clone_options['iwp_client_backup_tasks'] = $wpdb->get_results($qry, ARRAY_A);
3540
3541 /*if(!$clone_options['iwp_client_backup_tasks'])
3542 {
3543 return array(
3544 'error' => 'Unable to restore clone options.'
3545 );
3546 }*/
3547
3548 }
3549 else {
3550 $restore_options = array();
3551 $restore_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
3552 $restore_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
3553 $restore_options['iwp_client_user_hit_count'] = serialize(get_option('iwp_client_user_hit_count'));
3554 //$restore_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_multi_backup_temp_values'));
3555
3556 $qry = "SELECT * FROM ".$wpdb->base_prefix."iwp_backup_status";
3557 $restore_options['iwp_client_backup_tasks'] = $wpdb->get_results($qry, ARRAY_A);
3558
3559 /*if(!$restore_options['iwp_client_backup_tasks'])
3560 {
3561 return array(
3562 'error' => 'Unable to restore options.'
3563 );
3564 }*/
3565
3566 }
3567
3568 //Backup file will be extracted to a temporary path
3569 if(!is_array($backup_file))
3570 {
3571 $temp_backup_file = $backup_file;
3572 $backup_file = array();
3573 $backup_file[0] = $temp_backup_file;
3574 }
3575 foreach($backup_file as $single_backup_file)
3576 {
3577 echo "this backup file - ".$single_backup_file;
3578 //chdir(ABSPATH);
3579 $unzip = $this->get_unzip();
3580 $command = "$unzip -o $single_backup_file -d $new_temp_folder";
3581 iwp_mmb_print_flush('ZIP Extract CMD: Start');
3582 ob_start();
3583 $result = $this->iwp_mmb_exec($command);
3584 //$result = false;
3585 ob_get_clean();
3586 iwp_mmb_print_flush('ZIP Extract CMD: End');
3587
3588 if (!$result) { //fallback to pclzip
3589 ////define('IWP_PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
3590 //require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
3591 //require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
3592 iwp_mmb_print_flush('ZIP Extract PCL: Start');
3593 $archive = new IWPPclZip($single_backup_file);
3594 $result = $archive->extract(IWP_PCLZIP_OPT_PATH, $new_temp_folder, IWP_PCLZIP_OPT_REPLACE_NEWER);
3595 iwp_mmb_print_flush('ZIP Extract PCL: End');
3596 }
3597
3598 $this->wpdb_reconnect();
3599 if ($unlink_file) {
3600 @unlink($single_backup_file);
3601 }
3602
3603 if (!$result) {
3604 if ($unlink_file) {
3605 foreach($backup_file as $single_file)
3606 {
3607 @unlink($single_file);
3608 }
3609 }
3610 return array(
3611 'error' => 'Failed to unzip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string, 'error_code' => 'failed_to_unzip_files'
3612 );
3613 }
3614
3615 }
3616
3617 //appending files if split is done
3618 $joinedFilesArray = $this -> appendSplitFiles($new_temp_folder);
3619 //$compareHashValuesArray = $this -> compareHashValues($joinedFilesArray['orgHash'], $joinedFilesArray['afterSplitHash']);
3620
3621 //do the restore db part only if the category is full or db .. else skip it for files alone concept
3622 if(($what == 'full')||($what == 'db'))
3623 {
3624 $db_result = $this->restore_db($new_temp_folder);
3625
3626 if (!$db_result) {
3627 return array(
3628 'error' => 'Error restoring database.', 'error_code' => 'error_restoring_database'
3629 );
3630 } else if(is_array($db_result) && isset($db_result['error'])){
3631 return array(
3632 'error' => $db_result['error']
3633 );
3634 }
3635 }
3636
3637 }
3638 else {
3639 return array(
3640 'error' => 'Backup file not found.', 'error_code' => 'backup_file_not_found'
3641 );
3642 }
3643 $bError = error_get_last();
3644
3645
3646 //copy files from temp to ABSPATH
3647 $copy_result = $this->iwp_mmb_direct_to_any_copy_dir($new_temp_folder, $remote_abspath);
3648
3649 if ( is_wp_error($copy_result) ){
3650 $wp_temp_direct2 = new WP_Filesystem_Direct('');
3651 $wp_temp_direct2->delete($new_temp_folder, true);
3652 return $copy_result;
3653 }
3654
3655
3656 $this->wpdb_reconnect();
3657
3658
3659
3660 //Replace options and content urls
3661 if ($overwrite) {//fresh WP package or existing to existing site
3662 //Get New Table prefix
3663 $new_table_prefix = trim($this->get_table_prefix());
3664 //Retrieve old wp_config
3665 //@unlink(ABSPATH . 'wp-config.php');
3666 $wp_filesystem->delete($remote_abspath . 'wp-config.php', false, 'f');
3667 //Replace table prefix
3668 //$lines = file(ABSPATH . 'iwp-temp-wp-config.php');
3669 $lines = $wp_filesystem->get_contents_array($remote_abspath . 'iwp-temp-wp-config.php');
3670
3671 $new_lines = '';
3672 foreach ($lines as $line) {
3673 if (strstr($line, '$table_prefix')) {
3674 $line = '$table_prefix = "' . $new_table_prefix . '";' . PHP_EOL;
3675 }
3676 $new_lines .= $line;
3677 //file_put_contents(ABSPATH . 'wp-config.php', $line, FILE_APPEND);
3678 }
3679
3680 $wp_filesystem->put_contents($remote_abspath . 'wp-config.php', $new_lines);
3681
3682 //@unlink(ABSPATH . 'iwp-temp-wp-config.php');
3683 $wp_filesystem->delete($remote_abspath . 'iwp-temp-wp-config.php', false, 'f');
3684
3685 //Replace options
3686 $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
3687 $old = $wpdb->get_var($query);
3688 $old = rtrim($old, "/");
3689 $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'home'";
3690 $wpdb->query($wpdb->prepare($query, $home));
3691 $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'siteurl'";
3692 $wpdb->query($wpdb->prepare($query, $home));
3693 //Replace content urls
3694
3695 $regexp1 = 'src="(.*)'.$old.'(.*)"';
3696 $regexp2 = 'href="(.*)'.$old.'(.*)"';
3697 $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, %s,%s) WHERE post_content REGEXP %s OR post_content REGEXP %s";
3698 $wpdb->query($wpdb->prepare($query, $old, $home, $regexp1, $regexp2));
3699
3700 if (trim($new_password)) {
3701 $new_password = wp_hash_password($new_password);
3702 }
3703 if (!trim($clone_from_url) && !trim($iwp_clone)) {
3704 if ($new_user && $new_password) {
3705 $query = "UPDATE " . $new_table_prefix . "users SET user_login = %s, user_pass = %s WHERE user_login = %s";
3706 $wpdb->query($wpdb->prepare($query, $new_user, $new_password, $old_user));
3707 }
3708 } else {
3709
3710 // if ($iwp_clone) {
3711 if ($admin_email) {
3712 //Clean Install
3713 $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'admin_email'";
3714 $wpdb->query($wpdb->prepare($query, $admin_email));
3715 $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
3716 $temp_user = $wpdb->get_row($query);
3717 if (!empty($temp_user)) {
3718 $query = "UPDATE " . $new_table_prefix . "users SET user_email=%s, user_login = %s, user_pass = %s WHERE user_login = %s";
3719 $wpdb->query($wpdb->prepare($query, $admin_email, $new_user, $new_password, $temp_user->user_login));
3720 }
3721
3722 }
3723 // }
3724
3725 //if ($clone_from_url) {
3726 if ($new_user && $new_password) {
3727 $query = "UPDATE " . $new_table_prefix . "users SET user_pass = %s WHERE user_login = %s";
3728 $wpdb->query($wpdb->prepare($query, $new_password, $new_user));
3729 }
3730 // }
3731
3732 }
3733
3734 if (is_array($clone_options) && !empty($clone_options)) {
3735
3736 $GLOBALS['table_prefix'] = $new_table_prefix;
3737
3738 $this->clone_restore_options($clone_options);
3739
3740 if(!empty($clone_options['iwp_client_nossl_key'])){
3741
3742 $query = "SELECT * FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_nossl_key'";
3743 $temp_row = $wpdb->get_row($query);
3744 if (!empty($temp_row)) {
3745 $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'iwp_client_nossl_key'";
3746 $wpdb->query($wpdb->prepare($query, $clone_options['iwp_client_nossl_key']));
3747 } else {
3748 $insert = $wpdb->insert($new_table_prefix."options",array( 'option_name' => 'iwp_client_nossl_key', 'option_value' => $clone_options['iwp_client_nossl_key'], 'autoload' => 'yes'), array( '%s', '%s','%s') );
3749 }
3750 }
3751
3752 if(!empty($clone_options['iwp_client_public_key'])){
3753
3754 $query = "SELECT * FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_public_key'";
3755 $temp_row = $wpdb->get_row($query);
3756 if (!empty($temp_row)) {
3757 $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'iwp_client_public_key'";
3758 $wpdb->query($wpdb->prepare($query, $clone_options['iwp_client_public_key']));
3759 } else {
3760 $insert = $wpdb->insert($new_table_prefix."options",array( 'option_name' => 'iwp_client_public_key', 'option_value' => $clone_options['iwp_client_public_key'], 'autoload' => 'yes'), array( '%s', '%s','%s') );
3761 }
3762 }
3763 }
3764 $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
3765 $temp_user = $wpdb->get_row($query);
3766 $new_user = $temp_user->user_login;
3767
3768 //Remove hit count
3769 $query = "DELETE FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_user_hit_count'";
3770 $wpdb->query($query);
3771
3772 //Check for .htaccess permalinks update
3773 $this->replace_htaccess($home, $remote_abspath);
3774 }
3775 else {
3776 //restore client options
3777 if (is_array($restore_options) && !empty($restore_options)) {
3778
3779 $GLOBALS['table_prefix'] = $wpdb->base_prefix;
3780 $this->clone_restore_options($restore_options);
3781 }
3782 }
3783
3784 //clear the temp directory
3785 $wp_temp_direct2 = new WP_Filesystem_Direct('');
3786 $wp_temp_direct2->delete($new_temp_folder, true);
3787
3788 return !empty($new_user) ? $new_user : true ;
3789 }
3790
3791
3792 function clone_restore_options($clone_restore_options){
3793 global $wpdb;
3794
3795 $table = $GLOBALS['table_prefix'].'iwp_backup_status';
3796 $wpdb->query("SHOW TABLES LIKE '".$table."'");
3797 if($wpdb->num_rows == 1){
3798 $delete = $wpdb->query("DROP TABLE '".$table."' ");
3799 }
3800
3801 iwp_mmb_backup_db_changes();
3802
3803 if(!empty($clone_restore_options['iwp_client_backup_tasks'])){
3804 $this->insertBackupStatusContens($clone_restore_options['iwp_client_backup_tasks']);
3805 }
3806
3807 return true;
3808 }
3809
3810
3811 function insertBackupStatusContens($dataContent){
3812 global $wpdb;
3813
3814 $table = $GLOBALS['table_prefix'].'iwp_backup_status';
3815 if(!empty($dataContent)){
3816 foreach($dataContent as $key => $value){
3817 $insert = $wpdb->insert($table,array( 'ID' => $value['stage'], 'historyID' => $value['historyID'], 'taskName' => $value['taskName'], 'action' => $value['action'],'type' => $value['type'], 'category' => $value['category'], 'stage' => $value['stage'],'status' => $value['status'],'finalStatus' => $value['finalStatus'],'statusMsg' => $value['statusMsg'],'requestParams' => $value['requestParams'],'responseParams' => $value['responseParams'], 'taskResults' => $value['taskResults'], 'startTime' => $value['startTime'], 'endTime' => $value['endTime']), array( '%d', '%d','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d' ) );
3818
3819 }
3820 }
3821 }
3822
3823 function compareHashValues($joinedFilesArray, $hashValues)
3824 {
3825 $filesWithChangedHash = array();
3826 foreach($hashValues as $key => $value)
3827 {
3828 foreach($joinedFilesArray as $k => $v)
3829 {
3830
3831 $pos = strpos($k, $key);
3832 if($pos !== false)
3833 {
3834 if($value != $v)
3835 {
3836 $filesWithChangedHash[$k] = $key;
3837 }
3838 break;
3839 }
3840 }
3841 }
3842 return $filesWithChangedHash;
3843 }
3844
3845 function appendSplitFiles($fileToAppend)
3846 {
3847 // function to join the split files during multicall backup
3848 $directory_tree = get_all_files_from_dir($fileToAppend);
3849 usort($directory_tree, array($this, "sortString"));
3850
3851 $joinedFilesArray = array();
3852 $orgHashValues = array();
3853 $hashValue = '';
3854
3855 foreach($directory_tree as $k => $v)
3856 {
3857 $contents = '';
3858 $orgFileCount = 0;
3859 /* $subject = $v;
3860 $pattern = '/iwp_part/i';
3861 preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
3862 print_r($matches); */
3863 $pos = strpos($v, 'iwp_part');
3864 if($pos !== false)
3865 {
3866 $currentFile = explode(".",$v);
3867 $currentFileSize = count($currentFile);
3868 foreach($currentFile as $key => $val)
3869 {
3870 if(($key == ($currentFileSize-2))||($currentFileSize == 1))
3871 {
3872 $insPos = strpos($val, '_iwp_part');
3873 $rest = substr_replace($val, '', $insPos);
3874 $currentFile[$key] = $rest;
3875
3876 $insPos2 = strpos($rest, '_iwp_hash');
3877 if($insPos2 !== false)
3878 {
3879 $hashInitialPoint = strrpos($rest, "_iwp_hash");
3880 $hashValue = substr($rest, $hashInitialPoint+10);
3881 //$hashValue = substr($rest, -32);
3882 $rest = substr_replace($rest, '', $insPos2);
3883 $currentFile[$key] = $rest;
3884 }
3885 }
3886 }
3887 $orgFileCount++;
3888 $orgFileName = implode(".", $currentFile);
3889 $handle = fopen($v,"r");
3890 $contents = fread($handle, iwp_mmb_get_file_size($v));
3891 fclose($handle);
3892 if($orgFileCount == 1)
3893 {
3894 //clearing contents of file intially to prevent appending to already existing file
3895 //file_put_contents($orgFileName,'',FILE_APPEND);
3896 }
3897 file_put_contents($orgFileName,$contents,FILE_APPEND);
3898 $joinedFilesArray[$orgFileName] = 'hash';
3899 $orgHashValues[$orgFileName] = $hashValue;
3900 echo " orgFileName - ".$orgFileName;
3901 $file_to_ulink = realpath($v);
3902 $resultUnlink = unlink($file_to_ulink);
3903 $resultUnlink = error_get_last();
3904 if(!$resultUnlink)
3905 {
3906 if(is_file($v))
3907 {
3908 unlink($file_to_ulink);
3909 }
3910 }
3911
3912
3913 }
3914 }
3915 $hashValues = array();
3916 foreach($joinedFilesArray as $key => $value)
3917 {
3918 //$hashValues[$key] = md5_file($key);
3919 $hashValues[$key] = 'hash';
3920 }
3921 $totalHashValues = array();
3922 $totalHashValues['orgHash'] = $orgHashValues;
3923 $totalHashValues['afterSplitHash'] = $hashValues;
3924 return $totalHashValues;
3925 }
3926
3927 function sortString($a, $b)
3928 {
3929 // the uSort CallBack Function used in the appendSplitFiles function
3930 $stringArr = array();
3931 $stringArr[0] = $a;
3932 $stringArr[1] = $b;
3933 $strA = '';
3934 $strB = '';
3935 foreach($stringArr as $strKey => $strVal)
3936 {
3937 $mystring = $strVal;
3938 $findme = '_iwp_part'; //fileNameSplit logic
3939 $pos = strpos($mystring, $findme);
3940 $rest = substr($mystring, $pos);
3941 $pos2 = strrpos($rest, $findme);
3942 $len = strlen($rest);
3943 $actLen = $pos2+strlen($findme);
3944 $actPos = $len - $actLen -1;
3945 $actPartNum = substr($rest, -($actPos));
3946 $actPartNumArray = explode(".",$actPartNum);
3947 foreach($actPartNumArray as $key => $val)
3948 {
3949 if($key == 0)
3950 $actPartNum = $val;
3951 }
3952 if($strKey == 0)
3953 $strA = intval($actPartNum);
3954 else
3955 $strB = intval($actPartNum);
3956 }
3957 if ($strA == $strB){return 0;}
3958 return ($strA < $strB) ? -1 : 1;
3959 }
3960
3961 function restore_db($new_temp_folder)
3962 {
3963 global $wpdb;
3964 $paths = $this->check_mysqli_paths();
3965 $file_path = $new_temp_folder . '/iwp_db';
3966 @chmod($file_path,0755);
3967 $file_name = glob($file_path . '/*.sql');
3968 $file_name = $file_name[0];
3969
3970 if(!$file_name){
3971 return array('error' => 'Cannot access database file.');
3972 }
3973
3974 $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
3975 $command = $brace . $paths['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --default-character-set="utf8" ' . DB_NAME . ' < ' . $brace . $file_name . $brace;
3976 iwp_mmb_print_flush('DB Restore CMD: Start');
3977 ob_start();
3978 $result = $this->iwp_mmb_exec($command);
3979 ob_get_clean();
3980 iwp_mmb_print_flush('DB Restore CMD: End');
3981 if (!$result) {
3982 //try php
3983 $this->restore_db_php($file_name);
3984 }
3985
3986
3987 @unlink($file_name);
3988 @unlink(dirname($file_name).'/index.php');
3989 @rmdir(dirname($file_name));//remove its folder
3990 return true;
3991 }
3992
3993
3994
3995
3996 function restore_db_php($file_name)
3997 {
3998
3999 $this->wpdb_reconnect();
4000 global $wpdb;
4001
4002 $wpdb->query("SET NAMES 'utf8'");
4003
4004 $current_query = '';
4005 // Read in entire file
4006 $lines = file($file_name);
4007 // Loop through each line
4008 if(!empty($lines)){
4009 foreach ($lines as $line) {
4010 iwp_mmb_auto_print('restore_db_php');
4011 // Skip it if it's a comment
4012 if(substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 3) == '/*!')
4013 continue;
4014
4015 // Add this line to the current query
4016 $current_query .= $line;
4017 // If it has a semicolon at the end, it's the end of the query
4018 if (substr(trim($line), -1, 1) == ';') {
4019 // Perform the query
4020 $result = $wpdb->query($current_query);
4021 if ($result === false)
4022 return false;
4023 // Reset temp variable to empty
4024 $current_query = '';
4025 }
4026 }
4027 }
4028
4029 return true;
4030 }
4031
4032 function get_table_prefix()
4033 {
4034 $lines = file(ABSPATH . 'wp-config.php');
4035 foreach ($lines as $line) {
4036 if (strstr($line, '$table_prefix')) {
4037 $pattern = "/(\'|\")[^(\'|\")]*/";
4038 preg_match($pattern, $line, $matches);
4039 $prefix = substr($matches[0], 1);
4040 return $prefix;
4041 break;
4042 }
4043 }
4044 return 'wp_'; //default
4045 }
4046
4047 function optimize_tables()
4048 {
4049 global $wpdb;
4050 $query = 'SHOW TABLE STATUS';
4051 $tables = $wpdb->get_results($query, ARRAY_A);
4052 $table_string = '';
4053 foreach ($tables as $table) {
4054 if (in_array($table['Engine'], array(
4055 'MyISAM',
4056 'ISAM',
4057 'HEAP',
4058 'MEMORY',
4059 'ARCHIVE'
4060 )))
4061 $table_string .= $table['Name'] . ",";
4062 elseif ($table['Engine'] == 'InnoDB') {
4063 $optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
4064 }
4065 }
4066
4067 if(!empty($table_string)){
4068 $table_string = rtrim($table_string, ',');
4069 $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
4070 }
4071
4072 return $optimize ? true : false;
4073 }
4074
4075 ### Function: Auto Detect MYSQL and MYSQL Dump Paths
4076 function check_mysqli_paths()
4077 {
4078 global $wpdb;
4079 $paths = array(
4080 'mysql' => '',
4081 'mysqldump' => ''
4082 );
4083 if (substr(PHP_OS, 0, 3) == 'WIN') {
4084 $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
4085 if ($mysql_install) {
4086 $install_path = str_replace('\\', '/', $mysql_install->Value);
4087 $paths['mysql'] = $install_path . 'bin/mysql.exe';
4088 $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
4089 } else {
4090 $paths['mysql'] = 'mysql.exe';
4091 $paths['mysqldump'] = 'mysqldump.exe';
4092 }
4093 } else {
4094 $paths['mysql'] = $this->iwp_mmb_exec('which mysql', true);
4095 if (empty($paths['mysql']))
4096 $paths['mysql'] = 'mysql'; // try anyway
4097
4098 $paths['mysqldump'] = $this->iwp_mmb_exec('which mysqldump', true);
4099 if (empty($paths['mysqldump']))
4100 $paths['mysqldump'] = 'mysqldump'; // try anyway
4101
4102 }
4103
4104
4105 return $paths;
4106 }
4107
4108 //Check if exec, system, passthru functions exist
4109 function check_sys()
4110 {
4111 if ($this->iwp_mmb_function_exists('exec'))
4112 return 'exec';
4113
4114 if ($this->iwp_mmb_function_exists('system'))
4115 return 'system';
4116
4117 if ($this->iwp_mmb_function_exists('passthru'))
4118 return 'passthru';
4119
4120 return false;
4121
4122 }
4123
4124 function iwp_mmb_exec($command, $string = false, $rawreturn = false)
4125 {
4126 if ($command == '')
4127 return false;
4128
4129 if ($this->iwp_mmb_function_exists('exec')) {
4130 $log = @exec($command, $output, $return);
4131
4132 if ($string)
4133 return $log;
4134 if ($rawreturn)
4135 return $return;
4136
4137 return $return ? false : true;
4138 } elseif ($this->iwp_mmb_function_exists('system')) {
4139 $log = @system($command, $return);
4140
4141 if ($string)
4142 return $log;
4143
4144 if ($rawreturn)
4145 return $return;
4146
4147 return $return ? false : true;
4148 } elseif ($this->iwp_mmb_function_exists('passthru') && !$string) {
4149 $log = passthru($command, $return);
4150
4151 if ($rawreturn)
4152 return $return;
4153
4154 return $return ? false : true;
4155 }
4156
4157 if ($rawreturn)
4158 return -1;
4159
4160 return false;
4161 }
4162
4163 function get_zip()
4164 {
4165 $zip = $this->iwp_mmb_exec('which zip', true);
4166 if (!$zip)
4167 $zip = "zip";
4168 return $zip;
4169 }
4170
4171 function get_unzip()
4172 {
4173 $unzip = $this->iwp_mmb_exec('which unzip', true);
4174 if (!$unzip)
4175 $unzip = "unzip";
4176 return $unzip;
4177 }
4178
4179 function check_backup_compat()
4180 {
4181 $reqs = array();
4182 if (strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0) {
4183 $reqs['Server OS']['status'] = 'Linux (or compatible)';
4184 $reqs['Server OS']['pass'] = true;
4185 } else {
4186 $reqs['Server OS']['status'] = 'Windows';
4187 $reqs['Server OS']['pass'] = true;
4188 $pass = false;
4189 }
4190 $reqs['PHP Version']['status'] = phpversion();
4191 if ((float) phpversion() >= 5.1) {
4192 $reqs['PHP Version']['pass'] = true;
4193 } else {
4194 $reqs['PHP Version']['pass'] = false;
4195 $pass = false;
4196 }
4197
4198
4199 if (is_writable(WP_CONTENT_DIR)) {
4200 $reqs['Backup Folder']['status'] = "writable";
4201 $reqs['Backup Folder']['pass'] = true;
4202 } else {
4203 $reqs['Backup Folder']['status'] = "not writable";
4204 $reqs['Backup Folder']['pass'] = false;
4205 }
4206
4207
4208 $file_path = IWP_BACKUP_DIR;
4209 $reqs['Backup Folder']['status'] .= ' (' . $file_path . ')';
4210
4211 if ($func = $this->check_sys()) {
4212 $reqs['Execute Function']['status'] = $func;
4213 $reqs['Execute Function']['pass'] = true;
4214 } else {
4215 $reqs['Execute Function']['status'] = "not found";
4216 $reqs['Execute Function']['info'] = "(will try PHP replacement)";
4217 $reqs['Execute Function']['pass'] = false;
4218 }
4219 $reqs['Zip']['status'] = $this->get_zip();
4220
4221 $reqs['Zip']['pass'] = true;
4222
4223
4224
4225 $reqs['Unzip']['status'] = $this->get_unzip();
4226
4227 $reqs['Unzip']['pass'] = true;
4228
4229 $paths = $this->check_mysqli_paths();
4230
4231 if (!empty($paths['mysqldump'])) {
4232 $reqs['MySQL Dump']['status'] = $paths['mysqldump'];
4233 $reqs['MySQL Dump']['pass'] = true;
4234 } else {
4235 $reqs['MySQL Dump']['status'] = "not found";
4236 $reqs['MySQL Dump']['info'] = "(will try PHP replacement)";
4237 $reqs['MySQL Dump']['pass'] = false;
4238 }
4239
4240 $exec_time = ini_get('max_execution_time');
4241 $reqs['Execution time']['status'] = $exec_time ? $exec_time . "s" : 'unknown';
4242 $reqs['Execution time']['pass'] = true;
4243
4244 $mem_limit = ini_get('memory_limit');
4245 $reqs['Memory limit']['status'] = $mem_limit ? $mem_limit : 'unknown';
4246 $reqs['Memory limit']['pass'] = true;
4247
4248
4249 return $reqs;
4250 }
4251
4252 function ftp_backup($historyID,$args = '')
4253 {
4254 //getting the settings
4255 $this -> backup_settings_vals = get_option('iwp_client_multi_backup_temp_values');
4256 $current_file_num = 0;
4257 if($args == '')
4258 {
4259
4260 $responseParams = $this -> getRequiredData($historyID,"responseParams");
4261
4262 if(!$responseParams)
4263 return $this->statusLog($this -> hisID, array('stage' => 'UploadbackupFiles', 'status' => 'error', 'statusMsg' => 'FTP Backup failed: Error while fetching table data', 'statusCode' => 'ftp_backup_failed_error_while_fetching_table_data'));
4264
4265 $args = $responseParams['ftpArgs'];
4266 $current_file_num = $responseParams['current_file_num'];
4267 }
4268 $tempArgs = $args;
4269 extract($args);
4270 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder, $ftp_site_folderb
4271 $port = $ftp_port ? $ftp_port : 21; //default port is 21
4272 if (!empty($ftp_ssl)) {
4273 if (function_exists('ftp_ssl_connect')) {
4274 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
4275 if ($conn_id === false) {
4276 return array(
4277 'error' => 'Failed to connect to ' . $ftp_hostname,
4278 'partial' => 1, 'error_code' => 'failed_to_connect_to_hostname_ftp_ssl_connect'
4279 );
4280 }
4281 } else {
4282 return array(
4283 'error' => 'Your server doesn\'t support FTP SSL',
4284 'partial' => 1, 'error_code' => 'your_server_doesnt_support_ftp_ssl'
4285 );
4286 }
4287 }
4288 else {
4289 if (function_exists('ftp_connect')) {
4290 $conn_id = ftp_connect($ftp_hostname,$port);
4291 if ($conn_id === false) {
4292 return array(
4293 'error' => 'Failed to connect to ' . $ftp_hostname,
4294 'partial' => 1, 'error_code' => 'failed_to_connect_hostname_ftp_connect'
4295 );
4296 }
4297 } else {
4298 return array(
4299 'error' => 'Your server doesn\'t support FTP',
4300 'partial' => 1, 'error_code' => 'your_server_doesnt_support_ftp'
4301 );
4302 }
4303 }
4304
4305 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
4306 if ($login === false) {
4307 return array(
4308 'error' => 'FTP user name and password invalid',
4309 'partial' => 1, 'error_code' => 'ftp_login_failed'
4310 );
4311 }
4312
4313 if(!empty($ftp_passive)){
4314 @ftp_pasv($conn_id,true);
4315 }
4316
4317
4318
4319 @ftp_mkdir($conn_id, $ftp_remote_folder);
4320 if (!empty($ftp_site_folder)) {
4321 $ftp_remote_folder .= '/' . $this->site_name;
4322 }
4323 @ftp_mkdir($conn_id, $ftp_remote_folder);
4324
4325 //$upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
4326 if(!is_array($backup_file))
4327 {
4328 $temp_backup_file = $backup_file;
4329 $backup_file = array();
4330 $backup_file[] = $temp_backup_file;
4331 }
4332
4333 if(is_array($backup_file))
4334 {
4335 $backup_file_base_name = basename($backup_file[$current_file_num]);
4336 }
4337 else
4338 {
4339 $backup_file_base_name = basename($backup_file);
4340 }
4341
4342 $upload = $this -> ftp_multi_upload($conn_id, rtrim($ftp_remote_folder, '/') . '/' . basename($backup_file_base_name), $backup_file, FTP_BINARY, $historyID, $tempArgs, $current_file_num);
4343
4344
4345 if ($upload === false) { //Try ascii
4346 //$upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_ASCII); //darkCode testing purpose
4347 }
4348
4349 @ftp_close($conn_id);
4350
4351 if ($upload === false) {
4352 return array(
4353 'error' => 'Failed to upload file to FTP. Please check your specified path.',
4354 'partial' => 1, 'error_code' => 'failed_to_upload_file_to_ftp'
4355 );
4356 }
4357
4358 return $upload;
4359 }
4360
4361
4362 function ftp_multi_upload($conn_id, $remoteFileName, $backup_file, $mode, $historyID, $tempArgs, $current_file_num = 0)
4363 {
4364 $requestParams = $this->getRequiredData($historyID, "requestParams");
4365 $task_result = $this->getRequiredData($historyID, "taskResults");
4366
4367 if(!$remoteFileName)
4368 {
4369 return array(
4370 'error' => 'Failed to upload file to FTP. Please check your specified path.',
4371 'partial' => 1, 'error_code' => 'failed_to_upload_file_to_ftp'
4372 );
4373 }
4374
4375 $backup_files_base_name = array();
4376 if(is_array($backup_file))
4377 {
4378 foreach($backup_file as $value)
4379 {
4380 $backup_files_base_name[] = basename($value);
4381 }
4382 }
4383 else
4384 {
4385 $backup_files_base_name = basename($backup_file);
4386 }
4387
4388 $backup_files_count = count($backup_file);
4389
4390 if(is_array($backup_file))
4391 {
4392 $backup_file = $backup_file[$current_file_num];
4393 }
4394
4395
4396 $task_result['task_results'][$historyID]['ftp'] = $backup_files_base_name;
4397 $task_result['ftp'] = $backup_files_base_name;
4398
4399 $backup_settings_values = $this -> backup_settings_vals;
4400 /* $upload_loop_break_time = $backup_settings_values['upload_loop_break_time'];
4401 $del_host_file = $backup_settings_values['del_host_file']; */
4402
4403 $upload_loop_break_time = $requestParams['account_info']['upload_loop_break_time']; //darkcode changed
4404 $del_host_file = $requestParams['args']['del_host_file'];
4405
4406 if(!$upload_loop_break_time)
4407 {
4408 $upload_loop_break_time = 25; //safe
4409 }
4410
4411 $startTime = microtime(true);
4412 //get the filesize of the remote file first
4413 $file_size = ftp_size($conn_id, $remoteFileName);
4414 if ($file_size != -1)
4415 {
4416 echo "size of $remoteFileName is $file_size bytes";
4417 }
4418 else
4419 {
4420
4421 $file_size = 0;
4422 }
4423 if(!$file_size)
4424 $file_size = 0;
4425
4426 $real_size = filesize($backup_file);
4427 //read the parts local file , if it is a second call start reading the file from the left out part which is at the offset of the remote file's filesize.
4428 $fp = fopen($backup_file, 'r');
4429 fseek($fp,$file_size);
4430
4431 $ret = ftp_nb_fput($conn_id, $remoteFileName, $fp, FTP_BINARY, $file_size);
4432 if(!$ret || $ret == FTP_FAILED)
4433 {
4434 return array(
4435 'error' => "FTP upload Error. ftp_nb_fput(): Append/Restart not permitted. This feature is required for multi-call backup upload via FTP to work. Please contact your WP site's hosting provider and ask them to fix the problem. You can try dropbox, Amazon S3 or Google Driver as an alternative to it.",
4436 'partial' => 1, 'error_code' => 'ftp_nb_fput_not_permitted_error'
4437 );
4438 }
4439 $resArray = array (
4440 'status' => 'partiallyCompleted',
4441 'backupParentHID' => $historyID,
4442 );
4443 $result_arr = array();
4444 $result_arr['status'] = 'partiallyCompleted';
4445 $result_arr['nextFunc'] = 'ftp_backup';
4446 $result_arr['ftpArgs'] = $tempArgs;
4447 $result_arr['current_file_num'] = $current_file_num;
4448
4449 /*
4450 1.run the while loop as long as FTP_MOREDATA is set
4451 2.within the loop if time is greater than specified seconds break the loop and close ftp_con return as "partiallyCompleted" setting nextFunc as ftp_backup.
4452 3.if ret == FTP_FINISHED , it means the ftpUpload is complete .. return as "completed".
4453 */
4454 while ($ret == FTP_MOREDATA) {
4455 // Do whatever you want
4456 $endTime = microtime(true);
4457 $timeTaken = $endTime - $this->iwpScriptStartTime;
4458 // Continue upload...
4459 if($timeTaken > $upload_loop_break_time)
4460 {
4461 echo "being stopped --- ".$file_size;
4462 $result_arr['timeTaken'] = $timeTaken;
4463 $result_arr['file_size_written'] = $file_size;
4464 fclose($fp);
4465 $this->statusLog($historyID, array('stage' => 'ftpMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall being stopped --- ','nextFunc' => 'ftp_backup','task_result' => $task_result, 'responseParams' => $result_arr));
4466 break;
4467 }
4468 else
4469 {
4470 $ret = ftp_nb_continue($conn_id);
4471 }
4472 iwp_mmb_auto_print("ftploop");
4473 }
4474 if ($ret != FTP_FINISHED) {
4475 if (is_resource($fp)) {
4476 fclose($fp);
4477 }
4478 /* if($del_host_file)
4479 {
4480 @unlink($backup_file);
4481 } */
4482 echo "backup not yet finished";
4483 echo "real file size $real_size";
4484 echo "FTP file size $file_size";
4485 return $resArray;
4486 }
4487 else
4488 {
4489 //this is where the backup call ends completing all the uploads
4490 $current_file_num += 1;
4491 $result_arr['timeTaken'] = $timeTaken;
4492 $result_arr['file_size_written'] = $file_size;
4493 $result_arr['current_file_num'] = $current_file_num;
4494
4495 if($current_file_num == $backup_files_count)
4496 {
4497 $result_arr['status'] = 'completed';
4498 $result_arr['nextFunc'] = 'ftp_backup_over';
4499 unset($task_result['task_results'][$historyID]['server']);
4500 $resArray['status'] = 'completed';
4501 }
4502 else
4503 {
4504 $result_arr['status'] = 'partiallyCompleted';
4505 $resArray['status'] = 'partiallyCompleted';
4506 }
4507
4508
4509 $this->statusLog($historyID, array('stage' => 'ftpMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall','nextFunc' => 'ftp_backup','task_result' => $task_result, 'responseParams' => $result_arr));
4510
4511
4512 fclose($fp);
4513 //checking file size and comparing
4514 $verificationResult = $this -> postUploadVerification($conn_id, $backup_file, $remoteFileName, $type = "ftp");
4515 if(!$verificationResult)
4516 {
4517 return $this->statusLog($historyID, array('stage' => 'uploadFTP', 'status' => 'error', 'statusMsg' => 'FTP verification failed: File may be corrupted.', 'statusCode' => 'ftp_verification_failed_file_maybe_corrupted'));
4518 }
4519
4520
4521 if($del_host_file)
4522 {
4523 @unlink($backup_file); // darkcode testing purpose
4524 }
4525 iwp_mmb_print_flush('FTP upload: End');
4526
4527 return $resArray;
4528 }
4529 }
4530
4531 function sftp_backup($historyID,$args = array()){
4532 global $iwp_backup_core;
4533 $current_file_num = 0;
4534 if(empty($args))
4535 {
4536
4537 $responseParams = $this -> getRequiredData($historyID,"responseParams");
4538
4539 if(!$responseParams)
4540 return $this->statusLog($this -> hisID, array('stage' => 'UploadbackupFiles', 'status' => 'error', 'statusMsg' => 'FTP Backup failed: Error while fetching table data', 'statusCode' => 'ftp_backup_failed_error_while_fetching_table_data'));
4541
4542 $args = $responseParams['ftpArgs'];
4543 $current_file_num = $responseParams['current_file_num'];
4544 }
4545
4546 $host = !empty($args['ftp_hostname'])? $args['ftp_hostname']: '';
4547 $username = !empty($args['ftp_username'])? $args['ftp_username']: '';
4548 $password = !empty($args['ftp_password'])? $args['ftp_password']: '';
4549 $remote_folder = !empty($args['ftp_remote_folder'])? $args['ftp_remote_folder']: '';
4550 $port = !empty($args['ftp_port'])? $args['ftp_port']: '';
4551 $site_folder = !empty($args['ftp_site_folder'])? $args['ftp_site_folder']: '0';
4552 $use_sftp = !empty($args['use_sftp'])? $args['use_sftp']: '0';
4553 $ftp_passive = !empty($args['ftp_passive'])? $args['ftp_passive']: '0';
4554 $backup_file = !empty($args['backup_file'])? $args['backup_file']: array();
4555
4556 if(!is_array($backup_file)){
4557 $temp_backup_file = $backup_file;
4558 $backup_file = array();
4559 $backup_file[] = $temp_backup_file;
4560 }
4561
4562 $iwp_mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
4563 $path = $iwp_mmb_plugin_dir.'/lib/phpseclib/phpseclib/phpseclib';
4564 set_include_path(get_include_path() . PATH_SEPARATOR . $path);
4565 include_once('Net/SFTP.php');
4566
4567 $sftp = new Net_SFTP($host, $port);
4568
4569 if(!$sftp) {
4570 return $this->statusLog($this -> hisID, array('stage' => 'UploadbackupFiles', 'status' => 'error', 'statusMsg' => 'Failed to connect to SFTP host' . $host, 'statusCode' => 'sftp_backup_failed_to_connect_host'));
4571 }
4572
4573 $iwp_backup_core->ensure_phpseclib('Crypt_Blowfish', 'Crypt/Blowfish');
4574
4575 if (!$sftp->login($username, $password)) {
4576 return $this->statusLog($this -> hisID, array('stage' => 'UploadbackupFiles', 'status' => 'error', 'statusMsg' => 'SFTP login faield for '.$username, 'statusCode' => 'sftp_backup_failed_to_login'));
4577 }else{
4578 if ($site_folder != '0') {
4579 $remote_folder = rtrim($remote_folder, '/');
4580 $remote_folder .= '/' . $this->site_name;
4581 }
4582
4583 if ( !$sftp->is_dir($remote_folder) ) {
4584 $sftp->mkdir($remote_folder,-1,true);
4585 }
4586 $sftp->chdir($remote_folder);
4587 }
4588
4589 if(is_array($backup_file)){
4590 $backup_file_base_name = basename($backup_file[$current_file_num]);
4591 }
4592 else{
4593 $backup_file_base_name = basename($backup_file);
4594 }
4595
4596 $upload = $this->sftp_chunck_upload($sftp, rtrim($remote_folder, '/') . '/' . basename($backup_file_base_name), $backup_file, FTP_BINARY, $historyID, $args, $current_file_num);
4597
4598 if ($upload === false) {
4599 return array(
4600 'error' => 'Failed to upload file to SFTP. Please check your specified path.',
4601 'partial' => 1, 'error_code' => 'failed_to_upload_file_to_sftp'
4602 );
4603 }
4604
4605 return $upload;
4606
4607 }
4608
4609 function sftp_chunck_upload( $sftp, $remote_file, $backup_file, $mode, $historyID, $args, $current_file_num = 0){
4610 $requestParams = $this->getRequiredData($historyID, "requestParams");
4611 $task_result = $this->getRequiredData($historyID, "taskResults");
4612
4613 if(!$remote_file){
4614 return array(
4615 'error' => 'Failed to upload file to FTP. Please check your specified path.',
4616 'partial' => 1, 'error_code' => 'failed_to_upload_file_to_ftp'
4617 );
4618 }
4619
4620 $backup_files_base_name = array();
4621 if(is_array($backup_file)){
4622 foreach($backup_file as $value){
4623 $backup_files_base_name[] = basename($value);
4624 }
4625 }
4626 else{
4627 $backup_files_base_name = basename($backup_file);
4628 }
4629
4630 $backup_files_count = count($backup_file);
4631
4632 if(is_array($backup_file)){
4633 $backup_file = $backup_file[$current_file_num];
4634 }
4635
4636 $task_result['task_results'][$historyID]['ftp'] = $backup_files_base_name;
4637 $task_result['ftp'] = $backup_files_base_name;
4638 $upload_loop_break_time = $requestParams['account_info']['upload_loop_break_time']; //darkcode changed
4639 $del_host_file = $requestParams['args']['del_host_file'];
4640
4641 if(!$upload_loop_break_time){
4642 $upload_loop_break_time = 25; //safe
4643 }
4644
4645 if($upload_loop_break_time < 15){
4646 $upload_loop_break_time = 20; //safe
4647 }
4648
4649 $remote_stat = $sftp->stat($remote_file);
4650 $current_remote_size = (is_array($remote_stat) && isset($remote_stat['size']) && $remote_stat['size'] > 0) ? $remote_stat['size'] : 0;
4651
4652 $file_size = 0;
4653 if ($current_remote_size != 0) {
4654 echo "size of $remote_file is $current_remote_size bytes\n";
4655 $file_size = $current_remote_size;
4656 }
4657
4658 $fp = fopen($backup_file, 'rb');
4659 fseek($fp,$file_size);
4660
4661 if (!empty($requestParams['account_info']['upload_file_block_size'])) {
4662 $chunkSize = $requestParams['account_info']['upload_file_block_size'];
4663 }else{
4664 $chunkSize = 1024 * (1 * 1024);
4665 }
4666
4667
4668 $resArray = array (
4669 'status' => 'partiallyCompleted',
4670 'backupParentHID' => $historyID,
4671 );
4672 $result_arr = array();
4673 $result_arr['status'] = 'partiallyCompleted';
4674 $result_arr['nextFunc'] = 'sftp_backup';
4675 $result_arr['ftpArgs'] = $args;
4676 $result_arr['current_file_num'] = $current_file_num;
4677
4678 $totalBytesSent = 0;
4679 while (!feof($fp)) {
4680
4681 $endTime = microtime(true);
4682 $timeTaken = $endTime - $this->iwpScriptStartTime;
4683 if($timeTaken < $upload_loop_break_time){
4684 $chunk = fread($fp, $chunkSize);
4685 $upload = $sftp->put($remote_file, $chunk, (NET_SFTP_RESUME | NET_SFTP_RESUME_START));
4686 if ($upload === false) {
4687 return array(
4688 'error' => 'Failed to upload file to SFTP',
4689 'partial' => 1,
4690 'error_code' => 'sftp_put_error'
4691 );
4692 }
4693 }else{
4694 $result_arr['timeTaken'] = $timeTaken;
4695 $result_arr['file_size_written'] = $file_size;
4696 $this->statusLog($historyID, array('stage' => 'sftpMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall being stopped --- ','nextFunc' => 'sftp_backup','task_result' => $task_result, 'responseParams' => $result_arr));
4697 break;
4698 }
4699 $totalBytesSent += strlen($chunk);
4700 iwp_mmb_auto_print("sftploop");
4701 }
4702
4703 if (is_resource($fp)) {
4704 fclose($fp);
4705 }
4706
4707 $real_size = filesize($backup_file);
4708 $remote_stat = $sftp->stat($remote_file);
4709 $current_remote_size = (is_array($remote_stat) && isset($remote_stat['size']) && $remote_stat['size'] > 0) ? $remote_stat['size'] : 0;
4710
4711 if ( $real_size > $current_remote_size) {
4712 echo "backup not yet finished";
4713 echo "real file size $real_size";
4714 echo "\nSFTP file size $current_remote_size";
4715 echo "\nUploaded size $totalBytesSent";
4716 return $resArray;
4717 }
4718
4719 //this is where the backup call ends completing all the uploads
4720 $current_file_num += 1;
4721 $result_arr['timeTaken'] = $timeTaken;
4722 $result_arr['file_size_written'] = $file_size;
4723 $result_arr['current_file_num'] = $current_file_num;
4724
4725 if($current_file_num == $backup_files_count){
4726 $result_arr['status'] = 'completed';
4727 $result_arr['nextFunc'] = 'sftp_backup_over';
4728 unset($task_result['task_results'][$historyID]['server']);
4729 $resArray['status'] = 'completed';
4730 }else{
4731 $result_arr['status'] = 'partiallyCompleted';
4732 $resArray['status'] = 'partiallyCompleted';
4733 }
4734
4735
4736 $this->statusLog($historyID, array('stage' => 'ftpMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall','nextFunc' => 'ftp_backup','task_result' => $task_result, 'responseParams' => $result_arr));
4737
4738 $verificationResult = $this -> postUploadVerification($sftp, $backup_file, $remote_file, "sftp");
4739 if(!$verificationResult){
4740 return $this->statusLog($historyID, array('stage' => 'uploadFTP', 'status' => 'error', 'statusMsg' => 'STP verification failed: File may be corrupted.', 'statusCode' => 'stp_verification_failed_file_maybe_corrupted'));
4741 }else{
4742 echo "sftp post verifcation success\n";
4743 }
4744
4745 if($del_host_file){
4746 @unlink($backup_file); // darkcode testing purpose
4747 }
4748
4749 iwp_mmb_print_flush('SFTP upload: End');
4750
4751 return $resArray;
4752
4753 }
4754
4755 function get_files_base_name($backup_file)
4756 {
4757 $backup_files_base_name = array();
4758 if(is_array($backup_file))
4759 {
4760 foreach($backup_file as $value)
4761 {
4762 $backup_files_base_name[] = basename($value);
4763 }
4764 }
4765 else
4766 {
4767 $backup_files_base_name = basename($backup_file);
4768 }
4769 return $backup_files_base_name;
4770 }
4771
4772 function postUploadVerification(&$obj, $backup_file, $destFile, $type = "", $as3_bucket = "", $as3_access_key = "", $as3_secure_key = "", $as3_bucket_region = "")
4773 {
4774 $actual_file_size = iwp_mmb_get_file_size($backup_file);
4775 $size1 = $actual_file_size-((0.1) * $actual_file_size);
4776 $size2 = $actual_file_size+((0.1) * $actual_file_size);
4777 if($type == "dropbox")
4778 {
4779 $dBoxMetaData = $obj -> metaData($destFile);
4780 $filename = basename($backup_file);
4781 $path = '/'.$destFile.$filename;
4782 if (empty($dBoxMetaData['body']->contents)) {
4783 return true;
4784 }
4785 foreach ($dBoxMetaData['body']->contents as $key => $value) {
4786 if(strtolower($path) == strtolower($value->path)){
4787 $dBoxFileSize = $value->bytes;
4788 if((($dBoxFileSize >= $size1 && $dBoxFileSize <= $actual_file_size) || ($dBoxFileSize <= $size2 && $dBoxFileSize >= $actual_file_size) || ($dBoxFileSize == $actual_file_size)) && ($dBoxFileSize != 0))
4789 {
4790 return true;
4791 }
4792 }
4793 }
4794
4795 return false;
4796 }
4797 else if($type == "amazons3")
4798 {
4799 if(is_new_s3_compatible()){
4800 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
4801 $new_s3_obj = new IWP_MMB_S3_MULTICALL();
4802 return $new_s3_obj->postUploadS3Verification($backup_file, $destFile, $type, $as3_bucket, $as3_access_key, $as3_secure_key, $as3_bucket_region, $size1, $size2);
4803 }
4804 else{
4805 return $this->postUploadS3VerificationBwdComp($backup_file, $destFile, $obj, $type, $as3_bucket, $as3_access_key, $as3_secure_key, $as3_bucket_region, $actual_file_size, $size1, $size2);
4806 }
4807 }
4808 else if($type == "ftp")
4809 {
4810 ftp_chdir ($obj , dirname($destFile));
4811 $ftp_file_size = ftp_size($obj, basename($destFile));
4812 if($ftp_file_size > 0)
4813 {
4814 if((($ftp_file_size >= $size1 && $ftp_file_size <= $actual_file_size) || ($ftp_file_size <= $size2 && $ftp_file_size >= $actual_file_size) || ($ftp_file_size == $actual_file_size)) && ($ftp_file_size != 0))
4815 {
4816 return true;
4817 }
4818 else
4819 {
4820 return false;
4821 }
4822 }
4823 else
4824 {
4825 return false;
4826 }
4827 }
4828 else if($type == "sftp")
4829 {
4830 $remote_stat = $obj->stat($destFile);
4831 $ftp_file_size = (is_array($remote_stat) && isset($remote_stat['size']) && $remote_stat['size'] > 0) ? $remote_stat['size'] : 0;
4832 if($ftp_file_size > 0)
4833 {
4834 if((($ftp_file_size >= $size1 && $ftp_file_size <= $actual_file_size) || ($ftp_file_size <= $size2 && $ftp_file_size >= $actual_file_size) || ($ftp_file_size == $actual_file_size)) && ($ftp_file_size != 0))
4835 {
4836 return true;
4837 }
4838 else
4839 {
4840 return false;
4841 }
4842 }
4843 else
4844 {
4845 return false;
4846 }
4847 }
4848 }
4849
4850 function postUploadS3VerificationBwdComp($backup_file, $destFile, $obj, $type = "", $as3_bucket = "", $as3_access_key = "", $as3_secure_key = "", $as3_bucket_region = "", $actual_file_size = "", $size1 = 0 , $size2 = 0, $return_size = false){
4851
4852 $response = $obj -> if_object_exists($as3_bucket, $destFile);
4853 if($response == true)
4854 {
4855 $meta = $obj -> get_object_headers($as3_bucket, $destFile);
4856 $cfu_obj = new CFUtilities;
4857 $meta_response_array = $cfu_obj->convert_response_to_array($meta);
4858 $s3_filesize = $meta_response_array['header']['content-length'];
4859 if ($return_size == true) {
4860 return $s3_filesize;
4861 }
4862 echo "S3 fileszie during verification - ".$s3_filesize;
4863 if((($s3_filesize >= $size1 && $s3_filesize <= $actual_file_size) || ($s3_filesize <= $size2 && $s3_filesize >= $actual_file_size) || ($s3_filesize == $actual_file_size)) && ($s3_filesize != 0))
4864 {
4865 return true;
4866 }
4867 else
4868 {
4869 return false;
4870 }
4871 }
4872 else
4873 {
4874 return false;
4875 }
4876 }
4877
4878 function remove_ftp_backup($args)
4879 {
4880 global $iwp_backup_core;
4881 extract($args);
4882 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
4883 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
4884 if(isset($use_sftp) && $use_sftp==1) {
4885 $port = $ftp_port ? $ftp_port : 22; //default port is 22
4886 /*
4887 * SFTP section start here phpseclib library is used for this functionality
4888 */
4889 $iwp_mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
4890 $path = $iwp_mmb_plugin_dir.'/lib/phpseclib/phpseclib/phpseclib';
4891 set_include_path(get_include_path() . PATH_SEPARATOR . $path);
4892 include_once('Net/SFTP.php');
4893
4894
4895 $sftp = new Net_SFTP($ftp_hostname,$port);
4896 if(!$sftp) {
4897 return array(
4898 'error' => 'Failed to connect to ' . $ftp_hostname,
4899 'partial' => 1
4900 );
4901 }
4902 $iwp_backup_core->ensure_phpseclib('Crypt_Blowfish', 'Crypt/Blowfish');
4903 if (!$sftp->login($ftp_username, $ftp_password)) {
4904 return array(
4905 'error' => 'FTP user name and password invalid',
4906 'partial' => 1
4907 );
4908 } else {
4909 if ($ftp_site_folder) {
4910 $ftp_remote_folder = rtrim($ftp_remote_folder, '/');
4911 $ftp_remote_folder .= '/' . $this->site_name;
4912 }
4913
4914 $sftp->chdir($ftp_remote_folder);
4915
4916 if(!is_array($backup_file)){
4917 $temp_backup_file = $backup_file;
4918 $backup_file = array();
4919 $backup_file[] = $temp_backup_file;
4920 }
4921 foreach($backup_file as $key => $value){
4922 $sftp->delete(basename($value));
4923 }
4924
4925 }
4926 //SFTP library has automatic connection closed. So no need to call seperate connection close function
4927
4928 } else {
4929 $port = $ftp_port ? $ftp_port : 21; //default port is 21
4930 if (!empty($ftp_ssl) && function_exists('ftp_ssl_connect')) {
4931 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
4932 } else if (function_exists('ftp_connect')) {
4933 $conn_id = ftp_connect($ftp_hostname,$port);
4934 }
4935
4936 if ($conn_id) {
4937 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
4938 if ($ftp_site_folder)
4939 $ftp_remote_folder .= '/' . $this->site_name;
4940
4941 if($ftp_passive){
4942 @ftp_pasv($conn_id,true);
4943 }
4944
4945 if(!is_array($backup_file))
4946 {
4947 $temp_backup_file = $backup_file;
4948 $backup_file = array();
4949 $backup_file[] = $temp_backup_file;
4950 }
4951
4952 foreach($backup_file as $key => $value)
4953 {
4954 $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $value);
4955 }
4956 ftp_close($conn_id);
4957 }
4958 }
4959
4960 }
4961
4962 function get_ftp_backup($args, $current_file_num = 0)
4963 {
4964 global $iwp_backup_core;
4965 extract($args);
4966 if(isset($use_sftp) && $use_sftp==1) {
4967 $port = $ftp_port ? $ftp_port : 22; //default port is 22
4968 /*
4969 * SFTP section start here phpseclib library is used for this functionality
4970 */
4971 $iwp_mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
4972 $path = $iwp_mmb_plugin_dir.'/lib/phpseclib';
4973 set_include_path(get_include_path() . PATH_SEPARATOR . $path);
4974 include_once('Net/SFTP.php');
4975
4976
4977 $sftp = new Net_SFTP($ftp_hostname,$port);
4978 if(!$sftp) {
4979 return array(
4980 'error' => 'Failed to connect to ' . $ftp_hostname,
4981 'partial' => 1
4982 );
4983 }
4984 $iwp_backup_core->ensure_phpseclib('Crypt_Blowfish', 'Crypt/Blowfish');
4985 if (!$sftp->login($ftp_username, $ftp_password)) {
4986 return array(
4987 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
4988 'partial' => 1
4989 );
4990 } else {
4991 if ($ftp_site_folder) {
4992 $ftp_remote_folder .= '/' . $this->site_name;
4993 }
4994 $remote_loation = basename($backup_file);
4995 $local_location = $backup_file;
4996
4997 $sftp->chdir($ftp_remote_folder);
4998 //$sftp->delete(basename($backup_file));
4999 $temp = wp_tempnam('iwp_temp_backup.zip');
5000
5001 $get = $sftp->get(basename($backup_file), $temp);
5002 if ($get === false) {
5003 return false;
5004 } else {
5005 return $temp;
5006 }
5007 //SFTP library has automatic connection closed. So no need to call seperate connection close function
5008
5009 }
5010
5011 } else {
5012 //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
5013 $port = $ftp_port ? $ftp_port : 21; //default port is 21
5014 if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
5015 $conn_id = ftp_ssl_connect($ftp_hostname,$port);
5016
5017 } else if (function_exists('ftp_connect')) {
5018 $conn_id = ftp_connect($ftp_hostname,$port);
5019 if ($conn_id === false) {
5020 return false;
5021 }
5022 }
5023 $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
5024 if ($login === false) {
5025 return false;
5026 }
5027
5028 if ($ftp_site_folder)
5029 $ftp_remote_folder .= '/' . $this->site_name;
5030
5031 if($ftp_passive){
5032 @ftp_pasv($conn_id,true);
5033 }
5034
5035 //$temp = ABSPATH . 'iwp_temp_backup.zip';
5036 $temp = wp_tempnam('iwp_temp_backup.zip');
5037
5038 $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
5039 if ($get === false) {
5040 return false;
5041 } else {
5042 }
5043 ftp_close($conn_id);
5044
5045 return $temp;
5046 }
5047 }
5048
5049
5050 /*
5051 --The new Dropbox function which supports multiple calls--
5052
5053 1.first call the chunked_upload function with no upload_id and get a response array of upload_id and offset .
5054 2.pass the upload_id and offset in the multiple calls until the file is completely uploaded .
5055
5056 --note--
5057 1.the args should have the backup_file_size in bytes.
5058 2.on final call the chunked upload will be commited.
5059 3.there are some changes in the dropbox.php lib file .
5060
5061 */
5062
5063 function dropbox_backup($historyID = 0, $args = '', $uploadid = null, $offset = 0)
5064 {
5065 //included two arguments $uploadid and $offset
5066 $dBoxStartTime = $this->iwpScriptStartTime;
5067
5068 //get the settings
5069 //$this -> backup_settings_vals = get_option('iwp_client_multi_backup_temp_values');
5070 //$backup_settings_values = $this -> backup_settings_vals;
5071 //$upload_file_block_size = $backup_settings_values['upload_file_block_size'];
5072 //$actual_file_size = $backup_settings_values['actual_file_size'];
5073 //$del_host_file = $backup_settings_values['del_host_file'];
5074
5075 //get the settings other method
5076 $requestParams = $this->getRequiredData($historyID, "requestParams");
5077 $upload_loop_break_time = $requestParams['account_info']['upload_loop_break_time']; //darkcode changed
5078 $upload_file_block_size = $requestParams['account_info']['upload_file_block_size'];
5079 $del_host_file = $requestParams['args']['del_host_file'];
5080 $current_file_num = 0;
5081
5082 if($args == '')
5083 {
5084 //on the next call $args would be ''
5085 //set $args, $uploadid, $offset from the DB
5086 $responseParams = $this -> getRequiredData($historyID,"responseParams");
5087
5088 if(!$responseParams)
5089 $this->statusLog($historyID, array('stage' => 'backupFiles', 'status' => 'error', 'statusMsg' => 'errorGettingDBValues', 'statusCode' => 'error_getting_db_values'));
5090
5091 $args = $responseParams['dropboxArgs'];
5092 $prevChunkResults = $responseParams['response_data'];
5093 $uploadid = isset($prevChunkResults['upload_id']) ? $prevChunkResults['upload_id'] : 0;
5094 $offset = isset($prevChunkResults['offset']) ? $prevChunkResults['offset'] : 0;
5095 $current_file_num = $responseParams['current_file_num'];
5096 }
5097
5098 $tempArgs = $args;
5099 extract($args);
5100
5101 $task_result = $this->getRequiredData($historyID, "taskResults");
5102 $task_result['task_results'][$historyID]['dropbox'] = $this->get_files_base_name($backup_file);
5103 $task_result['dropbox'] = $this->get_files_base_name($backup_file);
5104
5105 if(!is_array($backup_file))
5106 {
5107 $temp_backup_file = $backup_file;
5108 $backup_file = array();
5109 $backup_file[] = $temp_backup_file;
5110 }
5111
5112 if(is_array($backup_file))
5113 {
5114 $backup_files_count = count($backup_file);
5115 $backup_file = $backup_file[$current_file_num];
5116 }
5117 $actual_file_size = iwp_mmb_get_file_size($backup_file);
5118 $backup_file_size = $actual_file_size;
5119 //$backup_file_size = 10394909; //darkCode testing purpose
5120
5121 if (!$this->iwp_mmb_function_exists('curl_init')) {
5122 return array(
5123 'error' => 'You cannot use Dropbox on your server. Please enable curl first.',
5124 'partial' => 1, 'error_code' => 'cannot_use_dropbox_enable_curl_first'
5125 );
5126 }
5127 $oldVersion = false;
5128 if((isset($consumer_secret) && !empty($consumer_secret)) || (isset($dropbox_access_token) && !empty($dropbox_access_token))){
5129 if(!isset($dropbox_access_token) && empty($dropbox_access_token)){
5130
5131 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
5132
5133 $dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
5134 $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
5135 $oldVersion = true;
5136 if (isset($dropbox_site_folder) && $dropbox_site_folder == true)
5137 $dropbox_destination .= '/' . $this->site_name . '/' . basename($backup_file);
5138 else
5139 $dropbox_destination .= '/' . basename($backup_file);
5140 }else{
5141
5142 if(!isset($dropbox_email) && empty($dropbox_email)){
5143 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/API.php';
5144 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/Exception.php';
5145 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/ConsumerAbstract.php';
5146 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/Curl.php';
5147
5148 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
5149
5150 $oauth = new IWP_Dropbox_OAuth_Consumer_Curl($dropbox_app_key, $dropbox_app_secure_key);
5151 $oauth->setToken($dropbox_access_token);
5152 $dropbox = new IWP_Dropbox_API($oauth);
5153
5154 }else{
5155 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
5156
5157 try{
5158 set_iwp_dropbox_auth_setting($args);
5159 $helper = new IWP_MMB_UploadModule_dropbox();
5160 $dropbox = $helper->bootstrap();
5161 }
5162 catch(Exception $e){
5163 return $this->statusLog($historyID, array('stage' => 'uploadDropBox', 'status' => 'error', 'statusMsg' => $e->getMessage(), 'statusCode' => 'dropbox_verification_failed_file_may_be_corrupted'));
5164 }
5165 }
5166
5167 $oldRoot = 'Apps/InfiniteWP/';
5168 $dropbox_destination = $oldRoot.ltrim(trim($dropbox_destination), '/');
5169 $dropbox_destination = rtrim($dropbox_destination, '/');
5170 if (isset($dropbox_site_folder) && $dropbox_site_folder == true){
5171 $dropbox_destination .= '/'.$this->site_name;
5172 }
5173 $folders = explode('/',$dropbox_destination);
5174 if (!isset($path)) {
5175 $path = '';
5176 }
5177 foreach ($folders as $key => $name) {
5178 $path.=trim($name).'/';
5179 }
5180 $dropbox_destination = $path;
5181
5182 }
5183
5184 try {
5185 //$dropbox->upload($backup_file, $dropbox_destination, true); //we are using new multiCAll function
5186
5187 // this is the dropbox loop ..
5188 $reloop = false;
5189 $chunkCount = 0;
5190 $chunkTimeTaken = 0;
5191 do
5192 {
5193 if($chunkCount == 0)
5194 {
5195 $chunkStartTime = $dBoxStartTime;
5196 }
5197 else
5198 {
5199 $chunkStartTime = microtime(true);
5200 }
5201 if(($backup_file_size - $offset) >= 4194304) //the chunk size is set here
5202 {
5203 $readsize = $upload_file_block_size;
5204 $isCommit = false;
5205 $status = 'partiallyCompleted';
5206 }
5207 else
5208 {
5209 $readsize = ($backup_file_size - $offset);
5210
5211 $isCommit = true;
5212 $status = 'completed';
5213 }
5214 if($oldVersion){
5215 $chunkResult = $dropbox->chunked_upload($backup_file, $dropbox_destination, true, $uploadid, $offset, $readsize, $isCommit);
5216 }else{
5217 $chunkResult = $dropbox->chunked_upload($backup_file ,$dropbox_destination, true, $uploadid, $offset, $isCommit);
5218 }
5219 $result_arr = array();
5220 $result_arr['response_data'] = $chunkResult;
5221 $result_arr['status'] = $status;
5222 $result_arr['nextFunc'] = 'dropbox_backup';
5223 $result_arr['dropboxArgs'] = $tempArgs;
5224 $result_arr['current_file_num'] = $current_file_num;
5225 //updating offset and uploadid values for relooping.
5226 $offset = isset($chunkResult['offset']) ? $chunkResult['offset'] : 0;
5227 $uploadid = isset($chunkResult['upload_id']) ? $chunkResult['upload_id'] : 0;
5228 echo 'completed-size'.($offset/1024/1024);
5229 //check time
5230 $chunkCompleteTime = microtime(true);
5231 $dBoxCompleteTime = microtime(true);
5232 $chunkTimeTaken = (($chunkTimeTaken + ($chunkCompleteTime - $chunkStartTime))/($chunkCount + 1)); // this is the average chunk time
5233 echo " thisChunkTimeTaken".$chunkTimeTaken;
5234 $dBoxTimeTaken = $dBoxCompleteTime - $dBoxStartTime;
5235 $dBoxTimeLeft = $upload_loop_break_time - $dBoxTimeTaken; //calculating time left for the dBOX upload ..
5236 $dBoxTimeLeft = $dBoxTimeLeft; //for safe time limit
5237 echo " dBoxTimeLeft".$dBoxTimeLeft;
5238 //$halfOfLoopTime = (($upload_loop_break_time / 2) - 1);
5239 if(($dBoxTimeLeft <= $chunkTimeTaken)||($status == 'completed')) //if the time Left for the dropbox upload is less than the time to upload a single chunk break the loop
5240 {
5241 if ($status == 'complete') {
5242 $result_arr['response_data']['offset'] = 0;
5243 $result_arr['response_data']['upload_id'] = null;
5244 }
5245 $reloop = false;
5246 }
5247 else
5248 {
5249
5250 $reloop = true;
5251 $chunkCount++;
5252 }
5253 }while($reloop);
5254
5255 $resArray = array (
5256 'status' => $status,
5257 'backupParentHID' => $historyID,
5258 );
5259
5260 if($status == 'completed')
5261 {
5262 $current_file_num += 1;
5263 if($current_file_num == $backup_files_count)
5264 {
5265 $result_arr['nextFunc'] = 'dropbox_backup_over';
5266 iwp_mmb_print_flush('Dropbox upload: End');
5267 unset($task_result['task_results'][$historyID]['server']);
5268 }
5269 else
5270 {
5271 $result_arr['nextFunc'] = 'dropbox_backup';
5272 $result_arr['current_file_num'] = $current_file_num;
5273 $result_arr['status'] = 'partiallyCompleted';
5274 $resArray['status'] = 'partiallyCompleted';
5275 }
5276 }
5277 $this->statusLog($historyID, array('stage' => 'dropboxMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall','nextFunc' => 'dropbox_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
5278
5279
5280 if($status == 'completed')
5281 {
5282 //checking file size and comparing
5283 $verificationResult = $this -> postUploadVerification($dropbox, $backup_file, $dropbox_destination, $type = "dropbox");
5284 if(!$verificationResult)
5285 {
5286 return $this->statusLog($historyID, array('stage' => 'uploadDropBox', 'status' => 'error', 'statusMsg' => 'Dropbox verification failed: File may be corrupted.', 'statusCode' => 'dropbox_verification_failed_file_may_be_corrupted'));
5287 }
5288 if($del_host_file)
5289 {
5290 @unlink($backup_file);
5291 }
5292 }
5293
5294 return $resArray;
5295
5296 }
5297 catch (Exception $e) {
5298 if (preg_match("/Submitted input out of alignment: got \[(\d+)\] expected \[(\d+)\]/i", $e->getMessage(), $matches)) {
5299 // Try the indicated offset
5300 $we_tried = $matches[1];
5301 $offset = $matches[2];
5302 /*if($oldVersion){
5303 $chunkResult = $dropbox->chunked_upload($backup_file, $dropbox_destination, true, $uploadid, $offset, $readsize, $isCommit);
5304 }else{
5305 $chunkResult = $dropbox->chunked_upload($backup_file ,$dropbox_destination, true, $uploadid, $offset, $isCommit);
5306 }*/
5307 echo "Submitted input out of alignment";
5308 $result_arr = array();
5309 $result_arr['nextFunc'] = 'dropbox_backup';
5310 $result_arr['dropboxArgs'] = $tempArgs;
5311 $chunkResult['offset'] = isset($offset) ? $offset : 0;
5312 $chunkResult['uploadid'] = isset($prevChunkResults['upload_id']) ? $prevChunkResults['upload_id'] : 0;
5313 $result_arr['response_data'] = $chunkResult;
5314 $resArray = array (
5315 'backupParentHID' => $historyID,
5316 'status' => 'partiallyCompleted'
5317 );
5318 $result_arr['nextFunc'] = 'dropbox_backup';
5319 $result_arr['current_file_num'] = $current_file_num;
5320 $result_arr['status'] = 'partiallyCompleted';
5321 $this->statusLog($historyID, array('stage' => 'dropboxMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall','nextFunc' => 'dropbox_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
5322 return $resArray;
5323 }
5324
5325 if ($e->getMessage() == 'path') {
5326
5327 $response = $dropbox->quotaInfo();
5328 $usedSize = $response['body']->used;
5329 $allocated = $response['body']->allocation->allocated;
5330 if ($usedSize>=$allocated) {
5331 return array(
5332 'error' => "Dropbox quota exceeded (Allowed ".round($allocated / (1024*1024), 2)." MB and used ".round($usedSize / (1024*1024), 2)." MB)",
5333 'partial' => 1
5334 );
5335 }
5336 }
5337 $this->_log($e->getMessage());
5338 return array(
5339 'error' => $e->getMessage(),
5340 'partial' => 1
5341 );
5342 }
5343
5344 //return true;
5345
5346 }
5347 else {
5348 return array(
5349 'error' => 'Please connect your InfiniteWP panel with your Dropbox account.', 'error_code' => 'please_connect_your_iwp_panel_with_your_dropbox_account'
5350 );
5351 }
5352 }
5353
5354
5355
5356 function remove_dropbox_backup($args) {
5357 extract($args);
5358
5359 if(!isset($dropbox_access_token) && empty($dropbox_access_token)){
5360
5361 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
5362
5363 $dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
5364 $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
5365 $oldVersion = true;
5366 if ($dropbox_site_folder == true)
5367 $dropbox_destination .= '/' . $this->site_name;
5368 }else{
5369 if(!isset($dropbox_email) && empty($dropbox_email)){
5370 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/API.php';
5371 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/Exception.php';
5372 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/ConsumerAbstract.php';
5373 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/Curl.php';
5374
5375 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
5376
5377 $oauth = new IWP_Dropbox_OAuth_Consumer_Curl($dropbox_app_key, $dropbox_app_secure_key);
5378 $oauth->setToken($dropbox_access_token);
5379 $dropbox = new IWP_Dropbox_API($oauth);
5380
5381 }else{
5382 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/backup/dropbox.php';
5383
5384 try{
5385 set_iwp_dropbox_auth_setting($args);
5386 $helper = new IWP_MMB_UploadModule_dropbox();
5387 $dropbox = $helper->bootstrap();
5388 }
5389 catch(Exception $e){
5390
5391 }
5392 }
5393 $oldRoot = 'Apps/InfiniteWP/';
5394 $dropbox_destination = $oldRoot.ltrim(trim($dropbox_destination), '/');
5395 $dropbox_destination = rtrim($dropbox_destination, '/');
5396 if (isset($dropbox_site_folder) && $dropbox_site_folder == true){
5397 $dropbox_destination .= '/'.$this->site_name;
5398 }
5399 $folders = explode('/',$dropbox_destination);
5400 if (!isset($path)) {
5401 $path = '';
5402 }
5403 foreach ($folders as $key => $name) {
5404 $path.=trim($name).'/';
5405 }
5406 $dropbox_destination = $path;
5407 $oldVersion = false;
5408 }
5409
5410
5411 $temp_backup_file = $backup_file;
5412 if(!is_array($backup_file))
5413 {
5414 $backup_file = array();
5415 $backup_file[] = $temp_backup_file;
5416 }
5417 foreach($backup_file as $key => $value)
5418 {
5419 try {
5420 if (is_object($dropbox)) {
5421 if ($oldVersion) {
5422 $dropbox->fileopsDelete($dropbox_destination . '/' . $value);
5423 }else{
5424 $dropbox->delete($dropbox_destination . '/' . $value);
5425 }
5426 }
5427 } catch (Exception $e) {
5428 $this->_log($e->getMessage());
5429 /*return array(
5430 'error' => $e->getMessage(),
5431 'partial' => 1
5432 );*/
5433 }
5434 }
5435 //return true;
5436 }
5437
5438
5439 function get_dropbox_backup($args) {
5440 if ($this->iwp_mmb_function_exists('curl_init')) {
5441 extract($args);
5442 if(!isset($dropbox_access_token) && empty($dropbox_access_token)){
5443
5444 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/dropbox.php';
5445
5446 $dropbox = new IWP_Dropbox($consumer_key, $consumer_secret);
5447 $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
5448 $oldVersion = true;
5449 if ($dropbox_site_folder == true)
5450 $dropbox_destination .= '/' . $this->site_name;
5451 }else{
5452 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/API.php';
5453 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/Exception.php';
5454 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/ConsumerAbstract.php';
5455 require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Dropbox/OAuth/Consumer/Curl.php';
5456
5457 $oauth = new IWP_Dropbox_OAuth_Consumer_Curl($dropbox_app_key, $dropbox_app_secure_key);
5458 $oauth->setToken($dropbox_access_token);
5459 $dropbox = new IWP_Dropbox_API($oauth);
5460 $oldRoot = 'Apps/InfiniteWP/';
5461 $dropbox_destination = $oldRoot.ltrim(trim($dropbox_destination), '/');
5462 $dropbox_destination = rtrim($dropbox_destination, '/');
5463 if (isset($dropbox_site_folder) && $dropbox_site_folder == true){
5464 $dropbox_destination .= '/'.$this->site_name;
5465 }
5466 $folders = explode('/',$dropbox_destination);
5467 foreach ($folders as $key => $name) {
5468 $path.=trim($name).'/';
5469 }
5470 $dropbox_destination = $path;
5471 $oldVersion = false;
5472 }
5473
5474
5475 //$temp = ABSPATH . 'iwp_temp_backup.zip';
5476 $temp = wp_tempnam('iwp_temp_backup.zip');
5477
5478 try {
5479 //exception should handle the errors
5480 if (is_object($dropbox)) {
5481 if ($oldVersion) {
5482 $dropbox->download($dropbox_destination.'/'.$backup_file, $temp);
5483 }else{
5484 $dropbox->getFile($dropbox_destination.'/'.$backup_file, $temp);
5485 }
5486 return $temp;
5487 }
5488 } catch (Exception $e) {
5489 $this->_log($e->getMessage());
5490 return array(
5491 'error' => $e->getMessage(),
5492 'partial' => 1
5493 );
5494 }
5495 }
5496 else{
5497 return array(
5498 'error' => 1,
5499 );
5500 }
5501 }
5502
5503 /*
5504 This is the new amazon s3 function with multiCall support
5505
5506 1.initiate the multipart process and get an upload_id in return [using the function initiate_multipart_upload() ].
5507 2.divide the backup file into many parts [ using the function get_multipart_counts() ]
5508 3.call the function upload_part() and upload the parts one by one by getting an partsArray of PartNumber and Etag as response.
5509 4.On the finalCall complete the multipart upload by calling the function complete_multipart_upload() - by providing the $uploadID as well as partsArray .
5510
5511 ---notes---
5512 1.complete the multiPart only on the final call
5513 2.the mulitpart upload process should have to be completed or aborted because amazon will charge for the data used
5514
5515 */
5516
5517 function amazons3_backup_bwd_comp($historyID , $args='' )
5518 {
5519 $s3StartTime = $this->iwpScriptStartTime;
5520 $this -> backup_settings_vals = get_option('iwp_client_multi_backup_temp_values');
5521 $backup_settings_values = $this -> backup_settings_vals;
5522 if(isset($backup_settings_values['s3_retrace_count']) && !empty($backup_settings_values['s3_retrace_count']))
5523 {
5524 $s3_retrace_count = $backup_settings_values['s3_retrace_count'][$historyID];
5525 }
5526 else
5527 {
5528 $s3_retrace_count = 0;
5529 }
5530 //get the settings by other method
5531 $requestParams = $this -> getRequiredData($historyID,"requestParams");
5532 $upload_loop_break_time = $requestParams['account_info']['upload_loop_break_time']; //darkcode changed
5533 $upload_file_block_size = $requestParams['account_info']['upload_file_block_size'];
5534 if($upload_file_block_size < (5*1024*1024))
5535 {
5536 $upload_file_block_size = (5*1024*1024)+1;
5537 }
5538 $del_host_file = $requestParams['args']['del_host_file'];
5539
5540 $task_result = $this -> getRequiredData($historyID,"taskResults");
5541
5542 @set_time_limit(0);
5543 $this -> hisID = $historyID;
5544
5545 $uploadLoopCount = 0;
5546 $upload_id = 'start';
5547 $partsArray = array();
5548 $nextPart = 1;
5549 $retrace = 'notSet';
5550 $doComplete = false;
5551
5552 if($args == '')
5553 {
5554 //on the next call $args would be ''
5555 //set $args, $uploadid, $offset from the DB
5556 $responseParams = $this -> getRequiredData($historyID,"responseParams");
5557
5558 if(!$responseParams)
5559 return $this->statusLog($this -> hisID, array('stage' => 's3Upload', 'status' => 'error', 'statusMsg' => 'S3 Upload failed: Error while fetching table data.', 'statusCode' => 's3_upload_failed_error_while_fetching_table_data'));
5560
5561 $args = $responseParams['s3Args'];
5562 $prevChunkResults = $responseParams['response_data'];
5563 $upload_id = $prevChunkResults['upload_id'];
5564 $nextPart = $prevChunkResults['nextPart'];
5565 $partsArray = $prevChunkResults['partsArray'];
5566 $current_file_num = $responseParams['current_file_num'];
5567 $dont_retrace = $responseParams['dont_retrace'];
5568 $start_new_backup = $responseParams['start_new_backup'];
5569
5570 }
5571 if(empty($current_file_num))
5572 {
5573 $current_file_num = 0;
5574 }
5575
5576 //traceback options and setting values
5577
5578 if((!$upload_id)&&(empty($dont_retrace)))
5579 {
5580 if($s3_retrace_count <= 3)
5581 {
5582 $args = $requestParams['secure']['account_info']['iwp_amazon_s3'];
5583 if($backup_settings_values['s3_upload_id'])
5584 {
5585 $upload_id = $backup_settings_values['s3_upload_id'][$historyID];
5586 }
5587 else
5588 {
5589 return $this->statusLog($this -> hisID, array('stage' => 's3Upload Retrace', 'status' => 'error', 'statusMsg' => 'S3 Upload failed: Error while fetching table data during retrace', 'statusCode' => 's3_upload_failed_error_while_fetching_table_data_during_retrace'));
5590 }
5591 $backup_file = $backup_settings_values['backup_file'];
5592 $retrace = 'set';
5593 $s3_retrace_count++;
5594 $backup_settings_values['s3_retrace_count'][$historyID] = $s3_retrace_count;
5595 update_option('iwp_client_multi_backup_temp_values', $backup_settings_values);
5596
5597 }
5598 else
5599 {
5600 return $this->statusLog($this -> hisID, array('stage' => 's3Upload', 'status' => 'error', 'statusMsg' => 'S3 upload failed: Retrace limit reached.', 'statusCode' => 's3_upload_failed_retrace_limit_reached'));
5601 }
5602 }
5603
5604 if (!$this->iwp_mmb_function_exists('curl_init')) {
5605 return array(
5606 'error' => 'You cannot use Amazon S3 on your server. Please enable curl first.',
5607 'partial' => 1, 'error_code' => 'cannot_use_s3_enable_curl_first'
5608 );
5609 }
5610 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3_bwd_comp/sdk.class.php');
5611
5612 $tempArgs = $args;
5613 extract($args);
5614
5615 if(!is_array($backup_file))
5616 {
5617 $temp_backup_file = $backup_file;
5618 $backup_file = array();
5619 $backup_file[] = $temp_backup_file;
5620 }
5621
5622 if(is_array($backup_file))
5623 {
5624 $backup_files_count = count($backup_file);
5625 $temp_single_file = $backup_file[$current_file_num];
5626 unset($backup_file);
5627 $backup_file = $temp_single_file;
5628 }
5629
5630 if ($as3_site_folder == true)
5631 {
5632 if(!empty($as3_directory))
5633 {
5634 $as3_directory .= '/' . $this->site_name;
5635 }
5636 else
5637 {
5638 $as3_directory = $this->site_name;
5639 }
5640 }
5641
5642 try{
5643
5644 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'));
5645 $s3 = new AmazonS3();
5646 $cfu_obj = new CFUtilities;
5647 //the mulitCall upload starts darkCode starts
5648
5649
5650 //$this->statusLog($this -> hisID, array('stage' => 'uploadingFiles', 'status' => 'partiallyCompleted', 'statusMsg' => 's3MultiCallStartsHere'));
5651 if(!empty($as3_directory)){
5652 $as3_file = $as3_directory . '/' . basename($backup_file);
5653 }
5654 else{
5655 $as3_file = basename($backup_file);
5656 }
5657
5658 if((iwp_mmb_get_file_size($backup_file) <= 5*1024*1024))
5659 {
5660 echo "<br>small backup so single upload<br>";
5661 $response = $s3->create_object($as3_bucket, $as3_file, array('fileUpload' => $backup_file));
5662 if($response->isOK())
5663 {
5664 $current_file_num += 1;
5665
5666 $resArray = array (
5667 'status' => "completed",
5668 'backupParentHID' => $historyID,
5669 );
5670
5671 $result_arr = array();
5672 $result_arr['status'] = 'completed';
5673 $result_arr['nextFunc'] = 'amazons3_backup_over';
5674 $result_arr['s3Args'] = $tempArgs;
5675 $result_arr['current_file_num'] = $current_file_num;
5676 $result_arr['dont_retrace'] = true;
5677
5678 $task_result['task_results'][$historyID]['amazons3'][$current_file_num-1] = basename($backup_file);
5679 $task_result['amazons3'][$current_file_num-1] = basename($backup_file);
5680
5681 if($current_file_num >= $backup_files_count)
5682 {
5683 unset($task_result['task_results'][$historyID]['server']);
5684 @unlink($backup_file);
5685 }
5686 else
5687 {
5688 //to continue zip split parts
5689
5690 $resArray['status'] = 'partiallyCompleted';
5691
5692 $chunkResult = array();
5693 $chunkResult['partsArray'] = array();
5694 $chunkResult['nextPart'] = 1;
5695 $chunkResult['upload_id'] = 'start';
5696
5697 $result_arr['response_data'] = $chunkResult;
5698 $result_arr['nextFunc'] = 'amazons3_backup';
5699 $result_arr['status'] = 'partiallyCompleted';
5700 $result_arr['start_new_backup'] = true;
5701
5702 @unlink($backup_file);
5703 }
5704 $this->statusLog($this -> hisID, array('stage' => 's3MultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall','nextFunc' => 'amazons3_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
5705
5706 return $resArray;
5707 }
5708 else
5709 {
5710 return array(
5711 'error' => 'Failed to upload to Amazon S3.'
5712 );
5713 }
5714 }
5715
5716 if($upload_id == 'start')
5717 {
5718 echo "initiating multiCall upload";
5719
5720 //initiate the multiPartUpload to get the uploadID from its response
5721 $response = $s3->initiate_multipart_upload($as3_bucket, $as3_file); //createMultipartUpload
5722
5723
5724
5725 //convert the response into an array
5726 $response_array = $cfu_obj->convert_response_to_array($response);
5727
5728
5729 //get the uploadID
5730 $upload_id = $response_array['body']['UploadId'];
5731
5732
5733 //storing the uploadID in DB
5734 $backup_settings_values['s3_upload_id'][$historyID] = $upload_id;
5735 $backup_settings_values['backup_file'] = $backup_file;
5736 update_option('iwp_client_multi_backup_temp_values', $backup_settings_values);
5737 }
5738
5739 //get the parts of the big file
5740 $parts = $s3->get_multipart_counts(iwp_mmb_get_file_size($backup_file), $upload_file_block_size); //1 MB chunks
5741
5742 if($retrace == 'set')
5743 {
5744 $list_parts_response = $s3->list_parts($as3_bucket, $as3_file, $upload_id);
5745 $partsArray = CFUtilities::convert_response_to_array($list_parts_response);
5746 $nextPart = (count($partsArray) + 1);
5747 $this->statusLog($this -> hisID, array('stage' => 's3MultiCall', 'status' => 'partiallyCompleted', 'statusMsg' => 'retracingValues','nextFunc' => 'amazons3_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
5748 $retrace = 'unset';
5749 }
5750
5751
5752 //this is the main upload loop break it on when the timeLimit is reached
5753 //chunk upload loop
5754 $partsArraySize = count($parts);
5755 $s3ChunkTimeTaken = 0;
5756 $s3ChunkCount = 0;
5757 $reloop = false;
5758 $reloopCount = 0;
5759 $status = '';
5760 do
5761 {
5762 $uploadLoopCount = 0;
5763 if($reloopCount == 0)
5764 {
5765 $s3ChunkStartTime = $s3StartTime;
5766 }
5767 else
5768 {
5769 $s3ChunkStartTime = microtime(true);
5770 }
5771
5772 foreach ($parts as $i => $part)
5773 {
5774 $uploadLoopCount += 1;
5775 if($uploadLoopCount == $nextPart)
5776 {
5777 $singleUploadResponse = $s3->/* batch()-> */upload_part($as3_bucket, $as3_file, $upload_id, array(
5778 //'expect' => '100-continue',
5779 'fileUpload' => $backup_file,
5780 'partNumber' => ($i + 1),
5781 'seekTo' => /* (integer) */$part['seekTo'],
5782 'length' => /* (integer) */$part['length'],
5783 ));
5784
5785 $singleUploadResult = $singleUploadResponse->isOk();
5786
5787 echo "singleUploadResult - ".$singleUploadResult;
5788
5789 $singleUploadResponseArray = $cfu_obj->convert_response_to_array($singleUploadResponse);
5790 /* $response = $s3->complete_multipart_upload($bucket, $filename, $upload_id, array(
5791 array('PartNumber' => 1, 'ETag' => '"25e317773f308e446cc84c503a6d1f85"'),
5792 array('PartNumber' => 2, 'ETag' => '"a6d1f85f58498973f308e446cc84c503"'),
5793 array('PartNumber' => 3, 'ETag' => '"bed3c0a4a1407f584989b4009e9ce33f"'),
5794 )); */
5795
5796 $nextPart = $uploadLoopCount;
5797 $partsArray[$i + 1]['PartNumber'] = $i + 1;
5798 $partsArray[$i + 1]['ETag'] = $singleUploadResponseArray['header']['etag'];
5799
5800
5801 $chunkResult = array();
5802 $chunkResult['partsArray'] = $partsArray;
5803 $chunkResult['nextPart'] = $nextPart+1;
5804 $chunkResult['upload_id'] = $upload_id;
5805 $nextPart = $nextPart + 1;
5806
5807 $backup_settings_values['s3_retrace_count'][$historyID] = 0;
5808 update_option('iwp_client_multi_backup_temp_values', $backup_settings_values);
5809
5810 $status = 'partiallyCompleted';
5811 if(($nextPart) == ($partsArraySize + 1))
5812 {
5813 $doComplete = true;
5814 $status = 'completed';
5815 }
5816
5817 $result_arr = array();
5818 $result_arr['response_data'] = $chunkResult;
5819 $result_arr['status'] = $status;
5820 $result_arr['nextFunc'] = 'amazons3_backup';
5821 $result_arr['s3Args'] = $tempArgs;
5822 $result_arr['current_file_num'] = $current_file_num;
5823
5824 $task_result['task_results'][$historyID]['amazons3'][$current_file_num] = basename($backup_file);
5825 $task_result['amazons3'][$current_file_num] = basename($backup_file);
5826
5827 $this->statusLog($this -> hisID, array('stage' => 's3MultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall','nextFunc' => 'amazons3_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
5828
5829 $resArray = array (
5830 'status' => $status,
5831 'backupParentHID' => $historyID,
5832 );
5833
5834 /* $resArray = array (
5835 'status' => 'completed',
5836 'backupParentHID' => $historyID,
5837 ); */
5838 break;
5839 //return $resArray;
5840 //exit;
5841 }
5842 else
5843 {
5844 if($nextPart == ($partsArraySize+1))
5845 {
5846 $doComplete = true;
5847 break;
5848 }
5849 }
5850 }
5851
5852 if($doComplete)
5853 {
5854 // complete the multipart upload
5855 $response = $s3->complete_multipart_upload($as3_bucket, $as3_file, $upload_id, $partsArray);
5856
5857 if($response->isOK() != true)
5858 {
5859
5860 $response = $s3->abort_multipart_upload($as3_bucket, $as3_file, $upload_id );
5861 }
5862 $response_array = $cfu_obj->convert_response_to_array($response);
5863
5864 $current_file_num += 1;
5865
5866 $result_arr = array();
5867 $result_arr['response_data'] = $chunkResult;
5868 $result_arr['status'] = 'completed';
5869 $result_arr['nextFunc'] = 'amazons3_backup_over';
5870 $result_arr['s3Args'] = $tempArgs;
5871 $result_arr['dont_retrace'] = true;
5872 $result_arr['current_file_num'] = $current_file_num;
5873
5874 $resArray = array (
5875 'status' => 'completed',
5876 'backupParentHID' => $historyID,
5877 );
5878
5879
5880
5881 if($current_file_num >= $backup_files_count)
5882 {
5883 $task_result['task_results'][$historyID]['amazons3'][$current_file_num-1] = basename($backup_file);
5884 $task_result['amazons3'][$current_file_num-1] = basename($backup_file);
5885 unset($task_result['task_results'][$historyID]['server']);
5886 }
5887 else
5888 {
5889 //to continue zip split parts
5890 $status = 'partiallyCompleted';
5891 $chunkResult = array();
5892 $chunkResult['partsArray'] = array();
5893 $chunkResult['nextPart'] = 1;
5894 $chunkResult['upload_id'] = 'start';
5895
5896 $result_arr['response_data'] = $chunkResult;
5897 $result_arr['status'] = 'partiallyCompleted';
5898 $result_arr['nextFunc'] = 'amazons3_backup';
5899 $result_arr['start_new_backup'] = true;
5900
5901 $resArray['status'] = 'partiallyCompleted';
5902 }
5903 $this->statusLog($this -> hisID, array('stage' => 's3MultiCall', 'status' => 'completed', 'statusMsg' => 'finalCall','nextFunc' => 'amazons3_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
5904
5905 $upload = $response->isOk();
5906 }
5907
5908
5909
5910 //check time
5911 $s3ChunkEndTime = microtime(true);
5912 $s3ChunkTimeTaken = (($s3ChunkEndTime - $s3ChunkStartTime) + ($s3ChunkTimeTaken) / ($reloopCount + 1));
5913 $s3EndTime = microtime(true);
5914 $s3TimeTaken = $s3EndTime - $s3StartTime;
5915 $s3TimeLeft = $upload_loop_break_time - $s3TimeTaken;
5916 $s3TimeLeft = $s3TimeLeft - 5; //for safe timeLimit
5917
5918 if(!empty($chunkResult['nextPart']))
5919 {
5920 echo 'parts'.$chunkResult['nextPart'];
5921 }
5922 echo " s3TimeTaken ".$s3TimeTaken;
5923 $s3UploadedSize = $uploadLoopCount * 5;
5924 echo " s3 approx file size written ".$s3UploadedSize;
5925 iwp_mmb_print_flush("s3loop");
5926 echo " s3TimeLeft ".$s3TimeLeft;
5927 echo " s3ChunkTimeTaken ".$s3ChunkTimeTaken;
5928 if(($s3TimeLeft <= $s3ChunkTimeTaken)||(!$singleUploadResult)||($doComplete))
5929 {
5930 $reloop = false;
5931 echo "reloop stopped";
5932 }
5933 else
5934 {
5935 $reloop = true;
5936 $reloopCount++;
5937 }
5938
5939 }while($reloop);
5940
5941 if(!$doComplete)
5942 {
5943 return $resArray;
5944 }
5945
5946 if($doComplete && $upload)
5947 {
5948
5949 $status = 'completed';
5950 iwp_mmb_print_flush('Amazon S3 upload: End');
5951 if($status == 'completed')
5952 {
5953 //file verification
5954 //checking file size and comparing
5955 //getting the hash value
5956 $partArrayLength = count($partsArray);
5957 $verificationResult = $this -> postUploadVerification($s3, $backup_file, $as3_file, $type = "amazons3", $as3_bucket);
5958 if(!$verificationResult)
5959 {
5960 return $this->statusLog($historyID, array('stage' => 'uploadAmazons3', 'status' => 'error', 'statusMsg' => 'S3 verification failed: File may be corrupted.', 'statusCode' => 'docomplete_S3_verification_failed_file_may_be_corrupted'));
5961 }
5962 if($del_host_file)
5963 {
5964 @unlink($backup_file);
5965 }
5966 }
5967 return $resArray;
5968 }
5969 else {
5970
5971 return array(
5972 'error' => 'Failed to upload to Amazon S3. Please check your details and set upload/delete permissions on your bucket.',
5973 'partial' => 1, 'error_code' => 'failed_to_upload_to_s3_check_your_details_and_set_upload_delete_permissions_on_your_bucket'
5974 );
5975 }
5976
5977
5978 }
5979 catch (Exception $e)
5980 {
5981
5982 $err = $e->getMessage();
5983 if($err){
5984 return array(
5985 'error' => 'Failed to upload to AmazonS3 ('.$err.').', 'error_code' => 'failed_to_upload_s3_err'
5986 );
5987 } else {
5988 return array(
5989 'error' => 'Failed to upload to Amazon S3.', 'error_code' => 'failed_to_upload_s3'
5990 );
5991 }
5992 }
5993 }
5994
5995 function remove_amazons3_backup_bwd_comp($args)
5996 {
5997 if ($this->iwp_mmb_function_exists('curl_init')) {
5998 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3_bwd_comp/sdk.class.php');
5999 extract($args);
6000
6001 if(!is_array($backup_file))
6002 {
6003 $temp_backup_file = $backup_file;
6004 $backup_file = array();
6005 $backup_file[] = $temp_backup_file;
6006 }
6007
6008 if ($as3_site_folder == true)
6009 {
6010 if(!empty($as3_directory))
6011 {
6012 $as3_directory .= '/' . $this->site_name;
6013 }
6014 else
6015 {
6016 $as3_directory = $this->site_name;
6017 }
6018 }
6019 try{
6020 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'));
6021 $s3 = new AmazonS3();
6022 foreach($backup_file as $single_backup_file)
6023 {
6024 if(empty($as3_directory))
6025 {
6026 $single_as3_file = $single_backup_file;
6027 }
6028 else
6029 {
6030 $single_as3_file = $as3_directory . '/' . $single_backup_file;
6031 }
6032 $s3->delete_object($as3_bucket, $single_as3_file);
6033 }
6034
6035 } catch (Exception $e){
6036
6037 }
6038 }
6039 }
6040
6041 function get_amazons3_backup_bwd_comp($args)
6042 {
6043 if ($this->iwp_mmb_function_exists('curl_init')) {
6044 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon_s3_bwd_comp/sdk.class.php');
6045 extract($args);
6046 $temp = '';
6047 try{
6048 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'));
6049 $s3 = new AmazonS3();
6050 if ($as3_site_folder == true)
6051 {
6052 if(!empty($as3_directory))
6053 {
6054 $as3_directory .= '/' . $this->site_name;
6055 }
6056 else
6057 {
6058 $as3_directory = $this->site_name;
6059 }
6060 }
6061 if(empty($as3_directory))
6062 {
6063 $single_as3_file = $backup_file;
6064 }
6065 else
6066 {
6067 $single_as3_file = $as3_directory . '/' . $backup_file;
6068 }
6069
6070 //$temp = ABSPATH . 'iwp_temp_backup.zip';
6071 $temp = wp_tempnam('iwp_temp_backup.zip');
6072 $s3->get_object($as3_bucket, $single_as3_file, array("fileDownload" => $temp));
6073 } catch (Exception $e){
6074 return false;
6075 }
6076 return $temp;
6077 }
6078 else{
6079 return array(
6080 'error' => 1,
6081 );
6082 }
6083 }
6084 //IWP Remove ends here
6085
6086 function get_google_drive_backup($args)
6087 {
6088 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Client.php');
6089 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Service/Drive.php');
6090
6091 //refresh token
6092 $client = new IWP_google_Client();
6093 $client->setClientId($args['clientID']);
6094 $client->setClientSecret($args['clientSecretKey']);
6095 $client->setRedirectUri($args['redirectURL']);
6096 $client->setScopes(array(
6097 'https://www.googleapis.com/auth/drive',
6098 'https://www.googleapis.com/auth/userinfo.email',
6099 'https://www.googleapis.com/auth/userinfo.profile'));
6100
6101 //$client->setUseObjects(true);
6102
6103 $accessToken = $args['token'];
6104 $refreshToken = $accessToken['refresh_token'];
6105
6106 try
6107 {
6108 $client->refreshToken($refreshToken);
6109 }
6110 catch(Exception $e)
6111 {
6112 echo 'google Error ', $e->getMessage(), "\n";
6113 return array("error" => $e->getMessage(), "error_code" => "google_error_refresh_token");
6114 }
6115
6116 //downloading the file
6117 $service = new IWP_google_Service_Drive($client);
6118
6119 $file = $service->files->get($args['backup_file']);
6120
6121 $downloadUrl = $file->getDownloadUrl();
6122
6123 $temp = wp_tempnam('iwp_temp_backup.zip');
6124
6125 try
6126 {
6127 if ($downloadUrl)
6128 {
6129 $request = new IWP_google_Http_Request($downloadUrl, 'GET', null, null);
6130
6131 $signHttpRequest = $client->getAuth()->sign($request);
6132 $httpRequest = $client->getIo()->makeRequest($signHttpRequest);
6133
6134 if ($httpRequest->getResponseHttpCode() == 200) {
6135 file_put_contents($temp, $httpRequest->getResponseBody());
6136 return $temp;
6137 } else {
6138 // An error occurred.
6139 return array("error" => "There is some error.", "error_code" => "google_error_bad_response_code");
6140 }
6141 }
6142 else
6143 {
6144 // The file doesn't have any content stored on Drive.
6145 return array("error" => "Google Drive file doesnt have nay content.", "error_code" => "google_error_download_url");
6146 }
6147 }catch(Exception $e)
6148 {
6149 echo 'google Error ', $e->getMessage(), "\n";
6150 return array("error" =>$e->getMessage(), "error_code" => "google_error_download_url_catch_excep");
6151 }
6152
6153
6154 }
6155
6156
6157 /*
6158 Google Drive Upload Function:
6159
6160 */
6161
6162 function google_drive_backup($historyID = 0, $args = '', $uploadid = null, $offset = 0){
6163 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Client.php');
6164 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Http/MediaFileUpload.php');
6165 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Service/Drive.php');
6166
6167 $this -> hisID = $historyID;
6168
6169 $requestParams = $this -> getRequiredData($historyID,"requestParams");
6170 $upload_loop_break_time = $requestParams['account_info']['upload_loop_break_time']; //darkcode changed
6171 $upload_file_block_size = $requestParams['account_info']['upload_file_block_size'];
6172 $upload_file_block_size = 5 *1024 *1024;
6173 $del_host_file = $requestParams['args']['del_host_file'];
6174 $iwp_folder_id = '';
6175 $sub_folder_id = '';
6176 $sub_folder_name = $this->site_name;
6177
6178 $task_result = $this->getRequiredData($historyID, "taskResults");
6179
6180 $fileSizeUploaded = 0;
6181 $resumeURI = false;
6182 $current_file_num = 0;
6183
6184 if($args == ''){
6185 //on the next call $args would be ''
6186 //set $args, $uploadid, $offset from the DB
6187 $responseParams = $this -> getRequiredData($historyID,"responseParams");
6188
6189 if(!$responseParams){
6190 return $this->statusLog($this -> hisID, array('stage' => 'google_drive_upload', 'status' => 'error', 'statusMsg' => 'google Upload failed: Error while fetching table data.','statusCode' => 'google_upload_failed_error_fetching_data'));
6191 }
6192
6193 $args = $responseParams['gDriveArgs'];
6194 $prevChunkResults = $responseParams['response_data'];
6195 if(is_array($prevChunkResults))
6196 {
6197 $resumeURI = $prevChunkResults['resumeURI'];
6198 $fileSizeUploaded = $prevChunkResults['fileSizeUploaded'];
6199 }
6200 $current_file_num = $responseParams['current_file_num'];
6201 }
6202 $create_sub_folder = $args['gdrive_site_folder'];
6203 $tempArgs = $args;
6204 $client = new IWP_google_Client();
6205 $client->setClientId($args['clientID']);
6206 $client->setClientSecret($args['clientSecretKey']);
6207 $client->setRedirectUri($args['redirectURL']);
6208 $client->setScopes(array(
6209 'https://www.googleapis.com/auth/drive',
6210 'https://www.googleapis.com/auth/userinfo.email',
6211 'https://www.googleapis.com/auth/userinfo.profile'));
6212 $accessToken = $args['token'];
6213 $refreshToken = $accessToken['refresh_token'];
6214 $backup_file = $args['backup_file'];
6215
6216 if(!is_array($backup_file)){
6217 $temp_backup_file = $backup_file;
6218 $backup_file = array();
6219 $backup_file[] = $temp_backup_file;
6220 }
6221
6222 if(is_array($backup_file)){
6223 $backup_files_count = count($backup_file);
6224 $backup_file = $backup_file[$current_file_num];
6225 }
6226
6227 try{
6228 $client->refreshToken($refreshToken);
6229 }
6230 catch(Exception $e){
6231 echo 'google Error ', $e->getMessage(), "\n";
6232 return array("error" => $e->getMessage(), "error_code" => "google_error_backup_refresh_token");
6233 }
6234
6235 //$client = new IWP_google_Client();
6236 //$accessToken = $client->authenticate($accessToken_early['refresh_token']);
6237 //$client->setAccessToken($accessToken);
6238
6239 $service = new IWP_google_Service_Drive($client);
6240
6241 //create iwp folder folder if it is not present
6242 try{
6243 $parameters = array();
6244 $parameters['q'] = "title = 'infinitewp' and trashed = false and 'root' in parents and 'me' in owners and mimeType= 'application/vnd.google-apps.folder'";
6245 $files = $service->files->listFiles($parameters);
6246 $list_result = array();
6247 $list_result = array_merge($list_result, $files->getItems());
6248 $list_result = (array)$list_result;
6249
6250 if(empty($list_result)){
6251 $file = new IWP_google_Service_Drive_DriveFile();
6252 $file->setTitle('infinitewp');
6253 $file->setMimeType('application/vnd.google-apps.folder');
6254
6255 $createdFolder = $service->files->insert($file, array(
6256 'mimeType' => 'application/vnd.google-apps.folder',
6257 ));
6258 if($createdFolder){
6259 $createdFolder = (array)$createdFolder;
6260 $iwp_folder_id = $createdFolder['id'];
6261 }
6262 }
6263 else{
6264 foreach($list_result as $k => $v){
6265 $iwp_folder_id = $v->id;
6266 }
6267 }
6268 }catch (Exception $e){
6269 print "An error occurred: " . $e->getMessage();
6270 return array('error' => $e->getMessage(), 'error_code' => 'google_error_occured_list_results');
6271 }
6272
6273 //create sub folder by site name
6274 if($create_sub_folder){
6275 $parameters = array();
6276 $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'";
6277 //$parameters['corpus'] = "DEFAULT";
6278 $files = $service->files->listFiles($parameters);
6279 $list_result = array();
6280 $list_result = array_merge($list_result, $files->getItems());
6281 $list_result = (array)$list_result;
6282
6283 if(empty($list_result)){
6284 $file = new IWP_google_Service_Drive_DriveFile();
6285 $file->setTitle($sub_folder_name);
6286 $file->setMimeType('application/vnd.google-apps.folder');
6287
6288 //setting parent as infinitewpFolder
6289 $parent = new IWP_google_Service_Drive_ParentReference();
6290 $parent->setId($iwp_folder_id);
6291 $file->setParents(array($parent));
6292
6293 $createdFolder = $service->files->insert($file, array(
6294 'mimeType' => 'application/vnd.google-apps.folder',
6295 ));
6296 if($createdFolder)
6297 {
6298 $createdFolder = (array)$createdFolder;
6299 $sub_folder_id = $createdFolder['id'];
6300 }
6301 }
6302 else{
6303 foreach($list_result as $k => $v){
6304 $sub_folder_id = $v->id;
6305 }
6306 }
6307 }
6308
6309 //Insert a file
6310 $file = new IWP_google_Service_Drive_DriveFile();
6311 $file->setTitle(basename($backup_file));
6312 $file->setMimeType('binary/octet-stream');
6313
6314 // Set the Parent Folder on Google Drive
6315 $parent = new IWP_google_Service_Drive_ParentReference();
6316 if(empty($sub_folder_id)){
6317 $parent->setId($iwp_folder_id);
6318 }
6319 else{
6320 $parent->setId($sub_folder_id);
6321 }
6322 $file->setParents(array($parent));
6323
6324 $gDriveID = '';
6325 try{
6326 if(false){
6327 //single upload
6328 $data = file_get_contents($backup_file);
6329 $createdFile = (array)$service->files->insert($file, array(
6330 'data' => $data,
6331 //'mimeType' => 'text/plain',
6332 ));
6333 $gDriveID = $createdFile['id'];
6334 }
6335
6336 //multipart upload
6337
6338 if(true){
6339 // Call the API with the media upload, defer so it doesn't immediately return.
6340 $client->setDefer(true);
6341 $request = $service->files->insert($file);
6342
6343 // Create a media file upload to represent our upload process.
6344 $media = new IWP_google_Http_MediaFileUpload($client, $request, 'application/zip', null, true, $upload_file_block_size);
6345 $media->setFileSize(filesize($backup_file));
6346
6347
6348 $status = false;
6349 $handle = fopen($backup_file, "rb");
6350 fseek($handle, $fileSizeUploaded);
6351
6352 $resArray = array (
6353 'status' => 'completed',
6354 'backupParentHID' => $historyID,
6355 );
6356
6357 while (!$status && !feof($handle)){
6358 iwp_mmb_auto_print('gdrive_chucked_upload');
6359 $chunk = fread($handle, $upload_file_block_size);
6360 $statusArray = $media->nextChunk($chunk, $resumeURI, $fileSizeUploaded);
6361 $status = $statusArray['status'];
6362 if (isset($statusArray['resumeURI'])) {
6363 $resumeURI = $statusArray['resumeURI'];
6364 }
6365 //$fileSizeUploaded = ftell($handle);
6366 $fileSizeUploaded = $statusArray['progress'];
6367
6368 $googleTimeTaken = microtime(1) - $GLOBALS['IWP_MMB_PROFILING']['ACTION_START'];
6369 if(($googleTimeTaken > $upload_loop_break_time)&&($status != true)){
6370 $chunkResult['resumeURI'] = $resumeURI;
6371 $chunkResult['fileSizeUploaded'] = $fileSizeUploaded;
6372
6373 echo "<br> file uploaded size in this call: ".$fileSizeUploaded."<br>";
6374
6375 $result_arr = array();
6376 $result_arr['response_data'] = $chunkResult;
6377 $result_arr['status'] = 'partiallyCompleted';
6378 $result_arr['nextFunc'] = 'google_drive_backup';
6379 $result_arr['gDriveArgs'] = $tempArgs;
6380 $result_arr['current_file_num'] = $current_file_num;
6381
6382 /* $task_result['task_results'][$historyID]['gDriveOrgFileName'][] = basename($backup_file);
6383 $task_result['task_results'][$historyID]['gDrive'][] = $gDriveID;
6384 //$task_result['gDrive'] = basename($backup_file);
6385 $task_result['gDrive'][] = $gDriveID; */
6386
6387 $this->statusLog($this -> hisID, array('stage' => 'amazonMultiCall', 'status' => 'partiallyCOmpleted', 'statusMsg' => 'nextCall','nextFunc' => 'amazons3_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
6388
6389 $resArray['status'] = "partiallyCompleted";
6390 return $resArray;
6391 }
6392 }
6393
6394 $result = false;
6395 if($status != false){
6396 $result = $status;
6397 }
6398
6399 fclose($handle);
6400 $client->setDefer(false);
6401
6402 $completeBackupResult = (array)$status;
6403
6404 //$gDriveID = $createdFile['id'];
6405 $gDriveID = $completeBackupResult['id'];
6406 }
6407 }catch (Exception $e){
6408 echo "An error occurred: " . $e->getMessage();
6409 return array("error" => "gDrive Error".$e->getMessage(), "error_code" => "google_error_multipart_upload");
6410 }
6411
6412 $current_file_num += 1;
6413 $result_arr = array();
6414 $result_arr['response_data'] = (isset($createdFile) && !empty($createdFile['id'])) ? $createdFile['id'] : array();
6415 $result_arr['status'] = "completed";
6416 $result_arr['nextFunc'] = 'google_drive_completed';
6417 $result_arr['gDriveArgs'] = $tempArgs;
6418 $result_arr['current_file_num'] = $current_file_num;
6419
6420 $resArray = array (
6421 'status' => 'completed',
6422 'backupParentHID' => $historyID,
6423 );
6424
6425 //$task_result = $this->getRequiredData($historyID, "taskResults");
6426 $task_result['task_results'][$historyID]['gDriveOrgFileName'][] = basename($backup_file);
6427 $task_result['task_results'][$historyID]['gDrive'][] = $gDriveID;
6428 //$task_result['gDrive'] = basename($backup_file);
6429 $task_result['gDrive'][] = $gDriveID;
6430
6431 if($current_file_num == $backup_files_count){
6432 $result_arr['nextFunc'] = 'google_drive_completed';
6433 iwp_mmb_print_flush('Google Drive upload: End');
6434 unset($task_result['task_results'][$historyID]['server']);
6435 }
6436 else{
6437 $result_arr['status'] = "partiallyCompleted";
6438 $result_arr['nextFunc'] = 'google_drive_backup';
6439 $result_arr['response_data'] = false;
6440 $resArray['status'] = 'partiallyCompleted';
6441 }
6442
6443 if($del_host_file){
6444 @unlink($backup_file);
6445 }
6446
6447 $this->statusLog($this -> hisID, array('stage' => 'gDriveMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall','nextFunc' => 'google_drive_completed', 'task_result' => $task_result, 'responseParams' => $result_arr));
6448
6449 return $resArray;
6450 }
6451
6452
6453 function remove_google_drive_backup($args)
6454 {
6455 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Client.php');
6456 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/lib/Google/Service/Drive.php');
6457
6458 $client = new IWP_google_Client();
6459 $client->setClientId($args['clientID']);
6460 $client->setClientSecret($args['clientSecretKey']);
6461 $client->setRedirectUri($args['redirectURL']);
6462 $client->setScopes(array(
6463 'https://www.googleapis.com/auth/drive',
6464 'https://www.googleapis.com/auth/userinfo.email',
6465 'https://www.googleapis.com/auth/userinfo.profile'));
6466
6467 //$client->setUseObjects(true);
6468
6469 $accessToken = $args['token'];
6470 $refreshToken = $accessToken['refresh_token'];
6471 $backup_file = $args['backup_file'];
6472 if(!is_array($backup_file))
6473 {
6474 $backup_file = array();
6475 $backup_file[0] = $args['backup_file'];
6476 }
6477
6478 try
6479 {
6480 $client->refreshToken($refreshToken);
6481 }
6482 catch(Exception $e)
6483 {
6484 echo 'google Error ', $e->getMessage(), "\n";
6485 return array("error" => $e->getMessage(), "error_code" => "google_error_remove_refresh_token");
6486 }
6487
6488 $service = new IWP_google_Service_Drive($client);
6489
6490 foreach($backup_file as $key => $value)
6491 {
6492 try
6493 {
6494 $service->files->delete($value);
6495 }
6496 catch (Exception $e)
6497 {
6498 echo "An error occurred: " . $e->getMessage();
6499 return array("error" => "gDrive Remove Error".$e->getMessage(), "error_code" => "google_error_delete");
6500 }
6501 }
6502 }
6503
6504 function schedule_next($type, $schedule)
6505 {
6506 $schedule = explode("|", $schedule);
6507 if (empty($schedule))
6508 return false;
6509 switch ($type) {
6510
6511 case 'daily':
6512
6513 if (isset($schedule[1]) && $schedule[1]) {
6514 $delay_time = $schedule[1] * 60;
6515 }
6516
6517 $current_hour = date("H");
6518 $schedule_hour = $schedule[0];
6519 if ($current_hour >= $schedule_hour){
6520 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 1, date("Y"));
6521 //$time ='0001#'.$current_hour.'|'.$schedule_hour;
6522
6523 }
6524
6525 else{
6526 $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
6527 //$time ='0000#'.$current_hour.'|'.$schedule_hour;
6528 }
6529 $time = time() + 30;
6530
6531
6532 break;
6533
6534
6535 case 'weekly':
6536 if (isset($schedule[2]) && $schedule[2]) {
6537 $delay_time = $schedule[2] * 60;
6538 }
6539 $current_weekday = date('w');
6540 $schedule_weekday = $schedule[1];
6541 $current_hour = date("H");
6542 $schedule_hour = $schedule[0];
6543
6544 if ($current_weekday > $schedule_weekday)
6545 $weekday_offset = 7 - ($schedule_weekday - $schedule[1]);
6546 else
6547 $weekday_offset = $schedule_weekday - $current_weekday;
6548
6549
6550 if (!$weekday_offset) { //today is scheduled weekday
6551 if ($current_hour >= $schedule_hour)
6552 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 7, date("Y"));
6553 else
6554 $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
6555 } else {
6556 $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + $weekday_offset, date("Y"));
6557 }
6558
6559 break;
6560
6561 case 'monthly':
6562 if (isset($schedule[2]) && $schedule[2]) {
6563 $delay_time = $schedule[2] * 60;
6564 }
6565 $current_monthday = date('j');
6566 $schedule_monthday = $schedule[1];
6567 $current_hour = date("H");
6568 $schedule_hour = $schedule[0];
6569
6570 if ($current_monthday > $schedule_monthday) {
6571 $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
6572 } else if ($current_monthday < $schedule_monthday) {
6573 $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
6574 } else if ($current_monthday == $schedule_monthday) {
6575 if ($current_hour >= $schedule_hour)
6576 $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
6577 else
6578 $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
6579 break;
6580 }
6581
6582 break;
6583 default:
6584 break;
6585 }
6586
6587 if (isset($delay_time) && $delay_time) {
6588 $time += $delay_time;
6589 }
6590
6591 return $time;
6592 }
6593
6594
6595 //Parse task arguments for info on IWP Admin Panel
6596 /* function get_backup_stats()
6597 {
6598 $stats = array();
6599 $tasks = $this->tasks;
6600 if (is_array($tasks) && !empty($tasks)) {
6601 foreach ($tasks as $task_name => $info) {
6602 if (is_array($info['task_results']) && !empty($info['task_results'])) {
6603 foreach ($info['task_results'] as $key => $result) {
6604 if (isset($result['server']) && !isset($result['error'])) {
6605 if (!file_exists($result['server']['file_path'])) {
6606 $info['task_results'][$key]['error'] = 'Backup created but manually removed from server.';
6607 }
6608 }
6609 }
6610 }
6611 if (is_array($info['task_results']))
6612 $stats[$task_name] = $info['task_results'];
6613 }
6614 }
6615 return $stats;
6616 } */
6617
6618
6619 /*function get_next_schedules()
6620 {
6621 $stats = array();
6622 $tasks = $this->tasks;
6623 if (is_array($tasks) && !empty($tasks)) {
6624 foreach ($tasks as $task_name => $info) {
6625 $stats[$task_name] = isset($info['task_args']['next']) ? $info['task_args']['next'] : array();
6626 }
6627 }
6628 return $stats;
6629 }
6630 */
6631
6632 function remove_old_backups($task_name, $limit = false)
6633 {
6634 //Check for previous failed backups first
6635 //$this->cleanup();
6636
6637 global $wpdb;
6638 $table_name = $wpdb->base_prefix . "iwp_backup_status";
6639
6640 //Check for previous failed backups first
6641 $this->cleanup();
6642
6643 //Remove by limit
6644 $backups = $this->get_all_tasks();
6645
6646 if ($limit === false) {
6647 $thisTask = $this->get_this_tasks();
6648 $requestParams = unserialize($thisTask['requestParams']);
6649 $limit = absint($requestParams['args']['limit']);
6650 }else{
6651 $limit = absint(($limit == 1) ? 0 : $limit);
6652 $fromNewBackup = true;
6653 }
6654 /*if ($task_name == 'Backup Now') {
6655 $num = 0;
6656 } else {
6657 $num = 1;
6658 }*/
6659 $other_method_backups = iwp_mmb_get_backup_ID_by_taskname('advanced', $task_name);
6660 $current_backups = $this->get_timestamp_by_label($task_name);
6661 $all_backups = array();
6662 $delete_backup = array();
6663 if (!empty($other_method_backups)) {
6664 $all_backups = array_merge($all_backups, $other_method_backups);
6665 if (!empty($current_backups)) {
6666 $all_backups = array_merge($all_backups, $current_backups);
6667 ksort($all_backups);
6668 ksort($current_backups);
6669 foreach ($other_method_backups as $timestamp => $historyID) {
6670 foreach ($current_backups as $time => $value) {
6671 if ($time > $timestamp) {
6672 $delete_backup[$timestamp] = $timestamp;
6673 }
6674 break;
6675 }
6676 }
6677 }
6678 }
6679 if (!empty($delete_backup)) {
6680 $total_backups = count($all_backups);
6681 if ($total_backups > $limit) {
6682 require_once($GLOBALS['iwp_mmb_plugin_dir'].'/backup/backup.core.class.php');
6683 iwp_mmb_define_constant();
6684 $backup_instance = new IWP_MMB_Backup_Core();
6685 foreach ($delete_backup as $timestamp => $historyID) {
6686 $total_backups--;
6687 $backup_instance->delete_backup(array('result_id' => $historyID));
6688 if ($total_backups<= $limit) {
6689 return;
6690 }
6691 }
6692 }
6693 }
6694
6695 $select_prev_backup = $wpdb->prepare(
6696 "SELECT historyID, taskResults FROM {$table_name} WHERE taskName = %s ORDER BY ID DESC LIMIT %d, 100",
6697 $task_name,
6698 $limit
6699 );
6700
6701 $select_prev_backup_res = $wpdb->get_results($select_prev_backup, ARRAY_A);
6702
6703
6704 foreach ( $select_prev_backup_res as $backup_data )
6705 {
6706 $deleted = 1;
6707 $task_result = unserialize($backup_data['taskResults']);
6708
6709 if (isset($task_result['task_results'][$backup_data['historyID']]['server'])) {
6710 $backup_file = $task_result['task_results'][$backup_data['historyID']]['server']['file_path'];
6711 if(!is_array($backup_file))
6712 {
6713 $temp_backup_file = $backup_file;
6714 $backup_file = array();
6715 $backup_file[0] = $temp_backup_file;
6716 }
6717 foreach($backup_file as $value)
6718 {
6719 @unlink($value);
6720 }
6721 }
6722
6723 $thisRequestParams = $this->getRequiredData($backup_data['historyID'], "requestParams");
6724
6725 if (isset($task_result['task_results'][$backup_data['historyID']]['ftp'])) {
6726 $ftp_file = $task_result['task_results'][$backup_data['historyID']]['ftp'];
6727 $args = $thisRequestParams['account_info']['iwp_ftp'];
6728 $args['backup_file'] = $ftp_file;
6729 $this->remove_ftp_backup($args);
6730 }
6731
6732 if (isset($task_result['task_results'][$backup_data['historyID']]['amazons3'])) {
6733 $amazons3_file = $task_result['task_results'][$backup_data['historyID']]['amazons3'];
6734 $args = $thisRequestParams['account_info']['iwp_amazon_s3'];
6735 $args['backup_file'] = $amazons3_file;
6736 if(is_new_s3_compatible()){
6737 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
6738 $new_s3_obj = new IWP_MMB_S3_MULTICALL();
6739 $new_s3_obj->remove_amazons3_backup($args);
6740 }
6741 else{
6742 $this->remove_amazons3_backup_bwd_comp($args);
6743 }
6744 }
6745
6746 if (isset($task_result['task_results'][$backup_data['historyID']]['dropbox']) && isset($thisRequestParams['account_info']['iwp_dropbox'])) {
6747 //To do: dropbox remove
6748 $dropbox_file = $task_result['task_results'][$backup_data['historyID']]['dropbox'];
6749 $args = $thisRequestParams['account_info']['iwp_dropbox'];
6750 $args['backup_file'] = $dropbox_file;
6751 if(!empty($args['dropbox_access_token']) || (empty($args['dropbox_access_token']) && time() < 1498608000)){
6752 $this->remove_dropbox_backup($args);
6753 }
6754 }
6755
6756 if (isset($task_result['task_results'][$backup_data['historyID']]['gDrive'])) {
6757 $gdrive_file = $task_result['task_results'][$backup_data['historyID']]['gDrive'];
6758 $args = $thisRequestParams['account_info']['iwp_gdrive'];
6759 $args['backup_file'] = $gdrive_file;
6760 $this->remove_google_drive_backup($args);
6761 }
6762
6763 $delete_query = $wpdb->prepare(
6764 "DELETE FROM {$table_name} WHERE historyID = %d",
6765 absint($backup_data['historyID'])
6766 );
6767
6768 $deleteRes = $wpdb->query($delete_query);
6769 }
6770 if (!empty($fromNewBackup) && $fromNewBackup) {
6771 return ($deleted)?true:false;
6772 }else{
6773 return true;
6774 }
6775
6776 }
6777
6778 function cleanup()
6779 {
6780 $tasks = $this->get_all_tasks(); //all backups task results array.
6781 $requestParams = $this->get_all_tasks(true);
6782 $thisTask = $this->get_this_tasks();
6783 $backup_folder = WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups/';
6784 $backup_folder_new = IWP_BACKUP_DIR . '/';
6785 $backup_temp_folder = IWP_PCLZIP_TEMPORARY_DIR;
6786 $files = glob($backup_folder . "*");
6787 $new = glob($backup_folder_new . "*");
6788 $new_temp = glob($backup_temp_folder . "*");
6789
6790 //Failed db files first
6791 $db_folder = IWP_DB_DIR . '/';
6792 $db_files = glob($db_folder . "*");
6793 if (is_array($db_files) && !empty($db_files)) {
6794 foreach ($db_files as $file) {
6795 @unlink($file);
6796 }
6797 @unlink(IWP_BACKUP_DIR.'/iwp_db/index.php');
6798 @rmdir(IWP_DB_DIR);
6799 }
6800
6801
6802 //clean_old folder?
6803 if ((count($files) == 1 && basename($files[0]) == 'index.php') || (!empty($files))) { //USE (!empty($files)
6804 foreach ($files as $file) {
6805 @unlink($file);
6806 }
6807 @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client') . '/iwp_backups');
6808 @rmdir(WP_CONTENT_DIR . '/' . md5('iwp_mmb-client'));
6809 }
6810
6811 if (!empty($new)) {
6812 foreach ($new as $b) {
6813 $files[] = $b;
6814 }
6815 }
6816 if (!empty($new_temp)) {
6817 foreach ($new_temp as $c) {
6818 $files[] = $c;
6819 }
6820 }
6821 $deleted = array();
6822
6823 $results = array();
6824 if (is_array($files) && count($files)) {
6825 $cloudFailedBackup = array();
6826 $failedBackupHisID = array();
6827 if (!empty($tasks)) {
6828 foreach ((array) $tasks as $taskName => $task) {
6829 //if (isset($task) && count($task)) {
6830 // foreach ($task as $backup) {
6831 if (isset($task['task_results']) && count($task['task_results'])) {
6832 foreach ($task['task_results'] as $historyID => $backup) {
6833 if (isset($backup['server'])) {
6834 $this_backup_file = $backup['server']['file_path'];
6835 if(is_array($this_backup_file))
6836 {
6837 foreach($this_backup_file as $single_backup_file)
6838 { if (!empty($requestParams[$taskName]['requestParams'][$historyID]['account_info']) && $thisTask['historyID'] != $historyID) {
6839 $cloudFailedBackup[]= $single_backup_file;
6840 $failedBackupHisID[$historyID]=$historyID;
6841 }
6842 $results[] = $single_backup_file;
6843 }
6844 }
6845 else
6846 {
6847 if (!empty($requestParams[$taskName]['requestParams'][$historyID]['account_info']) && !empty($thisTask['historyID']) && $thisTask['historyID'] != $historyID) {
6848 $cloudFailedBackup[]= $this_backup_file;
6849 $failedBackupHisID[$historyID]=$historyID;
6850 }
6851 $results[] = $this_backup_file;
6852 }
6853 $results[] = 'DE_clMemoryPeak.'.$historyID.'.txt';
6854 $results[] = 'DE_clMemoryUsage.'.$historyID.'.txt';
6855 $results[] = 'DE_clTimeTaken.'.$historyID.'.txt';
6856 $results[] = 'DE_clCPUUsage.'.$historyID.'.txt';
6857 }
6858 }
6859 }
6860 }
6861 }
6862
6863 $pheonixBackup = $GLOBALS['iwp_backup_core']->get_backup_history();
6864 if (!empty($pheonixBackup)) {
6865 foreach ($pheonixBackup as $timestamp => $backup) {
6866 if (!empty($backup['plugins'])) {
6867 $results = array_merge($results, $backup['plugins']);
6868 }
6869 if (!empty($backup['themes'])) {
6870 $results = array_merge($results, $backup['themes']);
6871 }
6872 if (!empty($backup['uploads'])) {
6873 $results = array_merge($results, $backup['uploads']);
6874 }
6875 if (!empty($backup['others'])) {
6876 $results = array_merge($results, $backup['others']);
6877 }
6878 if (!empty($backup['more'])) {
6879 $results = array_merge($results, $backup['more']);
6880 }
6881 if (!empty($backup['db'])) {
6882 $results[] = $backup['db'];
6883 }
6884 if (!empty($backup['backup_file_basename'])) {
6885 $results[] = $backup['backup_file_basename'];
6886 }
6887 }
6888 }
6889
6890 $num_deleted = 0;
6891 foreach ($files as $file) {
6892 if (((!in_array($file, $results) && !in_array(basename($file), $results)) || in_array($file, $failedBackupHisID)) && basename($file) != 'index.php') {
6893 @unlink($file);
6894 // $deleted[] = basename($file);
6895 $deleted[] = $file;
6896 $num_deleted++;
6897 }
6898 }
6899
6900 if (!empty($failedBackupHisID)) {
6901 $this->remove_failed_backups_by_hisID($failedBackupHisID);
6902 }
6903 }
6904 return $deleted;
6905 }
6906
6907
6908 /**
6909 * Delete specified backup
6910 * Args: $task_name, $result_id
6911 */
6912
6913 function delete_backup($args)
6914 {
6915
6916 if (empty($args))
6917 return false;
6918
6919 global $wpdb;
6920 $table_name = $wpdb->base_prefix . "iwp_backup_status";
6921
6922 extract($args);
6923
6924 $tasks = $this->get_requested_task($result_id);
6925
6926 $backup = $tasks['task_results'][$result_id];
6927
6928 $requestParams = unserialize($tasks['requestParams']);
6929 $args = $requestParams['secure']['account_info'];
6930
6931 if (isset($backup['server'])) {
6932 $backup_file = $backup['server']['file_path'];
6933 if(is_array($backup_file))
6934 {
6935 foreach($backup_file as $value)
6936 {
6937 @unlink($value);
6938 }
6939 }
6940 else
6941 {
6942 @unlink($backup_file);
6943 }
6944 }
6945
6946
6947 //Remove from ftp
6948 if (isset($backup['ftp'])) {
6949 $ftp_file = $backup['ftp'];
6950 $args = $args['iwp_ftp'];
6951 $args['backup_file'] = $ftp_file;
6952 $this->remove_ftp_backup($args);
6953 }
6954
6955 if (isset($backup['amazons3'])) {
6956 $amazons3_file = $backup['amazons3'];
6957 $args = $args['iwp_amazon_s3'];
6958 $args['backup_file'] = $amazons3_file;
6959 if(is_new_s3_compatible()){
6960 require_once $GLOBALS['iwp_mmb_plugin_dir'].'/lib/amazon/s3IWPBackup.php';
6961 $new_s3_obj = new IWP_MMB_S3_MULTICALL();
6962 $new_s3_obj->remove_amazons3_backup($args);
6963 }
6964 else{
6965 $this->remove_amazons3_backup_bwd_comp($args);
6966 }
6967 }
6968
6969 if (isset($backup['dropbox'])) {
6970 $dropbox_file = $backup['dropbox'];
6971 $args = $args['iwp_dropbox'];
6972 $args['backup_file'] = $dropbox_file;
6973 $this->remove_dropbox_backup($args);
6974 }
6975
6976 if (isset($backup['gDrive'])) {
6977 $g_drive_file = $backup['gDrive'];
6978 $args = $args['iwp_gdrive'];
6979 $args['backup_file'] = $g_drive_file;
6980 $this->remove_google_drive_backup($args);
6981 }
6982
6983 $delete_query = $wpdb->prepare(
6984 "DELETE FROM {$table_name} WHERE historyID = %d",
6985 absint($result_id)
6986 );
6987
6988 $deleteRes = $wpdb->query($delete_query);
6989
6990 return true;
6991
6992 }
6993
6994 function wpdb_reconnect(){
6995 if(version_compare(phpversion() , '8', '>=')){
6996 return;
6997 }
6998 global $wpdb;
6999 $old_wpdb = $wpdb;
7000 //Reconnect to avoid timeout problem after ZIP files
7001 if(class_exists('wpdb') && function_exists('wp_set_wpdb_vars')){
7002 if ($wpdb->use_mysqli) {
7003 @mysqli_close($wpdb->dbh);
7004 } else {
7005 if (function_exists('mysql_close')){
7006 @mysql_close($wpdb->dbh);
7007 }
7008 }
7009 $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
7010 wp_set_wpdb_vars();
7011 $wpdb->options = $old_wpdb->options;//fix for multi site full backup
7012 }
7013 }
7014
7015 function replace_htaccess($url, $remote_abspath)
7016 {
7017 global $wp_filesystem;
7018 //$file = @file_get_contents(ABSPATH.'.htaccess');
7019 $file = $wp_filesystem->get_contents($remote_abspath.'.htaccess');
7020 if ($file && strlen($file)) {
7021 $args = parse_url($url);
7022 $string = rtrim($args['path'], "/");
7023 $regex = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
7024 $replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
7025 $file = preg_replace($regex, $replace, $file);
7026 //@file_put_contents(ABSPATH.'.htaccess', $file);
7027 $wp_filesystem->put_contents($remote_abspath.'.htaccess', $file);
7028 }
7029 }
7030
7031 function check_cron_remove(){
7032 if(empty($this->tasks) || (count($this->tasks) == 1 && isset($this->tasks['Backup Now'])) ){
7033 wp_clear_scheduled_hook('iwp_client_backup_tasks');
7034 exit;
7035 }
7036 }
7037
7038 public function readd_tasks( $params = array() ){
7039 global $iwp_mmb_core;
7040
7041 if( empty($params) || !isset($params['backups']) )
7042 return $params;
7043
7044 $before = array();
7045 $tasks = $params['backups'];
7046 if( !empty($tasks) ){
7047 if( function_exists( 'wp_next_scheduled' ) ){
7048 if ( !wp_next_scheduled('iwp_client_backup_tasks') ) {
7049 wp_schedule_event( time(), 'tenminutes', 'iwp_client_backup_tasks' );
7050 }
7051 }
7052
7053 foreach( $tasks as $task ){
7054 $before[$task['task_name']] = array();
7055
7056 if(isset($task['secure'])){
7057 if($decrypted = $iwp_mmb_core->_secure_data($task['secure'])){
7058 $decrypted = maybe_unserialize($decrypted);
7059 if(is_array($decrypted)){
7060 foreach($decrypted as $key => $val){
7061 if(!is_numeric($key))
7062 $task[$key] = $val;
7063 }
7064 unset($task['secure']);
7065 } else
7066 $task['secure'] = $decrypted;
7067 }
7068
7069 }
7070 if (isset($task['account_info']) && is_array($task['account_info'])) { //only if sends from panel first time(secure data)
7071 $task['args']['account_info'] = $task['account_info'];
7072 }
7073
7074 $before[$task['task_name']]['task_args'] = $task['args'];
7075 $before[$task['task_name']]['task_args']['next'] = $this->schedule_next($task['args']['type'], $task['args']['schedule']);
7076 }
7077 }
7078 update_option('iwp_client_backup_tasks', $before);
7079
7080 unset($params['backups']);
7081 return $params;
7082 }
7083
7084 function is_server_writable(){
7085 if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), ABSPATH) != 'direct'))
7086 return false;
7087 else
7088 return true;
7089 }
7090
7091 function generate_hash(){
7092 return md5(microtime(true).uniqid('',true).substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(20,60)));
7093 }
7094
7095 function prepareBackupFileDetails($args){
7096 //Prepare .zip file name
7097 extract($args['args']); //{type, what, ..etc}
7098 extract($args); //{task_name, secure, mechanism}
7099
7100 $hash = $this->generate_hash();
7101 $label = $type ? $type : 'manual';
7102 $backup_file_name = $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
7103 $backup_file = IWP_BACKUP_DIR . '/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
7104 $backup_url = content_url() . '/infinitewp/backups/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
7105 $this -> backup_url = $backup_url;
7106
7107 if(empty($account_info))
7108 {
7109 $account_info = array();
7110 }
7111
7112 return array(
7113 'backup_file' => $backup_file,
7114 'backup_url' => $backup_url,
7115 'account_info' => $account_info,
7116 'what' => $what
7117 );
7118 }
7119
7120 function get_timestamp_by_label($label){
7121 $new_backup_keys = array();
7122 global $wpdb;
7123 $table_name = $wpdb->base_prefix . "iwp_backup_status";
7124 $select_prev_backup = $wpdb->prepare(
7125 "SELECT historyID, lastUpdateTime FROM {$table_name} WHERE taskName = %s ORDER BY ID DESC",
7126 $label
7127 );
7128 $select_prev_backup_res = $wpdb->get_results($select_prev_backup, ARRAY_A);
7129 foreach ($select_prev_backup_res as $key => $value) {
7130 $new_backup_keys[$value['lastUpdateTime']] = $value['historyID'];
7131 }
7132 return $new_backup_keys;
7133 }
7134 }
7135
7136 if( !function_exists('initialize_manual_debug') ){
7137 function initialize_manual_debug($conditions = ''){
7138 if(file_exists(WP_CONTENT_DIR . '/DE_clMemoryPeak.php')){ @unlink(WP_CONTENT_DIR . '/DE_clMemoryPeak.php');}
7139 if(file_exists(WP_CONTENT_DIR . '/DE_clMemoryUsage.php')){ @unlink(WP_CONTENT_DIR . '/DE_clMemoryUsage.php');}
7140 if(file_exists(WP_CONTENT_DIR . '/DE_clTimeTaken.php')){ @unlink(WP_CONTENT_DIR . '/DE_clTimeTaken.php');}
7141 if(file_exists(WP_CONTENT_DIR . '/DE_clCPUUsage.php')){ @unlink(WP_CONTENT_DIR . '/DE_clCPUUsage.php');}
7142 if (defined('DISABLE_IWP_MULTICALL_DEBUG') && DISABLE_IWP_MULTICALL_DEBUG) {
7143 return ;
7144 }
7145
7146 global $debug_count, $every_count, $iwp_multicall_hisID;
7147 $memoryPeakLog = 'DE_clMemoryPeak.'.$iwp_multicall_hisID.'.txt';
7148 $memoryUsageLog = 'DE_clMemoryUsage.'.$iwp_multicall_hisID.'.txt';
7149 $timeTakenLog = 'DE_clTimeTaken.'.$iwp_multicall_hisID.'.txt';
7150 $cpuUsageLog = 'DE_clCPUUsage.'.$iwp_multicall_hisID.'.txt';
7151 $debug_count = 0;
7152 $every_count = 0;
7153 $current_cpu_load = 0;
7154 if (function_exists('sys_getloadavg')) {
7155 $cpu_load = sys_getloadavg();
7156 $current_cpu_load = $cpu_load[0];
7157 }
7158 $this_memory_peak_in_mb = memory_get_peak_usage();
7159 $this_memory_peak_in_mb = $this_memory_peak_in_mb / 1048576;
7160 $this_memory_in_mb = memory_get_usage();
7161 $this_memory_in_mb = $this_memory_in_mb / 1048576;
7162 $this_time_taken = microtime(true) - $GLOBALS['IWP_MMB_PROFILING']['ACTION_START'];
7163 file_put_contents(IWP_BACKUP_DIR . '/'.$memoryPeakLog,$debug_count . " " . round($this_memory_peak_in_mb, 2) ."\n");
7164 file_put_contents(IWP_BACKUP_DIR . '/'.$memoryUsageLog,$debug_count . " " . round($this_memory_in_mb, 2) ."\n");
7165 file_put_contents(IWP_BACKUP_DIR . '/'.$timeTakenLog,$debug_count . " " . round($this_time_taken, 2) ."\n");
7166 file_put_contents(IWP_BACKUP_DIR . '/'.$cpuUsageLog,$debug_count . " " . $current_cpu_load ."\n");
7167 }
7168 }
7169
7170 if( !function_exists('manual_debug') ){
7171 function manual_debug($conditions = '', $printText = '', $forEvery = 0){
7172 if (defined('DISABLE_IWP_MULTICALL_DEBUG') && DISABLE_IWP_MULTICALL_DEBUG) {
7173 return ;
7174 }
7175
7176 global $debug_count;
7177 $debug_count++;
7178 $printText = ' ' . $printText;
7179
7180 global $every_count;
7181 //$conditions = 'printOnly';
7182
7183 if(empty($forEvery)){
7184 print_memory_debug($debug_count, $conditions, $printText);
7185 }
7186 else{
7187 $every_count++;
7188 if($every_count % $forEvery == 0){
7189 print_memory_debug($debug_count, $conditions, $printText);
7190 return true;
7191 }
7192 }
7193 }
7194 }
7195
7196 if( !function_exists('print_memory_debug') ){
7197 function print_memory_debug($debug_count, $conditions = '', $printText = ''){
7198 global $iwp_multicall_hisID;
7199 $this_memory_peak_in_mb = memory_get_peak_usage();
7200 $this_memory_peak_in_mb = $this_memory_peak_in_mb / 1048576;
7201 $this_memory_in_mb = memory_get_usage();
7202 $this_memory_in_mb = $this_memory_in_mb / 1048576;
7203 $this_time_taken = microtime(true) - $GLOBALS['IWP_MMB_PROFILING']['ACTION_START'];
7204 $current_cpu_load = 0;
7205 $memoryPeakLog = 'DE_clMemoryPeak.'.$iwp_multicall_hisID.'.txt';
7206 $memoryUsageLog = 'DE_clMemoryUsage.'.$iwp_multicall_hisID.'.txt';
7207 $timeTakenLog = 'DE_clTimeTaken.'.$iwp_multicall_hisID.'.txt';
7208 $cpuUsageLog = 'DE_clCPUUsage.'.$iwp_multicall_hisID.'.txt';
7209 if (function_exists('sys_getloadavg')) {
7210 $cpu_load = sys_getloadavg();
7211 if(!empty($cpu_load)){
7212 $current_cpu_load = $cpu_load[0];
7213 }
7214 }
7215
7216 if($conditions == 'printOnly'){
7217 if($this_memory_peak_in_mb >= 34){
7218 file_put_contents(IWP_BACKUP_DIR . '/'.$memoryPeakLog,$debug_count . $printText . " " . round($this_memory_peak_in_mb, 2) ."\n",FILE_APPEND);
7219 file_put_contents(IWP_BACKUP_DIR . '/'.$memoryUsageLog,$debug_count . $printText . " " . round($this_memory_in_mb, 2) ."\n",FILE_APPEND);
7220 file_put_contents(IWP_BACKUP_DIR . '/'.$timeTakenLog,$debug_count . $printText . " " . round($this_time_taken, 2) ."\n",FILE_APPEND);
7221 file_put_contents(IWP_BACKUP_DIR . '/'.$cpuUsageLog,$debug_count . $printText . " " . $current_cpu_load ."\n",FILE_APPEND);
7222 }
7223 }
7224 else{
7225 file_put_contents(IWP_BACKUP_DIR . '/'.$memoryPeakLog,$debug_count . $printText . " " . round($this_memory_peak_in_mb, 2) ."\n",FILE_APPEND);
7226 file_put_contents(IWP_BACKUP_DIR . '/'.$memoryUsageLog,$debug_count . $printText . " " . round($this_memory_in_mb, 2) ."\n",FILE_APPEND);
7227 file_put_contents(IWP_BACKUP_DIR . '/'.$timeTakenLog,$debug_count . $printText . " " . round($this_time_taken, 2) ."\n",FILE_APPEND);
7228 file_put_contents(IWP_BACKUP_DIR . '/'.$cpuUsageLog,$debug_count . $printText . " " . $current_cpu_load ."\n",FILE_APPEND);
7229
7230 }
7231 }
7232 }
7233
7234 if( !function_exists('print_debugg') ){
7235 function print_debugg($printText = '', $printVal = null, $forEvery = 0, $conditions = ''){
7236 static $print_count = 0;
7237 $print_count++;
7238 if($print_count > $forEvery){
7239 file_put_contents(WP_CONTENT_DIR . '/DE_clientPluginSIde.php',"\n -----".$printText."------- ".var_export($printVal,true)."\n",FILE_APPEND);
7240 $print_count = 0;
7241 }
7242 }
7243 }
7244
7245 if( !function_exists('refresh_iwp_files_db') ){
7246 function refresh_iwp_files_db($this_file_id = 0, $field = 'thisFileDetails' ){
7247 global $wpdb, $iwp_db_upgrade_error;
7248 $this_table_name = $wpdb->base_prefix . 'iwp_file_list'; //in case, if we are changing table name.
7249 $result = true;
7250
7251 $IWP_FILE_LIST_TABLE_VERSION = iwp_mmb_get_site_option('iwp_file_list_table_version');
7252 $this_table_name_from_db = $wpdb->get_var("SHOW TABLES LIKE '$this_table_name'");
7253 $this_table_name = check_iwp_file_list_table($this_table_name_from_db,$this_table_name);
7254 //write in db and refresh for_every_count, all_files_detail;
7255 if($this_table_name_from_db == $this_table_name) {
7256 $result = $wpdb->query('TRUNCATE TABLE ' . $this_table_name );
7257 $error_msg = 'Unable to empty File list table : <span style="font-weight:700;">' . $wpdb->last_error.'</span>' ;
7258 if(version_compare($IWP_FILE_LIST_TABLE_VERSION, '1.1') == -1){
7259 $result = iwp_create_file_list_table();
7260 $error_msg = 'Unable to update File list table : <span style="font-weight:700;">' . $iwp_db_upgrade_error.'</span>' ;
7261 }
7262 }
7263 else{
7264 $result = iwp_create_file_list_table();
7265 $error_msg = 'Unable to create File list table : <span style="font-weight:700;">'.$iwp_db_upgrade_error.'</span>';
7266 }
7267
7268 if($result === false){
7269 return array( 'error' => $error_msg);
7270 }
7271 return true;
7272 }
7273 }
7274
7275 if(!function_exists('iwp_create_file_list_table')){
7276 function iwp_create_file_list_table(){
7277 global $wpdb, $iwp_db_upgrade_error;
7278 if(method_exists($wpdb, 'get_charset_collate')){
7279 $charset_collate = $wpdb->get_charset_collate();
7280 }
7281 $table_created = false;
7282
7283 $IWP_FILE_LIST_TABLE_VERSION = iwp_mmb_get_site_option('iwp_file_list_table_version');
7284 $table_name = $wpdb->base_prefix . "iwp_file_list";
7285
7286 if (!empty($charset_collate)){
7287 $cachecollation = $charset_collate;
7288 }
7289 else{
7290 $cachecollation = ' DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci ';
7291 }
7292
7293 if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name){
7294 $sql = "
7295 CREATE TABLE IF NOT EXISTS $table_name (
7296 `ID` int(11) NOT NULL AUTO_INCREMENT,
7297 `thisFileDetails` text,
7298 `thisFileCount` int(11) DEFAULT NULL,
7299 `thisFileHeader` text,
7300 `thisFileName` varchar(255) DEFAULT NULL,
7301 `thisFileNameHash` varchar(32) DEFAULT NULL,
7302 UNIQUE KEY `thisFileNameHash` (`thisFileNameHash`(32)),
7303 PRIMARY KEY (`ID`)
7304 )".$cachecollation." ;
7305 ";
7306 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
7307 dbDelta($sql);
7308 if($wpdb->last_error !== '') {
7309 $iwp_db_upgrade_error = $wpdb->last_error;
7310 }
7311 $this_table_name_from_db = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
7312 $table_name = check_iwp_file_list_table($this_table_name_from_db,$table_name);
7313 if($this_table_name_from_db == $table_name){
7314 $table_created = true;
7315 update_option( "iwp_file_list_table_version", '1.1');
7316 }
7317 }
7318 else if(version_compare($IWP_FILE_LIST_TABLE_VERSION, '1.1') == -1){
7319 if(iwp_alter_file_list_table()){
7320 $table_created = true;
7321 }
7322 }
7323 return $table_created;
7324 }
7325 }
7326
7327 if( !function_exists('get_from_iwp_files_db') ){
7328 function get_from_iwp_files_db($this_file_id = 0, $field = 'thisFileDetails' ){
7329 global $wpdb;
7330 $this_table_name = 'iwp_file_list'; //in case, if we are changing table name.
7331 //$field = 'thisFileDetails';
7332
7333 // $this_obj = new IWP_MMB_Backup_Multicall();
7334 // $this_obj->wpdb_reconnect();
7335
7336 $this_file_id = $this_file_id + 1;
7337 //write in db and refresh for_every_count, all_files_detail;
7338 $all_files_detail = $wpdb->get_row("SELECT ".$field." FROM " . $wpdb->base_prefix. $this_table_name . " WHERE ID = " . $this_file_id );
7339
7340 if(!empty($all_files_detail))
7341 {
7342 $all_files_detail = (array)$all_files_detail;
7343 if(!empty($all_files_detail[$field])){
7344 return unserialize($all_files_detail[$field]);
7345 }
7346 else{
7347 return array( 'error' => 'emptyValues');
7348 }
7349 }
7350 else{
7351 return array( 'error' => $wpdb->last_error);
7352 }
7353 }
7354 }
7355
7356 if( !function_exists('get_iwp_files_db_count') ){
7357 function get_iwp_files_db_count($what_type = 'files', $how_many = 'total'){
7358 global $wpdb;
7359 $this_table_name = 'iwp_file_list';
7360
7361 if($what_type == 'files'){
7362 $result = $wpdb->get_var( "SELECT COUNT(*) FROM " . $wpdb->base_prefix . $this_table_name);
7363 }
7364 else if($what_type == 'headers'){
7365 $result = $wpdb->get_var( "SELECT COUNT(*) FROM " . $wpdb->base_prefix . $this_table_name . " WHERE thisFileHeader IS NOT NULL");
7366 }
7367
7368 if($result !== false)
7369 {
7370 return (int)$result;
7371 }
7372 else{
7373 return array( 'error' => $wpdb->last_error);
7374 }
7375 }
7376 }
7377
7378 if( !function_exists('delete_in_iwp_files_db') ){
7379 function delete_in_iwp_files_db($ID = 0){
7380 global $wpdb;
7381 $this_table_name = $wpdb->base_prefix . 'iwp_file_list';
7382 $ID = $ID + 1;
7383 $result = $wpdb->delete( $this_table_name, array( 'ID' => $ID ), array( '%d' ) );
7384
7385 return $result;
7386 }
7387 }
7388
7389 if( !function_exists('save_in_iwp_files_db') ){
7390 function save_in_iwp_files_db($for_every = 0, $this_file_details = array(), $this_header_details = array(), $action = 'insert', $ID = 0){
7391 //assuming insert only happens for file adding; update happens only for header adding.
7392 static $for_every_count; $for_every_count++;
7393 static $all_files_header_detail = array();
7394 if(!empty($this_file_details)){
7395 $all_files_header_detail[] = $this_file_details;
7396 }
7397 else{
7398 $all_files_header_detail[] = $this_header_details;
7399 }
7400
7401 global $wpdb;
7402 $this_table_name = 'iwp_file_list'; //in case, if we are changing table name.
7403 $this_insertID = 0;
7404 $result = true;
7405
7406 if($for_every_count >= $for_every){
7407 //write in db and refresh for_every_count, all_files_header_detail;
7408 //$this_obj = new IWP_MMB_Backup_Multicall();
7409 //$this_obj->wpdb_reconnect();
7410
7411 foreach($all_files_header_detail as $k => $v){
7412 if($action == 'insert'){
7413 $is_already = $wpdb->get_row("SELECT * FROM " . $wpdb->base_prefix. $this_table_name . " WHERE thisFileName = '". $v['stored_filename'].$v['splitFilename']."' AND thisFileNameHash = '".md5($v['stored_filename'].$v['splitFilename'])."'" );
7414 if(empty($is_already)){
7415 $wpdb->query("SET @@auto_increment_increment=1");
7416 $result = $wpdb->insert($wpdb->base_prefix . $this_table_name, array('thisFileDetails' => serialize($v), 'thisFileCount' => $k, 'thisFileName' => $v['stored_filename'].$v['splitFilename'],'thisFileNameHash'=>md5($v['stored_filename'].$v['splitFilename'])), array( '%s', '%d', '%s', '%s' ));
7417 }
7418 }
7419 else if($action == 'update'){
7420 $ID = $ID + 1;
7421 $result = $wpdb->update($wpdb->base_prefix . $this_table_name, array('thisFileHeader' => serialize($v), ), array( 'ID' => $ID), array('%s'), array('%d'));
7422 }
7423 if($result)
7424 {
7425 if($action == 'insert'){
7426 $this_insertID = $wpdb->insert_id;
7427 }
7428 }elseif ($result === false) {
7429 if($action == 'update'){
7430 return array('error' => 1);
7431 }
7432 }
7433 }
7434 $for_every_count = 0;
7435 $all_files_header_detail = array();
7436 if($action == 'insert'){
7437 $is_break = check_and_break_iwp();
7438 if($is_break){
7439 return array( 'break' => $this_insertID );
7440 }
7441 }
7442 }
7443 return false;
7444 }
7445 }
7446
7447 if( !function_exists('check_and_break_iwp') ){
7448 function check_and_break_iwp(){
7449 $timeLimit = 18;
7450 if (defined('IWP_FILE_LIST_BREAK_TIME') && IWP_FILE_LIST_BREAK_TIME) {
7451 $timeLimit = IWP_FILE_LIST_BREAK_TIME;
7452 }
7453 if((microtime(true) - $GLOBALS['IWP_MMB_PROFILING']['ACTION_START']) > $timeLimit){
7454 return true;
7455 }
7456 else{
7457 return false;
7458 }
7459 }
7460 }
7461
7462 if( !function_exists('check_and_break_iwp_test') ){
7463 function check_and_break_iwp_test(){
7464 static $this_count;
7465 $this_count++;
7466 if($this_count >= 20){
7467 $this_count = 0;
7468 return true;
7469 }
7470 else{
7471 return false;
7472 }
7473 }
7474 }
7475
7476 if( !function_exists('debug_put') ){
7477 function debug_put($values, $string){
7478 file_put_contents(WP_CONTENT_DIR . '/DE_clientPluginSIde.php',"\n -----".$string."------- ".var_export($values,true)."\n",FILE_APPEND);
7479 }
7480 }
7481
7482 if( !function_exists('is_new_s3_compatible') ){
7483 function is_new_s3_compatible(){
7484 if(phpversion() >= '5.3.3'){
7485 return true;
7486 }
7487 return false;
7488 }
7489 }
7490
7491 if( !function_exists('is_new_dropbox_compatible') ){
7492 function is_new_dropbox_compatible(){
7493 if(version_compare(phpversion() , '5.3.3', '>=')){
7494 return true;
7495 }
7496 return false;
7497 }
7498 }
7499
7500 if(!function_exists('iwp_alter_file_list_table')){
7501 function iwp_alter_file_list_table(){
7502 $altered = true;
7503 $IWP_FILE_LIST_TABLE_VERSION = iwp_mmb_get_site_option('iwp_file_list_table_version');
7504 $failed_alter = false;
7505 if(version_compare($IWP_FILE_LIST_TABLE_VERSION, '1.1') != -1){
7506 return true;
7507 }
7508
7509 /*upgrade file list table version from 1.0 to 1.1*/
7510 if(version_compare($IWP_FILE_LIST_TABLE_VERSION, '1.0', '=')){
7511 if(!alter_iwp_filelisttable_1_1()){
7512 $altered = false;
7513 }
7514 }
7515 return $altered;
7516 }
7517 }
7518
7519 if(!function_exists('alter_iwp_filelisttable_1_1')){
7520 function alter_iwp_filelisttable_1_1(){
7521 global $wpdb, $iwp_db_upgrade_error;
7522 if(method_exists($wpdb, 'get_charset_collate')){
7523 $charset_collate = $wpdb->get_charset_collate();
7524 }
7525 $table_name = $wpdb->base_prefix . "iwp_file_list";
7526
7527 $this_table_name_from_db = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
7528 $table_name = check_iwp_file_list_table($this_table_name_from_db,$table_name);
7529 if($this_table_name_from_db == $table_name) {
7530 if (!empty($charset_collate)){
7531 $cachecollation = str_ireplace('DEFAULT ', '', $charset_collate);
7532 }
7533 else{
7534 $cachecollation = ' CHARACTER SET utf8 COLLATE utf8_general_ci ';
7535 }
7536
7537 $sql = array();
7538
7539 $columnData = $wpdb->get_var("SHOW COLUMNS FROM $table_name WHERE Field = 'thisFileNameHash'");
7540 if(empty($columnData)) {
7541 $sql[] = "ALTER TABLE $table_name ADD `thisFileNameHash` VARCHAR(32) $cachecollation NULL DEFAULT NULL AFTER `thisFileName`";
7542 $sql[] = "ALTER IGNORE TABLE $table_name ADD UNIQUE `thisFileNameHash` (`thisFileNameHash`(32))";
7543 }
7544 $indexData = $wpdb->get_var("SHOW KEYS FROM $table_name WHERE Key_name = 'thisFileName'");
7545 if(!empty($indexData)){
7546 $sql[] = "ALTER TABLE $table_name DROP INDEX thisFileName;";
7547 }
7548
7549 //Running the alter queries to the table
7550 foreach($sql as $v){
7551 if(!$wpdb->query($v)){
7552 $failed_alter = true;
7553 $iwp_db_upgrade_error = $wpdb->last_error;
7554 }
7555 }
7556 if(!$failed_alter){
7557 update_option( "iwp_file_list_table_version", '1.1');
7558 return true;
7559 }
7560 return false;
7561 }
7562 }
7563 }
7564 if (!function_exists('iwp_modify_table_description')) {
7565
7566 function iwp_modify_table_description($table_data){
7567 $temp_table = array();
7568 foreach ($table_data as $key => $value) {
7569 $temp = $table_data[$key];
7570 $temp_table[$value['Field']] = $table_data[$key];
7571 }
7572 return $temp_table;
7573 }
7574 }
7575
7576 if( !function_exists('upgradeOldDropBoxBackupList')){
7577 function upgradeOldDropBoxBackupList($dropBoxInfo){
7578 if (!isset($dropBoxInfo['dropbox_access_token']) && empty($dropBoxInfo['dropbox_access_token']) ) {
7579 return false;
7580 }
7581 global $wpdb;
7582 $table_name = $wpdb->base_prefix . "iwp_backup_status";
7583
7584 $rows = $wpdb->get_results("SELECT ID, taskName, taskResults, requestParams FROM ".$table_name." ORDER BY ID DESC", ARRAY_A);
7585 if (empty($rows)) {
7586 return false;
7587 }
7588 foreach ($rows as $ID => $taskArray) {
7589 $requestParams = unserialize($taskArray['requestParams']);
7590 $accountInfo = $requestParams['account_info'];
7591 if (isset($accountInfo['iwp_dropbox']) && isset($accountInfo['iwp_dropbox']['oauth_token']) && !empty($accountInfo['iwp_dropbox']['oauth_token'])) {
7592 $requestParams['account_info']['iwp_dropbox']['consumer_key'] = '';
7593 $requestParams['account_info']['iwp_dropbox']['consumer_secret'] = '';
7594 $requestParams['account_info']['iwp_dropbox']['oauth_token'] = '';
7595 $requestParams['account_info']['iwp_dropbox']['oauth_token_secret'] = '';
7596 $requestParams['account_info']['iwp_dropbox']['dropbox_app_key'] = $dropBoxInfo['dropbox_app_key'];
7597 $requestParams['account_info']['iwp_dropbox']['dropbox_app_secure_key'] = $dropBoxInfo['dropbox_app_secure_key'];
7598 $requestParams['account_info']['iwp_dropbox']['dropbox_access_token'] = $dropBoxInfo['dropbox_access_token'];
7599 $update = $wpdb->update($table_name,array( 'requestParams' => serialize($requestParams)),array( 'ID' => $taskArray['ID']),array('%s'),array('%d'));
7600 }
7601 }
7602 }
7603 }
7604
7605 function check_iwp_file_list_table($this_table_name_from_db,$this_table_name_from_config){
7606 if(!empty($this_table_name_from_db)){
7607 $table_name = $this_table_name_from_db == $this_table_name_from_config ? $this_table_name_from_config : ($this_table_name_from_db == strtolower($this_table_name_from_config) ? strtolower($this_table_name_from_config) : strtoupper($this_table_name_from_config));
7608 return $table_name;
7609 }else{
7610 return $this_table_name_from_config;
7611 // the first time $this_table_name_from_db is NULL so we are try to create a table based on config file prefix
7612 }
7613 }
7614 /*if( function_exists('add_filter') ){
7615 add_filter( 'iwp_website_add', 'IWP_MMB_Backup::readd_tasks' );
7616 }*/
7617
7618 ?>