Completed
Push — update/base-styles-210 ( 2e278b...ad767b )
by Jeremy
22:25 queued 13:15
created

Actions   F

Complexity

Total Complexity 99

Size/Duplication

Total Lines 790
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 16

Importance

Changes 0
Metric Value
wmc 99
lcom 2
cbo 16
dl 0
loc 790
rs 1.81
c 0
b 0
f 0

28 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
A should_initialize_sender_enqueue() 0 7 2
B sync_allowed() 0 30 9
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 85 9
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 17 5
C get_sync_status() 0 54 11
A do_initial_sync() 0 22 5
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
C do_cron_sync_by_type() 0 38 13

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\Health;
14
use Automattic\Jetpack\Sync\Modules;
15
16
/**
17
 * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
18
 * when to send, when to perform a full sync, etc.
19
 *
20
 * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
21
 */
22
class Actions {
23
	/**
24
	 * A variable to hold a sync sender object.
25
	 *
26
	 * @access public
27
	 * @static
28
	 *
29
	 * @var Automattic\Jetpack\Sync\Sender
30
	 */
31
	public static $sender = null;
32
33
	/**
34
	 * A variable to hold a sync listener object.
35
	 *
36
	 * @access public
37
	 * @static
38
	 *
39
	 * @var Automattic\Jetpack\Sync\Listener
40
	 */
41
	public static $listener = null;
42
43
	/**
44
	 * Name of the sync cron schedule.
45
	 *
46
	 * @access public
47
	 *
48
	 * @var string
49
	 */
50
	const DEFAULT_SYNC_CRON_INTERVAL_NAME = 'jetpack_sync_interval';
51
52
	/**
53
	 * Interval between the last and the next sync cron action.
54
	 *
55
	 * @access public
56
	 *
57
	 * @var int
58
	 */
59
	const DEFAULT_SYNC_CRON_INTERVAL_VALUE = 300; // 5 * MINUTE_IN_SECONDS;
60
61
	/**
62
	 * Initialize Sync for cron jobs, set up listeners for WordPress Actions,
63
	 * and set up a shut-down action for sending actions to WordPress.com
64
	 *
65
	 * @access public
66
	 * @static
67
	 */
68
	public static function init() {
69
		// Everything below this point should only happen if we're a valid sync site.
70
		if ( ! self::sync_allowed() ) {
71
			return;
72
		}
73
74
		if ( self::sync_via_cron_allowed() ) {
75
			self::init_sync_cron_jobs();
76
		} elseif ( wp_next_scheduled( 'jetpack_sync_cron' ) ) {
77
			self::clear_sync_cron_jobs();
78
		}
79
		// When importing via cron, do not sync.
80
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
81
82
		// Sync connected user role changes to WordPress.com.
83
		Users::init();
84
85
		// Publicize filter to prevent publicizing blacklisted post types.
86
		add_filter( 'publicize_should_publicize_published_post', array( __CLASS__, 'prevent_publicize_blacklisted_posts' ), 10, 2 );
87
88
		/**
89
		 * Fires on every request before default loading sync listener code.
90
		 * Return false to not load sync listener code that monitors common
91
		 * WP actions to be serialized.
92
		 *
93
		 * By default this returns true for cron jobs, non-GET-requests, or requests where the
94
		 * user is logged-in.
95
		 *
96
		 * @since 4.2.0
97
		 *
98
		 * @param bool should we load sync listener code for this request
99
		 */
100
		if ( apply_filters( 'jetpack_sync_listener_should_load', true ) ) {
101
			self::initialize_listener();
102
		}
103
104
		add_action( 'init', array( __CLASS__, 'add_sender_shutdown' ), 90 );
105
	}
106
107
	/**
108
	 * Prepares sync to send actions on shutdown for the current request.
109
	 *
110
	 * @access public
111
	 * @static
112
	 */
113
	public static function add_sender_shutdown() {
114
		/**
115
		 * Fires on every request before default loading sync sender code.
116
		 * Return false to not load sync sender code that serializes pending
117
		 * data and sends it to WPCOM for processing.
118
		 *
119
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
120
		 * by users who can manage_options.
121
		 *
122
		 * @since 4.2.0
123
		 *
124
		 * @param bool should we load sync sender code for this request
125
		 */
126
		if ( apply_filters(
127
			'jetpack_sync_sender_should_load',
128
			self::should_initialize_sender()
129
		) ) {
130
			self::initialize_sender();
131
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
132
			add_action( 'shutdown', array( self::$sender, 'do_full_sync' ), 9999 );
133
		}
134
	}
135
136
	/**
137
	 * Decides if the sender should run on shutdown for this request.
138
	 *
139
	 * @access public
140
	 * @static
141
	 *
142
	 * @return bool
143
	 */
144
	public static function should_initialize_sender() {
145
		if ( Constants::is_true( 'DOING_CRON' ) ) {
146
			return self::sync_via_cron_allowed();
147
		}
148
149
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] ) {
150
			return true;
151
		}
