Completed
Push — fix/skip-w3-total-cache ( 7a8e79 )
by
unknown
346:59 queued 338:21
created

Jetpack_Sync_Actions::init()   C

Complexity

Conditions 10
Paths 13

Size

Total Lines 71
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 25
nc 13
nop 0
dl 0
loc 71
rs 5.9513
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_NAME = 'jetpack_sync_interval';
13
	const DEFAULT_SYNC_CRON_INTERVAL_VALUE = 300; // 5 * MINUTE_IN_SECONDS;
14
15
	static function init() {
16
17
		// everything below this point should only happen if we're a valid sync site
18
		if ( ! self::sync_allowed() ) {
19
			return;
20
		}
21
22
		if ( self::sync_via_cron_allowed() ) {
23
			self::init_sync_cron_jobs();
24
		} else if ( wp_next_scheduled( 'jetpack_sync_cron' ) ) {
25
			wp_clear_scheduled_hook( 'jetpack_sync_cron' );
26
			wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
27
		}
28
29
		// On jetpack authorization, schedule a full sync
30
		add_action( 'jetpack_client_authorized', array( __CLASS__, 'do_full_sync' ), 10, 0 );
31
32
		// When importing via cron, do not sync
33
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
34
35
		// Sync connected user role changes to .com
36
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-users.php';
37
38
		// publicize filter to prevent publicizing blacklisted post types
39
		add_filter( 'publicize_should_publicize_published_post', array( __CLASS__, 'prevent_publicize_blacklisted_posts' ), 10, 2 );
40
41
		// tell w3 total cache not to cache queue queries
42
		add_filter( 'w3tc_config_default_values', array( __CLASS__, 'bypass_w3_total_cache' ) );
43
44
		/**
45
		 * Fires on every request before default loading sync listener code.
46
		 * Return false to not load sync listener code that monitors common
47
		 * WP actions to be serialized.
48
		 *
49
		 * By default this returns true for cron jobs, non-GET-requests, or requests where the
50
		 * user is logged-in.
51
		 *
52
		 * @since 4.2.0
53
		 *
54
		 * @param bool should we load sync listener code for this request
55
		 */
56
		if ( apply_filters( 'jetpack_sync_listener_should_load', true ) ) {
57
			self::initialize_listener();
58
		}
59
60
		/**
61
		 * Fires on every request before default loading sync sender code.
62
		 * Return false to not load sync sender code that serializes pending
63
		 * data and sends it to WPCOM for processing.
64
		 *
65
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
66
		 * by users who can manage_options.
67
		 *
68
		 * @since 4.2.0
69
		 *
70
		 * @param bool should we load sync sender code for this request
71
		 */
72
		if ( apply_filters( 'jetpack_sync_sender_should_load',
73
			(
74
				( isset( $_SERVER["REQUEST_METHOD"] ) && 'POST' === $_SERVER['REQUEST_METHOD'] )
75
				||
76
				current_user_can( 'manage_options' )
77
				||
78
				is_admin()
79
				||
80
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
81
			)
82
		) ) {
83
			self::initialize_sender();
84
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
85
			add_action( 'shutdown', array( self::$sender, 'do_full_sync' ) );
86
		}
87
88
	}
89
90
	static function sync_allowed() {
91
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
92
		return ( ! Jetpack_Sync_Settings::get_setting( 'disable' ) && Jetpack::is_active() && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
93
			   || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
94
	}
95
96
	static function sync_via_cron_allowed() {
97
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
98
		return ( Jetpack_Sync_Settings::get_setting( 'sync_via_cron' ) );
99
	}
100
101
	static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
102
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
103
		if ( in_array( $post->post_type, Jetpack_Sync_Settings::get_setting( 'post_types_blacklist' ) ) ) {
104
			return false;
105
		}
106
107
		return $should_publicize;
108
	}
109
110
	static function bypass_w3_total_cache( $default_values ) {
111
		$default_values['dbcache.reject.words']['default'][] = '\bjpsq_\w'
112
		return $default_values;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

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