Completed
Push — fix/add-small-delay-to-regular... ( 94b9ea...f03336 )
by
unknown
33:06 queued 12:57
created

Jetpack_Sync_Actions::do_cron_full_sync()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 27
Code Lines 16

Duplication

Lines 27
Ratio 100 %

Importance

Changes 0
Metric Value
cc 7
eloc 16
nc 9
nop 0
dl 27
loc 27
rs 6.7272
c 0
b 0
f 0
1
<?php
2
require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
3
4
/**
5
 * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
6
 * when to send, when to perform a full sync, etc.
7
 *
8
 * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
9
 */
10
class Jetpack_Sync_Actions {
11
	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...
12
	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...
13
	const INITIAL_SYNC_MULTISITE_INTERVAL = 10;
14
	const DEFAULT_SYNC_CRON_INTERVAL = '1min';
15
16
	static function init() {
17
18
		// Add a custom "every minute" cron schedule
19
		add_filter( 'cron_schedules', array( __CLASS__, 'minute_cron_schedule' ) );
20
21
		// On jetpack authorization, schedule a full sync
22
		add_action( 'jetpack_client_authorized', array( __CLASS__, 'schedule_full_sync' ), 10, 0 );
23
24
		// When importing via cron, do not sync
25
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
26
27
		// Sync connected user role changes to .com
28
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-users.php';
29
30
		// everything below this point should only happen if we're a valid sync site
31
		if ( ! self::sync_allowed() ) {
32
			return;
33
		}
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
		// cron hooks
39
		add_action( 'jetpack_sync_full', array( __CLASS__, 'do_full_sync' ), 10, 1 );
40
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
41
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
42
43
		self::init_sync_cron_jobs();
44
45
		/**
46
		 * Fires on every request before default loading sync listener code.
47
		 * Return false to not load sync listener code that monitors common
48
		 * WP actions to be serialized.
49
		 *
50
		 * By default this returns true for cron jobs, non-GET-requests, or requests where the
51
		 * user is logged-in.
52
		 *
53
		 * @since 4.2.0
54
		 *
55
		 * @param bool should we load sync listener code for this request
56
		 */
57
		if ( apply_filters( 'jetpack_sync_listener_should_load',
58
			(
59
				( isset( $_SERVER["REQUEST_METHOD"] ) && 'GET' !== $_SERVER['REQUEST_METHOD'] )
60
				||
61
				is_user_logged_in()
62
				||
63
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
64
				||
65
				defined( 'DOING_CRON' ) && DOING_CRON
66
			)
67
		) ) {
68
			self::initialize_listener();
69
		}
70
71
		/**
72
		 * Fires on every request before default loading sync sender code.
73
		 * Return false to not load sync sender code that serializes pending
74
		 * data and sends it to WPCOM for processing.
75
		 *
76
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
77
		 * by users who can manage_options.
78
		 *
79
		 * @since 4.2.0
80
		 *
81
		 * @param bool should we load sync sender code for this request
82
		 */
83
		if ( apply_filters( 'jetpack_sync_sender_should_load',
84
			(
85
				( isset( $_SERVER["REQUEST_METHOD"] ) && 'POST' === $_SERVER['REQUEST_METHOD'] )
86
				||
87
				current_user_can( 'manage_options' )
88
				||
89
				is_admin()
90
				||
91
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
92
				||
93
				defined( 'DOING_CRON' ) && DOING_CRON
94
			)
95
		) ) {
96
			self::initialize_sender();
97
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
98
		}
99
100
	}
101
102
	static function sync_allowed() {
103
		return ( ! Jetpack_Sync_Settings::get_setting( 'disable' ) && Jetpack::is_active() && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
104
			   || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
105
	}
106
107
	static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
108
		if ( in_array( $post->post_type, Jetpack_Sync_Settings::get_setting( 'post_types_blacklist' ) ) ) {
109
			return false;
110
		}
111
112
		return $should_publicize;
113
	}
114
115
	static function set_is_importing_true() {
116
		Jetpack_Sync_Settings::set_importing( true );
117
	}
118
119
	static function send_data( $data, $codec_name, $sent_timestamp, $queue_id ) {
120
		Jetpack::load_xml_rpc_client();
121
122
		$query_args = array(
123
			'sync'      => '1',             // add an extra parameter to the URL so we can tell it's a sync action
124
			'codec'     => $codec_name,     // send the name of the codec used to encode the data
125
			'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
126
			'queue'     => $queue_id,       // sync or full_sync
127
			'home'      => get_home_url(),  // Send home url option to check for Identity Crisis server-side
128
			'siteurl'   => get_site_url(),  // Send siteurl option to check for Identity Crisis server-side
129
		);
130
131
		// Has the site opted in to IDC mitigation?
132
		if ( Jetpack::sync_idc_optin() ) {
133
			$query_args['idc'] = true;
134
		}
135
136
		$url = add_query_arg( $query_args, Jetpack::xmlrpc_api_url() );
137
138
		$rpc = new Jetpack_IXR_Client( array(
139
			'url'     => $url,
140
			'user_id' => JETPACK_MASTER_USER,
141
			'timeout' => 30,
142
		) );
143
144
		$result = $rpc->query( 'jetpack.syncActions', $data );
145
146
		if ( ! $result ) {
147
			$error = $rpc->get_jetpack_error();
148
			if ( 'jetpack_url_mismatch' === $error->get_error_code() ) {
149
				Jetpack_Options::update_option(
150
					'sync_error_idc',
151
					Jetpack::get_sync_error_idc_option()
152
				);
153
			}
154
			
155
			return $error;
156
		}
157
158
		return $rpc->getResponse();
159
	}
160
161
	static function schedule_initial_sync( $new_version = null, $old_version = null ) {
162
		$initial_sync_config = array(
163
			'options' => true,
164
			'network_options' => true,
165
			'functions' => true,
166
			'constants' => true,
167
		);
168
169
		if ( $old_version && ( version_compare( $old_version, '4.2', '<' ) ) ) {
170
			$initial_sync_config['users'] = 'initial';
171
		}
172
173
		// we need this function call here because we have to run this function
174
		// reeeeally early in init, before WP_CRON_LOCK_TIMEOUT is defined.
175
		wp_functionality_constants();
176
177
		if ( is_multisite() ) {
178
			// stagger initial syncs for multisite blogs so they don't all pile on top of each other
179
			$time_offset = ( rand() / getrandmax() ) * self::INITIAL_SYNC_MULTISITE_INTERVAL * get_blog_count();
180
		} else {
181
			$time_offset = 1;
182
		}
183
184
		self::schedule_full_sync(
185
			$initial_sync_config,
186
			$time_offset
187
		);
188
	}
189
190
	static function schedule_full_sync( $modules = null, $time_offset = 1 ) {
191
		if ( ! self::sync_allowed() ) {
192
			return false;
193
		}
194
195
		if ( Jetpack_Sync_Settings::get_setting( 'avoid_wp_cron' ) ) {
196
			// run queuing inline
197
			set_time_limit( 0 );
198
			self::do_full_sync( $modules );
199
			return false;
200
		}
201
202
		if ( self::is_scheduled_full_sync() ) {
203
			self::unschedule_all_full_syncs();
204
		}
205
206
		if ( $modules ) {
207
			wp_schedule_single_event( time() + $time_offset, 'jetpack_sync_full', array( $modules ) );
208
		} else {
209
			wp_schedule_single_event( time() + $time_offset, 'jetpack_sync_full' );
210
		}
211
212
		if ( $time_offset === 1 ) {
213
			spawn_cron();
214
		}
215
216
		return true;
217
	}
218
219
	static function unschedule_all_full_syncs() {
220
		foreach ( _get_cron_array() as $timestamp => $cron ) {
221
			if ( ! empty( $cron['jetpack_sync_full'] ) ) {
222
				foreach( $cron['jetpack_sync_full'] as $key => $config ) {
223
					wp_unschedule_event( $timestamp, 'jetpack_sync_full', $config['args'] );
224
				}
225
			}
226
		}
227
	}
228
229
	static function is_scheduled_full_sync( $modules = null ) {
230
		if ( is_null( $modules ) ) {
231
			$crons = _get_cron_array();
232
233
			foreach ( $crons as $timestamp => $cron ) {
234
				if ( ! empty( $cron['jetpack_sync_full'] ) ) {
235
					return true;
236
				}
237
			}
238
			return false;
239
		}
240
241
		return !! wp_next_scheduled( 'jetpack_sync_full', array( $modules ) );
242
	}
243
244
	static function do_full_sync( $modules = null ) {
245
		if ( ! self::sync_allowed() ) {
246
			return;
247
		}
248
249
		self::initialize_listener();
250
		Jetpack_Sync_Modules::get_module( 'full-sync' )->start( $modules );
251
		self::do_cron_full_sync(); // immediately run a cron full sync, which sends pending data
252
	}
253
254
	static function minute_cron_schedule( $schedules ) {
255
		if( ! isset( $schedules["1min"] ) ) {
256
			$schedules["1min"] = array(
257
				'interval' => 60,
258
				'display' => __( 'Every minute' )
259
			);
260
		}
261
		return $schedules;
262
	}
263
264
	// try to send actions until we run out of things to send,
265
	// or have to wait more than 15s before sending again,
266
	// or we hit a lock or some other sending issue
267 View Code Duplication
	static function do_cron_sync() {
268
		if ( ! self::sync_allowed() ) {
269
			return;
270
		}
271
272
		self::initialize_sender();
273
274
		// remove shutdown hook - no need to sync twice
275
		if ( has_action( 'shutdown', array( self::$sender, 'do_sync' ) ) ) {
276
			remove_action( 'shutdown', array( self::$sender, 'do_sync' ) );
277
		}
278
279
		do {
280
			$next_sync_time = self::$sender->get_next_sync_time( 'sync' );
281
282
			if ( $next_sync_time ) {
283
				$delay = $next_sync_time - time() + 1;
284
				if ( $delay > 15 ) {
285
					break;
286
				} elseif ( $delay > 0 ) {
287
					sleep( $delay );
288
				}
289
			}
290
291
			$result = self::$sender->do_sync();
292
		} while ( $result );
293
	}
294
295 View Code Duplication
	static function do_cron_full_sync() {
296
		if ( ! self::sync_allowed() ) {
297
			return;
298
		}
299
300
		self::initialize_sender();
301
302
		// remove shutdown hook - no need to sync twice
303
		if ( has_action( 'shutdown', array( self::$sender, 'do_sync' ) ) ) {
304
			remove_action( 'shutdown', array( self::$sender, 'do_sync' ) );
305
		}
306
307
		do {
308
			$next_sync_time = self::$sender->get_next_sync_time( 'full_sync' );
309
310
			if ( $next_sync_time ) {
311
				$delay = $next_sync_time - time() + 1;
312
				if ( $delay > 15 ) {
313
					break;
314
				} elseif ( $delay > 0 ) {
315
					sleep( $delay );
316
				}
317
			}
318
319
			$result = self::$sender->do_full_sync();
320
		} while ( $result );
321
	}
322
323
	static function initialize_listener() {
324
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
325
		self::$listener = Jetpack_Sync_Listener::get_instance();
326
	}
327
328
	static function initialize_sender() {
329
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
330
		self::$sender = Jetpack_Sync_Sender::get_instance();
331
332
		// bind the sending process
333
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 4 );
334
	}
