GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#1071)
by Tom
03:14
created

actions.php ➔ edit_schedule_submit()   F

Complexity

Conditions 34
Paths > 20000

Size

Total Lines 166
Code Lines 91

Duplication

Lines 54
Ratio 32.53 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 34
eloc 91
nc 1492993
nop 0
dl 54
loc 166
rs 2
c 2
b 1
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace HM\BackUpWordPress;
4
5
/**
6
 * Delete the backup and then redirect back to the backups page
7
 */
8
function request_delete_backup() {
9
10
	check_admin_referer( 'hmbkp_delete_backup', 'hmbkp_delete_backup_nonce' );
11
12
	$schedule = new Scheduled_Backup( sanitize_text_field( urldecode( $_GET['hmbkp_schedule_id'] ) ) );
13
14
	$deleted = $schedule->delete_backup( sanitize_text_field( base64_decode( $_GET['hmbkp_backup_archive'] ) ) );
15
16
	if ( is_wp_error( $deleted ) ) {
17
		wp_die( $deleted->get_error_message() );
18
	}
19
20
	wp_safe_redirect( get_settings_url(), 303 );
21
22
	die;
23
24
}
25
add_action( 'admin_post_hmbkp_request_delete_backup', 'HM\BackUpWordPress\request_delete_backup' );
26
27
/**
28
 * Enable support and then redirect back to the backups page
29
 */
30
function request_enable_support() {
31
32
	check_admin_referer( 'hmbkp_enable_support', 'hmbkp_enable_support_nonce' );
33
34
	update_option( 'hmbkp_enable_support', true );
35
36
	wp_safe_redirect( get_settings_url(), 303 );
37
38
	die;
39
40
}
41
add_action( 'admin_post_hmbkp_request_enable_support', 'HM\BackUpWordPress\request_enable_support' );
42
43
/**
44
 * Delete a schedule and all it's backups and then redirect back to the backups page
45
 */
46
function request_delete_schedule() {
47
48
	check_admin_referer( 'hmbkp_delete_schedule', 'hmbkp_delete_schedule_nonce' );
49
50
	$schedule = new Scheduled_Backup( sanitize_text_field( urldecode( $_GET['hmbkp_schedule_id'] ) ) );
51
	$schedule->cancel( true );
52
53
	wp_safe_redirect( get_settings_url(), 303 );
54
55
	die;
56
57
}
58
add_action( 'admin_post_hmbkp_request_delete_schedule', 'HM\BackUpWordPress\request_delete_schedule' );
59
60
/**
61
 * Perform a manual backup
62
 *
63
 * Handles ajax requests as well as standard GET requests
64
 */
65
function request_do_backup() {
66
67
	if ( empty( $_REQUEST['hmbkp_schedule_id'] ) ) {
68
		die;
69
	}
70
71
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
72
		check_ajax_referer( 'hmbkp_run_schedule', 'hmbkp_run_schedule_nonce' );
73
	} else {
74
		check_admin_referer( 'hmbkp_run_schedule', 'hmbkp_run_schedule_nonce' );
75
	}
76
77
	Path::get_instance()->cleanup();
78
79
	// Fixes an issue on servers which only allow a single session per client
80
	session_write_close();
81
82
	$schedule_id = sanitize_text_field( urldecode( $_REQUEST['hmbkp_schedule_id'] ) );
83
	$task = new \HM\Backdrop\Task( '\HM\BackUpWordPress\run_schedule_async', $schedule_id );
84
85
	/**
86
	 * Backdrop doesn't cleanup tasks which fatal before they can finish
87
	 * so we manually cancel the task if it's already scheduled.
88
	 */
89
	if ( $task->is_scheduled() ) {
90
		$task->cancel();
91
	}
92
	$task->schedule();
93
94
	die;
95
96
}
97
add_action( 'wp_ajax_hmbkp_run_schedule', 'HM\BackUpWordPress\request_do_backup' );
98
99
function run_schedule_async( $schedule_id ) {
100
	$schedule = new Scheduled_Backup( $schedule_id );
101
	$schedule->run();
102
}
103
104
/**
105
 * Send the download file to the browser and then redirect back to the backups page
106
 */
