Completed
Push — add/network-disable-jetpack-sy... ( a1688c...d01925 )
by
unknown
17:40 queued 09:48
created

Jetpack_Sync_Actions::sync_allowed()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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