152
153
		if ( current_user_can( 'manage_options' ) ) {
154
			return true;
155
		}
156
157
		if ( is_admin() ) {
158
			return true;
159
		}
160
161
		if ( defined( 'PHPUNIT_JETPACK_TESTSUITE' ) ) {
162
			return true;
163
		}
164
165
		if ( Constants::get_constant( 'WP_CLI' ) ) {
166
			return true;
167
		}
168
169
		return false;
170
	}
171
172
	/**
173
	 * Decides if the sender should run on shutdown when actions are queued.
174
	 *
175
	 * @access public
176
	 * @static
177
	 *
178
	 * @return bool
179
	 */
180
	public static function should_initialize_sender_enqueue() {
181
		if ( Constants::is_true( 'DOING_CRON' ) ) {
182
			return self::sync_via_cron_allowed();
183
		}
184
185
		return true;
186
	}
187
188
	/**
189
	 * Decides if sync should run at all during this request.
190
	 *
191
	 * @access public
192
	 * @static
193
	 *
194
	 * @return bool
195
	 */
196
	public static function sync_allowed() {
197
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
198
			return false;
199
		}
200
201
		if ( defined( 'PHPUNIT_JETPACK_TESTSUITE' ) ) {
202
			return true;
203
		}
204
205
		if ( ! Settings::is_sync_enabled() ) {
206
			return false;
207
		}
208
209
		if ( ( new Status() )->is_offline_mode() ) {
210
			return false;
211
		}
212
213
		if ( ( new Status() )->is_staging_site() ) {
214
			return false;
215
		}
216
217
		$connection = new Jetpack_Connection();
218
		if ( ! $connection->is_active() ) {
219
			if ( ! doing_action( 'jetpack_user_authorized' ) ) {
220
				return false;
221
			}
222
		}
223
224
		return true;
225
	}
226
227
	/**
228
	 * Determines if syncing during a cron job is allowed.
229
	 *
230
	 * @access public
231
	 * @static
232
	 *
233
	 * @return bool|int
234
	 */
235
	public static function sync_via_cron_allowed() {
236
		return ( Settings::get_setting( 'sync_via_cron' ) );
237
	}
238
239
	/**
240
	 * Decides if the given post should be Publicized based on its type.
241
	 *
242
	 * @access public
243
	 * @static
244
	 *
245
	 * @param bool     $should_publicize  Publicize status prior to this filter running.
246
	 * @param \WP_Post $post              The post to test for Publicizability.
247
	 * @return bool
248
	 */
249
	public static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
250
		if ( in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true ) ) {
251
			return false;
252
		}
253
254
		return $should_publicize;
255
	}
256
257
	/**
258
	 * Set an importing flag to `true` in sync settings.
259
	 *
260
	 * @access public
261
	 * @static
262
	 */
263
	public static function set_is_importing_true() {
264
		Settings::set_importing( true );
265
	}
