Completed
Push — feature/jetpack-packages ( cf65ba...5255bf )
by Marin
09:02
created

Jetpack_Sync_Actions::should_initialize_sender()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 6
nop 0
dl 0
loc 23
rs 8.6186
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Constants\Manager as Constants_Manager;
4
5
/**
6
 * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
7
 * when to send, when to perform a full sync, etc.
8
 *
9
 * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
10
 */
11
class Jetpack_Sync_Actions {
12
	static $sender                         = null;
13
	static $listener                       = null;
14
	const DEFAULT_SYNC_CRON_INTERVAL_NAME  = 'jetpack_sync_interval';
15
	const DEFAULT_SYNC_CRON_INTERVAL_VALUE = 300; // 5 * MINUTE_IN_SECONDS;
16
17
	static function init() {
18
		// everything below this point should only happen if we're a valid sync site
19
		if ( ! self::sync_allowed() ) {
20
			return;
21
		}
22
23
		if ( self::sync_via_cron_allowed() ) {
24
			self::init_sync_cron_jobs();
25
		} elseif ( wp_next_scheduled( 'jetpack_sync_cron' ) ) {
26
			self::clear_sync_cron_jobs();
27
		}
28
		// When importing via cron, do not sync
29
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
30
31
		// Sync connected user role changes to .com
32
		Jetpack_Sync_Users::init();
33
34
		// publicize filter to prevent publicizing blacklisted post types
35
		add_filter( 'publicize_should_publicize_published_post', array( __CLASS__, 'prevent_publicize_blacklisted_posts' ), 10, 2 );
36
37
		/**
38
		 * Fires on every request before default loading sync listener code.
39
		 * Return false to not load sync listener code that monitors common
40
		 * WP actions to be serialized.
41
		 *
42
		 * By default this returns true for cron jobs, non-GET-requests, or requests where the
43
		 * user is logged-in.
44
		 *
45
		 * @since 4.2.0
46
		 *
47
		 * @param bool should we load sync listener code for this request
48
		 */
49
		if ( apply_filters( 'jetpack_sync_listener_should_load', true ) ) {
50
			self::initialize_listener();
51
		}
52
53
		add_action( 'init', array( __CLASS__, 'add_sender_shutdown' ), 90 );
54
	}
55
56
	static function add_sender_shutdown() {
57
		/**
58
		 * Fires on every request before default loading sync sender code.
59
		 * Return false to not load sync sender code that serializes pending
60
		 * data and sends it to WPCOM for processing.
61
		 *
62
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
63
		 * by users who can manage_options.
64
		 *
65
		 * @since 4.2.0
66
		 *
67
		 * @param bool should we load sync sender code for this request
68
		 */
69
		if ( apply_filters(
70
			'jetpack_sync_sender_should_load',
71
			self::should_initialize_sender()
72
		) ) {
73
			self::initialize_sender();
74
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
75
			add_action( 'shutdown', array( self::$sender, 'do_full_sync' ) );
76
		}
77
	}
78
79
	static function should_initialize_sender() {
80
		if ( Constants_Manager::is_true( 'DOING_CRON' ) ) {
81
			return self::sync_via_cron_allowed();
82
		}
83
84
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] ) {
85
			return true;
86
		}
87
88
		if ( current_user_can( 'manage_options' ) ) {
89
			return true;
90
		}
91
92
		if ( is_admin() ) {
93
			return true;
94
		}
95
96
		if ( defined( 'PHPUNIT_JETPACK_TESTSUITE' ) ) {
97
			return true;
98
		}
99
100
		return false;
101
	}
102
103
	static function sync_allowed() {
104
		if ( defined( 'PHPUNIT_JETPACK_TESTSUITE' ) ) {
105
			return true;
106
		}
107
		if ( ! Jetpack_Sync_Settings::is_sync_enabled() ) {
108
			return false;
109
		}
110
		if ( Jetpack::is_development_mode() ) {
111
			return false;
112
		}
113
		if ( Jetpack::is_staging_site() ) {
114
			return false;
115
		}
116
		if ( ! Jetpack::is_active() ) {
117
			if ( ! doing_action( 'jetpack_user_authorized' ) ) {
118
				return false;
119
			}
120
		}
121
122
		return true;
123
	}
124
125
	static function sync_via_cron_allowed() {
126
		return ( Jetpack_Sync_Settings::get_setting( 'sync_via_cron' ) );
127
	}
128
129
	static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
130
		if ( in_array( $post->post_type, Jetpack_Sync_Settings::get_setting( 'post_types_blacklist' ) ) ) {
131
			return false;
132
		}
