Completed
Push — fix/queue-up-full-sync-on-netw... ( fcd777...aef030 )
by
unknown
128:41 queued 121:15
created

Jetpack_Sync_Actions::sync_allowed()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 4
nc 6
nop 0
dl 0
loc 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
5
 * when to send, when to perform a full sync, etc.
6
 *
7
 * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
8
 */
9
class Jetpack_Sync_Actions {
10
	static $sender = null;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $sender.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
11
	static $listener = null;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $listener.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
12
	const DEFAULT_SYNC_CRON_INTERVAL_NAME = 'jetpack_sync_interval';
13
	const DEFAULT_SYNC_CRON_INTERVAL_VALUE = 300; // 5 * MINUTE_IN_SECONDS;
14
	
15
	const NETWORK_UPDATE_RAMP_UP_BLOGS_PER_SECOND = 10;
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
		} else if ( wp_next_scheduled( 'jetpack_sync_cron' ) ) {
27
			wp_clear_scheduled_hook( 'jetpack_sync_cron' );
28
			wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
29
		}
30
31
		// Multi sites shouldn't  do a full sync all at once
32
		// If we haven't update yet lets see if we should do it.
33
		if ( is_multisite() && Jetpack_Options::get_option( 'network_version', 0 ) !== JETPACK__VERSION ) {
34
			add_action( 'shutdown', array( __CLASS__, 'maybe_start_initial_sync' ), 1 );
35
		}
36
37
		// On jetpack authorization, schedule a full sync
38
		add_action( 'jetpack_client_authorized', array( __CLASS__, 'do_full_sync' ), 10, 0 );
39
40
		// When importing via cron, do not sync
41
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
42
43
		// Sync connected user role changes to .com
44
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-users.php';
45
46
		// publicize filter to prevent publicizing blacklisted post types
47
		add_filter( 'publicize_should_publicize_published_post', array( __CLASS__, 'prevent_publicize_blacklisted_posts' ), 10, 2 );
48
49
		/**
50
		 * Fires on every request before default loading sync listener code.
51
		 * Return false to not load sync listener code that monitors common
52
		 * WP actions to be serialized.
53
		 *
54
		 * By default this returns true for cron jobs, non-GET-requests, or requests where the
55
		 * user is logged-in.
56
		 *
57
		 * @since 4.2.0
58
		 *
59
		 * @param bool should we load sync listener code for this request
60
		 */
61
		if ( apply_filters( 'jetpack_sync_listener_should_load', true ) ) {
62
			self::initialize_listener();
63
		}
64
65
		add_action( 'init', array( __CLASS__, 'add_sender_shutdown' ), 90 );
66
67
	}
68
69
	static function maybe_start_initial_sync() {
70
		if ( ! self::can_do_initial_sync() ) {
71
			return;
72
		}
73
		// Previous
74
		$previous_version_and_time = Jetpack_Options::get_option( 'old_version', 0 );
75
		$previous_version = explode( ':', $previous_version_and_time );
76
		self::do_initial_sync( JETPACK__VERSION, $previous_version[ 0 ], true );
77
	}
78
79
	static function can_do_initial_sync( $current_blog_id = null, $current_time = null ) {
80
		if ( empty( $current_blog_id ) ) {
81
			$current_blog_id = get_current_blog_id();
82
		}
83
		if ( empty( $current_time ) ) {
84
			$current_time = time();
85
		}
86
87
		$version_with_time = explode( ':', Jetpack_Options::get_option( 'version', 0 ) );
88
		if ( ! isset( $version_with_time[ 1 ] ) ) {
89
			// This is not very likely to happen.
90
			// lets set it to 0 so that the update happends right away
91
			$version_with_time[ 1 ] = 0;
92
		}
93
		$version_updated = $version_with_time[ 1 ];
94
95
		/**
96
		 * Allows the dev to change the number of blogs that the nework is allowed update per second.
97
		 * By default this value is set to 10 blogs per second.
98
		 * The blogs blog_id determins if a site can update.
99
		 *
100
		 * @since 4.5.0
101
		 *
102
		 * @param int the number of blogs per second that should be allowed to update.
103
		 */
104
		$blogs_per_seconds = (int) apply_filters( 'jetpack_network_ramp_up_blogs_per_second', self::NETWORK_UPDATE_RAMP_UP_BLOGS_PER_SECOND );
105
		$time_difference = ( $current_time - $version_updated );
106
		
107
		return ( $current_blog_id <= ( $time_difference  * $blogs_per_seconds ) );
108
	}