266
267
	/**
268
	 * Sends data to WordPress.com via an XMLRPC request.
269
	 *
270
	 * @access public
271
	 * @static
272
	 *
273
	 * @param object $data                   Data relating to a sync action.
274
	 * @param string $codec_name             The name of the codec that encodes the data.
275
	 * @param float  $sent_timestamp         Current server time so we can compensate for clock differences.
276
	 * @param string $queue_id               The queue the action belongs to, sync or full_sync.
277
	 * @param float  $checkout_duration      Time spent retrieving queue items from the DB.
278
	 * @param float  $preprocess_duration    Time spent converting queue items into data to send.
279
	 * @param int    $queue_size             The size of the sync queue at the time of processing.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $queue_size not be integer|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...
280
	 * @param string $buffer_id              The ID of the Queue buffer checked out for processing.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $buffer_id 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...
281
	 * @return Jetpack_Error|mixed|WP_Error  The result of the sending request.
282
	 */
283
	public static function send_data( $data, $codec_name, $sent_timestamp, $queue_id, $checkout_duration, $preprocess_duration, $queue_size = null, $buffer_id = null ) {
284
		$query_args = array(
285
			'sync'       => '1',             // Add an extra parameter to the URL so we can tell it's a sync action.
286
			'codec'      => $codec_name,
287
			'timestamp'  => $sent_timestamp,
288
			'queue'      => $queue_id,
289
			'home'       => Functions::home_url(),  // Send home url option to check for Identity Crisis server-side.
290
			'siteurl'    => Functions::site_url(),  // Send siteurl option to check for Identity Crisis server-side.
291
			'cd'         => sprintf( '%.4f', $checkout_duration ),
292
			'pd'         => sprintf( '%.4f', $preprocess_duration ),
293
			'queue_size' => $queue_size,
294
			'buffer_id'  => $buffer_id,
295
		);
296
297
		// Has the site opted in to IDC mitigation?
298
		if ( \Jetpack::sync_idc_optin() ) {
299
			$query_args['idc'] = true;
300
		}
301
302
		if ( \Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
303
			$query_args['migrate_for_idc'] = true;
304
		}
305
306
		$query_args['timeout'] = Settings::is_doing_cron() ? 30 : 15;
307
308
		/**
309
		 * Filters query parameters appended to the Sync request URL sent to WordPress.com.
310
		 *
311
		 * @since 4.7.0
312
		 *
313
		 * @param array $query_args associative array of query parameters.
314
		 */
315
		$query_args = apply_filters( 'jetpack_sync_send_data_query_args', $query_args );
316
317
		$connection = new Jetpack_Connection();
318
		$url        = add_query_arg( $query_args, $connection->xmlrpc_api_url() );
319
320
		// If we're currently updating to Jetpack 7.7, the IXR client may be missing briefly
321
		// because since 7.7 it's being autoloaded with Composer.
322
		if ( ! class_exists( '\\Jetpack_IXR_Client' ) ) {
323
			return new \WP_Error(
324
				'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...
325
				esc_html__( 'Sync has been aborted because the IXR client is missing.', 'jetpack' )
326
			);
327
		}
328
329
		$rpc = new \Jetpack_IXR_Client(
330
			array(
331
				'url'     => $url,
332
				'timeout' => $query_args['timeout'],
333
			)
334
		);
335
336
		$result = $rpc->query( 'jetpack.syncActions', $data );
337
338
		if ( ! $result ) {
339
			return $rpc->get_jetpack_error();
340
		}
341
342
		$response = $rpc->getResponse();
343
344
		// Check if WordPress.com IDC mitigation blocked the sync request.
345
		if ( is_array( $response ) && isset( $response['error_code'] ) ) {
346
			$error_code              = $response['error_code'];
347
			$allowed_idc_error_codes = array(
348
				'jetpack_url_mismatch',
349
				'jetpack_home_url_mismatch',
350
				'jetpack_site_url_mismatch',
351
			);
352
353
			if ( in_array( $error_code, $allowed_idc_error_codes, true ) ) {
354
				\Jetpack_Options::update_option(
355
					'sync_error_idc',
356
					\Jetpack::get_sync_error_idc_option( $response )
357
				);
358
			}
359
360
			return new \WP_Error(
361
				'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...
362
				esc_html__( 'Sync has been blocked from WordPress.com because it would cause an identity crisis', 'jetpack' )
363
			);
364
		}
365
366
		return $response;
367
	}
