Completed
Push — branch-8.2 ( e77137...af475e )
by Jeremy
41:20 queued 34:20
created

Actions::do_full_sync()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
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' ), 9999 );
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( 'IS_WPCOM' ) && IS_WPCOM ) {
181
			return false;
182
		}
183
184
		if ( defined( 'PHPUNIT_JETPACK_TESTSUITE' ) ) {
185
			return true;
186
		}
187
188
		if ( ! Settings::is_sync_enabled() ) {
189
			return false;
190
		}
191
192
		if ( ( new Status() )->is_development_mode() ) {
193
			return false;
194
		}
195
196
		if ( ( new Status() )->is_staging_site() ) {
197
			return false;
198
		}
199
200
		$connection = new Jetpack_Connection();
201
		if ( ! $connection->is_active() ) {
202
			if ( ! doing_action( 'jetpack_user_authorized' ) ) {
203
				return false;
204
			}
205
		}
206
207
		return true;
208
	}
209
210
	/**
211
	 * Determines if syncing during a cron job is allowed.
212
	 *
213
	 * @access public
214
	 * @static
215
	 *
216
	 * @return bool|int
217
	 */
218
	public static function sync_via_cron_allowed() {
219
		return ( Settings::get_setting( 'sync_via_cron' ) );
220
	}
221
222
	/**
223
	 * Decides if the given post should be Publicized based on its type.
224
	 *
225
	 * @access public
226
	 * @static
227
	 *
228
	 * @param bool     $should_publicize  Publicize status prior to this filter running.
229
	 * @param \WP_Post $post              The post to test for Publicizability.
230
	 * @return bool
231
	 */
232
	public static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
233
		if ( in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true ) ) {
234
			return false;
235
		}
236
237
		return $should_publicize;
238
	}
239
240
	/**
241
	 * Set an importing flag to `true` in sync settings.
242
	 *
243
	 * @access public
244
	 * @static
245
	 */
246
	public static function set_is_importing_true() {
247
		Settings::set_importing( true );
248
	}
249
250
	/**
251
	 * Sends data to WordPress.com via an XMLRPC request.
252
	 *
253
	 * @access public
254
	 * @static
255
	 *
256
	 * @param object $data                   Data relating to a sync action.
257
	 * @param string $codec_name             The name of the codec that encodes the data.
258
	 * @param float  $sent_timestamp         Current server time so we can compensate for clock differences.
259
	 * @param string $queue_id               The queue the action belongs to, sync or full_sync.
260
	 * @param float  $checkout_duration      Time spent retrieving queue items from the DB.
261
	 * @param float  $preprocess_duration    Time spent converting queue items into data to send.
262
	 * @return Jetpack_Error|mixed|WP_Error  The result of the sending request.
263
	 */
