Completed
Push — update/recurring-payments-use-... ( 5d3385...c82a4d )
by
unknown
23:39 queued 16:08
created

Actions   F

Complexity

Total Complexity 90

Size/Duplication

Total Lines 747
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 15

Importance

Changes 0
Metric Value
wmc 90
lcom 2
cbo 15
dl 0
loc 747
rs 1.853
c 0
b 0
f 0

27 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 38 5
A add_sender_shutdown() 0 22 2
B should_initialize_sender() 0 27 8
B sync_allowed() 0 27 7
A sync_via_cron_allowed() 0 3 1
A prevent_publicize_blacklisted_posts() 0 7 2
A set_is_importing_true() 0 3 1
C send_data() 0 83 9
B do_initial_sync() 0 25 6
A do_full_sync() 0 17 3
A jetpack_cron_schedule() 0 14 3
A do_cron_sync() 0 3 1
A do_cron_full_sync() 0 3 1
B do_cron_sync_by_type() 0 25 11
A initialize_listener() 0 3 1
A initialize_sender() 0 4 1
A initialize_woocommerce() 0 6 2
A add_woocommerce_sync_module() 0 4 1
A initialize_wp_super_cache() 0 6 2
A add_wp_super_cache_sync_module() 0 4 1
A sanitize_filtered_sync_cron_schedule() 0 11 2
A get_start_time_offset() 0 24 2
A maybe_schedule_sync_cron() 0 16 4
A clear_sync_cron_jobs() 0 4 1
A init_sync_cron_jobs() 0 26 1
A cleanup_on_upgrade() 0 15 5
B get_sync_status() 0 46 7

How to fix   Complexity   

Complex Class

Complex classes like Actions often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Actions, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * A class that defines syncable actions for Jetpack.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync;
9
10
use Automattic\Jetpack\Connection\Manager as Jetpack_Connection;
11
use Automattic\Jetpack\Constants;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Modules;
14
15
/**
16
 * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
17
 * when to send, when to perform a full sync, etc.
18
 *
19
 * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
20
 */