109
110
	static function add_sender_shutdown() {
111
		/**
112
		 * Fires on every request before default loading sync sender code.
113
		 * Return false to not load sync sender code that serializes pending
114
		 * data and sends it to WPCOM for processing.
115
		 *
116
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
117
		 * by users who can manage_options.
118
		 *
119
		 * @since 4.2.0
120
		 *
121
		 * @param bool should we load sync sender code for this request
122
		 */
123
		if ( apply_filters( 'jetpack_sync_sender_should_load',
124
			(
125
				( isset( $_SERVER["REQUEST_METHOD"] ) && 'POST' === $_SERVER['REQUEST_METHOD'] )
126
				||
127
				current_user_can( 'manage_options' )
128
				||
129
				is_admin()
130
				||
131
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
132
			)
133
		) ) {
134
			self::initialize_sender();
135
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
136
			add_action( 'shutdown', array( self::$sender, 'do_full_sync' ) );
137
		}
138
	}
139
140
	static function sync_allowed() {
141
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
142
		return ( ! Jetpack_Sync_Settings::get_setting( 'disable' ) && Jetpack::is_active() && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
143
			   || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
144
	}
145
146
	static function sync_via_cron_allowed() {
147
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
148
		return ( Jetpack_Sync_Settings::get_setting( 'sync_via_cron' ) );
149
	}
150
151
	static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
152
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
153
		if ( in_array( $post->post_type, Jetpack_Sync_Settings::get_setting( 'post_types_blacklist' ) ) ) {
154
			return false;
155
		}
156
157
		return $should_publicize;
158
	}
159
160
	static function set_is_importing_true() {
161
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
162
		Jetpack_Sync_Settings::set_importing( true );
163
	}
164
165
	static function send_data( $data, $codec_name, $sent_timestamp, $queue_id, $checkout_duration, $preprocess_duration ) {
166
		Jetpack::load_xml_rpc_client();
167
168
		$query_args = array(
169
			'sync'      => '1',             // add an extra parameter to the URL so we can tell it's a sync action
170
			'codec'     => $codec_name,     // send the name of the codec used to encode the data
171
			'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
172
			'queue'     => $queue_id,       // sync or full_sync
173
			'home'      => get_home_url(),  // Send home url option to check for Identity Crisis server-side
174
			'siteurl'   => get_site_url(),  // Send siteurl option to check for Identity Crisis server-side
175
			'cd'        => sprintf( '%.4f', $checkout_duration),   // Time spent retrieving queue items from the DB
176
			'pd'        => sprintf( '%.4f', $preprocess_duration), // Time spent converting queue items into data to send
177
		);
178
179
		// Has the site opted in to IDC mitigation?
180
		if ( Jetpack::sync_idc_optin() ) {
181
			$query_args['idc'] = true;
182
		}
183
184
		if ( Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
185
			$query_args['migrate_for_idc'] = true;
186
		}
187
188
		$query_args['timeout'] = Jetpack_Sync_Settings::is_doing_cron() ? 30 : 15;
189
190
		$url = add_query_arg( $query_args, Jetpack::xmlrpc_api_url() );
191
192
		$rpc = new Jetpack_IXR_Client( array(
193
			'url'     => $url,
194
			'user_id' => JETPACK_MASTER_USER,
195
			'timeout' => $query_args['timeout'],
196
		) );
197
198
		$result = $rpc->query( 'jetpack.syncActions', $data );
199
200
		if ( ! $result ) {
201
			return $rpc->get_jetpack_error();
202
		}
203
204
		$response = $rpc->getResponse();
205
206
		// Check if WordPress.com IDC mitigation blocked the sync request
207
		if ( is_array( $response ) && isset( $response['error_code'] ) ) {
208
			$error_code = $response['error_code'];
209
			$allowed_idc_error_codes = array(
210
				'jetpack_url_mismatch',
211
				'jetpack_home_url_mismatch',
212
				'jetpack_site_url_mismatch'
213
			);
214
215
			if ( in_array( $error_code, $allowed_idc_error_codes ) ) {
216
				Jetpack_Options::update_option(
217
					'sync_error_idc',
218
					Jetpack::get_sync_error_idc_option( $response )
219
				);
220
			}
221
222
			return new WP_Error(
223
				'sync_error_idc',
224
				esc_html__( 'Sync has been blocked from WordPress.com because it would cause an identity crisis', 'jetpack' )
225
			);
226
		}
227
228
		return $response;
229
	}