264
	public static function send_data( $data, $codec_name, $sent_timestamp, $queue_id, $checkout_duration, $preprocess_duration ) {
265
		$query_args = array(
266
			'sync'      => '1',             // Add an extra parameter to the URL so we can tell it's a sync action.
267
			'codec'     => $codec_name,
268
			'timestamp' => $sent_timestamp,
269
			'queue'     => $queue_id,
270
			'home'      => Functions::home_url(),  // Send home url option to check for Identity Crisis server-side.
271
			'siteurl'   => Functions::site_url(),  // Send siteurl option to check for Identity Crisis server-side.
272
			'cd'        => sprintf( '%.4f', $checkout_duration ),
273
			'pd'        => sprintf( '%.4f', $preprocess_duration ),
274
		);
275
276
		// Has the site opted in to IDC mitigation?
277
		if ( \Jetpack::sync_idc_optin() ) {
278
			$query_args['idc'] = true;
279
		}
280
281
		if ( \Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
282
			$query_args['migrate_for_idc'] = true;
283
		}
284
285
		$query_args['timeout'] = Settings::is_doing_cron() ? 30 : 15;
286
287
		/**
288
		 * Filters query parameters appended to the Sync request URL sent to WordPress.com.
289
		 *
290
		 * @since 4.7.0
291
		 *
292
		 * @param array $query_args associative array of query parameters.
293
		 */
294
		$query_args = apply_filters( 'jetpack_sync_send_data_query_args', $query_args );
295
296
		$connection = new Jetpack_Connection();
297
		$url        = add_query_arg( $query_args, $connection->xmlrpc_api_url() );
298
299
		// If we're currently updating to Jetpack 7.7, the IXR client may be missing briefly
300
		// because since 7.7 it's being autoloaded with Composer.
301
		if ( ! class_exists( '\\Jetpack_IXR_Client' ) ) {
302
			return new \WP_Error(
303
				'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...
304
				esc_html__( 'Sync has been aborted because the IXR client is missing.', 'jetpack' )
305
			);
306
		}
307
308
		$rpc = new \Jetpack_IXR_Client(
309
			array(
310
				'url'     => $url,
311
				'user_id' => JETPACK_MASTER_USER,
312
				'timeout' => $query_args['timeout'],
313
			)
314
		);
315
316
		$result = $rpc->query( 'jetpack.syncActions', $data );
317
318
		if ( ! $result ) {
319
			return $rpc->get_jetpack_error();
320
		}
321
322
		$response = $rpc->getResponse();
323
324
		// Check if WordPress.com IDC mitigation blocked the sync request.
325
		if ( is_array( $response ) && isset( $response['error_code'] ) ) {
326
			$error_code              = $response['error_code'];
327
			$allowed_idc_error_codes = array(
328
				'jetpack_url_mismatch',
329
				'jetpack_home_url_mismatch',
330
				'jetpack_site_url_mismatch',
331
			);
332
333
			if ( in_array( $error_code, $allowed_idc_error_codes, true ) ) {
334
				\Jetpack_Options::update_option(
335
					'sync_error_idc',
336
					\Jetpack::get_sync_error_idc_option( $response )
337
				);
338
			}
339
340
			return new \WP_Error(
341
				'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...
342
				esc_html__( 'Sync has been blocked from WordPress.com because it would cause an identity crisis', 'jetpack' )
343
			);
344
		}
345
346
		return $response;
347
	}
348
349
	/**
350
	 * Kicks off the initial sync.
351
	 *
352
	 * @access public
353
	 * @static
354
	 *
355
	 * @return bool|null False if sync is not allowed.
356
	 */
357
	public static function do_initial_sync() {
358
		// Lets not sync if we are not suppose to.
359
		if ( ! self::sync_allowed() ) {
360
			return false;
361
		}
362
363
		// Don't start new sync if a full sync is in process.
364
		$full_sync_module = Modules::get_module( 'full-sync' );
365
		if ( $full_sync_module && $full_sync_module->is_started() && ! $full_sync_module->is_finished() ) {
366
			return false;
367
		}
368
369
		$initial_sync_config = array(
370
			'options'   => true,
371
			'functions' => true,
372
			'constants' => true,
373
			'users'     => array( get_current_user_id() ),
374
		);
375
376
		if ( is_multisite() ) {
377
			$initial_sync_config['network_options'] = true;
378
		}
379
380
		self::do_full_sync( $initial_sync_config );
381
	}
382
383
	/**
384
	 * Kicks off a full sync.
385
	 *
386
	 * @access public
387
	 * @static
388
	 *
389
	 * @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...
390
	 * @return bool           True if full sync was successfully started.
391
	 */
392
	public static function do_full_sync( $modules = null ) {
393
		if ( ! self::sync_allowed() ) {
394
			return false;
395
		}
396
397
		$full_sync_module = Modules::get_module( 'full-sync' );
398
399
		if ( ! $full_sync_module ) {
400
			return false;
401
		}
402
403
		self::initialize_listener();
404
405
		$full_sync_module->start( $modules );
406
407
		return true;
408
	}
409
410
	/**
411
	 * Adds a cron schedule for regular syncing via cron, unless the schedule already exists.
412
	 *
413
	 * @access public
414
	 * @static
415
	 *
416
	 * @param array $schedules  The list of WordPress cron schedules prior to this filter.
417
	 * @return array            A list of WordPress cron schedules with the Jetpack sync interval added.
418
	 */
