PluginProbe
WP Database Backup – Unlimited Database & Files Backup by Backup for WP / 6.4
WP Database Backup – Unlimited Database & Files Backup by Backup for WP v6.4
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.4, at includes/admin/cron-create-full-backup.php

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