368
369
	/**
370
	 * Kicks off the initial sync.
371
	 *
372
	 * @access public
373
	 * @static
374
	 *
375
	 * @return bool|null False if sync is not allowed.
376
	 */
377
	public static function do_initial_sync() {
378
		// Lets not sync if we are not suppose to.
379
		if ( ! self::sync_allowed() ) {
380
			return false;
381
		}
382
383
		// Don't start new sync if a full sync is in process.
384
		$full_sync_module = Modules::get_module( 'full-sync' );
385
		if ( $full_sync_module && $full_sync_module->is_started() && ! $full_sync_module->is_finished() ) {
386
			return false;
387
		}
388
389
		$initial_sync_config = array(
390
			'options'         => true,
391
			'functions'       => true,
392
			'constants'       => true,
393
			'users'           => array( get_current_user_id() ),
394
			'network_options' => true,
395
		);
396
397
		self::do_full_sync( $initial_sync_config );
398
	}
399
400
	/**
401
	 * Kicks off a full sync.
402
	 *
403
	 * @access public
404
	 * @static
405
	 *
406
	 * @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...
407
	 * @return bool           True if full sync was successfully started.
408
	 */
409
	public static function do_full_sync( $modules = null ) {
410
		if ( ! self::sync_allowed() ) {
411
			return false;
412
		}
413
414
		$full_sync_module = Modules::get_module( 'full-sync' );
415
416
		if ( ! $full_sync_module ) {
417
			return false;
418
		}
419
420
		self::initialize_listener();
421
422
		$full_sync_module->start( $modules );
423
424
		return true;
425
	}
426
427
	/**
428
	 * Adds a cron schedule for regular syncing via cron, unless the schedule already exists.
429
	 *
430
	 * @access public
431
	 * @static
432
	 *
433
	 * @param array $schedules  The list of WordPress cron schedules prior to this filter.
434
	 * @return array            A list of WordPress cron schedules with the Jetpack sync interval added.
435
	 */
436
	public static function jetpack_cron_schedule( $schedules ) {
437
		if ( ! isset( $schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] ) ) {
438
			$minutes = intval( self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60 );
439
			$display = ( 1 === $minutes ) ?
440
				__( 'Every minute', 'jetpack' ) :
441
				/* translators: %d is an integer indicating the number of minutes. */
442
				sprintf( __( 'Every %d minutes', 'jetpack' ), $minutes );
443
			$schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] = array(
444
				'interval' => self::DEFAULT_SYNC_CRON_INTERVAL_VALUE,
445
				'display'  => $display,
446
			);
447
		}
448
		return $schedules;
449
	}
450
451
	/**
452
	 * Starts an incremental sync via cron.
453
	 *
454
	 * @access public
455
	 * @static
456
	 */
457
	public static function do_cron_sync() {
458
		self::do_cron_sync_by_type( 'sync' );
459
	}
460
461
	/**
462
	 * Starts a full sync via cron.
463
	 *
464
	 * @access public
465
	 * @static
466
	 */
467
	public static function do_cron_full_sync() {
468
		self::do_cron_sync_by_type( 'full_sync' );
469
	}
470
471
	/**
472
	 * Try to send actions until we run out of things to send,
473
	 * or have to wait more than 15s before sending again,
474
	 * or we hit a lock or some other sending issue
475
	 *
476
	 * @access public
477
	 * @static
478
	 *
479
	 * @param string $type Sync type. Can be `sync` or `full_sync`.
480
	 */