419
	public static function jetpack_cron_schedule( $schedules ) {
420
		if ( ! isset( $schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] ) ) {
421
			$minutes = intval( self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60 );
422
			$display = ( 1 === $minutes ) ?
423
				__( 'Every minute', 'jetpack' ) :
424
				/* translators: %d is an integer indicating the number of minutes. */
425
				sprintf( __( 'Every %d minutes', 'jetpack' ), $minutes );
426
			$schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] = array(
427
				'interval' => self::DEFAULT_SYNC_CRON_INTERVAL_VALUE,
428
				'display'  => $display,
429
			);
430
		}
431
		return $schedules;
432
	}
433
434
	/**
435
	 * Starts an incremental sync via cron.
436
	 *
437
	 * @access public
438
	 * @static
439
	 */
440
	public static function do_cron_sync() {
441
		self::do_cron_sync_by_type( 'sync' );
442
	}
443
444
	/**
445
	 * Starts a full sync via cron.
446
	 *
447
	 * @access public
448
	 * @static
449
	 */
450
	public static function do_cron_full_sync() {
451
		self::do_cron_sync_by_type( 'full_sync' );
452
	}
453
454
	/**
455
	 * Try to send actions until we run out of things to send,
456
	 * or have to wait more than 15s before sending again,
457
	 * or we hit a lock or some other sending issue
458
	 *
459
	 * @access public
460
	 * @static
461
	 *
462
	 * @param string $type Sync type. Can be `sync` or `full_sync`.
463
	 */
464
	public static function do_cron_sync_by_type( $type ) {
465
		if ( ! self::sync_allowed() || ( 'sync' !== $type && 'full_sync' !== $type ) ) {
466
			return;
467
		}
468
469
		self::initialize_sender();
470
471
		$time_limit = Settings::get_setting( 'cron_sync_time_limit' );
472
		$start_time = time();
473
474
		do {
475
			$next_sync_time = self::$sender->get_next_sync_time( $type );
476
477
			if ( $next_sync_time ) {
478
				$delay = $next_sync_time - time() + 1;
479
				if ( $delay > 15 ) {
480
					break;
481
				} elseif ( $delay > 0 ) {
482
					sleep( $delay );
483
				}
484
			}
485
486
			$result = 'full_sync' === $type ? self::$sender->do_full_sync() : self::$sender->do_sync();
487
		} while ( $result && ! is_wp_error( $result ) && ( $start_time + $time_limit ) > time() );
488
	}
489
490
	/**
491
	 * Initialize the sync listener.
492
	 *
493
	 * @access public
494
	 * @static
495
	 */
496
	public static function initialize_listener() {
497
		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...
498
	}
499
500
	/**
501
	 * Initializes the sync sender.
502
	 *
503
	 * @access public
504
	 * @static
505
	 */
506
	public static function initialize_sender() {
507
		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...
508
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 6 );
509
	}
510
511
	/**
512
	 * Initializes sync for WooCommerce.
513
	 *
514
	 * @access public
515
	 * @static
516
	 */
517
	public static function initialize_woocommerce() {
518
		if ( false === class_exists( 'WooCommerce' ) ) {
519
			return;
520
		}
521
		add_filter( 'jetpack_sync_modules', array( __CLASS__, 'add_woocommerce_sync_module' ) );
522
	}
523
524
	/**
525
	 * Adds Woo's sync modules to existing modules for sending.
526
	 *
527
	 * @access public
528
	 * @static
529
	 *
530
	 * @param array $sync_modules The list of sync modules declared prior to this filter.
531
	 * @return array A list of sync modules that now includes Woo's modules.
532
	 */
533
	public static function add_woocommerce_sync_module( $sync_modules ) {
534
		$sync_modules[] = 'Automattic\\Jetpack\\Sync\\Modules\\WooCommerce';
535
		return $sync_modules;
536
	}
537
538
	/**
539
	 * Initializes sync for WP Super Cache.
540
	 *
541
	 * @access public
542
	 * @static
543
	 */
544
	public static function initialize_wp_super_cache() {
545
		if ( false === function_exists( 'wp_cache_is_enabled' ) ) {
546
			return;
547
		}
548
		add_filter( 'jetpack_sync_modules', array( __CLASS__, 'add_wp_super_cache_sync_module' ) );
549
	}
