Completed
Push — update/jetpack-sync-cron-defau... ( eda2c7 )
by
unknown
65:19 queued 57:04
created

Jetpack_Sync_Actions::do_full_sync()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
rs 9.4285
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 = '5min';
13
14
	static function init() {
15
16
		// everything below this point should only happen if we're a valid sync site
17
		if ( ! self::sync_allowed() ) {
18
			return;
19
		}
20
21
		if ( self::sync_via_cron_allowed() ) {
22
			self::init_sync_cron_jobs();
23
		}
24
25
		// On jetpack authorization, schedule a full sync
26
		add_action( 'jetpack_client_authorized', array( __CLASS__, 'do_full_sync' ), 10, 0 );
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
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-users.php';
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
		/**
54
		 * Fires on every request before default loading sync sender code.
55
		 * Return false to not load sync sender code that serializes pending
56
		 * data and sends it to WPCOM for processing.
57
		 *
58
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
59
		 * by users who can manage_options.
60
		 *
61
		 * @since 4.2.0
62
		 *
63
		 * @param bool should we load sync sender code for this request
64
		 */
65
		if ( apply_filters( 'jetpack_sync_sender_should_load',
66
			(
67
				( isset( $_SERVER["REQUEST_METHOD"] ) && 'POST' === $_SERVER['REQUEST_METHOD'] )
68
				||
69
				current_user_can( 'manage_options' )
70
				||
71
				is_admin()
72
				||
73
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
74
			)
75
		) ) {
76
			self::initialize_sender();
77
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
78
			add_action( 'shutdown', array( self::$sender, 'do_full_sync' ) );
79
		}
80
81
	}
82
83
	static function sync_allowed() {
84
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
85
		return ( ! Jetpack_Sync_Settings::get_setting( 'disable' ) && Jetpack::is_active() && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
86
			   || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
87
	}
88
89
	static function sync_via_cron_allowed() {
90
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
91
		return ( Jetpack_Sync_Settings::get_setting( 'sync_via_cron' ) );
92
	}
93
94
	static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
95
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
96
		if ( in_array( $post->post_type, Jetpack_Sync_Settings::get_setting( 'post_types_blacklist' ) ) ) {
97
			return false;
98
		}
99
100
		return $should_publicize;
101
	}
102
103
	static function set_is_importing_true() {
104
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
105
		Jetpack_Sync_Settings::set_importing( true );
106
	}
107
108
	static function send_data( $data, $codec_name, $sent_timestamp, $queue_id ) {
109
		Jetpack::load_xml_rpc_client();
110
111
		$query_args = array(
112
			'sync'      => '1',             // add an extra parameter to the URL so we can tell it's a sync action
113
			'codec'     => $codec_name,     // send the name of the codec used to encode the data
114
			'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
115
			'queue'     => $queue_id,       // sync or full_sync
116
			'home'      => get_home_url(),  // Send home url option to check for Identity Crisis server-side
117
			'siteurl'   => get_site_url(),  // Send siteurl option to check for Identity Crisis server-side
118
		);
119
120
		// Has the site opted in to IDC mitigation?
121
		if ( Jetpack::sync_idc_optin() ) {
122
			$query_args['idc'] = true;
123
		}
124
125
		if ( Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
126
			$query_args['migrate_for_idc'] = true;
127
		}
128
129
		$url = add_query_arg( $query_args, Jetpack::xmlrpc_api_url() );
130
131
		$rpc = new Jetpack_IXR_Client( array(
132
			'url'     => $url,
133
			'user_id' => JETPACK_MASTER_USER,
134
			'timeout' => 30,
135
		) );
136
137
		$result = $rpc->query( 'jetpack.syncActions', $data );
138
139
		if ( ! $result ) {
140
			return $rpc->get_jetpack_error();
141
		}
142
143
		$response = $rpc->getResponse();
144
145
		// Check if WordPress.com IDC mitigation blocked the sync request
146
		if ( is_array( $response ) && isset( $response['error_code'] ) ) {
147
			$error_code = $response['error_code'];
148
			$allowed_idc_error_codes = array(
149
				'jetpack_url_mismatch',
150
				'jetpack_home_url_mismatch',
151
				'jetpack_site_url_mismatch'
152
			);
153
154
			if ( in_array( $error_code, $allowed_idc_error_codes ) ) {
155
				Jetpack_Options::update_option(
156
					'sync_error_idc',
157
					Jetpack::get_sync_error_idc_option( $response )
158
				);
159
			}
160
161
			return new WP_Error(
162
				'sync_error_idc',
163
				esc_html__( 'Sync has been blocked from WordPress.com because it would cause an identity crisis', 'jetpack' )
164
			);
165
		}
166
167
		return $response;
168
	}
169
170
	static function do_initial_sync( $new_version = null, $old_version = null ) {
171
		$initial_sync_config = array(
172
			'options' => true,
173
			'network_options' => true,
174
			'functions' => true,
175
			'constants' => true,
176
		);
177
178
		if ( $old_version && ( version_compare( $old_version, '4.2', '<' ) ) ) {
179
			$initial_sync_config['users'] = 'initial';
180
		}
181
182
		self::do_full_sync( $initial_sync_config );
183
	}