107
function request_download_backup() {
108
109
	check_admin_referer( 'hmbkp_download_backup', 'hmbkp_download_backup_nonce' );
110
111
	if ( ! file_exists( sanitize_text_field( base64_decode( $_GET['hmbkp_backup_archive'] ) ) )  ) {
112
		return;
113
	}
114
115
	$url = str_replace( wp_normalize_path( Path::get_home_path() ), home_url( '/' ), trailingslashit( dirname( sanitize_text_field( base64_decode( $_GET['hmbkp_backup_archive'] ) ) ) ) ) . urlencode( pathinfo( sanitize_text_field( base64_decode( $_GET['hmbkp_backup_archive'] ) ), PATHINFO_BASENAME ) );
116
117
	global $is_apache;
118
119
	if ( $is_apache ) {
120
121
		Path::get_instance()->protect_path( 'reset' );
122
123
		$url = add_query_arg( 'key', HMBKP_SECURE_KEY, $url );
124
125
	}
126
127
	wp_safe_redirect( $url, 303 );
128
129
	die;
130
131
}
132
add_action( 'admin_post_hmbkp_request_download_backup', 'HM\BackUpWordPress\request_download_backup' );
133
134
/**
135
 * Cancels a running backup then redirect back to the backups page
136
 */
137
function request_cancel_backup() {
138
139
	check_admin_referer( 'hmbkp_request_cancel_backup', 'hmbkp-request_cancel_backup_nonce' );
140
141
	$schedule = new Scheduled_Backup( sanitize_text_field( urldecode( $_GET['hmbkp_schedule_id'] ) ) );
142
	$status = $schedule->get_status();
143
144
	// Delete the running backup
145
	if ( $status->get_backup_filename() && file_exists( trailingslashit( Path::get_path() ) . $status->get_backup_filename() ) ) {
146
		unlink( trailingslashit( Path::get_path() ) . $status->get_backup_filename() );
147
	}
148
149
	if ( file_exists( $status->get_status_filepath() ) ) {
150
		unlink( $status->get_status_filepath() );
151
	}
152
153
	Path::get_instance()->cleanup();
154
155
	wp_safe_redirect( get_settings_url(), 303 );
156
157
	die;
158
159
}
160
add_action( 'admin_post_hmbkp_request_cancel_backup', 'HM\BackUpWordPress\request_cancel_backup' );
161
162
/**
163
 * Dismiss an error and then redirect back to the backups page
164
 */
165
function dismiss_error() {
166
167
	Path::get_instance()->cleanup();
168
169
	Notices::get_instance()->clear_all_notices();
170
171
	wp_safe_redirect( wp_get_referer(), 303 );
172
173
	die;
174
175
}
176
add_action( 'wp_ajax_hmbkp_dismiss_error', 'HM\BackUpWordPress\dismiss_error' );
177
178
/**
179
 * Catch the schedule service settings form submission
180
 *
181
 * Validate and either return errors or update the schedule
182
 */
183
function edit_schedule_services_submit() {
184
185
	check_admin_referer( 'hmbkp-edit-schedule-services', 'hmbkp-edit-schedule-services-nonce' );
186
187
	if ( empty( $_POST['hmbkp_schedule_id'] ) ) {
188
		wp_die( __( 'The schedule ID was not provided. Aborting.', 'backupwordpress' ) );
189
	}
190
191
	$schedule = new Scheduled_Backup( sanitize_text_field( $_POST['hmbkp_schedule_id'] ) );
192
193
	$errors = array();
194
195
	// Save the service options
196
	foreach ( Services::get_services( $schedule ) as $service ) {
197
		$errors = array_merge( $errors, $service->save() );
198
	}
199
200
	$schedule->save();
201
202
	if ( ! empty( $errors ) ) {
203
		foreach ( $errors as $error ) {
204
			add_settings_error( $error );
205
		}
206
	}
207
208
	$redirect = remove_query_arg( array( 'hmbkp_panel', 'action' ), wp_get_referer() );
209
210
	if ( ! empty( $errors ) ) {
211
		$redirect = wp_get_referer();
212
	}
213
214
	wp_safe_redirect( $redirect, '303' );
215
	die;
216
217
}
218
add_action( 'admin_post_hmbkp_edit_schedule_services_submit', 'HM\BackUpWordPress\edit_schedule_services_submit' );
219
220
/**
221
 * Catch the schedule settings form submission
222
 *
223
 * Validate and either return errors or update the schedule
224
 */