133
134
		return $should_publicize;
135
	}
136
137
	static function set_is_importing_true() {
138
		Jetpack_Sync_Settings::set_importing( true );
139
	}
140
141
	static function send_data( $data, $codec_name, $sent_timestamp, $queue_id, $checkout_duration, $preprocess_duration ) {
142
		Jetpack::load_xml_rpc_client();
143
144
		$query_args = array(
145
			'sync'      => '1',             // add an extra parameter to the URL so we can tell it's a sync action
146
			'codec'     => $codec_name,     // send the name of the codec used to encode the data
147
			'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
148
			'queue'     => $queue_id,       // sync or full_sync
149
			'home'      => Jetpack_Sync_Functions::home_url(),  // Send home url option to check for Identity Crisis server-side
150
			'siteurl'   => Jetpack_Sync_Functions::site_url(),  // Send siteurl option to check for Identity Crisis server-side
151
			'cd'        => sprintf( '%.4f', $checkout_duration ),   // Time spent retrieving queue items from the DB
152
			'pd'        => sprintf( '%.4f', $preprocess_duration ), // Time spent converting queue items into data to send
153
		);
154
155
		// Has the site opted in to IDC mitigation?
156
		if ( Jetpack::sync_idc_optin() ) {
157
			$query_args['idc'] = true;
158
		}
159
160
		if ( Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
161
			$query_args['migrate_for_idc'] = true;
162
		}
163
164
		$query_args['timeout'] = Jetpack_Sync_Settings::is_doing_cron() ? 30 : 15;
165
166
		/**
167
		 * Filters query parameters appended to the Sync request URL sent to WordPress.com.
168
		 *
169
		 * @since 4.7.0
170
		 *
171
		 * @param array $query_args associative array of query parameters.
172
		 */
173
		$query_args = apply_filters( 'jetpack_sync_send_data_query_args', $query_args );
174
175
		$url = add_query_arg( $query_args, Jetpack::xmlrpc_api_url() );
176
177
		$rpc = new Jetpack_IXR_Client(
178
			array(
179
				'url'     => $url,
180
				'user_id' => JETPACK_MASTER_USER,
181
				'timeout' => $query_args['timeout'],
182
			)
183
		);
184
185
		$result = $rpc->query( 'jetpack.syncActions', $data );
186
187
		if ( ! $result ) {
188
			return $rpc->get_jetpack_error();
189
		}
190
191
		$response = $rpc->getResponse();
192
193
		// Check if WordPress.com IDC mitigation blocked the sync request
194
		if ( is_array( $response ) && isset( $response['error_code'] ) ) {
195
			$error_code              = $response['error_code'];
196
			$allowed_idc_error_codes = array(
197
				'jetpack_url_mismatch',
198
				'jetpack_home_url_mismatch',
199
				'jetpack_site_url_mismatch',
200
			);
201
202
			if ( in_array( $error_code, $allowed_idc_error_codes ) ) {
203
				Jetpack_Options::update_option(
204
					'sync_error_idc',
205
					Jetpack::get_sync_error_idc_option( $response )
206
				);
207
			}
208
209
			return new WP_Error(
210
				'sync_error_idc',
211
				esc_html__( 'Sync has been blocked from WordPress.com because it would cause an identity crisis', 'jetpack' )
212
			);
213
		}
214
215
		return $response;
216
	}
217
218
	static function do_initial_sync() {
219
		// Lets not sync if we are not suppose to.
220
		if ( ! self::sync_allowed() ) {
221
			return false;
222
		}
223
224
		$initial_sync_config = array(
225
			'options'   => true,
226
			'functions' => true,
227
			'constants' => true,
228
			'users'     => array( get_current_user_id() ),
229
		);
230
231
		if ( is_multisite() ) {
232
			$initial_sync_config['network_options'] = true;
233
		}
234
235
		self::do_full_sync( $initial_sync_config );
236
	}
237
238
	static function do_full_sync( $modules = null ) {
239
		if ( ! self::sync_allowed() ) {
240
			return false;
241
		}
242
243
		$full_sync_module = Jetpack_Sync_Modules::get_module( 'full-sync' );
244
245
		if ( ! $full_sync_module ) {
246
			return false;
247
		}
248
249
		self::initialize_listener();
250
251
		$full_sync_module->start( $modules );
252
253
		return true;
254
	}
