Completed
Push — fix/queue-up-full-sync-on-netw... ( 805ba4...4f03a6 )
by
unknown
38:40 queued 29:45
created

Jetpack_Sync_Actions::init()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 54
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 20
nc 13
nop 0
dl 0
loc 54
rs 7.8331
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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