Completed
Push — enhance/plugin-list-connection... ( fe5281...e17089 )
by
unknown
504:18 queued 496:40
created

Jetpack_Sync_Actions::init_sync_cron_jobs()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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