255
256
	static function jetpack_cron_schedule( $schedules ) {
257
		if ( ! isset( $schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] ) ) {
258
			$schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] = array(
259
				'interval' => self::DEFAULT_SYNC_CRON_INTERVAL_VALUE,
260
				'display'  => sprintf(
261
					esc_html( _n( 'Every minute', 'Every %d minutes', intval( self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60 ), 'jetpack' ) ),
262
					intval( self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60 )
263
				),
264
			);
265
		}
266
		return $schedules;
267
	}
268
269
	static function do_cron_sync() {
270
		self::do_cron_sync_by_type( 'sync' );
271
	}
272
273
	static function do_cron_full_sync() {
274
		self::do_cron_sync_by_type( 'full_sync' );
275
	}
276
277
	/**
278
	 * Try to send actions until we run out of things to send,
279
	 * or have to wait more than 15s before sending again,
280
	 * or we hit a lock or some other sending issue
281
	 *
282
	 * @param string $type Sync type. Can be `sync` or `full_sync`.
283
	 */
284
	static function do_cron_sync_by_type( $type ) {
285
		if ( ! self::sync_allowed() || ( 'sync' !== $type && 'full_sync' !== $type ) ) {
286
			return;
287
		}
288
289
		self::initialize_sender();
290
291
		$time_limit = Jetpack_Sync_Settings::get_setting( 'cron_sync_time_limit' );
292
		$start_time = time();
293
294
		do {
295
			$next_sync_time = self::$sender->get_next_sync_time( $type );
296
297
			if ( $next_sync_time ) {
298
				$delay = $next_sync_time - time() + 1;
299
				if ( $delay > 15 ) {
300
					break;
301
				} elseif ( $delay > 0 ) {
302
					sleep( $delay );
303
				}
304
			}
305
306
			$result = 'full_sync' === $type ? self::$sender->do_full_sync() : self::$sender->do_sync();
307
		} while ( $result && ! is_wp_error( $result ) && ( $start_time + $time_limit ) > time() );
308
	}
309
310
	static function initialize_listener() {
311
		self::$listener = Jetpack_Sync_Listener::get_instance();
312
	}
313
314
	static function initialize_sender() {
315
		self::$sender = Jetpack_Sync_Sender::get_instance();
316
317
		// bind the sending process
318
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 6 );
319
	}
320
321
	static function initialize_woocommerce() {
322
		if ( false === class_exists( 'WooCommerce' ) ) {
323
			return;
324
		}
325
		add_filter( 'jetpack_sync_modules', array( 'Jetpack_Sync_Actions', 'add_woocommerce_sync_module' ) );
326
	}
327
328
	static function add_woocommerce_sync_module( $sync_modules ) {
329
		$sync_modules[] = 'Jetpack_Sync_Module_WooCommerce';
330
		return $sync_modules;
331
	}
332
333
	static function initialize_wp_super_cache() {
334
		if ( false === function_exists( 'wp_cache_is_enabled' ) ) {
335
			return;
336
		}
337
		add_filter( 'jetpack_sync_modules', array( 'Jetpack_Sync_Actions', 'add_wp_super_cache_sync_module' ) );
338
	}
339
340
	static function add_wp_super_cache_sync_module( $sync_modules ) {
341
		$sync_modules[] = 'Jetpack_Sync_Module_WP_Super_Cache';
342
		return $sync_modules;
343
	}
344
345
	static function sanitize_filtered_sync_cron_schedule( $schedule ) {
346
		$schedule  = sanitize_key( $schedule );
347
		$schedules = wp_get_schedules();
348
349
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
350
		if ( isset( $schedules[ $schedule ] ) ) {
351
			return $schedule;
352
		}
353
354
		return self::DEFAULT_SYNC_CRON_INTERVAL_NAME;
355
	}
356
357
	static function get_start_time_offset( $schedule = '', $hook = '' ) {
358
		$start_time_offset = is_multisite()
359
			? mt_rand( 0, ( 2 * self::DEFAULT_SYNC_CRON_INTERVAL_VALUE ) )
360
			: 0;
361
362
		/**
363
		 * Allows overriding the offset that the sync cron jobs will first run. This can be useful when scheduling
364
		 * cron jobs across multiple sites in a network.
365
		 *
366
		 * @since 4.5.0
367
		 *
368
		 * @param int    $start_time_offset
369
		 * @param string $hook
370
		 * @param string $schedule
371
		 */
372
		return intval(
373
			apply_filters(
374
				'jetpack_sync_cron_start_time_offset',
375
				$start_time_offset,
376
				$hook,
377
				$schedule
378
			)
379
		);
380
	}