21
class Actions {
22
	/**
23
	 * A variable to hold a sync sender object.
24
	 *
25
	 * @access public
26
	 * @static
27
	 *
28
	 * @var Automattic\Jetpack\Sync\Sender
29
	 */
30
	public static $sender = null;
31
32
	/**
33
	 * A variable to hold a sync listener object.
34
	 *
35
	 * @access public
36
	 * @static
37
	 *
38
	 * @var Automattic\Jetpack\Sync\Listener
39
	 */
40
	public static $listener = null;
41
42
	/**
43
	 * Name of the sync cron schedule.
44
	 *
45
	 * @access public
46
	 *
47
	 * @var string
48
	 */
49
	const DEFAULT_SYNC_CRON_INTERVAL_NAME = 'jetpack_sync_interval';
50
51
	/**
52
	 * Interval between the last and the next sync cron action.
53
	 *
54
	 * @access public
55
	 *
56
	 * @var int
57
	 */
58
	const DEFAULT_SYNC_CRON_INTERVAL_VALUE = 300; // 5 * MINUTE_IN_SECONDS;
59
60
	/**
61
	 * Initialize Sync for cron jobs, set up listeners for WordPress Actions,
62
	 * and set up a shut-down action for sending actions to WordPress.com
63
	 *
64
	 * @access public
65
	 * @static
66
	 */
67
	public static function init() {
68
		// Everything below this point should only happen if we're a valid sync site.
69
		if ( ! self::sync_allowed() ) {
70
			return;
71
		}
72
73
		if ( self::sync_via_cron_allowed() ) {
74
			self::init_sync_cron_jobs();
75
		} elseif ( wp_next_scheduled( 'jetpack_sync_cron' ) ) {
76
			self::clear_sync_cron_jobs();
77
		}
78
		// When importing via cron, do not sync.
79
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
80
81
		// Sync connected user role changes to WordPress.com.
82
		Users::init();
83
84
		// Publicize filter to prevent publicizing blacklisted post types.
85
		add_filter( 'publicize_should_publicize_published_post', array( __CLASS__, 'prevent_publicize_blacklisted_posts' ), 10, 2 );
86
87
		/**
88
		 * Fires on every request before default loading sync listener code.
89
		 * Return false to not load sync listener code that monitors common
90
		 * WP actions to be serialized.
91
		 *
92
		 * By default this returns true for cron jobs, non-GET-requests, or requests where the
93
		 * user is logged-in.
94
		 *
95
		 * @since 4.2.0
96
		 *
97
		 * @param bool should we load sync listener code for this request
98
		 */
99
		if ( apply_filters( 'jetpack_sync_listener_should_load', true ) ) {
100
			self::initialize_listener();
101
		}
102
103
		add_action( 'init', array( __CLASS__, 'add_sender_shutdown' ), 90 );
104
	}
105
106
	/**
107
	 * Prepares sync to send actions on shutdown for the current request.
108
	 *
109
	 * @access public
110
	 * @static
111
	 */
112
	public static function add_sender_shutdown() {
113
		/**
114
		 * Fires on every request before default loading sync sender code.
115
		 * Return false to not load sync sender code that serializes pending
116
		 * data and sends it to WPCOM for processing.
117
		 *
118
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
119
		 * by users who can manage_options.
120
		 *
121
		 * @since 4.2.0
122
		 *
123
		 * @param bool should we load sync sender code for this request
124
		 */
125
		if ( apply_filters(
126
			'jetpack_sync_sender_should_load',
127
			self::should_initialize_sender()
128
		) ) {
129
			self::initialize_sender();
130
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
131
			add_action( 'shutdown', array( self::$sender, 'do_full_sync' ) );
132
		}
133
	}
134
135
	/**
136
	 * Decides if the sender should run on shutdown for this request.
137
	 *
138
	 * @access public
139
	 * @static
140
	 *
141
	 * @return bool
142
	 */
143
	public static function should_initialize_sender() {
144
		if ( Constants::is_true( 'DOING_CRON' ) ) {
145
			return self::sync_via_cron_allowed();
146
		}
147
148
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] ) {
149
			return true;
150
		}
151
152
		if ( current_user_can( 'manage_options' ) ) {
153
			return true;
154
		}
155
156
		if ( is_admin() ) {
157
			return true;
158
		}
159
160
		if ( defined( 'PHPUNIT_JETPACK_TESTSUITE' ) ) {
161
			return true;
162
		}
163
164
		if ( Constants::get_constant( 'WP_CLI' ) ) {
165
			return true;
166
		}
167
168
		return false;
169
	}
170
171
	/**
172
	 * Decides if sync should run at all during this request.
173
	 *
174
	 * @access public
175
	 * @static
176
	 *
177
	 * @return bool
178
	 */
179
	public static function sync_allowed() {
180
		if ( defined( 'PHPUNIT_JETPACK_TESTSUITE' ) ) {
181
			return true;
182
		}
183
184
		if ( ! Settings::is_sync_enabled() ) {
185
			return false;
186
		}
187
188
		$status = new Status();
189
		if ( $status->is_development_mode() ) {
190
			return false;
191
		}
192
193
		if ( \Jetpack::is_staging_site() ) {
194
			return false;
195
		}
196
197
		$connection = new Jetpack_Connection();
198
		if ( ! $connection->is_active() ) {
199
			if ( ! doing_action( 'jetpack_user_authorized' ) ) {
200
				return false;
201
			}
202
		}
203
204
		return true;
205
	}
206
207
	/**
208
	 * Determines if syncing during a cron job is allowed.
209
	 *
210
	 * @access public
211
	 * @static
212
	 *
213
	 * @return bool|int
214
	 */
215
	public static function sync_via_cron_allowed() {
216
		return ( Settings::get_setting( 'sync_via_cron' ) );
217
	}