225
function edit_schedule_submit() {
226
227
	check_admin_referer( 'hmbkp-edit-schedule', 'hmbkp-edit-schedule-nonce' );
228
229
	if ( empty( $_POST['hmbkp_schedule_id'] ) ) {
230
		die;
231
	}
232
233
	$schedule = new Scheduled_Backup( sanitize_text_field( $_POST['hmbkp_schedule_id'] ) );
234
	$site_size = new Site_Size( $schedule->get_type(), $schedule->get_excludes() );
235
236
	$errors = array();
237
238
	$settings = array();
239
240
	if ( isset( $_POST['hmbkp_schedule_type'] ) ) {
241
242
		$schedule_type = sanitize_text_field( $_POST['hmbkp_schedule_type'] );
243
244
		if ( ! trim( $schedule_type ) ) {
245
			$errors['hmbkp_schedule_type'] = __( 'Backup type cannot be empty', 'backupwordpress' );
246
		} elseif ( ! in_array( $schedule_type, array( 'complete', 'file', 'database' ) ) ) {
247
			$errors['hmbkp_schedule_type'] = __( 'Invalid backup type', 'backupwordpress' );
248
		} else {
249
			$settings['type'] = $schedule_type;
250
		}
251
	}
252
253
	if ( isset( $_POST['hmbkp_schedule_recurrence']['hmbkp_type'] ) ) {
254
255
		$schedule_recurrence_type = sanitize_text_field( $_POST['hmbkp_schedule_recurrence']['hmbkp_type'] );
256
257
		if ( empty( $schedule_recurrence_type ) ) {
258
			$errors['hmbkp_schedule_recurrence']['hmbkp_type'] = __( 'Schedule cannot be empty', 'backupwordpress' );
259
		} elseif ( ! in_array( $schedule_recurrence_type, array_keys( cron_schedules() ) ) && 'manually' !== $schedule_recurrence_type ) {
260
			$errors['hmbkp_schedule_recurrence']['hmbkp_type'] = __( 'Invalid schedule', 'backupwordpress' );
261
		} else {
262
			$settings['recurrence'] = $schedule_recurrence_type;
263
		}
264
	}
265
266
	if ( isset( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_day_of_week'] ) ) {
267
268
		$day_of_week = sanitize_text_field( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_day_of_week'] );
269
270
		if ( ! in_array( $day_of_week, array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ) ) ) {
271
			$errors['hmbkp_schedule_start_day_of_week'] = __( 'Day of the week must be a valid, lowercase day name', 'backupwordpress' );
272
		} else {
273
			$settings['start_time']['day_of_week'] = $day_of_week;
274
		}
275
	}
276
277 View Code Duplication
	if ( ( 'monthly' === $schedule_recurrence_type ) && isset( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_day_of_month'] ) ) {
0 ignored issues
show
Bug introduced by
The variable $schedule_recurrence_type does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
278
279
		$day_of_month = absint( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_day_of_month'] );
280
281
		$options = array(
282
			'min_range' => 1,
283
			'max_range' => 31,
284
		);
285
286
		if ( false === filter_var( $day_of_month, FILTER_VALIDATE_INT, array( 'options' => $options ) ) ) {
287
			$errors['hmbkp_schedule_start_day_of_month'] = __( 'Day of month must be between 1 and 31', 'backupwordpress' );
288
		} else {
289
			$settings['start_time']['day_of_month'] = $day_of_month;
290
		}
291
	}
292
293 View Code Duplication
	if ( isset( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_hours'] ) ) {
294
295
		$hours = absint( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_hours'] );
296
297
		$options = array(
298
			'min_range' => 0,
299
			'max_range' => 23,
300
		);
301
302
		if ( false === filter_var( $hours, FILTER_VALIDATE_INT, array( 'options' => $options ) ) ) {
303
			$errors['hmbkp_schedule_start_hours'] = __( 'Hours must be between 0 and 23', 'backupwordpress' );
304
		} else {
305
			$settings['start_time']['hours'] = $hours;
306
		}
307
	}
308
309 View Code Duplication
	if ( isset( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_minutes'] ) ) {
310
311
		$minutes = absint( $_POST['hmbkp_schedule_recurrence']['hmbkp_schedule_start_minutes'] );
312
313
		$options = array(
314
			'min_range' => 0,
315
			'max_range' => 59,
316
		);
317
318
		if ( false === filter_var( $minutes, FILTER_VALIDATE_INT, array( 'options' => $options ) ) ) {
319
			$errors['hmbkp_schedule_start_minutes'] = __( 'Minutes must be between 0 and 59', 'backupwordpress' );
320
		} else {
321
			$settings['start_time']['minutes'] = $minutes;
322
		}
323
	}
324
325
	if ( isset( $_POST['hmbkp_schedule_max_backups'] ) ) {
326
327
		$max_backups = sanitize_text_field( $_POST['hmbkp_schedule_max_backups'] );
328
329
		if ( empty( $max_backups ) ) {
330
			$errors['hmbkp_schedule_max_backups'] = __( 'Max backups can\'t be empty', 'backupwordpress' );
331
		} elseif ( ! is_numeric( $max_backups ) ) {
332
			$errors['hmbkp_schedule_max_backups'] = __( 'Max backups must be a number', 'backupwordpress' );
333
		} elseif ( ! ( $max_backups >= 1 ) ) {
334
			$errors['hmbkp_schedule_max_backups'] = __( 'Max backups must be greater than 0', 'backupwordpress' );
335
		} elseif ( $site_size->is_site_size_cached() && disk_space_low( $site_size->get_site_size() * $max_backups ) ) {
336
			$errors['hmbkp_schedule_max_backups'] = sprintf( __( 'Storing %s backups would use %s of disk space but your server only has %s free.', 'backupwordpress' ), '<code>' . number_format_i18n( $max_backups ) . '</code>', '<code>' . size_format( $max_backups * $site_size->get_site_size() ) . '</code>', '<code>' . size_format( disk_free_space( Path::get_path() ) ) . '</code>' );
337
		} else {
338
			$settings['max_backups'] = absint( $max_backups );
339
		}
340
	}
341
342
	// Save the service options
343
	foreach ( Services::get_services( $schedule ) as $service ) {
344
		$errors = array_merge( $errors, $service->save() );
345
	}
346
347
	if ( ! empty( $settings['recurrence'] ) && ! empty( $settings['start_time'] ) ) {
348
349
		// Calculate the start time depending on the recurrence
350
		$start_time = determine_start_time( $settings['recurrence'], $settings['start_time'] );
351
352
		if ( $start_time ) {
353
			$schedule->set_schedule_start_time( $start_time );
354
		}
355
	}
356
357
	if ( ! empty( $settings['recurrence'] ) ) {
358
		$schedule->set_reoccurrence( $settings['recurrence'] );
359
	}
360
361
	if ( ! empty( $settings['type'] ) ) {
362
		$schedule->set_type( $settings['type'] );
363
	}
364
365
	if ( ! empty( $settings['max_backups'] ) ) {
366
		$schedule->set_max_backups( $settings['max_backups'] );
367
	}
368
369
	// Save the new settings
370
	$schedule->save();
371
372
	// Remove any old backups in-case max backups was reduced
373
	$schedule->delete_old_backups();
374
375
	if ( $errors ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
376
		foreach ( $errors as $error ) {
377
			add_settings_error( $error );
378
		}
379
	}
380
381
	$redirect = remove_query_arg( array( 'hmbkp_panel', 'action' ), wp_get_referer() );
382
383
	if ( $errors ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
384
		$redirect = wp_get_referer();
385
	}
386
387
	wp_safe_redirect( $redirect, '303' );
388
	die;
389
390
}
391
add_action( 'admin_post_hmbkp_edit_schedule_submit', 'HM\BackUpWordPress\edit_schedule_submit' );
392
393
/**
394
 * Add an exclude rule
395
 *
396
 * @access public
397
 * @return void
398
 */
399
function add_exclude_rule() {
400
401
	check_admin_referer( 'hmbkp-add-exclude-rule', 'hmbkp-add-exclude-rule-nonce' );
402
403
	if ( ! isset( $_GET['hmbkp_exclude_pathname'] ) ) {
404
		return;
405
	}
406
407
	$schedule = new Scheduled_Backup( sanitize_text_field( $_GET['hmbkp_schedule_id'] ) );
408
409
	$exclude_rule = sanitize_text_field( $_GET['hmbkp_exclude_pathname'] );
410
411
	$schedule->set_excludes( $exclude_rule, true );
412
413
	$schedule->save();
414
415
	wp_safe_redirect( wp_get_referer(), '303' );
416
417
	die;
418
419
}
420
add_action( 'admin_post_hmbkp_add_exclude_rule', 'HM\BackUpWordPress\add_exclude_rule' );
421
422
/**
423
 * Delete an exclude rule
424
 *
425
 * @access public
426
 * @return void
427
 */
428
function remove_exclude_rule() {
429
430
	check_admin_referer( 'hmbkp_remove_exclude_rule', 'hmbkp-remove_exclude_rule_nonce' );
431
432
	if ( ! isset( $_GET['hmbkp_remove_exclude'] ) ) {
433
		die;
434
	}
435
436
	$schedule = new Scheduled_Backup( sanitize_text_field( $_GET['hmbkp_schedule_id'] ) );
437
438
	$excludes = $schedule->get_excludes();
439
	$exclude_rule_to_remove = stripslashes( sanitize_text_field( $_GET['hmbkp_remove_exclude'] ) );
440
441
	$schedule->set_excludes( array_diff( $excludes->get_user_excludes(), (array) $exclude_rule_to_remove ) );
442
443
	$schedule->save();
444
445
	wp_safe_redirect( wp_get_referer(), '303' );
446
447
	die;
448
449
}
450
add_action( 'admin_post_hmbkp_remove_exclude_rule', 'HM\BackUpWordPress\remove_exclude_rule' );
451
452
/**
453
 *
454
 * @param null
455
 */
456
function recalculate_directory_filesize() {
457
458
	if ( ! isset( $_GET['hmbkp_recalculate_directory_filesize'] ) || ! check_admin_referer( 'hmbkp-recalculate_directory_filesize' ) ) {
459
		return;
460
	}
461
462
	// Delete the cached directory size
463
	@unlink( trailingslashit( Path::get_path() ) . '.files' );
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
464
465
	$url = add_query_arg( array( 'action' => 'hmbkp_edit_schedule', 'hmbkp_panel' => 'hmbkp_edit_schedule_excludes' ), get_settings_url() );
466
467
	if ( isset( $_GET['hmbkp_directory_browse'] ) ) {
468
		$url = add_query_arg( 'hmbkp_directory_browse', sanitize_text_field( $_GET['hmbkp_directory_browse'] ), $url );
469
	}
470
471
	wp_safe_redirect( $url, '303' );
472
	die;
473
474
}
475
add_action( 'load-' . HMBKP_ADMIN_PAGE, 'HM\BackUpWordPress\recalculate_directory_filesize' );
476
477
function calculate_site_size() {
478
479
	$site_size = new Site_Size;
480
481
	if ( ! $site_size->is_site_size_cached() ) {
482
		$root = new \SplFileInfo( Path::get_root() );
483
		$site_size->filesize( $root );
484
	}
485
486
}
487
add_action( 'load-' . HMBKP_ADMIN_PAGE, 'HM\BackUpWordPress\calculate_site_size' );
488
489
/**
490
 * Receive the heartbeat and return backup status
491
 */
492
function heartbeat_received( $response, $data ) {
493
494
	$response['heartbeat_interval'] = 'fast';
495
496
	if ( ! empty( $data['hmbkp_schedule_id'] ) ) {
497
498
		$schedule = new Scheduled_Backup( sanitize_text_field( urldecode( $data['hmbkp_schedule_id'] ) ) );
499
		$status = new Backup_Status( $schedule->get_id() );
500
501
		if ( ! empty( $data['hmbkp_is_in_progress'] ) ) {
502
503
			if ( ! $status->get_status() ) {
504
				$response['hmbkp_schedule_status'] = 0;
505
506
				// Slow the heartbeat back down
507
				$response['heartbeat_interval'] = 'slow';
508
509
			} else {
510
				$response['hmbkp_schedule_status'] = schedule_status( $schedule, false );
511
			}
512
		}
513
514
		if ( ! empty( $data['hmbkp_client_request'] ) ) {
515
516
			$site_size = new Site_Size( $schedule->get_type(),  $schedule->get_excludes() );
517
518
			// Pass the site size to be displayed when it's ready.
519
			if ( $site_size->is_site_size_cached() ) {
520
521
				$response['hmbkp_site_size'] = $site_size->get_formatted_site_size();
522
523
				ob_start();
524
				require( HMBKP_PLUGIN_PATH . 'admin/schedule-form-excludes.php' );
525
				$response['hmbkp_dir_sizes'] = ob_get_clean();
526
527
				// Slow the heartbeat back down
528
				$response['heartbeat_interval'] = 'slow';
529
			}
530
		}
531
	}
532
533
	return $response;
534
535
}
536
add_filter( 'heartbeat_received', 'HM\BackUpWordPress\heartbeat_received', 10, 2 );
537
538
/**
539
 * Load the enable support modal contents
540
 *
541
 * @return void
542
 */
543
function load_enable_support() {
544
545
	check_ajax_referer( 'hmbkp_nonce', '_wpnonce' );
546
547
	require_once HMBKP_PLUGIN_PATH . 'admin/enable-support.php';
548
549
	die;
550
551
}
552
add_action( 'wp_ajax_load_enable_support', 'HM\BackUpWordPress\load_enable_support' );
553
554
/**
555
 * Display the running status via ajax
556
 */
557
function ajax_is_backup_in_progress() {
558
559
	check_ajax_referer( 'hmbkp_nonce', 'nonce' );
560
561
	if ( empty( $_POST['hmbkp_schedule_id'] ) ) {
562
		die;
563
	}
564
565
	$schedule = new Scheduled_Backup( sanitize_text_field( urldecode( $_POST['hmbkp_schedule_id'] ) ) );
566
567
	if ( ! $schedule->get_status() ) {
568
		echo 0;
569
	} else {
570
		hmbkp_schedule_status( $schedule );
571
	}
572
573
	die;
574
575
}
576
add_action( 'wp_ajax_hmbkp_is_in_progress', 'HM\BackUpWordPress\ajax_is_backup_in_progress' );
577
578
/**
579
 * Display the calculated size via ajax
580
 */
581
function ajax_calculate_backup_size() {
582
583
	check_ajax_referer( 'hmbkp_nonce', 'nonce' );
584
585
	if ( empty( $_POST['hmbkp_schedule_id'] ) ) {
586
		die;
587
	}
588
589
	$schedule = new Scheduled_Backup( sanitize_text_field( urldecode( $_POST['hmbkp_schedule_id'] ) ) );
590
591
	$recalculate_filesize = true;
592
593
	require( HMBKP_PLUGIN_PATH . 'admin/schedule-sentence.php' );
594
595
	die;
596
597
}
598
add_action( 'wp_ajax_hmbkp_calculate', 'HM\BackUpWordPress\ajax_calculate_backup_size' );
599
600
/**
601
 * Test the cron response and if it's not 200 show a warning message
602
 */
603
function ajax_cron_test() {
604
605
	check_ajax_referer( 'hmbkp_nonce', 'nonce' );
606
607
	// Only run the test once per week
608
	if ( get_transient( 'hmbkp_wp_cron_test_beacon' ) ) {
609
610
		echo 1;
611
612
		die;
613
614
	}
615
616
	// Skip the test if they are using Alternate Cron
617
	if ( defined( 'ALTERNATE_WP_CRON' ) ) {
618
619
		delete_option( 'hmbkp_wp_cron_test_failed' );
620
621
		echo 1;
622
623
		die;
624
625
	}
626
627
	$url = site_url( 'wp-cron.php' );
628
629
	// Attempt to load wp-cron.php 3 times, if we get the same error each time then inform the user.
630
	$response1 = wp_remote_head( $url, array( 'timeout' => 30 ) );
631
	$response2 = wp_remote_head( $url, array( 'timeout' => 30 ) );
632
	$response3 = wp_remote_head( $url, array( 'timeout' => 30 ) );
633
634
	if ( is_wp_error( $response1 ) && is_wp_error( $response2 ) && is_wp_error( $response3 ) ) {
635
636
		echo '<div id="hmbkp-warning" class="updated fade"><p><strong>' . __( 'BackUpWordPress has detected a problem.', 'backupwordpress' ) . '</strong> ' . sprintf( __( '%1$s is returning a %2$s response which could mean cron jobs aren\'t getting fired properly. BackUpWordPress relies on wp-cron to run scheduled backups. See the %3$s for more details.', 'backupwordpress' ), '<code>wp-cron.php</code>', '<code>' . $response1->get_error_message() . '</code>', '<a href="http://wordpress.org/extend/plugins/backupwordpress/faq/">FAQ</a>' ) . '</p></div>';
637
638
		update_option( 'hmbkp_wp_cron_test_failed', true );
639
640
	} elseif ( ! in_array( 200, array_map( 'wp_remote_retrieve_response_code', array( $response1, $response2, $response3 ) ) ) ) {
641
642
		echo '<div id="hmbkp-warning" class="updated fade"><p><strong>' . __( 'BackUpWordPress has detected a problem.', 'backupwordpress' ) . '</strong> ' . sprintf( __( '%1$s is returning a %2$s response which could mean cron jobs aren\'t getting fired properly. BackUpWordPress relies on wp-cron to run scheduled backups, and more generally relies on HTTP loopback connections not being blocked for manual backups. See the %3$s for more details.', 'backupwordpress' ), '<code>wp-cron.php</code>', '<code>' . esc_html( wp_remote_retrieve_response_code( $response1 ) ) . ' ' . esc_html( get_status_header_desc( wp_remote_retrieve_response_code( $response1 ) ) ) . '</code>', '<a href="http://wordpress.org/extend/plugins/backupwordpress/faq/">FAQ</a>' ) . '</p></div>';
643
644
		update_option( 'hmbkp_wp_cron_test_failed', true );
645
646
	} else {
647
648
		echo 1;
649
650
		delete_option( 'hmbkp_wp_cron_test_failed' );
651
		set_transient( 'hmbkp_wp_cron_test_beacon', 1, WEEK_IN_SECONDS );
652
653
	}
654
655
	die;
656
657
}
658
add_action( 'wp_ajax_hmbkp_cron_test', 'HM\BackUpWordPress\ajax_cron_test' );
659
660
/**
661
 * Remember notice dismissal
662
 */
663
function hmbkp_dismiss_notice() {
664
	update_site_option( 'hmbkp_hide_info_notice', true );
665
}
666
add_action( 'wp_ajax_hmbkp_dismiss_notice', 'HM\BackUpWordPress\hmbkp_dismiss_notice' );
667