Completed
Push — update/sync-scheduled-posts ( 47f0f0 )
by
unknown
123:17 queued 112:16
created

Jetpack_Sync_Actions   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 278
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 278
rs 6.5957
wmc 56
lcom 2
cbo 6

14 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize_listener() 0 4 1
D init() 0 90 16
B sync_allowed() 0 4 5
A prevent_publicize_blacklisted_posts() 0 7 2
A set_is_importing_true() 0 3 1
B send_data() 0 24 2
B schedule_initial_sync() 0 28 4
B schedule_full_sync() 0 21 5
A unschedule_all_full_syncs() 0 9 4
A is_scheduled_full_sync() 0 14 4
A do_full_sync() 0 9 2
A minute_cron_schedule() 0 9 2
C do_cron_sync() 0 27 7
A initialize_sender() 0 7 1

How to fix   Complexity   

Complex Class

Complex classes like Jetpack_Sync_Actions often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Sync_Actions, and based on these observations, apply Extract Interface, too.

1
<?php
2
require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
3
4
/**
5
 * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
6
 * when to send, when to perform a full sync, etc.
7
 *
8
 * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
9
 */
10
class Jetpack_Sync_Actions {
11
	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...
12
	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...
13
	const INITIAL_SYNC_MULTISITE_INTERVAL = 10;
14
15
	static function init() {
16
17
		// Add a custom "every minute" cron schedule
18
		add_filter( 'cron_schedules', array( __CLASS__, 'minute_cron_schedule' ) );
19
20
		// On jetpack authorization, schedule a full sync
21
		add_action( 'jetpack_client_authorized', array( __CLASS__, 'schedule_full_sync' ), 10, 0 );
22
23
		// When imports are finished, schedule a full sync
24
		add_action( 'import_end', array( __CLASS__, 'schedule_full_sync' ) );
25
26
		// When importing via cron, do not sync
27
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
28
29
		// Sync connected user role changes to .com
30
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-users.php';
31
32
		// everything below this point should only happen if we're a valid sync site
33
		if ( ! self::sync_allowed() ) {
34
			return;
35
		}
36
37
		// publicize filter to prevent publicizing blacklisted post types
38
		add_filter( 'publicize_should_publicize_published_post', array( __CLASS__, 'prevent_publicize_blacklisted_posts' ), 10, 2 );
39
40
		// cron hooks
41
		add_action( 'jetpack_sync_full', array( __CLASS__, 'do_full_sync' ), 10, 1 );
42
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
43
44
		if ( ! wp_next_scheduled( 'jetpack_sync_cron' ) ) {
45
			// Schedule a job to send pending queue items once a minute
46
			wp_schedule_event( time(), '1min', 'jetpack_sync_cron' );
47
		}
48
49
		/**
50
		 * Fires on every request before default loading sync listener code.
51
		 * Return false to not load sync listener code that monitors common
52
		 * WP actions to be serialized.
53
		 *
54
		 * By default this returns true for cron jobs, non-GET-requests, or requests where the
55
		 * user is logged-in.
56
		 *
57
		 * @since 4.2.0
58
		 *
59
		 * @param bool should we load sync listener code for this request
60
		 */
61
		if ( apply_filters( 'jetpack_sync_listener_should_load',
62
			(
63
				( isset( $_SERVER["REQUEST_METHOD"] ) && 'GET' !== $_SERVER['REQUEST_METHOD'] )
64
				||
65
				is_user_logged_in()
66
				||
67
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
68
				||
69
				defined( 'DOING_CRON' ) && DOING_CRON
70
			)
71
		) ) {
72
			self::initialize_listener();
73
		}
74
75
		/**
76
		 * Fires on every request before default loading sync sender code.
77
		 * Return false to not load sync sender code that serializes pending
78
		 * data and sends it to WPCOM for processing.
79
		 *
80
		 * By default this returns true for cron jobs, POST requests, admin requests, or requests
81
		 * by users who can manage_options.
82
		 *
83
		 * @since 4.2.0
84
		 *
85
		 * @param bool should we load sync sender code for this request
86
		 */
87
		if ( apply_filters( 'jetpack_sync_sender_should_load',
88
			(
89
				( isset( $_SERVER["REQUEST_METHOD"] ) && 'POST' === $_SERVER['REQUEST_METHOD'] )
90
				||
91
				current_user_can( 'manage_options' )
92
				||
93
				is_admin()
94
				||
95
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
96
				||
97
				defined( 'DOING_CRON' ) && DOING_CRON
98
			)
99
		) ) {
100
			self::initialize_sender();
101
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
102
		}
103
104
	}
105
106
	static function sync_allowed() {
107
		return ( ! Jetpack_Sync_Settings::get_setting( 'disable' ) && Jetpack::is_active() && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
108
			   || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
109
	}
110
111
	static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
112
		if ( in_array( $post->post_type, Jetpack_Sync_Settings::get_setting( 'post_types_blacklist' ) ) ) {
113
			return false;
114
		}
115
116
		return $should_publicize;
117
	}
118
119
	static function set_is_importing_true() {
120
		Jetpack_Sync_Settings::set_importing( true );
121
	}
122
123
	static function send_data( $data, $codec_name, $sent_timestamp, $queue_id ) {
124
		Jetpack::load_xml_rpc_client();
125
126
		$url = add_query_arg( array(
127
			'sync'      => '1', // add an extra parameter to the URL so we can tell it's a sync action
128
			'codec'     => $codec_name, // send the name of the codec used to encode the data
129
			'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
130
			'queue'     => $queue_id, // sync or full_sync
131
		), 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
		return $rpc->getResponse();
146
	}
147
148
	static function schedule_initial_sync( $new_version = null, $old_version = null ) {
149
		$initial_sync_config = array(
150
			'options' => true,
151
			'network_options' => true,
152
			'functions' => true,
153
			'constants' => true,
154
		);
155
156
		if ( $old_version && ( version_compare( $old_version, '4.2', '<' ) ) ) {
157
			$initial_sync_config['users'] = 'initial';
158
		}
159
160
		// we need this function call here because we have to run this function
161
		// reeeeally early in init, before WP_CRON_LOCK_TIMEOUT is defined.
162
		wp_functionality_constants();
163
164
		if ( is_multisite() ) {
165
			// stagger initial syncs for multisite blogs so they don't all pile on top of each other
166
			$time_offset = ( rand() / getrandmax() ) * self::INITIAL_SYNC_MULTISITE_INTERVAL * get_blog_count();
167
		} else {
168
			$time_offset = 1;
169
		}
170
171
		self::schedule_full_sync(
172
			$initial_sync_config,
173
			$time_offset
174
		);
175
	}
176
177
	static function schedule_full_sync( $modules = null, $time_offset = 1 ) {
178
		if ( ! self::sync_allowed() ) {
179
			return false;
180
		}
181
182
		if ( self::is_scheduled_full_sync() ) {
183
			self::unschedule_all_full_syncs();
184
		}
185
186
		if ( $modules ) {
187
			wp_schedule_single_event( time() + $time_offset, 'jetpack_sync_full', array( $modules ) );
188
		} else {
189
			wp_schedule_single_event( time() + $time_offset, 'jetpack_sync_full' );
190
		}
191
192
		if ( $time_offset === 1 ) {
193
			spawn_cron();
194
		}
195
196
		return true;
197
	}
198
199
	static function unschedule_all_full_syncs() {
200
		foreach ( _get_cron_array() as $timestamp => $cron ) {
201
			if ( ! empty( $cron['jetpack_sync_full'] ) ) {
202
				foreach( $cron['jetpack_sync_full'] as $key => $config ) {
203
					wp_unschedule_event( $timestamp, 'jetpack_sync_full', $config['args'] );
204
				}
205
			}
206
		}
207
	}
208
209
	static function is_scheduled_full_sync( $modules = null ) {
210
		if ( is_null( $modules ) ) {
211
			$crons = _get_cron_array();
212
213
			foreach ( $crons as $timestamp => $cron ) {
214
				if ( ! empty( $cron['jetpack_sync_full'] ) ) {
215
					return true;
216
				}
217
			}
218
			return false;
219
		}
220
221
		return !! wp_next_scheduled( 'jetpack_sync_full', array( $modules ) );
222
	}
223
224
	static function do_full_sync( $modules = null ) {
225
		if ( ! self::sync_allowed() ) {
226
			return;
227
		}
228
229
		self::initialize_listener();
230
		Jetpack_Sync_Modules::get_module( 'full-sync' )->start( $modules );
231
		self::do_cron_sync(); // immediately run a cron sync, which sends pending data
232
	}
233
234
	static function minute_cron_schedule( $schedules ) {
235
		if( ! isset( $schedules["1min"] ) ) {
236
			$schedules["1min"] = array(
237
				'interval' => 60,
238
				'display' => __( 'Every minute' )
239
			);
240
		}
241
		return $schedules;
242
	}
243
244
	// try to send actions until we run out of things to send,
245
	// or have to wait more than 15s before sending again,
246
	// or we hit a lock or some other sending issue
247
	static function do_cron_sync() {
248
		if ( ! self::sync_allowed() ) {
249
			return;
250
		}
251
252
		self::initialize_sender();
253
254
		// remove shutdown hook - no need to sync twice
255
		if ( has_action( 'shutdown', array( self::$sender, 'do_sync' ) ) ) {
256
			remove_action( 'shutdown', array( self::$sender, 'do_sync' ) );
257
		}
258
259
		do {
260
			$next_sync_time = self::$sender->get_next_sync_time();
261
262
			if ( $next_sync_time ) {
263
				$delay = $next_sync_time - time() + 1;
264
				if ( $delay > 15 ) {
265
					break;
266
				} elseif ( $delay > 0 ) {
267
					sleep( $delay );
268
				}
269
			}
270
271
			$result = self::$sender->do_sync();
272
		} while ( $result );
273
	}
274
275
	static function initialize_listener() {
276
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
277
		self::$listener = Jetpack_Sync_Listener::get_instance();
278
	}
279
280
	static function initialize_sender() {
281
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
282
		self::$sender = Jetpack_Sync_Sender::get_instance();
283
284
		// bind the sending process
285
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 4 );
286
	}
287
}
288
289
// Allow other plugins to add filters before we initialize the actions.
290
// Load the listeners if before modules get loaded so that we can capture version changes etc.
291
add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
292
293
// We need to define this here so that it's hooked before `updating_jetpack_version` is called
294
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'schedule_initial_sync' ), 10, 2 );
295