218
219
	/**
220
	 * Decides if the given post should be Publicized based on its type.
221
	 *
222
	 * @access public
223
	 * @static
224
	 *
225
	 * @param bool     $should_publicize  Publicize status prior to this filter running.
226
	 * @param \WP_Post $post              The post to test for Publicizability.
227
	 * @return bool
228
	 */
229
	public static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
230
		if ( in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true ) ) {
231
			return false;
232
		}
233
234
		return $should_publicize;
235
	}
236
237
	/**
238
	 * Set an importing flag to `true` in sync settings.
239
	 *
240
	 * @access public
241
	 * @static
242
	 */
243
	public static function set_is_importing_true() {
244
		Settings::set_importing( true );
245
	}
246
247
	/**
248
	 * Sends data to WordPress.com via an XMLRPC request.
249
	 *
250
	 * @access public
251
	 * @static
252
	 *
253
	 * @param object $data                   Data relating to a sync action.
254
	 * @param string $codec_name             The name of the codec that encodes the data.
255
	 * @param float  $sent_timestamp         Current server time so we can compensate for clock differences.
256
	 * @param string $queue_id               The queue the action belongs to, sync or full_sync.
257
	 * @param float  $checkout_duration      Time spent retrieving queue items from the DB.
258
	 * @param float  $preprocess_duration    Time spent converting queue items into data to send.
259
	 * @return Jetpack_Error|mixed|WP_Error  The result of the sending request.
260
	 */
261
	public static function send_data( $data, $codec_name, $sent_timestamp, $queue_id, $checkout_duration, $preprocess_duration ) {
262
		$query_args = array(
263
			'sync'      => '1',             // Add an extra parameter to the URL so we can tell it's a sync action.
264
			'codec'     => $codec_name,
265
			'timestamp' => $sent_timestamp,
266
			'queue'     => $queue_id,
267
			'home'      => Functions::home_url(),  // Send home url option to check for Identity Crisis server-side.
268
			'siteurl'   => Functions::site_url(),  // Send siteurl option to check for Identity Crisis server-side.
269
			'cd'        => sprintf( '%.4f', $checkout_duration ),
270
			'pd'        => sprintf( '%.4f', $preprocess_duration ),
271
		);
272
273
		// Has the site opted in to IDC mitigation?
274
		if ( \Jetpack::sync_idc_optin() ) {
275
			$query_args['idc'] = true;
276
		}
277
278
		if ( \Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
279
			$query_args['migrate_for_idc'] = true;
280
		}
281
282
		$query_args['timeout'] = Settings::is_doing_cron() ? 30 : 15;
283
284
		/**
285
		 * Filters query parameters appended to the Sync request URL sent to WordPress.com.
286
		 *
287
		 * @since 4.7.0
288
		 *
289
		 * @param array $query_args associative array of query parameters.
290
		 */
291
		$query_args = apply_filters( 'jetpack_sync_send_data_query_args', $query_args );
292
293
		$url = add_query_arg( $query_args, \Jetpack::xmlrpc_api_url() );
294
295
		// If we're currently updating to Jetpack 7.7, the IXR client may be missing briefly
296
		// because since 7.7 it's being autoloaded with Composer.
297
		if ( ! class_exists( '\\Jetpack_IXR_Client' ) ) {
298
			return new \WP_Error(
299
				'ixr_client_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'ixr_client_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
300
				esc_html__( 'Sync has been aborted because the IXR client is missing.', 'jetpack' )
301
			);
302
		}
303
304
		$rpc = new \Jetpack_IXR_Client(
305
			array(
306
				'url'     => $url,
307
				'user_id' => JETPACK_MASTER_USER,
308
				'timeout' => $query_args['timeout'],
309
			)
310
		);
311
312
		$result = $rpc->query( 'jetpack.syncActions', $data );
313
314
		if ( ! $result ) {
315
			return $rpc->get_jetpack_error();
316
		}
317
318
		$response = $rpc->getResponse();
319
320
		// Check if WordPress.com IDC mitigation blocked the sync request.
321
		if ( is_array( $response ) && isset( $response['error_code'] ) ) {
322
			$error_code              = $response['error_code'];
323
			$allowed_idc_error_codes = array(
324
				'jetpack_url_mismatch',
325
				'jetpack_home_url_mismatch',
326
				'jetpack_site_url_mismatch',
327
			);
328
329
			if ( in_array( $error_code, $allowed_idc_error_codes, true ) ) {
330
				\Jetpack_Options::update_option(
331
					'sync_error_idc',
332
					\Jetpack::get_sync_error_idc_option( $response )
333
				);
334
			}
335
336
			return new \WP_Error(
337
				'sync_error_idc',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'sync_error_idc'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
338
				esc_html__( 'Sync has been blocked from WordPress.com because it would cause an identity crisis', 'jetpack' )
339
			);
340
		}
341
342
		return $response;
343
	}