335
336
	static function sanitize_filtered_sync_cron_schedule( $schedule ) {
337
		$schedule = sanitize_key( $schedule );
338
		$schedules = wp_get_schedules();
339
340
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
341
		if ( isset( $schedules[ $schedule ] ) ) {
342
			return $schedule;
343
		}
344
345
		return self::DEFAULT_SYNC_CRON_INTERVAL;
346
	}
347
348
	static function maybe_schedule_sync_cron( $schedule, $hook ) {
349
		if ( ! $hook ) {
350
			return;
351
		}
352
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
353
354
		if ( ! wp_next_scheduled( $hook ) ) {
355
			// Schedule a job to send pending queue items once a minute
356
			wp_schedule_event( time(), $schedule, $hook );
357
		} else if ( $schedule != wp_get_schedule( $hook ) ) {
358
			// If the schedule has changed, update the schedule
359
			wp_clear_scheduled_hook( $hook );
360
			wp_schedule_event( time(), $schedule, $hook );
361
		}
362
	}
363
364
	static function init_sync_cron_jobs() {
365
		/**
366
		 * Allows overriding of the default incremental sync cron schedule which defaults to once per minute.
367
		 *
368
		 * @since 4.3.2
369
		 *
370
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL
371
		 */
372
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL );
373
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
374
375
		/**
376
		 * Allows overriding of the full sync cron schedule which defaults to once per minute.
377
		 *
378
		 * @since 4.3.2
379
		 *
380
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL
381
		 */
382
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL );
383
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
384
	}
385
}
386
387
/**
388
 * If the site is using alternate cron, we need to init the listener and sender before cron
389
 * runs. So, we init at a priority of 9.
390
 * 
391
 * If the site is using a regular cron job, we init at a priority of 90 which gives plugins a chance
392
 * to add filters before we initialize.
393
 */
394
if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) {
395
	add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 9 );
396
} else {
397
	add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
398
}
399
400
// We need to define this here so that it's hooked before `updating_jetpack_version` is called
401
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'schedule_initial_sync' ), 10, 2 );
402