481
	public static function do_cron_sync_by_type( $type ) {
482
		if ( ! self::sync_allowed() || ( 'sync' !== $type && 'full_sync' !== $type ) ) {
483
			return;
484
		}
485
486
		self::initialize_sender();
487
488
		$time_limit = Settings::get_setting( 'cron_sync_time_limit' );
489
		$start_time = time();
490
		$executions = 0;
491
492
		do {
493
			$next_sync_time = self::$sender->get_next_sync_time( $type );
494
495
			if ( $next_sync_time ) {
496
				$delay = $next_sync_time - time() + 1;
497
				if ( $delay > 15 ) {
498
					break;
499
				} elseif ( $delay > 0 ) {
500
					sleep( $delay );
501
				}
502
			}
503
504
			// Explicitly only allow 1 do_full_sync call until issue with Immediate Full Sync is resolved.
505
			// For more context see p1HpG7-9pe-p2.
506
			if ( 'full_sync' === $type && $executions >= 1 ) {
507
				break;
508
			}
509
510
			$result = 'full_sync' === $type ? self::$sender->do_full_sync() : self::$sender->do_sync();
511
512
			// # of send actions performed.
513
			$executions ++;
514
515
		} while ( $result && ! is_wp_error( $result ) && ( $start_time + $time_limit ) > time() );
516
517
		return $executions;
518
	}
519
520
	/**
521
	 * Initialize the sync listener.
522
	 *
523
	 * @access public
524
	 * @static
525
	 */
526
	public static function initialize_listener() {
527
		self::$listener = Listener::get_instance();
0 ignored issues
show
Documentation Bug introduced by
It seems like \Automattic\Jetpack\Sync\Listener::get_instance() of type object<Automattic\Jetpack\Sync\Listener> is incompatible with the declared type object<Automattic\Jetpac...\Jetpack\Sync\Listener> of property $listener.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
528
	}
529
530
	/**
531
	 * Initializes the sync sender.
532
	 *
533
	 * @access public
534
	 * @static
535
	 */
536
	public static function initialize_sender() {
537
		self::$sender = Sender::get_instance();
0 ignored issues
show
Documentation Bug introduced by
It seems like \Automattic\Jetpack\Sync\Sender::get_instance() of type object<Automattic\Jetpack\Sync\Sender> is incompatible with the declared type object<Automattic\Jetpac...ic\Jetpack\Sync\Sender> of property $sender.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
538
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 8 );
539
	}
540
541
	/**
542
	 * Initializes sync for WooCommerce.
543
	 *
544
	 * @access public
545
	 * @static
546
	 */
547
	public static function initialize_woocommerce() {
548
		if ( false === class_exists( 'WooCommerce' ) ) {
549
			return;
550
		}
551
		add_filter( 'jetpack_sync_modules', array( __CLASS__, 'add_woocommerce_sync_module' ) );
552
	}
553
554
	/**
555
	 * Adds Woo's sync modules to existing modules for sending.
556
	 *
557
	 * @access public
558
	 * @static
559
	 *
560
	 * @param array $sync_modules The list of sync modules declared prior to this filter.
561
	 * @return array A list of sync modules that now includes Woo's modules.
562
	 */
563
	public static function add_woocommerce_sync_module( $sync_modules ) {
564
		$sync_modules[] = 'Automattic\\Jetpack\\Sync\\Modules\\WooCommerce';
565
		return $sync_modules;
566
	}
567
568
	/**
569
	 * Initializes sync for WP Super Cache.
570
	 *
571
	 * @access public
572
	 * @static
573
	 */
574
	public static function initialize_wp_super_cache() {
575
		if ( false === function_exists( 'wp_cache_is_enabled' ) ) {
576
			return;
577
		}
578
		add_filter( 'jetpack_sync_modules', array( __CLASS__, 'add_wp_super_cache_sync_module' ) );
579
	}
580
581
	/**
582
	 * Adds WP Super Cache's sync modules to existing modules for sending.
583
	 *
584
	 * @access public
585
	 * @static
586
	 *
587
	 * @param array $sync_modules The list of sync modules declared prior to this filer.
588
	 * @return array A list of sync modules that now includes WP Super Cache's modules.
589
	 */