344
345
	/**
346
	 * Kicks off the initial sync.
347
	 *
348
	 * @access public
349
	 * @static
350
	 *
351
	 * @return bool|null False if sync is not allowed.
352
	 */
353
	public static function do_initial_sync() {
354
		// Lets not sync if we are not suppose to.
355
		if ( ! self::sync_allowed() ) {
356
			return false;
357
		}
358
359
		// Don't start new sync if a full sync is in process.
360
		$full_sync_module = Modules::get_module( 'full-sync' );
361
		if ( $full_sync_module && $full_sync_module->is_started() && ! $full_sync_module->is_finished() ) {
362
			return false;
363
		}
364
365
		$initial_sync_config = array(
366
			'options'   => true,
367
			'functions' => true,
368
			'constants' => true,
369
			'users'     => array( get_current_user_id() ),
370
		);
371
372
		if ( is_multisite() ) {
373
			$initial_sync_config['network_options'] = true;
374
		}
375
376
		self::do_full_sync( $initial_sync_config );
377
	}
378
379
	/**
380
	 * Kicks off a full sync.
381
	 *
382
	 * @access public
383
	 * @static
384
	 *
385
	 * @param array $modules  The sync modules should be included in this full sync. All will be included if null.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $modules not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
386
	 * @return bool           True if full sync was successfully started.
387
	 */
388
	public static function do_full_sync( $modules = null ) {
389
		if ( ! self::sync_allowed() ) {
390
			return false;
391
		}
392
393
		$full_sync_module = Modules::get_module( 'full-sync' );
394
395
		if ( ! $full_sync_module ) {
396
			return false;
397
		}
398
399
		self::initialize_listener();
400
401
		$full_sync_module->start( $modules );
402
403
		return true;
404
	}
405
406
	/**
407
	 * Adds a cron schedule for regular syncing via cron, unless the schedule already exists.
408
	 *
409
	 * @access public
410
	 * @static
411
	 *
412
	 * @param array $schedules  The list of WordPress cron schedules prior to this filter.
413
	 * @return array            A list of WordPress cron schedules with the Jetpack sync interval added.
414
	 */
415
	public static function jetpack_cron_schedule( $schedules ) {
416
		if ( ! isset( $schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] ) ) {
417
			$minutes = intval( self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60 );
418
			$display = ( 1 === $minutes ) ?
419
				__( 'Every minute', 'jetpack' ) :
420
				/* translators: %d is an integer indicating the number of minutes. */
421
				sprintf( __( 'Every %d minutes', 'jetpack' ), $minutes );
422
			$schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] = array(
423
				'interval' => self::DEFAULT_SYNC_CRON_INTERVAL_VALUE,
424
				'display'  => $display,
425
			);
426
		}
427
		return $schedules;
428
	}
429
430
	/**
431
	 * Starts an incremental sync via cron.
432
	 *
433
	 * @access public
434
	 * @static
435
	 */