381
382
	static function maybe_schedule_sync_cron( $schedule, $hook ) {
383
		if ( ! $hook ) {
384
			return;
385
		}
386
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
387
388
		$start_time = time() + self::get_start_time_offset( $schedule, $hook );
389
		if ( ! wp_next_scheduled( $hook ) ) {
390
			// Schedule a job to send pending queue items once a minute
391
			wp_schedule_event( $start_time, $schedule, $hook );
392
		} elseif ( $schedule != wp_get_schedule( $hook ) ) {
393
			// If the schedule has changed, update the schedule
394
			wp_clear_scheduled_hook( $hook );
395
			wp_schedule_event( $start_time, $schedule, $hook );
396
		}
397
	}
398
399
	static function clear_sync_cron_jobs() {
400
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
401
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
402
	}
403
404
	static function init_sync_cron_jobs() {
405
		add_filter( 'cron_schedules', array( __CLASS__, 'jetpack_cron_schedule' ) );
406
407
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
408
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
409
410
		/**
411
		 * Allows overriding of the default incremental sync cron schedule which defaults to once every 5 minutes.
412
		 *
413
		 * @since 4.3.2
414
		 *
415
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
416
		 */
417
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
418
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
419
420
		/**
421
		 * Allows overriding of the full sync cron schedule which defaults to once every 5 minutes.
422
		 *
423
		 * @since 4.3.2
424
		 *
425
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
426
		 */
427
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
428
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
429
	}
430
431
	static function cleanup_on_upgrade( $new_version = null, $old_version = null ) {
432
		if ( wp_next_scheduled( 'jetpack_sync_send_db_checksum' ) ) {
433
			wp_clear_scheduled_hook( 'jetpack_sync_send_db_checksum' );
434
		}
435
436
		$is_new_sync_upgrade = version_compare( $old_version, '4.2', '>=' );
437
		if ( ! empty( $old_version ) && $is_new_sync_upgrade && version_compare( $old_version, '4.5', '<' ) ) {
438
			self::clear_sync_cron_jobs();
439
			Jetpack_Sync_Settings::update_settings(
440
				array(
441
					'render_filtered_content' => Jetpack_Sync_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 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...
442
				)
443
			);
444
		}
445
	}
446
447
	/**
448
	 * Get the sync status
449
	 *
450
	 * @param string|null $fields A comma-separated string of the fields to include in the array from the JSON response.
451
	 * @return array
452
	 */
453
	static function get_sync_status( $fields = null ) {
454
		self::initialize_sender();
455
456
		$sync_module     = Jetpack_Sync_Modules::get_module( 'full-sync' );
457
		$queue           = self::$sender->get_sync_queue();
458
		$full_queue      = self::$sender->get_full_sync_queue();
459
		$cron_timestamps = array_keys( _get_cron_array() );
460
		$next_cron       = $cron_timestamps[0] - time();
461
462
		$checksums = array();
463
464
		if ( ! empty( $fields ) ) {
465
			$store         = new Jetpack_Sync_WP_Replicastore();
466
			$fields_params = array_map( 'trim', explode( ',', $fields ) );
467
468
			if ( in_array( 'posts_checksum', $fields_params, true ) ) {
469
				$checksums['posts_checksum'] = $store->posts_checksum();
470
			}
471
			if ( in_array( 'comments_checksum', $fields_params, true ) ) {
472
				$checksums['comments_checksum'] = $store->comments_checksum();
473
			}
474
			if ( in_array( 'post_meta_checksum', $fields_params, true ) ) {
475
				$checksums['post_meta_checksum'] = $store->post_meta_checksum();
476
			}
477
			if ( in_array( 'comment_meta_checksum', $fields_params, true ) ) {
478
				$checksums['comment_meta_checksum'] = $store->comment_meta_checksum();
479
			}
480
		}
481
482
		$full_sync_status = ( $sync_module ) ? $sync_module->get_status() : array();
483
484
		return array_merge(
485
			$full_sync_status,
486
			$checksums,
487
			array(
488
				'cron_size'            => count( $cron_timestamps ),
489
				'next_cron'            => $next_cron,
490
				'queue_size'           => $queue->size(),
491
				'queue_lag'            => $queue->lag(),
492
				'queue_next_sync'      => ( self::$sender->get_next_sync_time( 'sync' ) - microtime( true ) ),
493
				'full_queue_size'      => $full_queue->size(),
494
				'full_queue_lag'       => $full_queue->lag(),
495
				'full_queue_next_sync' => ( self::$sender->get_next_sync_time( 'full_sync' ) - microtime( true ) ),
496
			)
497
		);
498
	}
499
}
500