550
551
	/**
552
	 * Adds WP Super Cache's sync modules to existing modules for sending.
553
	 *
554
	 * @access public
555
	 * @static
556
	 *
557
	 * @param array $sync_modules The list of sync modules declared prior to this filer.
558
	 * @return array A list of sync modules that now includes WP Super Cache's modules.
559
	 */
560
	public static function add_wp_super_cache_sync_module( $sync_modules ) {
561
		$sync_modules[] = 'Automattic\\Jetpack\\Sync\\Modules\\WP_Super_Cache';
562
		return $sync_modules;
563
	}
564
565
	/**
566
	 * Sanitizes the name of sync's cron schedule.
567
	 *
568
	 * @access public
569
	 * @static
570
	 *
571
	 * @param string $schedule The name of a WordPress cron schedule.
572
	 * @return string The sanitized name of sync's cron schedule.
573
	 */
574
	public static function sanitize_filtered_sync_cron_schedule( $schedule ) {
575
		$schedule  = sanitize_key( $schedule );
576
		$schedules = wp_get_schedules();
577
578
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
579
		if ( isset( $schedules[ $schedule ] ) ) {
580
			return $schedule;
581
		}
582
583
		return self::DEFAULT_SYNC_CRON_INTERVAL_NAME;
584
	}
585
586
	/**
587
	 * Allows offsetting of start times for sync cron jobs.
588
	 *
589
	 * @access public
590
	 * @static
591
	 *
592
	 * @param string $schedule The name of a cron schedule.
593
	 * @param string $hook     The hook that this method is responding to.
594
	 * @return int The offset for the sync cron schedule.
595
	 */
596
	public static function get_start_time_offset( $schedule = '', $hook = '' ) {
597
		$start_time_offset = is_multisite()
598
			? wp_rand( 0, ( 2 * self::DEFAULT_SYNC_CRON_INTERVAL_VALUE ) )
599
			: 0;
600
601
		/**
602
		 * Allows overriding the offset that the sync cron jobs will first run. This can be useful when scheduling
603
		 * cron jobs across multiple sites in a network.
604
		 *
605
		 * @since 4.5.0
606
		 *
607
		 * @param int    $start_time_offset
608
		 * @param string $hook
609
		 * @param string $schedule
610
		 */
611
		return intval(
612
			apply_filters(
613
				'jetpack_sync_cron_start_time_offset',
614
				$start_time_offset,
615
				$hook,
616
				$schedule
617
			)
618
		);
619
	}
620
621
	/**
622
	 * Decides if a sync cron should be scheduled.
623
	 *
624
	 * @access public
625
	 * @static
626
	 *
627
	 * @param string $schedule The name of a cron schedule.
628
	 * @param string $hook     The hook that this method is responding to.
629
	 */
630
	public static function maybe_schedule_sync_cron( $schedule, $hook ) {
631
		if ( ! $hook ) {
632
			return;
633
		}
634
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
635
636
		$start_time = time() + self::get_start_time_offset( $schedule, $hook );
637
		if ( ! wp_next_scheduled( $hook ) ) {
638
			// Schedule a job to send pending queue items once a minute.
639
			wp_schedule_event( $start_time, $schedule, $hook );
640
		} elseif ( wp_get_schedule( $hook ) !== $schedule ) {
641
			// If the schedule has changed, update the schedule.
642
			wp_clear_scheduled_hook( $hook );
643
			wp_schedule_event( $start_time, $schedule, $hook );
644
		}
645
	}
646
647
	/**
648
	 * Clears Jetpack sync cron jobs.
649
	 *
650
	 * @access public
651
	 * @static
652
	 */
653
	public static function clear_sync_cron_jobs() {
654
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
655
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
656
	}
657
658
	/**
659
	 * Initializes Jetpack sync cron jobs.
660
	 *
661
	 * @access public
662
	 * @static
663
	 */