184
185
	static function do_full_sync( $modules = null ) {
186
		if ( ! self::sync_allowed() ) {
187
			return false;
188
		}
189
190
		self::initialize_listener();
191
		Jetpack_Sync_Modules::get_module( 'full-sync' )->start( $modules );
192
193
		return true;
194
	}
195
196 View Code Duplication
	static function jetpack_cron_schedule( $schedules ) {
197
		if( ! isset( $schedules['5min'] ) ) {
198
			$schedules['5min'] = array(
199
				'interval' => 5 * 60,
200
				'display' => esc_html__( 'Every 5 minutes', 'jetpack' )
201
			);
202
		}
203
		return $schedules;
204
	}
205
206
	// try to send actions until we run out of things to send,
207
	// or have to wait more than 15s before sending again,
208
	// or we hit a lock or some other sending issue
209 View Code Duplication
	static function do_cron_sync() {
210
		if ( ! self::sync_allowed() ) {
211
			return;
212
		}
213
214
		self::initialize_sender();
215
216
		do {
217
			$next_sync_time = self::$sender->get_next_sync_time( 'sync' );
218
219
			if ( $next_sync_time ) {
220
				$delay = $next_sync_time - time() + 1;
221
				if ( $delay > 15 ) {
222
					break;
223
				} elseif ( $delay > 0 ) {
224
					sleep( $delay );
225
				}
226
			}
227
228
			$result = self::$sender->do_sync();
229
		} while ( $result );
230
	}
231
232 View Code Duplication
	static function do_cron_full_sync() {
233
		if ( ! self::sync_allowed() ) {
234
			return;
235
		}
236
237
		self::initialize_sender();
238
239
		do {
240
			$next_sync_time = self::$sender->get_next_sync_time( 'full_sync' );
241
242
			if ( $next_sync_time ) {
243
				$delay = $next_sync_time - time() + 1;
244
				if ( $delay > 15 ) {
245
					break;
246
				} elseif ( $delay > 0 ) {
247
					sleep( $delay );
248
				}
249
			}
250
251
			$result = self::$sender->do_full_sync();
252
		} while ( $result );
253
	}
254
255
	static function initialize_listener() {
256
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
257
		self::$listener = Jetpack_Sync_Listener::get_instance();
258
	}
259
260
	static function initialize_sender() {
261
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
262
		self::$sender = Jetpack_Sync_Sender::get_instance();
263
264
		// bind the sending process
265
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 4 );
266
	}
267
268
	static function sanitize_filtered_sync_cron_schedule( $schedule ) {
269
		$schedule = sanitize_key( $schedule );
270
		$schedules = wp_get_schedules();
271
272
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
273
		if ( isset( $schedules[ $schedule ] ) ) {
274
			return $schedule;
275
		}
276
277
		return self::DEFAULT_SYNC_CRON_INTERVAL;
278
	}
279
280
	static function maybe_schedule_sync_cron( $schedule, $hook ) {
281
		if ( ! $hook ) {
282
			return;
283
		}
284
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
285
286
		if ( ! wp_next_scheduled( $hook ) ) {
287
			// Schedule a job to send pending queue items once a minute
288
			wp_schedule_event( time(), $schedule, $hook );
289
		} else if ( $schedule != wp_get_schedule( $hook ) ) {
290
			// If the schedule has changed, update the schedule
291
			wp_clear_scheduled_hook( $hook );
292
			wp_schedule_event( time(), $schedule, $hook );
293
		}
294
	}
295
296
	static function init_sync_cron_jobs() {
297
		// Add a custom "every minute" cron schedule
298
		add_filter( 'cron_schedules', array( __CLASS__, 'jetpack_cron_schedule' ) );
299
300
		// cron hooks
301
		add_action( 'jetpack_sync_full', array( __CLASS__, 'do_full_sync' ), 10, 1 );
302
303
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
304
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
305
306
		/**
307
		 * Allows overriding of the default incremental sync cron schedule which defaults to once every 5 minutes.
308
		 *
309
		 * @since 4.3.2
310
		 *
311
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL
312
		 */
313
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL );
314
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
315
316
		/**
317
		 * Allows overriding of the full sync cron schedule which defaults to once every 5 minutes.
318
		 *
319
		 * @since 4.3.2
320
		 *
321
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL
322
		 */
323
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL );
324
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
325
	}
326
}
327
328
/**
329
 * If the site is using alternate cron, we need to init the listener and sender before cron
330
 * runs. So, we init at a priority of 9.
331
 * 
332
 * If the site is using a regular cron job, we init at a priority of 90 which gives plugins a chance
333
 * to add filters before we initialize.
334
 */
335
if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) {
336
	add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 9 );
337
} else {
338
	add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
339
}
340
341
// We need to define this here so that it's hooked before `updating_jetpack_version` is called
342
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'do_initial_sync' ), 10, 2 );
343