Completed
Push — add/personal-plan ( 90bdfb...ddbb79 )
by
unknown
160:30 queued 135:09
created

Jetpack_Sync_Actions::init()   C

Complexity

Conditions 10
Paths 5

Size

Total Lines 76
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 27
nc 5
nop 0
dl 0
loc 76
rs 5.7198
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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