590
	public static function add_wp_super_cache_sync_module( $sync_modules ) {
591
		$sync_modules[] = 'Automattic\\Jetpack\\Sync\\Modules\\WP_Super_Cache';
592
		return $sync_modules;
593
	}
594
595
	/**
596
	 * Sanitizes the name of sync's cron schedule.
597
	 *
598
	 * @access public
599
	 * @static
600
	 *
601
	 * @param string $schedule The name of a WordPress cron schedule.
602
	 * @return string The sanitized name of sync's cron schedule.
603
	 */
604
	public static function sanitize_filtered_sync_cron_schedule( $schedule ) {
605
		$schedule  = sanitize_key( $schedule );
606
		$schedules = wp_get_schedules();
607
608
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
609
		if ( isset( $schedules[ $schedule ] ) ) {
610
			return $schedule;
611
		}
612
613
		return self::DEFAULT_SYNC_CRON_INTERVAL_NAME;
614
	}
615
616
	/**
617
	 * Allows offsetting of start times for sync cron jobs.
618
	 *
619
	 * @access public
620
	 * @static
621
	 *
622
	 * @param string $schedule The name of a cron schedule.
623
	 * @param string $hook     The hook that this method is responding to.
624
	 * @return int The offset for the sync cron schedule.
625
	 */
626
	public static function get_start_time_offset( $schedule = '', $hook = '' ) {
627
		$start_time_offset = is_multisite()
628
			? wp_rand( 0, ( 2 * self::DEFAULT_SYNC_CRON_INTERVAL_VALUE ) )
629
			: 0;
630
631
		/**
632
		 * Allows overriding the offset that the sync cron jobs will first run. This can be useful when scheduling
633
		 * cron jobs across multiple sites in a network.
634
		 *
635
		 * @since 4.5.0
636
		 *
637
		 * @param int    $start_time_offset
638
		 * @param string $hook
639
		 * @param string $schedule
640
		 */
641
		return intval(
642
			apply_filters(
643
				'jetpack_sync_cron_start_time_offset',
644
				$start_time_offset,
645
				$hook,
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $hook.

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...
646
				$schedule
647
			)
648
		);
649
	}
650
651
	/**
652
	 * Decides if a sync cron should be scheduled.
653
	 *
654
	 * @access public
655
	 * @static
656
	 *
657
	 * @param string $schedule The name of a cron schedule.
658
	 * @param string $hook     The hook that this method is responding to.
659
	 */
660
	public static function maybe_schedule_sync_cron( $schedule, $hook ) {
661
		if ( ! $hook ) {
662
			return;
663
		}
664
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
665
666
		$start_time = time() + self::get_start_time_offset( $schedule, $hook );
667
		if ( ! wp_next_scheduled( $hook ) ) {
668
			// Schedule a job to send pending queue items once a minute.
669
			wp_schedule_event( $start_time, $schedule, $hook );
670
		} elseif ( wp_get_schedule( $hook ) !== $schedule ) {
671
			// If the schedule has changed, update the schedule.
672
			wp_clear_scheduled_hook( $hook );
673
			wp_schedule_event( $start_time, $schedule, $hook );
674
		}
675
	}
676
677
	/**
678
	 * Clears Jetpack sync cron jobs.
679
	 *
680
	 * @access public
681
	 * @static
682
	 */
683
	public static function clear_sync_cron_jobs() {
684
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
685
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
686
	}
687
688
	/**
689
	 * Initializes Jetpack sync cron jobs.
690
	 *
691
	 * @access public
692
	 * @static
693
	 */
694
	public static function init_sync_cron_jobs() {
695
		add_filter( 'cron_schedules', array( __CLASS__, 'jetpack_cron_schedule' ) ); // phpcs:ignore WordPress.WP.CronInterval.ChangeDetected
696
697
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
698
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
699
700
		/**
701
		 * Allows overriding of the default incremental sync cron schedule which defaults to once every 5 minutes.
702
		 *
703
		 * @since 4.3.2
704
		 *
705
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
706
		 */
707
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
708
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
709
710
		/**
711
		 * Allows overriding of the full sync cron schedule which defaults to once every 5 minutes.
712
		 *
713
		 * @since 4.3.2
714
		 *
715
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
716
		 */
717
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
718
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
719
	}