436
	public static function do_cron_sync() {
437
		self::do_cron_sync_by_type( 'sync' );
438
	}
439
440
	/**
441
	 * Starts a full sync via cron.
442
	 *
443
	 * @access public
444
	 * @static
445
	 */
446
	public static function do_cron_full_sync() {
447
		self::do_cron_sync_by_type( 'full_sync' );
448
	}
449
450
	/**
451
	 * Try to send actions until we run out of things to send,
452
	 * or have to wait more than 15s before sending again,
453
	 * or we hit a lock or some other sending issue
454
	 *
455
	 * @access public
456
	 * @static
457
	 *
458
	 * @param string $type Sync type. Can be `sync` or `full_sync`.
459
	 */
460
	public static function do_cron_sync_by_type( $type ) {
461
		if ( ! self::sync_allowed() || ( 'sync' !== $type && 'full_sync' !== $type ) ) {
462
			return;
463
		}
464
465
		self::initialize_sender();
466
467
		$time_limit = Settings::get_setting( 'cron_sync_time_limit' );
468
		$start_time = time();
469
470
		do {
471
			$next_sync_time = self::$sender->get_next_sync_time( $type );
472
473
			if ( $next_sync_time ) {
474
				$delay = $next_sync_time - time() + 1;
475
				if ( $delay > 15 ) {
476
					break;
477
				} elseif ( $delay > 0 ) {
478
					sleep( $delay );
479
				}
480
			}
481
482
			$result = 'full_sync' === $type ? self::$sender->do_full_sync() : self::$sender->do_sync();
483
		} while ( $result && ! is_wp_error( $result ) && ( $start_time + $time_limit ) > time() );
484
	}
485
486
	/**
487
	 * Initialize the sync listener.
488
	 *
489
	 * @access public
490
	 * @static
491
	 */
492
	public static function initialize_listener() {
493
		self::$listener = Listener::get_instance();
494
	}
495
496
	/**
497
	 * Initializes the sync sender.
498
	 *
499
	 * @access public
500
	 * @static
501
	 */
502
	public static function initialize_sender() {
503
		self::$sender = Sender::get_instance();
504
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 6 );
505
	}
506
507
	/**
508
	 * Initializes sync for WooCommerce.
509
	 *
510
	 * @access public
511
	 * @static
512
	 */
513
	public static function initialize_woocommerce() {
514
		if ( false === class_exists( 'WooCommerce' ) ) {
515
			return;
516
		}
517
		add_filter( 'jetpack_sync_modules', array( __CLASS__, 'add_woocommerce_sync_module' ) );
518
	}
519
520
	/**
521
	 * Adds Woo's sync modules to existing modules for sending.
522
	 *
523
	 * @access public
524
	 * @static
525
	 *
526
	 * @param array $sync_modules The list of sync modules declared prior to this filter.
527
	 * @return array A list of sync modules that now includes Woo's modules.
528
	 */
529
	public static function add_woocommerce_sync_module( $sync_modules ) {
530
		$sync_modules[] = 'Automattic\\Jetpack\\Sync\\Modules\\WooCommerce';
531
		return $sync_modules;
532
	}
533
534
	/**
535
	 * Initializes sync for WP Super Cache.
536
	 *
537
	 * @access public
538
	 * @static
539
	 */
540
	public static function initialize_wp_super_cache() {
541
		if ( false === function_exists( 'wp_cache_is_enabled' ) ) {
542
			return;
543
		}
544
		add_filter( 'jetpack_sync_modules', array( __CLASS__, 'add_wp_super_cache_sync_module' ) );
545
	}
546
547
	/**
548
	 * Adds WP Super Cache's sync modules to existing modules for sending.
549
	 *
550
	 * @access public
551
	 * @static
552
	 *
553
	 * @param array $sync_modules The list of sync modules declared prior to this filer.
554
	 * @return array A list of sync modules that now includes WP Super Cache's modules.
555
	 */