230
231
	static function do_initial_sync( $new_version = null, $old_version = null, $network_site = false ) {
232
		$initial_sync_config = self::get_update_full_sync_config();
233
234
		if ( $old_version && ( version_compare( $old_version, '4.2', '<' ) ) ) {
235
			$initial_sync_config['users'] = 'initial';
236
		}
237
238
		if ( $network_site || ! is_multisite() ) {
239
			self::do_full_sync( $initial_sync_config );
240
			Jetpack_Options::update_option( 'network_version', JETPACK__VERSION );
241
		}
242
	}
243
244
	static function get_update_full_sync_config() {
245
		return array(
246
			'options' => true,
247
			'network_options' => true,
248
			'functions' => true,
249
			'constants' => true,
250
		);
251
	}
252
253
	static function do_full_sync( $modules = null ) {
254
		if ( ! self::sync_allowed() ) {
255
			return false;
256
		}
257
		self::initialize_listener();
258
		Jetpack_Sync_Modules::get_module( 'full-sync' )->start( $modules );
259
260
		return true;
261
	}
262
263
	static function jetpack_cron_schedule( $schedules ) {
264
		if ( ! isset( $schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] ) ) {
265
			$schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] = array(
266
				'interval' => self::DEFAULT_SYNC_CRON_INTERVAL_VALUE,
267
				'display' => sprintf(
268
					esc_html__( 'Every %d minutes', 'jetpack' ),
269
					self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60
270
				)
271
			);
272
		}
273
		return $schedules;
274
	}
275
276
	// try to send actions until we run out of things to send,
277
	// or have to wait more than 15s before sending again,
278
	// or we hit a lock or some other sending issue
279 View Code Duplication
	static function do_cron_sync() {
280
		if ( ! self::sync_allowed() ) {
281
			return;
282
		}
283
284
		self::initialize_sender();
285
286
		$time_limit = Jetpack_Sync_Settings::get_setting( 'cron_sync_time_limit' );
287
		$start_time = time();
288
289
		do {
290
			$next_sync_time = self::$sender->get_next_sync_time( 'sync' );
291
292
			if ( $next_sync_time ) {
293
				$delay = $next_sync_time - time() + 1;
294
				if ( $delay > 15 ) {
295
					break;
296
				} elseif ( $delay > 0 ) {
297
					sleep( $delay );
298
				}
299
			}
300
301
			$result = self::$sender->do_sync();
302
		} while ( $result && ( $start_time + $time_limit ) > time() );
303
	}
304
305 View Code Duplication
	static function do_cron_full_sync() {
306
		if ( ! self::sync_allowed() ) {
307
			return;
308
		}
309
310
		self::initialize_sender();
311
312
		$time_limit = Jetpack_Sync_Settings::get_setting( 'cron_sync_time_limit' );
313
		$start_time = time();
314
315
		do {
316
			$next_sync_time = self::$sender->get_next_sync_time( 'full_sync' );
317
318
			if ( $next_sync_time ) {
319
				$delay = $next_sync_time - time() + 1;
320
				if ( $delay > 15 ) {
321
					break;
322
				} elseif ( $delay > 0 ) {
323
					sleep( $delay );
324
				}
325
			}
326
327
			$result = self::$sender->do_full_sync();
328
		} while ( $result && ( $start_time + $time_limit ) > time() );
329
	}
