Completed
Push — add/shorter-sync-request-timeo... ( 00cecc )
by
unknown
119:08 queued 110:56
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
		) ) {
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
		$query_args['timeout'] = Jetpack_Sync_Settings::is_doing_cron() ? 30 : 15;
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' => $query_args['timeout'],
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
		do {
219
			$next_sync_time = self::$sender->get_next_sync_time( 'sync' );
220
221
			if ( $next_sync_time ) {
222
				$delay = $next_sync_time - time() + 1;
223
				if ( $delay > 15 ) {
224
					break;
225
				} elseif ( $delay > 0 ) {
226
					sleep( $delay );
227
				}
228
			}
229
230
			$result = self::$sender->do_sync();
231
		} while ( $result );
232
	}
233
234 View Code Duplication
	static function do_cron_full_sync() {
235
		if ( ! self::sync_allowed() ) {
236
			return;
237
		}
238
239
		self::initialize_sender();
240
241
		do {
242
			$next_sync_time = self::$sender->get_next_sync_time( 'full_sync' );
243
244
			if ( $next_sync_time ) {
245
				$delay = $next_sync_time - time() + 1;
246
				if ( $delay > 15 ) {
247
					break;
248
				} elseif ( $delay > 0 ) {
249
					sleep( $delay );
250
				}
251
			}
252
253
			$result = self::$sender->do_full_sync();
254
		} while ( $result );
255
	}
256
257
	static function initialize_listener() {
258
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
259
		self::$listener = Jetpack_Sync_Listener::get_instance();
260
	}
261
262
	static function initialize_sender() {
263
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
264
		self::$sender = Jetpack_Sync_Sender::get_instance();
265
266
		// bind the sending process
267
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 4 );
268
	}
269
270
	static function sanitize_filtered_sync_cron_schedule( $schedule ) {
271
		$schedule = sanitize_key( $schedule );
272
		$schedules = wp_get_schedules();
273
274
		// Make sure that the schedule has actually been registered using the `cron_intervals` filter.
275
		if ( isset( $schedules[ $schedule ] ) ) {
276
			return $schedule;
277
		}
278
279
		return self::DEFAULT_SYNC_CRON_INTERVAL;
280
	}
281
282
	static function maybe_schedule_sync_cron( $schedule, $hook ) {
283
		if ( ! $hook ) {
284
			return;
285
		}
286
		$schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
287
288
		if ( ! wp_next_scheduled( $hook ) ) {
289
			// Schedule a job to send pending queue items once a minute
290
			wp_schedule_event( time(), $schedule, $hook );
291
		} else if ( $schedule != wp_get_schedule( $hook ) ) {
292
			// If the schedule has changed, update the schedule
293
			wp_clear_scheduled_hook( $hook );
294
			wp_schedule_event( time(), $schedule, $hook );
295
		}
296
	}
297
298
	static function init_sync_cron_jobs() {
299
		// Add a custom "every minute" cron schedule
300
		add_filter( 'cron_schedules', array( __CLASS__, 'minute_cron_schedule' ) );
301
302
		// cron hooks
303
		add_action( 'jetpack_sync_full', array( __CLASS__, 'do_full_sync' ), 10, 1 );
304
305
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
306
		add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
307
308
		/**
309
		 * Allows overriding of the default incremental sync cron schedule which defaults to once per minute.
310
		 *
311
		 * @since 4.3.2
312
		 *
313
		 * @param string self::DEFAULT_SYNC_CRON_INTERVAL
314
		 */
315
		$incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL );
316
		self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
317
318
		/**
319
		 * Allows overriding of the full 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
		$full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL );
326
		self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
327
	}
328
}
329
330
/**
331
 * If the site is using alternate cron, we need to init the listener and sender before cron
332
 * runs. So, we init at a priority of 9.
333
 * 
334
 * If the site is using a regular cron job, we init at a priority of 90 which gives plugins a chance
335
 * to add filters before we initialize.
336
 */
337
if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) {
338
	add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 9 );
339
} else {
340
	add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
341
}
342
343
// We need to define this here so that it's hooked before `updating_jetpack_version` is called
344
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'do_initial_sync' ), 10, 2 );
345