556
	public static function add_wp_super_cache_sync_module( $sync_modules ) {
557
		$sync_modules[] = 'Automattic\\Jetpack\\Sync\\Modules\\WP_Super_Cache';
558
		return $sync_modules;
559
	}
560
561
	/**
562
	 * Sanitizes the name of sync's cron schedule.
563
	 *
564
	 * @access public
565
	 * @static
566
	 *
567
	 * @param string $schedule The name of a WordPress cron schedule.
568
	 * @return string The sanitized name of sync's cron schedule.
569
	 */
570
	public static function sanitize_filtered_sync_cron_schedule( $schedule ) {
571
		$schedule  = sanitize_key( $schedule );
572
		$schedules = wp_get_schedules();
573
574
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
575
		if ( isset( $schedules[ $schedule ] ) ) {
576
			return $schedule;
577
		}
578
579
		return self::DEFAULT_SYNC_CRON_INTERVAL_NAME;
580
	}
581
582
	/**
583
	 * Allows offsetting of start times for sync cron jobs.
584
	 *
585
	 * @access public
586
	 * @static
587
	 *
588
	 * @param string $schedule The name of a cron schedule.
589
	 * @param string $hook     The hook that this method is responding to.
590
	 * @return int The offset for the sync cron schedule.
591
	 */
592
	public static function get_start_time_offset( $schedule = '', $hook = '' ) {
593
		$start_time_offset = is_multisite()
594
			? wp_rand( 0, ( 2 * self::DEFAULT_SYNC_CRON_INTERVAL_VALUE ) )
595
			: 0;
596
597
		/**
598
		 * Allows overriding the offset that the sync cron jobs will first run. This can be useful when scheduling
599
		 * cron jobs across multiple sites in a network.
600
		 *
601
		 * @since 4.5.0
602
		 *
603
		 * @param int    $start_time_offset
604
		 * @param string $hook
605
		 * @param string $schedule
606
		 */
607
		return intval(
608
			apply_filters(
609
				'jetpack_sync_cron_start_time_offset',
610
				$start_time_offset,
611
				$hook,
612
				$schedule
613
			)
614
		);
615
	}
616
617
	/**
618
	 * Decides if a sync cron should be scheduled.
619
	 *
620
	 * @access public
621
	 * @static
622
	 *
623
	 * @param string $schedule The name of a cron schedule.
624
	 * @param string $hook     The hook that this method is responding to.
625
	 */
626
	public static function maybe_schedule_sync_cron( $schedule, $hook ) {
627
		if ( ! $hook ) {
628
			return;
629
		}
630
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
631
632
		$start_time = time() + self::get_start_time_offset( $schedule, $hook );
633
		if ( ! wp_next_scheduled( $hook ) ) {
634
			// Schedule a job to send pending queue items once a minute.
635
			wp_schedule_event( $start_time, $schedule, $hook );
636
		} elseif ( wp_get_schedule( $hook ) !== $schedule ) {
637
			// If the schedule has changed, update the schedule.
638
			wp_clear_scheduled_hook( $hook );
639
			wp_schedule_event( $start_time, $schedule, $hook );
640
		}
641
	}
642
643
	/**
644
	 * Clears Jetpack sync cron jobs.
645
	 *
646
	 * @access public
647
	 * @static
648
	 */
649
	public static function clear_sync_cron_jobs() {
650
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
651
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
652
	}
653
654
	/**
655
	 * Initializes Jetpack sync cron jobs.
656
	 *
657
	 * @access public
658
	 * @static
659
	 */
660
	public static function init_sync_cron_jobs() {
661
		add_filter( 'cron_schedules', array( __CLASS__, 'jetpack_cron_schedule' ) );
662
663
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
664
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
665
666
		/**
667
		 * Allows overriding of the default incremental sync cron schedule which defaults to once every 5 minutes.
668
		 *
669
		 * @since 4.3.2
670
		 *
671
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
672
		 */
673
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
674
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
675
676
		/**
677
		 * Allows overriding of the full sync cron schedule which defaults to once every 5 minutes.
678
		 *
679
		 * @since 4.3.2
680
		 *
681
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
682
		 */
683
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
684
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
685
	}