720
721
	/**
722
	 * Perform maintenance when a plugin upgrade occurs.
723
	 *
724
	 * @access public
725
	 * @static
726
	 *
727
	 * @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...
728
	 * @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...
729
	 */
730
	public static function cleanup_on_upgrade( $new_version = null, $old_version = null ) {
731
		if ( wp_next_scheduled( 'jetpack_sync_send_db_checksum' ) ) {
732
			wp_clear_scheduled_hook( 'jetpack_sync_send_db_checksum' );
733
		}
734
735
		$is_new_sync_upgrade = version_compare( $old_version, '4.2', '>=' );
736
		if ( ! empty( $old_version ) && $is_new_sync_upgrade && version_compare( $old_version, '4.5', '<' ) ) {
737
			self::clear_sync_cron_jobs();
738
			Settings::update_settings(
739
				array(
740
					'render_filtered_content' => Defaults::$default_render_filtered_content,
741
				)
742
			);
743
		}
744
745
		Health::on_jetpack_upgraded();
746
	}
747
748
	/**
749
	 * Get syncing status for the given fields.
750
	 *
751
	 * @access public
752
	 * @static
753
	 *
754
	 * @param string|null $fields A comma-separated string of the fields to include in the array from the JSON response.
755
	 * @return array An associative array with the status report.
756
	 */
757
	public static function get_sync_status( $fields = null ) {
758
		self::initialize_sender();
759
760
		$sync_module = Modules::get_module( 'full-sync' );
761
		$queue       = self::$sender->get_sync_queue();
762
763
		// _get_cron_array can be false
764
		$cron_timestamps = ( _get_cron_array() ) ? array_keys( _get_cron_array() ) : array();
765
		$next_cron       = ( ! empty( $cron_timestamps ) ) ? $cron_timestamps[0] - time() : '';
766
767
		$checksums = array();
768
769
		if ( ! empty( $fields ) ) {
770
			$store         = new Replicastore();
771
			$fields_params = array_map( 'trim', explode( ',', $fields ) );
772
773
			if ( in_array( 'posts_checksum', $fields_params, true ) ) {
774
				$checksums['posts_checksum'] = $store->posts_checksum();
775
			}
776
			if ( in_array( 'comments_checksum', $fields_params, true ) ) {
777
				$checksums['comments_checksum'] = $store->comments_checksum();
778
			}
779
			if ( in_array( 'post_meta_checksum', $fields_params, true ) ) {
780
				$checksums['post_meta_checksum'] = $store->post_meta_checksum();
781
			}
782
			if ( in_array( 'comment_meta_checksum', $fields_params, true ) ) {
783
				$checksums['comment_meta_checksum'] = $store->comment_meta_checksum();
784
			}
785
		}
786
787
		$full_sync_status = ( $sync_module ) ? $sync_module->get_status() : array();
788
789
		$full_queue = self::$sender->get_full_sync_queue();
790
791
		$result = array_merge(
792
			$full_sync_status,
793
			$checksums,
794
			array(
795
				'cron_size'            => count( $cron_timestamps ),
796
				'next_cron'            => $next_cron,
797
				'queue_size'           => $queue->size(),
798
				'queue_lag'            => $queue->lag(),
799
				'queue_next_sync'      => ( self::$sender->get_next_sync_time( 'sync' ) - microtime( true ) ),
800
				'full_queue_next_sync' => ( self::$sender->get_next_sync_time( 'full_sync' ) - microtime( true ) ),
801
			)
802
		);
803
804
		// Verify $sync_module is not false.
805
		if ( ( $sync_module ) && false === strpos( get_class( $sync_module ), 'Full_Sync_Immediately' ) ) {
806
			$result['full_queue_size'] = $full_queue->size();
807
			$result['full_queue_lag']  = $full_queue->lag();
808
		}
809
		return $result;
810
	}
811
}
812