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

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