686
687
	/**
688
	 * Perform maintenance when a plugin upgrade occurs.
689
	 *
690
	 * @access public
691
	 * @static
692
	 *
693
	 * @param string $new_version New version of the plugin.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $new_version not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
694
	 * @param string $old_version Old version of the plugin.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_version not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
695
	 */
696
	public static function cleanup_on_upgrade( $new_version = null, $old_version = null ) {
697
		if ( wp_next_scheduled( 'jetpack_sync_send_db_checksum' ) ) {
698
			wp_clear_scheduled_hook( 'jetpack_sync_send_db_checksum' );
699
		}
700
701
		$is_new_sync_upgrade = version_compare( $old_version, '4.2', '>=' );
702
		if ( ! empty( $old_version ) && $is_new_sync_upgrade && version_compare( $old_version, '4.5', '<' ) ) {
703
			self::clear_sync_cron_jobs();
704
			Settings::update_settings(
705
				array(
706
					'render_filtered_content' => Defaults::$default_render_filtered_content,
0 ignored issues
show
Bug introduced by
The property default_render_filtered_content cannot be accessed from this context as it is declared private in class Automattic\Jetpack\Sync\Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
707
				)
708
			);
709
		}
710
	}
711
712
	/**
713
	 * Get syncing status for the given fields.
714
	 *
715
	 * @access public
716
	 * @static
717
	 *
718
	 * @param string|null $fields A comma-separated string of the fields to include in the array from the JSON response.
719
	 * @return array An associative array with the status report.
720
	 */
721
	public static function get_sync_status( $fields = null ) {
722
		self::initialize_sender();
723
724
		$sync_module     = Modules::get_module( 'full-sync' );
725
		$queue           = self::$sender->get_sync_queue();
726
		$full_queue      = self::$sender->get_full_sync_queue();
727
		$cron_timestamps = array_keys( _get_cron_array() );
728
		$next_cron       = $cron_timestamps[0] - time();
729
730
		$checksums = array();
731
732
		if ( ! empty( $fields ) ) {
733
			$store         = new Replicastore();
734
			$fields_params = array_map( 'trim', explode( ',', $fields ) );
735
736
			if ( in_array( 'posts_checksum', $fields_params, true ) ) {
737
				$checksums['posts_checksum'] = $store->posts_checksum();
738
			}
739
			if ( in_array( 'comments_checksum', $fields_params, true ) ) {
740
				$checksums['comments_checksum'] = $store->comments_checksum();
741
			}
742
			if ( in_array( 'post_meta_checksum', $fields_params, true ) ) {
743
				$checksums['post_meta_checksum'] = $store->post_meta_checksum();
744
			}
745
			if ( in_array( 'comment_meta_checksum', $fields_params, true ) ) {
746
				$checksums['comment_meta_checksum'] = $store->comment_meta_checksum();
747
			}
748
		}
749
750
		$full_sync_status = ( $sync_module ) ? $sync_module->get_status() : array();
751
752
		return array_merge(
753
			$full_sync_status,
754
			$checksums,
755
			array(
756
				'cron_size'            => count( $cron_timestamps ),
757
				'next_cron'            => $next_cron,
758
				'queue_size'           => $queue->size(),
759
				'queue_lag'            => $queue->lag(),
760
				'queue_next_sync'      => ( self::$sender->get_next_sync_time( 'sync' ) - microtime( true ) ),
761
				'full_queue_size'      => $full_queue->size(),
762
				'full_queue_lag'       => $full_queue->lag(),
763
				'full_queue_next_sync' => ( self::$sender->get_next_sync_time( 'full_sync' ) - microtime( true ) ),
764
			)
765
		);
766
	}
767
}
768