664
	public static function init_sync_cron_jobs() {
665
		add_filter( 'cron_schedules', array( __CLASS__, 'jetpack_cron_schedule' ) ); // phpcs:ignore WordPress.WP.CronInterval.ChangeDetected
666
667
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
668
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
669
670
		/**
671
		 * Allows overriding of the default incremental sync cron schedule which defaults to once every 5 minutes.
672
		 *
673
		 * @since 4.3.2
674
		 *
675
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
676
		 */
677
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
678
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
679
680
		/**
681
		 * Allows overriding of the full sync cron schedule which defaults to once every 5 minutes.
682
		 *
683
		 * @since 4.3.2
684
		 *
685
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
686
		 */
687
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
688
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
689
	}
690
691
	/**
692
	 * Perform maintenance when a plugin upgrade occurs.
693
	 *
694
	 * @access public
695
	 * @static
696
	 *
697
	 * @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...
698
	 * @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...
699
	 */
700
	public static function cleanup_on_upgrade( $new_version = null, $old_version = null ) {
701
		if ( wp_next_scheduled( 'jetpack_sync_send_db_checksum' ) ) {
702
			wp_clear_scheduled_hook( 'jetpack_sync_send_db_checksum' );
703
		}
704
705
		$is_new_sync_upgrade = version_compare( $old_version, '4.2', '>=' );
706
		if ( ! empty( $old_version ) && $is_new_sync_upgrade && version_compare( $old_version, '4.5', '<' ) ) {
707
			self::clear_sync_cron_jobs();
708
			Settings::update_settings(
709
				array(
710
					'render_filtered_content' => Defaults::$default_render_filtered_content,
711
				)
712
			);
713
		}
714
	}
715
716
	/**
717
	 * Get syncing status for the given fields.
718
	 *
719
	 * @access public
720
	 * @static
721
	 *
722
	 * @param string|null $fields A comma-separated string of the fields to include in the array from the JSON response.
723
	 * @return array An associative array with the status report.
724
	 */
725
	public static function get_sync_status( $fields = null ) {
726
		self::initialize_sender();
727
728
		$sync_module     = Modules::get_module( 'full-sync' );
729
		$queue           = self::$sender->get_sync_queue();
730
731
		// _get_cron_array can be false
732
		$cron_timestamps = ( _get_cron_array() ) ? array_keys( _get_cron_array() ) : array();
733
		$next_cron       = ( ! empty( $cron_timestamps ) ) ? $cron_timestamps[0] - time() : '';
734
735
		$checksums = array();
736
737
		if ( ! empty( $fields ) ) {
738
			$store         = new Replicastore();
739
			$fields_params = array_map( 'trim', explode( ',', $fields ) );
740
741
			if ( in_array( 'posts_checksum', $fields_params, true ) ) {
742
				$checksums['posts_checksum'] = $store->posts_checksum();
743
			}
744
			if ( in_array( 'comments_checksum', $fields_params, true ) ) {
745
				$checksums['comments_checksum'] = $store->comments_checksum();
746
			}
747
			if ( in_array( 'post_meta_checksum', $fields_params, true ) ) {
748
				$checksums['post_meta_checksum'] = $store->post_meta_checksum();
749
			}
750
			if ( in_array( 'comment_meta_checksum', $fields_params, true ) ) {
751
				$checksums['comment_meta_checksum'] = $store->comment_meta_checksum();
752
			}
753
		}
754
755
		$full_sync_status = ( $sync_module ) ? $sync_module->get_status() : array();
756
757
		$full_queue = self::$sender->get_full_sync_queue();
758
759
		$result = array_merge(
760
			$full_sync_status,
761
			$checksums,
762
			array(
763
				'cron_size'            => count( $cron_timestamps ),
764
				'next_cron'            => $next_cron,
765
				'queue_size'           => $queue->size(),
766
				'queue_lag'            => $queue->lag(),
767
				'queue_next_sync'      => ( self::$sender->get_next_sync_time( 'sync' ) - microtime( true ) ),
768
				'full_queue_next_sync' => ( self::$sender->get_next_sync_time( 'full_sync' ) - microtime( true ) ),
769
			)
770
		);
771
772
		// Verify $sync_module is not false
773
		if ( ( $sync_module ) && false === strpos( get_class( $sync_module ), 'Full_Sync_Immediately' ) ) {
774
			$result['full_queue_size'] = $full_queue->size();
775
			$result['full_queue_lag']  = $full_queue->lag();
776
		}
777
		return $result;
778
	}
779
}
780