330
331
	static function initialize_listener() {
332
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
333
		self::$listener = Jetpack_Sync_Listener::get_instance();
334
	}
335
336
	static function initialize_sender() {
337
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
338
		self::$sender = Jetpack_Sync_Sender::get_instance();
339
340
		// bind the sending process
341
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 6 );
342
	}
343
344
	static function sanitize_filtered_sync_cron_schedule( $schedule ) {
345
		$schedule = sanitize_key( $schedule );
346
		$schedules = wp_get_schedules();
347
348
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
349
		if ( isset( $schedules[ $schedule ] ) ) {
350
			return $schedule;
351
		}
352
353
		return self::DEFAULT_SYNC_CRON_INTERVAL_NAME;
354
	}
355
356
	static function maybe_schedule_sync_cron( $schedule, $hook ) {
357
		if ( ! $hook ) {
358
			return;
359
		}
360
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
361
362
		if ( ! wp_next_scheduled( $hook ) ) {
363
			// Schedule a job to send pending queue items once a minute
364
			wp_schedule_event( time(), $schedule, $hook );
365
		} else if ( $schedule != wp_get_schedule( $hook ) ) {
366
			// If the schedule has changed, update the schedule
367
			wp_clear_scheduled_hook( $hook );
368
			wp_schedule_event( time(), $schedule, $hook );
369
		}
370
	}
371
372
	static function init_sync_cron_jobs() {
373
		// Add a custom "every minute" cron schedule
374
		add_filter( 'cron_schedules', array( __CLASS__, 'jetpack_cron_schedule' ) );
375
376
		// cron hooks
377
		add_action( 'jetpack_sync_full', array( __CLASS__, 'do_full_sync' ), 10, 1 );
378
379
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
380
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
381
382
		/**
383
		 * Allows overriding of the default incremental sync cron schedule which defaults to once every 5 minutes.
384
		 *
385
		 * @since 4.3.2
386
		 *
387
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
388
		 */
389
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
390
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
391
392
		/**
393
		 * Allows overriding of the full sync cron schedule which defaults to once every 5 minutes.
394
		 *
395
		 * @since 4.3.2
396
		 *
397
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
398
		 */
399
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
400
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
401
	}
402
403
	static function cleanup_on_upgrade() {
404
		if ( wp_next_scheduled( 'jetpack_sync_send_db_checksum' ) ) {
405
			wp_clear_scheduled_hook( 'jetpack_sync_send_db_checksum' );
406
		}
407
	}
408
409
	static function get_sync_status() {
410
		self::initialize_sender();
411
412
		$sync_module = Jetpack_Sync_Modules::get_module( 'full-sync' );
413
		$queue       = self::$sender->get_sync_queue();
414
		$full_queue  = self::$sender->get_full_sync_queue();
415
		$cron_timestamps = array_keys( _get_cron_array() );
416
		$next_cron = $cron_timestamps[0] - time();
417
418
		return array_merge(
419
			$sync_module->get_status(),
420
			array(
421
				'cron_size'             => count( $cron_timestamps ),
422
				'next_cron'             => $next_cron,
423
				'queue_size'            => $queue->size(),
424
				'queue_lag'             => $queue->lag(),
425
				'queue_next_sync'       => ( self::$sender->get_next_sync_time( 'sync' ) - microtime( true ) ),
426
				'full_queue_size'       => $full_queue->size(),
427
				'full_queue_lag'        => $full_queue->lag(),
428
				'full_queue_next_sync'  => ( self::$sender->get_next_sync_time( 'full_sync' ) - microtime( true ) ),
429
			)
430
		);
431
	}
432
}
433
434
/**
435
 * If the site is using alternate cron, we need to init the listener and sender before cron
436
 * runs. So, we init at a priority of 9.
437
 *
438
 * If the site is using a regular cron job, we init at a priority of 90 which gives plugins a chance
439
 * to add filters before we initialize.
440
 */
441
add_action( 'plugins_loaded', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
442
443
// We need to define this here so that it's hooked before `updating_jetpack_version` is called
444
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'do_initial_sync' ), 10, 2 );
445
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'cleanup_on_upgrade' ) );
446