PluginProbe
WP Database Backup – Unlimited Database & Files Backup by Backup for WP / 6.3
WP Database Backup – Unlimited Database & Files Backup by Backup for WP v6.3
7.13 7.12 trunk 1.1 2.1.1 5.9 6.0 6.1 6.10 6.11 6.12 6.12.1 6.2 6.3 6.4 6.5 6.5.1 6.6 6.7 6.8 6.9 7.0 7.0.1 7.1 7.10 All 34 releases
wp-database-backup / includes / admin / cron-create-full-backup.php

cron-create-full-backup.php in WP Database Backup – Unlimited Database & Files Backup by Backup for WP 6.3, at includes/admin/cron-create-full-backup.php

820 lines 33.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if ( ! defined( 'ABSPATH' ) ) {
3 exit; // Exit if accessed directly
4 }
5 /**********************************
6 * Cron schedule for full backup
7 **********************************/
8 add_action( 'init','wp_db_fullbackup_scheduler_activation');
9
10 function wp_db_fullbackup_scheduler_activation() {
11 $options = get_option( 'wp_db_backup_options' );
12 if ( ( ! wp_next_scheduled( 'wpdbkup_event_fullbackup' ) ) && ( true === isset( $options['enable_autobackups'] ) ) ) {
13 if(isset($options['full_autobackup_frequency']) && $options['full_autobackup_frequency'] != 'disabled'){
14 wp_schedule_event( time(), $options['full_autobackup_frequency'], 'wpdbkup_event_fullbackup' );
15 }
16 }
17 }
18 add_action( 'wpdbkup_event_fullbackup', 'wpdbbkp_cron_backup' );
19
20 /*************************************************
21 * Create custom enpoint for running cron backup
22 *************************************************/
23
24 add_action( 'rest_api_init', 'wpdbbkp_cron_backup_api');
25
26 function wpdbbkp_cron_backup_api(){
27 register_rest_route( 'wpdbbkp/v1', '/cron_backup/(?P<token>[a-zA-Z0-9]+)', array(
28 'methods' => 'GET',
29 'callback' => 'wpdbbkp_cron_backup',
30 'args' => array(
31 'token' => array(
32 'validate_callback' => function($param, $request, $key) {
33 $saved_token=get_option('wpdbbkp_api_token',false);
34 delete_option('wpdbbkp_api_token');
35 if($saved_token && $saved_token==$param){return true;}else{return false;}
36 }),
37
38 )
39 ));
40 }
41
42 /************************************************
43 * Adding ajax call to check if any cron is working
44 ************************************************/
45
46 add_action('wp_ajax_wpdbbkp_check_fullbackup_stat', 'wpdbbkp_check_fullbackup_stat');
47
48 function wpdbbkp_check_fullbackup_stat(){
49 $wpdbbkp_fullbackup_stat=['status'=>'inactive'];
50 if(current_user_can('manage_options') && isset($_POST['wpdbbkp_admin_security_nonce']) && wp_verify_nonce($_POST['wpdbbkp_admin_security_nonce'], 'wpdbbkp_ajax_check_nonce')){
51 $wpdbbkp_cron_manual=['status'=>'success','msg'=>'Cron Started'];
52 $stat=get_option('wpdbbkp_backupcron_status',false);
53 if($stat=='active'){
54 $wpdbbkp_fullbackup_stat['status']='active';
55 }
56 }
57 echo json_encode($wpdbbkp_fullbackup_stat);
58 wp_die();
59
60 }
61
62
63 /************************************************
64 * Adding ajax call to start manual cron backup
65 ************************************************/
66
67 add_action('wp_ajax_wpdbbkp_start_cron_manual', 'wpdbbkp_start_cron_manual');
68
69 function wpdbbkp_start_cron_manual(){
70 $wpdbbkp_cron_manual=['status'=>'fail','msg'=>'Invalid Action'];
71 if(current_user_can('manage_options') && isset($_POST['wpdbbkp_admin_security_nonce']) && wp_verify_nonce($_POST['wpdbbkp_admin_security_nonce'], 'wpdbbkp_ajax_check_nonce')){
72 $wpdbbkp_cron_manual=['status'=>'success','msg'=>'Cron Started'];
73 $token=wpdbbkp_token_gen();
74 update_option('wpdbbkp_api_token',$token);
75 $response = wp_remote_get(site_url('/wp-json/wpdbbkp/v1/cron_backup/'.$token),
76 array(
77 'timeout' => 3,
78 'httpversion' => '1.1',
79 )
80 );
81 }
82 $wpdbbkp_cron_manual['response']=$response;
83 echo json_encode($wpdbbkp_cron_manual);
84 wp_die();
85
86 }
87
88 /************************************************
89 * Adding ajax endoint to track backup progress
90 ************************************************/
91
92 add_action('wp_ajax_wpdbbkp_get_progress', 'wpdbbkp_get_progress');
93 function wpdbbkp_get_progress(){
94 $wpdbbkp_progress=['status'=>'fail','msg'=>'Unable to track progress, try reloading the page'];
95 if(isset($_POST['wpdbbkp_admin_security_nonce']) && wp_verify_nonce($_POST['wpdbbkp_admin_security_nonce'], 'wpdbbkp_ajax_check_nonce')){
96 $wpdbbkp_progress['backupcron_status']=get_option('wpdbbkp_backupcron_status',false);
97 $wpdbbkp_progress['backupcron_step']=get_option('wpdbbkp_backupcron_step',false);
98 $wpdbbkp_progress['backupcron_current']=get_option('wpdbbkp_backupcron_current',false);
99 $wpdbbkp_progress['backupcron_progress']=get_option('wpdbbkp_backupcron_progress',false);
100 $wpdbbkp_progress['status']='success';
101 $wpdbbkp_progress['redirect_url'] = site_url() . '/wp-admin/admin.php?page=wp-database-backup&notification=create&_wpnonce='.wp_create_nonce( 'wp-database-backup' );
102 }
103 echo json_encode($wpdbbkp_progress);
104 wp_die();
105
106 }
107
108 /*****************************************
109 * Main function to backup DB and Files
110 *****************************************/
111
112 function wpdbbkp_cron_backup(){
113 // make sure only one backup process is started at oe
114 if(get_transient( 'wpdbbkp_backup_status' )=='active'){
115 wp_die();
116 }
117
118 set_time_limit(0);
119 $progress = 0.00;
120 set_transient('wpdbbkp_backup_status','active',1800);
121 update_option('wpdbbkp_backupcron_status','active');
122 update_option('wpdbbkp_backupcron_step','Initialization');
123 update_option('wpdbbkp_backupcron_current','Fetching Config');
124 $progress = $progress+1;
125 update_option('wpdbbkp_backupcron_progress',intval($progress));
126
127 $config= wpdbbkp_wp_cron_config_path();
128 $common_args=$config;
129
130 update_option('wpdbbkp_backupcron_step','Fetching Tables');
131 $progress = $progress+4;
132 update_option('wpdbbkp_backupcron_progress',intval($progress));
133
134 $tables= wpdbbkp_cron_mysqldump($config);
135 $count_tables = count($tables['tables']);
136 $single_item_percent = number_format(((1/$count_tables)*30),2,".","");
137 foreach($tables['tables'] as $table){
138 $common_args['tableName']= $table;
139 update_option('wpdbbkp_backupcron_current',$table);
140 $progress = $progress+$single_item_percent;
141 update_option('wpdbbkp_backupcron_progress',intval($progress));
142 set_transient('wpdbbkp_backup_status','active',1800);
143 wpdbbkp_cron_create_mysql_backup($common_args);
144 sleep(1);
145 }
146
147 update_option('wpdbbkp_backupcron_current','DB Backed Up');
148
149 $method_zip = wpdbbkp_cron_method_zip($common_args);
150 if(isset($method_zip['status']) && $method_zip['status']=='success'){
151
152 if($method_zip['ZipArchive']){
153
154 update_option('wpdbbkp_backupcron_step','Creating Backup');
155 update_option('wpdbbkp_backupcron_current','Starting File Backup');
156
157 $backup_info=wpdbbkp_cron_get_backup_files($common_args);
158 if(isset($backup_info['status']) && $backup_info['status']=='success' && isset($backup_info['chunk_count']) && $backup_info['chunk_count'] > 0){
159
160 $total_chunk=$backup_info['chunk_count']+1;
161
162 update_option('wpdbbkp_backupcron_current','0 of '.$total_chunk.' parts done' );
163
164 $common_args['total_chunk_cnt']=$total_chunk;
165 $single_chunk_percent = number_format(((1/$total_chunk)*64),2,".","");
166 for($count = 1; $count <= $total_chunk; $count++){
167 $common_args['chunk_count']=$count;
168 wpdbbkp_cron_files_backup($common_args);
169 update_option('wpdbbkp_backupcron_current',$count.' of '.$total_chunk.' parts done' );
170 $progress = $progress+$single_chunk_percent;
171 update_option('wpdbbkp_backupcron_progress',intval($progress));
172 set_transient('wpdbbkp_backup_status','active',1800);
173 sleep(1);
174 }
175
176 }
177 else{
178 error_log('No files were found to backup');
179 }
180 }
181 else{
182 update_option('wpdbbkp_backupcron_step','Creating Backup');
183 update_option('wpdbbkp_backupcron_current','File Backup Started');
184 wpdbbkp_cron_execute_file_backup_else($common_args);
185 update_option('wpdbbkp_backupcron_current','File Backup Complete');
186 update_option('wpdbbkp_backupcron_progress',100);
187 }
188 wpdbbkp_cron_backup_event_process($method_zip['update_backup_info']);
189 }
190 }
191
192 /*********************************************
193 * Fetch config and initialize backup process
194 **********************************************/
195
196 if(!function_exists('wpdbbkp_wp_cron_config_path')){
197 function wpdbbkp_wp_cron_config_path()
198 {
199 $path_info = wp_upload_dir();
200 $files_added = 0;
201
202 wp_mkdir_p($path_info['basedir'] . '/' . WPDB_BACKUPS_DIR);
203 wp_mkdir_p($path_info['basedir'] . '/' . WPDB_BACKUPS_DIR . '/log');
204 fclose(fopen($path_info['basedir'] . '/' . WPDB_BACKUPS_DIR . '/index.php', 'w'));
205 fclose(fopen($path_info['basedir'] . '/' . WPDB_BACKUPS_DIR . '/log/index.php', 'w'));
206 //added htaccess file 08-05-2015 for prevent directory listing
207 //Fixed Vulnerability 22-06-2016 for prevent direct download
208 //fclose(fopen($path_info['basedir'] . '/' . WPDB_BACKUPS_DIR .'/.htaccess', $htassesText));
209 $f = fopen($path_info['basedir'] . '/' . WPDB_BACKUPS_DIR . '/.htaccess', "w");
210 fwrite($f, "#These next two lines will already exist in your .htaccess file
211 RewriteEngine On
212 RewriteBase /
213 # Add these lines right after the preceding two
214 RewriteCond %{REQUEST_FILENAME} ^.*(.zip)$
215 RewriteCond %{HTTP_COOKIE} !^.*can_download.*$ [NC]
216 RewriteRule . - [R=403,L]");
217 fclose($f);
218 $siteName = preg_replace('/[^A-Za-z0-9\_]/', '_', get_bloginfo('name')); //added in v2.1 for Backup zip labeled with the site name(Help when backing up multiple sites).
219 $FileName = $siteName . '_' . Date("Y_m_d") . '_' . Time() .'_'. substr(md5(AUTH_KEY), 0, 7).'_wpall';
220 $WPDBFileName = $FileName . '.zip';
221 $wp_all_backup_type = get_option('wp_db_backup_backup_type');
222 $logFile = $path_info['basedir'] . '/' . WPDB_BACKUPS_DIR . '/log/' . $FileName . '.txt';
223 $upload_folder = str_replace(site_url(),'',$path_info['basedir']);
224 $logFileUrl = $path_info['baseurl'].'/'.WPDB_BACKUPS_DIR . '/log/' . $FileName . '.txt';
225
226 $logMessage = "\n#--------------------------------------------------------\n";
227 $logMessage .= "NOTICE: Do NOT post to public sites or forums\n";
228 $logMessage .= "#--------------------------------------------------------\n";
229 $logMessage .= " Backup File Name : " . $WPDBFileName."\n";
230 $logMessage .= " Backup File Path : " . $path_info['baseurl'] . '/' . WPDB_BACKUPS_DIR . '/' . $WPDBFileName."\n";
231 $logMessage .= " Backup Type : " . $wp_all_backup_type."\n";
232 $logMessage .= "#--------------------------------------------------------\n";
233
234 $return_data['files_added'] = $files_added;
235 $return_data['siteName'] = $siteName;
236 $return_data['FileName'] = $FileName;
237 $return_data['logFile'] = $logFile;
238 $return_data['logFileUrl'] = $logFileUrl;
239 $return_data['logMessage'] = $logMessage;
240 return $return_data;
241 }
242 }
243
244 /*************************
245 * Get dump of DB tables
246 **************************/
247
248 if(!function_exists('wpdbbkp_cron_mysqldump')){
249 function wpdbbkp_cron_mysqldump($args)
250 {
251 require_once WPDB_PATH.'includes/admin/class-wpdb-admin.php';
252 $all_db_tables = array();
253 $all_db_tables['status'] = 'failure';
254 $wpdbbkp_admin_class_obj = new Wpdb_Admin();
255 if((isset($args['FileName']) && !empty($args['FileName'])) && (isset($args['logFile']) && !empty($args['logFile']))){
256 $FileName = sanitize_text_field($args['FileName']);
257 $logFile = sanitize_text_field($args['logFile']);
258 $path_info = wp_upload_dir();
259 if (get_option('wp_db_backup_backup_type') == 'Database' || get_option('wp_db_backup_backup_type') == 'complete') {
260
261 $filename = $FileName . '.sql';
262 /* Begin : Generate SQL DUMP using cmd 06-03-2016 */
263 $mySqlDump = 0;
264
265 if ($wpdbbkp_admin_class_obj->get_mysqldump_command_path()) {
266 if (!$wpdbbkp_admin_class_obj->mysqldump($path_info['basedir'] . '/db-backup/' . $filename)) {
267 $mySqlDump = 1;
268 } else {
269 $logMessage = "\n# Database dump method: mysqldump";
270 }
271 } else {
272 $mySqlDump = 1;
273 }
274 $mySqlDump = 1;
275 if ($mySqlDump == 1) {
276 global $wpdb;
277 $tables = $wpdb->get_col('SHOW TABLES');
278 $all_db_tables['status'] = 'success';
279 $all_db_tables['tables'] = $tables;
280 }
281 }
282 }
283
284 return $all_db_tables;
285 }
286
287 }
288
289 /*******************
290 * Create DB Backup
291 ********************/
292 if(!function_exists('wpdbbkp_cron_create_mysql_backup')){
293 function wpdbbkp_cron_create_mysql_backup($args)
294 {
295
296 if((isset($args['logFile']) && !empty($args['logFile'])) && (isset($args['tableName']) && !empty($args['tableName'])) && (isset($args['FileName']) && !empty($args['FileName']))){
297 $logFile = sanitize_text_field($args['logFile']);
298 $table = sanitize_text_field($args['tableName']);
299 $FileName = sanitize_text_field($args['FileName']);
300 $filename = $FileName . '.sql';
301 $path_info = wp_upload_dir();
302
303 $wpdbbkp_admin_class_obj = new Wpdb_Admin();
304 $handle = fopen($path_info['basedir'] . '/db-backup/' . $filename, 'a+');
305
306 global $wpdb;
307 /* BEGIN : Prevent saving backup plugin settings in the database dump */
308 $options_backup = get_option('wp_db_backup_backups');
309 $settings_backup = get_option('wp_all_backup_options');
310 delete_option('wp_all_backup_options');
311 delete_option('wp_db_backup_backups');
312 $wp_db_exclude_table = array();
313 $wp_db_exclude_table = get_option('wp_db_exclude_table');
314 $logMessage = "\n#--------------------------------------------------------\n";
315 $logMessage .= "\n Database Table Backup";
316 $logMessage .= "\n#--------------------------------------------------------\n";
317 if (!empty($wp_db_exclude_table)) {
318 $logMessage.= 'Exclude Table : ' . implode(', ', $wp_db_exclude_table);
319 $logMessage .= "\n#--------------------------------------------------------\n";
320 }
321 /* END : Prevent saving backup plugin settings in the database dump */
322 $tables = $wpdb->get_col('SHOW TABLES');
323 $output = '';
324 if (empty($wp_db_exclude_table) || (!(in_array($table, $wp_db_exclude_table)))) {
325 $logMessage .= "\n $table";
326 $result = $wpdb->get_results("SELECT * FROM {$table}", ARRAY_N);
327 $row2 = $wpdb->get_row('SHOW CREATE TABLE ' . $table, ARRAY_N);
328 $output .= "\n\n" . $row2[1] . ";\n\n";
329 $logMessage .= "(" . count($result) . ")";
330 $result_count=count($result);
331 for ($i = 0; $i < $result_count; $i++) {
332 $row = $result[$i];
333 $output .= 'INSERT INTO ' . $table . ' VALUES(';
334 for ($j = 0; $j < count($result[0]); $j++) {
335 $row[$j] = $wpdb->_real_escape($row[$j]);
336 $output .= (isset($row[$j])) ? '"' . $row[$j] . '"' : '""';
337 if ($j < (count($result[0]) - 1)) {
338 $output .= ',';
339 }
340 }
341 $output .= ");\n";
342 }
343 $output .= "\n";
344 }
345 $wpdb->flush();
346 $logMessage .= "\n#--------------------------------------------------------\n";
347 /* BEGIN : Prevent saving backup plugin settings in the database dump */
348 add_option('wp_db_backup_backups', $options_backup);
349 add_option('wp_all_backup_options', $settings_backup);
350 /* END : Prevent saving backup plugin settings in the database dump */
351 if (get_option('wp_db_log') == 1) {
352 wpdbbkp_write_log($logFile, $logMessage);
353 $upload_path['logfile'] = $logFile;
354 } else {
355 $upload_path['logfile'] = "";
356 }
357 fwrite($handle, $output);
358 fclose($handle);
359
360 $logMessage = "\n# Database dump method: PHP\n";
361 if (get_option('wp_db_log') == 1) {
362 wpdbbkp_write_log($logFile, $logMessage);
363 }
364 }
365 }
366
367 }
368
369 /***********************
370 * Funtion to write log
371 ************************/
372 if(!function_exists('wpdbbkp_write_log')){
373 function wpdbbkp_write_log($logFile, $logMessage) {
374 // Actually write the log file
375 if (is_writable($logFile) || !file_exists($logFile)) {
376
377 if (!$handle = @fopen($logFile, 'a'))
378 return;
379
380 if (!fwrite($handle, $logMessage))
381 return;
382
383 fclose($handle);
384
385 return true;
386 }
387 }
388 }
389
390
391 /************************************
392 * Fetch method for Zip compression
393 ************************************/
394
395 if(!function_exists('wpdbbkp_cron_method_zip')){
396 function wpdbbkp_cron_method_zip($args) {
397 $method_zip_array = array();
398 $method_zip_array['status'] = 'failure';
399 require_once WPDB_PATH.'includes/admin/class-wpdb-admin.php';
400 if((isset($args['FileName']) && !empty($args['FileName'])) && (isset($args['logFile']) && !empty($args['logFile'])) && (isset($args['logMessage']) && !empty($args['logMessage']))){
401 $FileName = sanitize_text_field($args['FileName']);
402 $logFile = sanitize_text_field($args['logFile']);
403 $log_msg = sanitize_text_field($args['logMessage']);
404 $log_msg.="\n Exclude Folders and Files : " . get_option('wp_db_backup_exclude_dir')."\n";
405 $method_zip_array['logMessage'] = $log_msg;
406 $wpdbbkp_admin_class_obj = new Wpdb_Admin();
407 $update_backup_info = $wpdbbkp_admin_class_obj->wpdbbkp_update_backup_info($FileName, $logFile, $log_msg);
408 $method_zip_array['update_backup_info'] = $update_backup_info;
409 $method_zip_array['status'] = 'success';
410 $method_zip_array['logMessage'] = $log_msg;
411 $method_zip_array['ZipArchive'] = class_exists('ZipArchive');;
412 }
413 return $method_zip_array;
414 }
415 }
416
417 /***************************************
418 * Create Zip file and check totalfiles
419 ****************************************/
420
421 if(!function_exists('wpdbbkp_cron_get_backup_files')){
422 function wpdbbkp_cron_get_backup_files($args) {
423 $backup_files_array = array(); $file_iterator_count = 0;
424 $backup_files_array['status'] = 'failure';
425 $path_info = wp_upload_dir();
426 require_once WPDB_PATH.'includes/admin/class-wpdb-admin.php';
427 $wpdbbkp_admin_class_obj = new Wpdb_Admin();
428
429 if((isset($args['FileName']) && !empty($args['FileName'])) && (isset($args['logMessage']) && !empty($args['logMessage'])) && (isset($args['logFile']) && !empty($args['logFile']))){
430 $FileName = sanitize_text_field($args['FileName']);
431 $WPDBFileName = $FileName . '.zip';
432 $logMessage = sanitize_text_field($args['logMessage']);
433 $logFile = sanitize_text_field($args['logFile']);
434 if (get_option('wp_db_backup_backup_type') == 'File' || get_option('wp_db_backup_backup_type') == 'complete') {
435 $files_object = array();
436 $wp_all_backup_exclude_dir = get_option('wp_db_backup_exclude_dir');
437 if (empty($wp_all_backup_exclude_dir)) {
438 $excludes = WPDB_BACKUPS_DIR;
439 } else {
440 $excludes = WPDB_BACKUPS_DIR . '|' . $wp_all_backup_exclude_dir;
441 }
442 $logMessage.="\n Exclude Folders and Files : $excludes";
443 $wp_backup_files = '';
444 $wp_backup_files = $wpdbbkp_admin_class_obj->get_files();
445 $file_iterator_count = iterator_count($wp_backup_files);
446 $file_iterator_count = ceil($file_iterator_count / 2000);
447 }
448
449 $logMessage .= "\n Zip method: ZipArchive \n";
450 $zip = new ZipArchive;
451 $zip->open($path_info['basedir'] . '/db-backup/' . $WPDBFileName, ZipArchive::CREATE);
452
453 if (get_option('wp_db_backup_backup_type') == 'Database' || get_option('wp_db_backup_backup_type') == 'complete') {
454 $filename = $FileName . '.sql';
455 $zip->addFile($path_info['basedir'] . '/db-backup/' . $filename, $filename);
456 }
457 $zip->close();
458
459 $backup_files_array['status'] = 'success';
460 $backup_files_array['chunk_count'] = $file_iterator_count;
461 if (get_option('wp_db_log') == 1) {
462 wpdbbkp_write_log($logFile, $logMessage);
463 }
464 }
465
466 return $backup_files_array;
467 }
468 }
469
470 /***************************************
471 * Adding files to ZIP
472 ****************************************/
473 if(!function_exists('wpdbbkp_cron_files_backup')){
474 function wpdbbkp_cron_files_backup($args) {
475 $file_backup_array = array();
476 $file_backup_array['status'] = 'failure';
477 require_once WPDB_PATH.'includes/admin/class-wpdb-admin.php';
478 $wpdbbkp_admin_class_obj = new Wpdb_Admin();
479
480 if((isset($args['FileName']) && !empty($args['FileName'])) && (isset($args['logFile']) && !empty($args['logFile'])) && (isset($args['chunk_count'])) && (isset($args['files_added']))){
481 $FileName = sanitize_text_field($args['FileName']);
482 $logFile = sanitize_text_field($args['logFile']);
483 $logMessage = '';
484 $files_added = intval($args['files_added']);
485 $bkp_chunk_cnt = intval($args['chunk_count']);
486 $WPDBFileName = $FileName . '.zip';
487 $path_info = wp_upload_dir();
488 $total_chunk_cnt = intval($args['total_chunk_cnt']);
489
490 $zip = new ZipArchive;
491 $zip->open($path_info['basedir'] . '/db-backup/' . $WPDBFileName, ZipArchive::CREATE);
492 if (get_option('wp_db_backup_backup_type') == 'File' || get_option('wp_db_backup_backup_type') == 'complete') {
493 $wp_all_backup_exclude_dir = get_option('wp_db_backup_exclude_dir');
494 if (empty($wp_all_backup_exclude_dir)) {
495 $excludes = WPDB_BACKUPS_DIR;
496 } else {
497 $excludes = WPDB_BACKUPS_DIR . '|' . $wp_all_backup_exclude_dir;
498 }
499
500 $file_object = array();
501 $wp_backup_files = '';
502 $wp_backup_files = $wpdbbkp_admin_class_obj->get_files();
503 $file_start_offset = 1;
504 if($bkp_chunk_cnt > 1){
505 $file_start_offset = ($bkp_chunk_cnt - 1) * 2000;
506 }
507 $file_end_offset = $file_start_offset + 2000;
508 $file_loop_cnt = 1;
509 foreach ($wp_backup_files as $file) {
510 if($file_loop_cnt < $file_start_offset){
511 $file_loop_cnt++;
512 continue;
513 }
514 if($file_start_offset >= $file_loop_cnt && $file_loop_cnt < $file_end_offset){
515 if(!empty($file->getPathname())){
516 $file_object[] = $file;
517 }
518 $file_start_offset++;
519 }else{
520 if($file_loop_cnt > $file_end_offset){
521 break;
522 }
523 }
524 $file_loop_cnt++;
525 }
526
527
528 if(!empty($file_object)){
529 if(is_array($file_object)){
530 foreach ($file_object as $file) {
531 if(!empty($file->getPathname())){
532 // Skip dot files,
533 if (method_exists($file, 'isDot') && $file->isDot()){
534 continue;
535 }
536
537 // Skip unreadable files
538 if (!@realpath($file->getPathname()) || !$file->isReadable()){
539 continue;
540 }
541
542 // Excludes
543 if ($excludes && preg_match('(' . $excludes . ')', str_ireplace(trailingslashit($wpdbbkp_admin_class_obj->get_root()), '', conform_dir($file->getPathname())))){
544 continue;
545 }
546
547 if ($file->isDir()){
548 $zip->addEmptyDir(trailingslashit(str_ireplace(trailingslashit($wpdbbkp_admin_class_obj->get_root()), '', conform_dir($file->getPathname()))));
549 }
550 elseif ($file->isFile()) {
551 $zip->addFile($file->getPathname(), str_ireplace(trailingslashit($wpdbbkp_admin_class_obj->get_root()), '', conform_dir($file->getPathname())));
552 $logMessage .= "\n Added File: " . $file->getPathname();
553 }
554
555 }
556 }
557 }
558 }
559 }
560 $zip->close();
561 if($total_chunk_cnt == $bkp_chunk_cnt){
562 $update_backup_info = $wpdbbkp_admin_class_obj->wpdbbkp_update_backup_info($FileName, $logFile, $logMessage);
563 $file_backup_array['update_backup_info'] = $update_backup_info;
564 }
565 $file_backup_array['status'] = 'success';
566 $file_backup_array['files_added'] = $files_added;
567
568 }
569 return $file_backup_array;
570 }
571 }
572
573 /**********************************************
574 * Alternative method for adding files to ZIP
575 ***********************************************/
576 if(!function_exists('wpdbbkp_cron_execute_file_backup_else')){
577 function wpdbbkp_cron_execute_file_backup_else($args) {
578 $return_data_array = array();
579 $return_data_array['status'] = 'failure';
580 require_once WPDB_PATH.'includes/admin/class-wpdb-admin.php';
581 $wpdbbkp_admin_class_obj = new Wpdb_Admin();
582 if((isset($args['FileName']) && !empty($args['FileName'])) && (isset($args['logFile']) && !empty($args['logFile']))){
583 $FileName = sanitize_text_field($args['FileName']);
584 $logFile = sanitize_text_field($args['logFile']);
585 $WPDBFileName = $FileName . '.zip';
586 $path_info = wp_upload_dir();
587 $logMessage = '';
588
589 $logMessage .= "\n Zip method: pclzip \n";
590 // set maximum execution time go non stop
591 // Include the PclZip library
592 require_once( WPDB_PATH.'includes/admin/lib/class-pclzip.php' );
593
594 // Set the arhive filename
595 $arcname = $path_info['basedir'] . '/db-backup/' . $WPDBFileName;
596 $archive = new PclZip($arcname);
597
598 $wp_all_backup_exclude_dir = get_option('wp_db_backup_exclude_dir');
599 if (empty($wp_all_backup_exclude_dir)) {
600 $excludes = WPDB_BACKUPS_DIR;
601 } else {
602 $excludes = WPDB_BACKUPS_DIR . '|' . $wp_all_backup_exclude_dir;
603 }
604 $logMessage.="\n Exclude Folders and Files : $excludes";
605
606 // Set the dir to archive
607 if (get_option('wp_db_backup_backup_type') == 'Database') {
608 $filename = $FileName . '.sql';
609 $v_dir = $path_info['basedir'] . '/db-backup/' . $filename;
610
611 $v_remove = $wpdbbkp_admin_class_obj->wp_db_backup_wp_config_path();
612
613 // Create the archive
614 $v_list = $archive->create($v_dir, PCLZIP_OPT_REMOVE_PATH, $v_remove);
615 if ($v_list == 0) {
616 error_log("ERROR : '" . $archive->errorInfo(true) . "'");
617 }
618 } else {
619 $v_dir = $wpdbbkp_admin_class_obj->wp_db_backup_wp_config_path();
620 $v_remove = $v_dir;
621 // Create the archive
622 update_option('wpdbbkp_backupcron_current','Backing up files');
623 $v_list = $archive->create($v_dir, PCLZIP_OPT_REMOVE_PATH, $v_remove);
624 if ($v_list == 0) {
625 error_log("Error : " . $archive->errorInfo(true));
626 }
627 }
628 $update_backup_info = $wpdbbkp_admin_class_obj->wpdbbkp_update_backup_info($FileName, $logFile, $logMessage);
629 $return_data_array['status'] = 'success';
630 $return_data_array['update_backup_info'] = $update_backup_info;
631
632 }
633 return $return_data_array;
634 }
635 }
636
637 if(!function_exists('conform_dir')){
638 function conform_dir($dir, $recursive = false) {
639 // Assume empty dir is root
640 if (!$dir)
641 $dir = '/';
642
643 // Replace single forward slash (looks like double slash because we have to escape it)
644 $dir = str_replace('\\', '/', $dir);
645 $dir = str_replace('//', '/', $dir);
646
647 // Remove the trailing slash
648 if ($dir !== '/')
649 $dir = untrailingslashit($dir);
650
651 // Carry on until completely normalized
652 if (!$recursive && conform_dir($dir, true) != $dir)
653 return conform_dir($dir);
654
655 return (string) $dir;
656 }
657 }
658
659 /**********************************************
660 * TO complete the backup process
661 ***********************************************/
662
663 if(!function_exists('wpdbbkp_cron_backup_event_process')){
664 function wpdbbkp_cron_backup_event_process($args) {
665
666 $details = array();
667 $details['filename'] = isset($args['filename'])?sanitize_text_field($args['filename']):'';
668 $details['dir'] = isset($args['dir'])?sanitize_text_field($args['dir']):'';
669 $details['url'] = isset($args['url'])?sanitize_url($args['url']):'';
670 $details['size'] = isset($args['size'])?intval($args['size']):'';
671 $details['type'] = isset($args['type'])?sanitize_text_field($args['type']):'';
672 $details['logfile'] = isset($args['logfile'])?$args['logfile']:'';
673 $details['logfileDir'] = isset($args['logfileDir'])?sanitize_text_field($args['logfileDir']):'';
674 $details['logMessage'] = isset($args['logMessage'])?$args['logMessage']:'';
675
676 $options = get_option('wp_db_backup_backups');
677 $Destination = "";
678 $logMessageAttachment = "";
679 $logMessage = $details['logMessage'];
680 if (!$options) {
681 $options = array();
682 }
683
684 $newoptions = array();
685 $number_of_existing_backups = count( (array) $options );
686 $number_of_backups_from_user = get_option( 'wp_local_db_backup_count' );
687 if ( ! empty( $number_of_backups_from_user ) ) {
688 if ( ! ( $number_of_existing_backups < $number_of_backups_from_user ) ) {
689 $diff = $number_of_existing_backups - $number_of_backups_from_user;
690 for ( $i = 0; $i <= $diff; $i++ ) {
691 $index = $i;
692 if ( file_exists( $options[ $index ]['dir'] ) ) {
693 unlink( $options[ $index ]['dir'] );
694 }
695 $file_sql = explode( '.', $options[ $index ]['dir'] );
696 if ( file_exists( $file_sql[0] . '.sql' ) ) {
697 unlink( $file_sql[0] . '.sql' );
698 }
699 }
700 for ( $i = ( $diff + 1 ); $i < $number_of_existing_backups; $i++ ) {
701 $index = $i;
702
703 $newoptions[] = $options[ $index ];
704 }
705
706 update_option( 'wp_db_backup_backups', $newoptions );
707 }
708 }
709
710 //Email
711
712 if (get_option('wp_db_log') == 1) {
713 wpdbbkp_write_log($details['logfileDir'], $logMessage);
714 }
715
716 $options = get_option('wp_db_backup_backups');
717
718 $Destination.="Local, ";
719 $path_info = wp_upload_dir();
720 $filesize = @filesize($path_info['basedir'] . '/' . WPDB_BACKUPS_DIR . '/' . $details['filename']);
721 $options[] = array(
722 'date' => time(),
723 'filename' => $details['filename'],
724 'url' => $details['url'],
725 'dir' => $details['dir'],
726 'log' => $details['logfile'],
727 'destination' => $Destination,
728 'type' => $details['type'],
729 'size' => $filesize
730 );
731 update_option('wp_db_backup_backups', $options);
732
733 $args2 = array($details['filename'], $details['dir'], $logMessage, $filesize,$Destination,$details['logfile']);
734
735 WPDBBackupLocal::wp_db_backup_completed($args2);
736 WPDBBackupFTP::wp_db_backup_completed($args2);
737 WPDBBackupEmail::wp_db_backup_completed($args2);
738 WPDBBackupGoogle::wp_db_backup_completed($args2);
739 WPDBBackupDropbox::wp_db_backup_completed($args2);
740 WPDatabaseBackupS3::wp_db_backup_completed($args2);
741 wpdbbkp_fullbackup_log($args2);
742 wpdbbkp_backup_completed_notification($args2);
743 update_option('wpdbbkp_dashboard_notify','create');
744 update_option('wpdbbkp_backupcron_status','inactive');
745 update_option('wpdbbkp_backupcron_progress',100);
746 update_option('wpdbbkp_backupcron_current','Backup Completed');
747 delete_transient('wpdbbkp_backup_status');
748 }
749
750 }
751
752 function wpdbbkp_backup_completed_notification($args){
753
754 $to = sanitize_email( get_option( 'admin_email' ) );
755 $subject = 'Full Website Backup (' . get_bloginfo( 'name' ) . ')';
756 $filename = $args[0];
757 $filesize = $args[3];
758 $site_url = site_url();
759 $log_message_attachment = '';
760 $message = '';
761
762 require_once( WPDB_PATH.'includes/admin/Destination/Email/template-email-notification-bg.php' );
763 $headers = array( 'Content-Type: text/html; charset=UTF-8' );
764 wp_mail( $to, $subject, $message, $headers );
765 }
766
767 function wpdbbkp_fullbackup_log(&$args) {
768
769 $options = get_option('wp_db_backup_backups');
770 $newoptions = array();
771 $count = 0;
772
773 if(!empty($options) && is_array($options)){
774
775 foreach ($options as $option) {
776 if ($option['filename'] == $args[0]) {
777 $newoptions[] = array(
778 'date' => $option['date'],
779 'filename' => $option['filename'],
780 'url' =>$option['url'],
781 'dir' => $option['dir'],
782 'log' =>$option['log'],
783 'destination' => $args[4],
784 'type' => $option['type'],
785 'size' => $option['size']
786 );
787
788 }else{
789 $newoptions[] = $option;
790 }
791 $count++;
792 }
793
794 }
795
796 update_option('wp_db_backup_backups', $newoptions);
797
798 if (get_option('wp_db_log') == 1) {
799 if(isset($args[4]) && !empty($args[4]))
800 {
801 if (is_writable($args[5]) || !file_exists($args[5])) {
802
803 if (!$handle = @fopen($args[5], 'a'))
804 return;
805
806 if (!fwrite($handle, str_replace("<br>", "\n", $args[2])))
807 return;
808
809 fclose($handle);
810
811 return true;
812 }
813 }
814 }
815 }
816 function wpdbbkp_token_gen($length_of_string = 16)
817 {
818 $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
819 return substr(str_shuffle($str_result),0, $length_of_string);
820 }