Completed
Push — add/pathinfo-sitemap ( eb9d33...02fba8 )
by Jeremy
14:23 queued 04:10
created

Jetpack_Sync_Client   D

Complexity

Total Complexity 131

Size/Duplication

Total Lines 850
Duplicated Lines 7.18 %

Coupling/Cohesion

Components 3
Dependencies 7

Importance

Changes 12
Bugs 0 Features 5
Metric Value
c 12
b 0
f 5
dl 61
loc 850
rs 4
wmc 131
lcom 3
cbo 7

60 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 7 2
A __construct() 0 4 1
A reset_data() 0 3 1
A set_options_whitelist() 0 3 1
A get_options_whitelist() 0 3 1
A set_constants_whitelist() 0 3 1
A get_callable_whitelist() 0 3 1
A set_callable_whitelist() 0 3 1
A set_network_options_whitelist() 0 3 1
A set_dequeue_max_bytes() 0 3 1
A set_upload_max_bytes() 0 3 1
A set_upload_max_rows() 0 3 1
A set_sync_wait_time() 0 3 1
A get_sync_wait_time() 0 3 1
A get_last_sync_time() 0 3 1
A set_last_sync_time() 0 3 1
A set_taxonomy_whitelist() 0 3 1
A is_whitelisted_option() 0 3 1
A is_whitelisted_network_option() 0 3 2
A set_codec() 0 3 1
A set_full_sync_client() 0 12 2
A get_full_sync_client() 0 3 1
C action_handler() 0 50 13
A send_theme_info() 0 23 3
A send_wp_version() 0 14 3
A save_term_handler() 0 16 2
A send_attachment_info() 0 13 1
B save_user_handler() 0 26 4
A save_user_role_handler() 0 12 1
A save_user_cap_handler() 0 13 2
A sanitize_user() 0 5 1
D do_sync() 0 112 19
A buffer_includes_action() 0 9 3
A expand_wp_insert_post() 0 3 1
A filter_post_content_and_add_links() 0 18 2
A expand_wp_comment_status_change() 0 3 1
A expand_wp_insert_comment() 0 3 1
A filter_comment_and_add_hc_meta() 0 14 2
A schedule_sync() 0 3 1
A force_sync_options() 0 10 1
A force_sync_network_options() 0 10 1
A get_all_constants() 0 6 1
A get_constant() 0 7 2
A force_sync_callables() 0 8 2
A get_all_callables() 0 6 1
A get_callable() 0 3 1
A get_all_options() 0 8 2
A get_all_network_options() 0 8 2
A get_check_sum() 0 3 1
B jetpack_sync_core_icon() 0 16 5
A get_sync_queue() 0 3 1
A reset_sync_queue() 0 3 1
A get_settings() 0 8 2
A update_settings() 0 6 2
A update_options_whitelist() 0 4 1
B init() 0 132 6
A force_sync_constants() 0 8 2
B maybe_sync_constants() 31 31 5
B maybe_sync_callables() 30 30 5
B set_defaults() 0 26 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_Sync_Client 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_Client, and based on these observations, apply Extract Interface, too.

1
<?php
2
require_once dirname( __FILE__ ) . '/class.jetpack-sync-deflate-codec.php';
3
require_once dirname( __FILE__ ) . '/class.jetpack-sync-queue.php';
4
require_once dirname( __FILE__ ) . '/class.jetpack-sync-functions.php';
5
require_once dirname( __FILE__ ) . '/class.jetpack-sync-full.php';
6
require_once dirname( __FILE__ ) . '/class.jetpack-sync-defaults.php';
7
8
class Jetpack_Sync_Client {
9
10
	const CONSTANTS_CHECKSUM_OPTION_NAME = 'jetpack_constants_sync_checksum';
11
	const CALLABLES_CHECKSUM_OPTION_NAME = 'jetpack_callables_sync_checksum';
12
	const SYNC_THROTTLE_OPTION_NAME = 'jetpack_sync_min_wait';
13
	const LAST_SYNC_TIME_OPTION_NAME = 'jetpack_last_sync_time';
14
	const CALLABLES_AWAIT_TRANSIENT_NAME = 'jetpack_sync_callables_await';
15
	const CONSTANTS_AWAIT_TRANSIENT_NAME = 'jetpack_sync_constants_await';
16
	const SETTINGS_OPTION_PREFIX = 'jetpack_sync_settings_';
17
	
18
	private static $valid_settings = array( 'dequeue_max_bytes' => true, 'upload_max_bytes' => true, 'upload_max_rows' => true, 'sync_wait_time' => true );
19
20
	private $dequeue_max_bytes;
21
	private $upload_max_bytes;
22
	private $upload_max_rows;
23
	private $sync_queue;
24
	private $full_sync_client;
25
	private $codec;
26
	private $options_whitelist;
27
	private $constants_whitelist;
28
	private $meta_types = array( 'post', 'comment' );
29
	private $callable_whitelist;
30
	private $network_options_whitelist;
31
	private $taxonomy_whitelist;
32
	private $is_multisite;
33
34
	// singleton functions
35
	private static $instance;
36
37
	public static function getInstance() {
38
		if ( null === self::$instance ) {
39
			self::$instance = new self();
40
		}
41
42
		return self::$instance;
43
	}
44
45
	// this is necessary because you can't use "new" when you declare instance properties >:(
46
	protected function __construct() {
47
		$this->set_defaults();
48
		$this->init();
49
	}
50
51
	private function init() {
52
53
		$handler = array( $this, 'action_handler' );
54
55
		/**
56
		 * Most of the following hooks are sent to the same $handler
57
		 * for immediate serialization and queuing be sent to the server.
58
		 * The only exceptions are actions which need additional processing.
59
		 */
60
61
		// constants
62
		add_action( 'jetpack_sync_constant', $handler, 10, 2 );
63
64
		// callables
65
		add_action( 'jetpack_sync_callable', $handler, 10, 2 );
66
67
		// posts
68
		add_action( 'wp_insert_post', $handler, 10, 3 );
69
		add_action( 'deleted_post', $handler, 10 );
70
		add_filter( 'jetpack_sync_before_send_wp_insert_post', array( $this, 'expand_wp_insert_post' ) );
71
72
		add_action( 'jetpack_publicize_post', $handler );
73
74
		// attachments
75
76
		add_action( 'edit_attachment', array( $this, 'send_attachment_info' ) );
77
		// Once we don't have to support 4.3 we can start using add_action( 'attachment_updated', $handler, 10, 3 ); instead
78
		add_action( 'add_attachment', array( $this, 'send_attachment_info' ) );
79
		add_action( 'jetpack_sync_save_add_attachment', $handler, 10, 2 );
80
81
		// comments
82
		add_action( 'wp_insert_comment', $handler, 10, 2 );
83
		add_action( 'deleted_comment', $handler, 10 );
84
		add_action( 'trashed_comment', $handler, 10 );
85
		add_action( 'spammed_comment', $handler, 10 );
86
		add_filter( 'jetpack_sync_before_send_wp_insert_comment', array( $this, 'expand_wp_insert_comment' ) );
87
88
		// even though it's messy, we implement these hooks because
89
		// the edit_comment hook doesn't include the data
90
		// so this saves us a DB read for every comment event
91
		foreach ( array( '', 'trackback', 'pingback' ) as $comment_type ) {
92
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
93
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
94
				add_action( $comment_action_name, $handler, 10, 2 );
95
				add_filter( "jetpack_sync_before_send_{$comment_action_name}", array( $this, 'expand_wp_comment_status_change' ) );
96
			}
97
		}
98
99
		// options
100
		add_action( 'added_option', $handler, 10, 2 );
101
		add_action( 'updated_option', $handler, 10, 3 );
102
		add_action( 'deleted_option', $handler, 10, 1 );
103
104
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
105
		add_action( 'add_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
106
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
107
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
108
109
		// wordpress version
110
		add_action( 'upgrader_process_complete', array( $this, 'send_wp_version' ), 10, 2 );
111
		add_action( 'jetpack_sync_wp_version', $handler );
112
113
		// themes
114
		add_action( 'switch_theme', array( $this, 'send_theme_info' ) );
115
		add_action( 'jetpack_sync_current_theme_support', $handler, 10 ); // custom hook, see meta-hooks below
116
117
		// post-meta, and in the future - other meta?
118
		foreach ( $this->meta_types as $meta_type ) {
119
			add_action( "added_{$meta_type}_meta", $handler, 10, 4 );
120
			add_action( "updated_{$meta_type}_meta", $handler, 10, 4 );
121
			add_action( "deleted_{$meta_type}_meta", $handler, 10, 4 );
122
		}
123
124
		// terms
125
		add_action( 'created_term', array( $this, 'save_term_handler' ), 10, 3 );
126
		add_action( 'edited_term', array( $this, 'save_term_handler' ), 10, 3 );
127
		add_action( 'jetpack_sync_save_term', $handler, 10, 4 );
128
		add_action( 'delete_term', $handler, 10, 4 );
129
		add_action( 'set_object_terms', $handler, 10, 6 );
130
		add_action( 'deleted_term_relationships', $handler, 10, 2 );
131
132
		// users
133
		add_action( 'user_register', array( $this, 'save_user_handler' ) );
134
		add_action( 'profile_update', array( $this, 'save_user_handler' ), 10, 2 );
135
		add_action( 'jetpack_sync_save_user', $handler, 10, 2 );
136
		add_action( 'deleted_user', $handler, 10, 2 );
137
138
		// user roles
139
		add_action( 'add_user_role', array( $this, 'save_user_role_handler' ), 10, 2 );
140
		add_action( 'set_user_role', array( $this, 'save_user_role_handler' ), 10, 3 );
141
		add_action( 'remove_user_role', array( $this, 'save_user_role_handler' ), 10, 2 );
142
143
144
		// user capabilities
145
		add_action( 'added_user_meta', array( $this, 'save_user_cap_handler' ), 10, 4 );
146
		add_action( 'updated_user_meta', array( $this, 'save_user_cap_handler' ), 10, 4 );
147
		add_action( 'deleted_user_meta', array( $this, 'save_user_cap_handler' ), 10, 4 );
148
149
		// themes
150
		add_action( 'set_site_transient_update_plugins', $handler, 10, 1 );
151
		add_action( 'set_site_transient_update_themes', $handler, 10, 1 );
152
		add_action( 'set_site_transient_update_core', $handler, 10, 1 );
153
154
		// multi site network options
155
		if ( $this->is_multisite ) {
156
			add_action( 'add_site_option', $handler, 10, 2 );
157
			add_action( 'update_site_option', $handler, 10, 3 );
158
			add_action( 'delete_site_option', $handler, 10, 1 );
159
		}
160
161
		// synthetic actions for full sync
162
		add_action( 'jetpack_full_sync_start', $handler );
163
		add_action( 'jetpack_full_sync_end', $handler );
164
		add_action( 'jetpack_full_sync_options', $handler );
165
		add_action( 'jetpack_full_sync_posts', $handler ); // also sends post meta
166
		add_action( 'jetpack_full_sync_comments', $handler ); // also send comments meta
167
		add_action( 'jetpack_full_sync_users', $handler );
168
		add_action( 'jetpack_full_sync_terms', $handler, 10, 2 );
169
		if ( is_multisite() ) {
170
			add_action( 'jetpack_full_sync_network_options', $handler );
171
		}
172
173
174
		// Module Activation
175
		add_action( 'jetpack_activate_module', $handler );
176
		add_action( 'jetpack_deactivate_module', $handler );
177
178
		/**
179
		 * Sync all pending actions with server
180
		 */
181
		add_action( 'jetpack_sync_actions', array( $this, 'do_sync' ) );
182
	}
183
184
	// TODO: Refactor to use one set whitelist function, with one is_whitelisted.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
185
	function set_options_whitelist( $options ) {
186
		$this->options_whitelist = $options;
187
	}
188
189
	function get_options_whitelist() {
190
		return $this->options_whitelist;
191
	}
192
193
	function set_constants_whitelist( $constants ) {
194
		$this->constants_whitelist = $constants;
195
	}
196
197
	function get_callable_whitelist() {
198
		return $this->callable_whitelist;
199
	}
200
201
	function set_callable_whitelist( $callables ) {
202
		$this->callable_whitelist = $callables;
203
	}
204
205
	function set_network_options_whitelist( $options ) {
206
		$this->network_options_whitelist = $options;
207
	}
208
209
	function set_dequeue_max_bytes( $size ) {
210
		$this->dequeue_max_bytes = $size;
211
	}
212
213
	// in bytes
214
	function set_upload_max_bytes( $max_bytes ) {
215
		$this->upload_max_bytes = $max_bytes;
216
	}
217
218
	// in rows
219
	function set_upload_max_rows( $max_rows ) {
220
		$this->upload_max_rows = $max_rows;
221
	}
222
223
	// in seconds
224
	function set_sync_wait_time( $seconds ) {
225
		update_option( self::SYNC_THROTTLE_OPTION_NAME, $seconds, true );
226
	}
227
228
	function get_sync_wait_time() {
229
		return get_option( self::SYNC_THROTTLE_OPTION_NAME );
230
	}
231
232
	private function get_last_sync_time() {
233
		return (double) get_option( self::LAST_SYNC_TIME_OPTION_NAME );
234
	}
235
236
	private function set_last_sync_time() {
237
		return update_option( self::LAST_SYNC_TIME_OPTION_NAME, microtime( true ), true );
238
	}
239
240
	function set_taxonomy_whitelist( $taxonomies ) {
241
		$this->taxonomy_whitelist = $taxonomies;
242
	}
243
244
	function is_whitelisted_option( $option ) {
245
		return in_array( $option, $this->options_whitelist );
246
	}
247
248
	function is_whitelisted_network_option( $option ) {
249
		return $this->is_multisite && in_array( $option, $this->network_options_whitelist );
250
	}
251
252
	function set_codec( iJetpack_Sync_Codec $codec ) {
253
		$this->codec = $codec;
254
	}
255
256
	function set_full_sync_client( $full_sync_client ) {
257
		if ( $this->full_sync_client ) {
258
			remove_action( 'jetpack_sync_full', array( $this->full_sync_client, 'start' ) );
259
		}
260
261
		$this->full_sync_client = $full_sync_client;
262
263
		/**
264
		 * Sync all objects in the database with the server
265
		 */
266
		add_action( 'jetpack_sync_full', array( $this->full_sync_client, 'start' ) );
267
	}
268
269
	function get_full_sync_client() {
270
		return $this->full_sync_client;
271
	}
272
273
	function action_handler() {
274
		// TODO: it's really silly to have this function here - it should be
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
275
		// wherever we initialize the action listeners or we're just wasting cycles
276
		if ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) {
277
			return false;
278
		}
279
280
		$current_filter = current_filter();
281
		$args           = func_get_args();
282
283
		if ( $current_filter === 'wp_insert_post' && $args[1]->post_type === 'revision' ) {
284
			return;
285
		}
286
287
		if ( in_array( $current_filter, array( 'deleted_option', 'added_option', 'updated_option' ) )
288
		     &&
289
		     ! $this->is_whitelisted_option( $args[0] )
290
		) {
291
			return;
292
		}
293
294
		if ( in_array( $current_filter, array( 'delete_site_option', 'add_site_option', 'update_site_option' ) )
295
		     &&
296
		     ! $this->is_whitelisted_network_option( $args[0] )
297
		) {
298
			return;
299
		}
300
301
		// don't sync private meta
302
		if ( preg_match( '/^(added|updated|deleted)_.*_meta$/', $current_filter )
303
		     && $args[2][0] === '_'
304
		     && ! in_array( $args[2], Jetpack_Sync_Defaults::$default_whitelist_meta_keys )
0 ignored issues
show
Bug introduced by
The property default_whitelist_meta_keys cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
305
		) {
306
			return;
307
		}
308
309
		// if we add any items to the queue, we should 
310
		// try to ensure that our script can't be killed before
311
		// they are sent
312
		if ( function_exists( 'ignore_user_abort' ) ) {
313
			ignore_user_abort( true );
314
		}
315
316
		$this->sync_queue->add( array(
317
			$current_filter,
318
			$args,
319
			get_current_user_id(),
320
			microtime( true )
321
		) );
322
	}
323
324
	function send_theme_info() {
325
		global $_wp_theme_features;
326
327
		$theme_support = array();
328
329
		foreach ( Jetpack_Sync_Defaults::$default_theme_support_whitelist as $theme_feature ) {
0 ignored issues
show
Bug introduced by
The property default_theme_support_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
330
			$has_support = current_theme_supports( $theme_feature );
331
			if ( $has_support ) {
332
				$theme_support[ $theme_feature ] = $_wp_theme_features[ $theme_feature ];
333
			}
334
335
		}
336
337
		/**
338
		 * Fires when the client needs to sync theme support info
339
		 * Only sends theme support attributes whitelisted in Jetpack_Sync_Defaults::$default_theme_support_whitelist
340
		 *
341
		 * @since 4.1.0
342
		 *
343
		 * @param object the theme support hash
344
		 */
345
		do_action( 'jetpack_sync_current_theme_support', $theme_support );
346
	}
347
348
	function send_wp_version( $update, $meta_data ) {
349
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
350
			global $wp_version;
351
352
			/**
353
			 * Fires when the client needs to sync WordPress version
354
			 *
355
			 * @since 4.1.0
356
			 *
357
			 * @param string The WordPress version number
358
			 */
359
			do_action( 'jetpack_sync_wp_version', $wp_version );
360
		}
361
	}
362
363
	function save_term_handler( $term_id, $tt_id, $taxonomy ) {
364
		if ( class_exists( 'WP_Term' ) ) {
365
			$term_object = WP_Term::get_instance( $term_id, $taxonomy );
366
		} else {
367
			$term_object = get_term_by( 'id', $term_id, $taxonomy );
368
		}
369
370
		/**
371
		 * Fires when the client needs to sync a new term
372
		 *
373
		 * @since 4.1.0
374
		 *
375
		 * @param object the Term object
376
		 */
377
		do_action( 'jetpack_sync_save_term', $term_object );
378
	}
379
380
	function send_attachment_info( $attachment_id ) {
381
		$attachment = get_post( $attachment_id );
382
383
		/**
384
		 * Fires when the client needs to sync an attachment for a post
385
		 *
386
		 * @since 4.1.0
387
		 *
388
		 * @param int The attachment ID
389
		 * @param object The attachment
390
		 */
391
		do_action( 'jetpack_sync_save_add_attachment', $attachment_id, $attachment );
392
	}
393
394
	function save_user_handler( $user_id, $old_user_data = null ) {
395
		$user = $this->sanitize_user( get_user_by( 'id', $user_id ) );
396
397
		// Older versions of WP don't pass the old_user_data in ->data
398
		if ( isset( $old_user_data->data ) ) {
399
			$old_user = $old_user_data->data;
400
		} else {
401
			$old_user = $old_user_data;
402
		}
403
404
		if ( $old_user !== null ) {
405
			unset( $old_user->user_pass );
406
			if ( serialize( $old_user ) === serialize( $user->data ) ) {
407
				return;
408
			}
409
		}
410
411
		/**
412
		 * Fires when the client needs to sync an updated user
413
		 *
414
		 * @since 4.1.0
415
		 *
416
		 * @param object The WP_User object
417
		 */
418
		do_action( 'jetpack_sync_save_user', $user );
419
	}
420
421
	function save_user_role_handler( $user_id, $role, $old_roles = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $role is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $old_roles is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
422
		$user = $this->sanitize_user( get_user_by( 'id', $user_id ) );
423
424
		/**
425
		 * Fires when the client needs to sync an updated user
426
		 *
427
		 * @since 4.1.0
428
		 *
429
		 * @param object The WP_User object
430
		 */
431
		do_action( 'jetpack_sync_save_user', $user );
432
	}
433
434
	function save_user_cap_handler( $meta_id, $user_id, $meta_key, $capabilities ) {
0 ignored issues
show
Unused Code introduced by
The parameter $capabilities is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
435
		$user = $this->sanitize_user( get_user_by( 'id', $user_id ) );
436
		if ( $meta_key === $user->cap_key ) {
437
			/**
438
			 * Fires when the client needs to sync an updated user
439
			 *
440
			 * @since 4.1.0
441
			 *
442
			 * @param object The WP_User object
443
			 */
444
			do_action( 'jetpack_sync_save_user', $user );
445
		}
446
	}
447
448
	public function sanitize_user( $user ) {
449
		unset( $user->data->user_pass );
450
451
		return $user;
452
	}
453
454
455
	function do_sync() {
456
		// don't sync if importing
457
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
458
			$this->schedule_sync( "+1 minute" );
459
460
			return false;
461
		}
462
463
		// don't sync if we are throttled
464
		$sync_wait = $this->get_sync_wait_time();
465
		$last_sync = $this->get_last_sync_time();
466
467
		if ( $last_sync && $sync_wait && $last_sync + $sync_wait > microtime( true ) ) {
468
			return false;
469
		}
470
471
		$this->set_last_sync_time();
472
		$this->maybe_sync_constants();
473
		$this->maybe_sync_callables();
474
475
		if ( $this->sync_queue->size() === 0 ) {
476
			return false;
477
		}
478
479
		// now that we're sure we are about to sync, try to
480
		// ignore user abort so we can avoid getting into a
481
		// bad state
482
		if ( function_exists( 'ignore_user_abort' ) ) {
483
			ignore_user_abort( true );
484
		}
485
486
		$buffer = $this->sync_queue->checkout_with_memory_limit( $this->dequeue_max_bytes, $this->upload_max_rows );
487
488
		if ( ! $buffer ) {
489
			// buffer has no items
490
			return false;
491
		}
492
493
		if ( is_wp_error( $buffer ) ) {
494
			// another buffer is currently sending
495
			return false;
496
		}
497
498
		$upload_size   = 0;
499
		$items_to_send = array();
500
501
		// we estimate the total encoded size as we go by encoding each item individually
502
		// this is expensive, but the only way to really know :/
503
		foreach ( $buffer->get_items() as $key => $item ) {
504
505
			/**
506
			 * Modify the data within an action before it is serialized and sent to the server
507
			 * For example, during full sync this expands Post ID's into full Post objects,
508
			 * so that we don't have to serialize the whole object into the queue.
509
			 *
510
			 * @since 4.1.0
511
			 *
512
			 * @param array The action parameters
513
			 */
514
			$item[1] = apply_filters( "jetpack_sync_before_send_" . $item[0], $item[1] );
515
516
			$encoded_item = $this->codec->encode( $item );
517
			$upload_size += strlen( $encoded_item );
518
519
			if ( $upload_size > $this->upload_max_bytes && count( $items_to_send ) > 0 ) {
520
				break;
521
			}
522
523
			$items_to_send[ $key ] = $encoded_item;
524
		}
525
526
		/**
527
		 * Fires when data is ready to send to the server.
528
		 * Return false or WP_Error to abort the sync (e.g. if there's an error)
529
		 * The items will be automatically re-sent later
530
		 *
531
		 * @since 4.1
532
		 *
533
		 * @param array $data The action buffer
534
		 */
535
		$result = apply_filters( 'jetpack_sync_client_send_data', $items_to_send );
536
537
		if ( ! $result || is_wp_error( $result ) ) {
538
			// error_log("There was an error sending data:");
539
			// error_log(print_r($result, 1));
540
			$result = $this->sync_queue->checkin( $buffer );
541
542
			if ( is_wp_error( $result ) ) {
543
				error_log( "Error checking in buffer: " . $result->get_error_message() );
544
				$this->sync_queue->force_checkin();
545
			}
546
			// try again in 1 minute
547
			$this->schedule_sync( "+1 minute" );
548
		} else {
549
550
			// scan the sent data to see if a full sync started or finished
551
			if ( $this->buffer_includes_action( $buffer, 'jetpack_full_sync_start' ) ) {
552
				$this->full_sync_client->set_status_sending_started();
553
			}
554
555
			if ( $this->buffer_includes_action( $buffer, 'jetpack_full_sync_end' ) ) {
556
				$this->full_sync_client->set_status_sending_finished();
557
			}
558
559
			$this->sync_queue->close( $buffer, $result );
560
			// check if there are any more events in the buffer
561
			// if so, schedule a cron job to happen soon
562
			if ( $this->sync_queue->has_any_items() ) {
563
				$this->schedule_sync( "+1 minute" );
564
			}
565
		}
566
	}
567
568
	private function buffer_includes_action( $buffer, $action_name ) {
569
		foreach ( $buffer->get_items() as $item ) {
570
			if ( $item[0] === $action_name ) {
571
				return true;
572
			}
573
		}
574
575
		return false;
576
	}
577
578
	function expand_wp_insert_post( $args ) {
579
		return array( $args[0], $this->filter_post_content_and_add_links( $args[1] ), $args[2] );
580
	}
581
582
	// Expands wp_insert_post to include filtered content
583
	function filter_post_content_and_add_links( $post ) {
584
		if ( 0 < strlen( $post->post_password ) ) {
585
			$post->post_password = 'auto-' . wp_generate_password( 10, false );
586
		}
587
		/** This filter is already documented in core. wp-includes/post-template.php */
588
		$post->post_content_filtered   = apply_filters( 'the_content', $post->post_content );
589
		$post->permalink               = get_permalink( $post->ID );
590
		$post->shortlink               = wp_get_shortlink( $post->ID );
591
		
592
		// legacy fields until we fully sync users
593
		$extra = array();
594
		$extra['author_email']            = get_the_author_meta( 'email', $post->post_author );
595
		$extra['author_display_name']     = get_the_author_meta( 'display_name', $post->post_author );
596
		$extra['dont_email_post_to_subs'] = get_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', true );
597
		$post->extra = $extra;
598
599
		return $post;
600
	}
601
602
	function expand_wp_comment_status_change( $args ) {
603
		return array( $args[0], $this->filter_comment_and_add_hc_meta( $args[1] ) );
604
	}
605
606
	function expand_wp_insert_comment( $args ) {
607
		return array( $args[0], $this->filter_comment_and_add_hc_meta( $args[1] ) );
608
	}
609
610
	function filter_comment_and_add_hc_meta( $comment ) {
611
		// add meta-property with Highlander Comment meta, which we 
612
		// we need to process synchronously on .com
613
		$hc_post_as = get_comment_meta( $comment->comment_ID, 'hc_post_as', true );
614
		if ( 'wordpress' === $hc_post_as ) {
615
			$meta = array();
616
			$meta['hc_post_as']         = $hc_post_as;
617
			$meta['hc_wpcom_id_sig']    = get_comment_meta( $comment->comment_ID, 'hc_wpcom_id_sig', true );
618
			$meta['hc_foreign_user_id'] = get_comment_meta( $comment->comment_ID, 'hc_foreign_user_id', true );
619
			$comment->meta = $meta;	
620
		}
621
622
		return $comment;
623
	}
624
625
	private function schedule_sync( $when ) {
626
		wp_schedule_single_event( strtotime( $when ), 'jetpack_sync_actions' );
627
	}
628
629
	function force_sync_constants() {
630
		foreach ( $this->constants_whitelist as $name ) {
631
			delete_option( self::CONSTANTS_CHECKSUM_OPTION_NAME . "_$name" );
632
		}
633
634
		delete_transient( self::CONSTANTS_AWAIT_TRANSIENT_NAME );
635
		$this->maybe_sync_constants();
636
	}
637
638
	function force_sync_options() {
639
		/**
640
		 * Tells the client to sync all options to the server
641
		 *
642
		 * @since 4.1
643
		 *
644
		 * @param boolean Whether to expand options (should always be true)
645
		 */
646
		do_action( 'jetpack_full_sync_options', true );
647
	}
648
649
	function force_sync_network_options() {
650
		/**
651
		 * Tells the client to sync all network options to the server
652
		 *
653
		 * @since 4.1
654
		 *
655
		 * @param boolean Whether to expand options (should always be true)
656
		 */
657
		do_action( 'jetpack_full_sync_network_options', true );
658
	}
659
660 View Code Duplication
	private function maybe_sync_constants() {
661
		if ( get_transient( self::CONSTANTS_AWAIT_TRANSIENT_NAME ) ) {
662
			return;
663
		}
664
665
		$constants = $this->get_all_constants();
666
		if ( empty( $constants ) ) {
667
			return;
668
		}
669
670
		set_transient( self::CONSTANTS_AWAIT_TRANSIENT_NAME, microtime( true ), Jetpack_Sync_Defaults::$default_sync_constants_wait_time );
0 ignored issues
show
Bug introduced by
The property default_sync_constants_wait_time cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
671
672
		// only send the constants that have changed
673
		foreach ( $constants as $name => $value ) {
674
			$checksum = $this->get_check_sum( $value );
675
676
			// explicitly not using Identical comparison as get_option returns a string
677
			if ( $checksum != get_option( self::CONSTANTS_CHECKSUM_OPTION_NAME . "_$name" ) ) {
678
				/**
679
				 * Tells the client to sync a constant to the server
680
				 *
681
				 * @since 4.1
682
				 *
683
				 * @param string The name of the constant
684
				 * @param mixed The value of the constant
685
				 */
686
				do_action( 'jetpack_sync_constant', $name, $value );
687
				update_option( self::CONSTANTS_CHECKSUM_OPTION_NAME . "_$name", $checksum );
688
			}
689
		}
690
	}
691
692
	private function get_all_constants() {
693
		return array_combine(
694
			$this->constants_whitelist,
695
			array_map( array( $this, 'get_constant' ), $this->constants_whitelist )
696
		);
697
	}
698
699
	private function get_constant( $constant ) {
700
		if ( defined( $constant ) ) {
701
			return constant( $constant );
702
		}
703
704
		return null;
705
	}
706
707
	public function force_sync_callables() {
708
		foreach ( $this->callable_whitelist as $name => $config ) {
709
			delete_option( self::CALLABLES_CHECKSUM_OPTION_NAME . "_$name" );
710
		}
711
712
		delete_transient( self::CALLABLES_AWAIT_TRANSIENT_NAME );
713
		$this->maybe_sync_callables();
714
	}
715
716 View Code Duplication
	private function maybe_sync_callables() {
717
		if ( get_transient( self::CALLABLES_AWAIT_TRANSIENT_NAME ) ) {
718
			return;
719
		}
720
721
		$callables = $this->get_all_callables();
722
		if ( empty( $callables ) ) {
723
			return;
724
		}
725
726
		set_transient( self::CALLABLES_AWAIT_TRANSIENT_NAME, microtime( true ), Jetpack_Sync_Defaults::$default_sync_callables_wait_time );
0 ignored issues
show
Bug introduced by
The property default_sync_callables_wait_time cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
727
728
		// only send the callables that have changed
729
		foreach ( $callables as $name => $value ) {
730
			$checksum = $this->get_check_sum( $value );
731
			// explicitly not using Identical comparison as get_option returns a string
732
			if ( $checksum != get_option( self::CALLABLES_CHECKSUM_OPTION_NAME . "_$name" ) ) {
733
				/**
734
				 * Tells the client to sync a callable (aka function) to the server
735
				 *
736
				 * @since 4.1
737
				 *
738
				 * @param string The name of the callable
739
				 * @param mixed The value of the callable
740
				 */
741
				do_action( 'jetpack_sync_callable', $name, $value );
742
				update_option( self::CALLABLES_CHECKSUM_OPTION_NAME . "_$name", $checksum );
743
			}
744
		}
745
	}
746
747
	private function get_all_callables() {
748
		return array_combine(
749
			array_keys( $this->callable_whitelist ),
750
			array_map( array( $this, 'get_callable' ), array_values( $this->callable_whitelist ) )
751
		);
752
	}
753
754
	private function get_callable( $callable ) {
755
		return call_user_func( $callable );
756
	}
757
758
	// Is public so that we don't have to store so much data all the options twice.
759
	function get_all_options() {
760
		$options = array();
761
		foreach ( $this->options_whitelist as $option ) {
762
			$options[ $option ] = get_option( $option );
763
		}
764
765
		return $options;
766
	}
767
768
	function get_all_network_options() {
769
		$options = array();
770
		foreach ( $this->network_options_whitelist as $option ) {
771
			$options[ $option ] = get_site_option( $option );
772
		}
773
774
		return $options;
775
	}
776
777
	private function get_check_sum( $values ) {
778
		return crc32( json_encode( $values ) );
779
	}
780
781
	function jetpack_sync_core_icon() {
782
		if ( function_exists( 'get_site_icon_url' ) ) {
783
			$url = get_site_icon_url();
784
		} else {
785
			return;
786
		}
787
788
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
789
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
790
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
791
			// This is the option that is synced with dotcom
792
			Jetpack_Options::update_option( 'site_icon_url', $url );
793
		} else if ( empty( $url ) ) {
794
			Jetpack_Options::delete_option( 'site_icon_url' );
795
		}
796
	}
797
798
	function get_sync_queue() {
799
		return $this->sync_queue;
800
	}
801
802
	function reset_sync_queue() {
803
		$this->sync_queue->reset();
804
	}
805
806
	function get_settings() {
807
		$settings = array();
808
		foreach( array_keys( self::$valid_settings ) as $setting ) {
809
			$default_name = "default_$setting"; // e.g. default_dequeue_max_bytes
810
			$settings[ $setting ] = (int) get_option( self::SETTINGS_OPTION_PREFIX.$setting, Jetpack_Sync_Defaults::$$default_name );
811
		}
812
		return $settings;
813
	}
814
815
	function update_settings( $new_settings ) {
816
		$validated_settings = array_intersect_key( $new_settings, self::$valid_settings );
817
		foreach( $validated_settings as $setting => $value ) {
818
			update_option( self::SETTINGS_OPTION_PREFIX.$setting, $value, true );
819
		}
820
	}
821
822
	function update_options_whitelist() {
823
		/** This filter is already documented in json-endpoints/jetpack/class.wpcom-json-api-get-option-endpoint.php */
824
		$this->options_whitelist = apply_filters( 'jetpack_options_whitelist', Jetpack_Sync_Defaults::$default_options_whitelist );
0 ignored issues
show
Bug introduced by
The property default_options_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
825
	}
826
827
	function set_defaults() {
828
		$this->sync_queue = new Jetpack_Sync_Queue( 'sync' );
829
830
		// saved settings
831
		$settings = $this->get_settings();
832
		$this->set_dequeue_max_bytes( $settings['dequeue_max_bytes'] );
833
		$this->set_upload_max_bytes( $settings['upload_max_bytes'] );
834
		$this->set_upload_max_rows( $settings['upload_max_rows'] );
835
		$this->set_sync_wait_time( $settings['sync_wait_time'] );
836
837
		$this->set_full_sync_client( Jetpack_Sync_Full::getInstance() );
838
		$this->codec                     = new Jetpack_Sync_Deflate_Codec();
839
		$this->constants_whitelist       = Jetpack_Sync_Defaults::$default_constants_whitelist;
0 ignored issues
show
Bug introduced by
The property default_constants_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
840
		$this->update_options_whitelist();
841
		$this->network_options_whitelist = Jetpack_Sync_Defaults::$default_network_options_whitelist;
0 ignored issues
show
Bug introduced by
The property default_network_options_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
842
		$this->taxonomy_whitelist        = Jetpack_Sync_Defaults::$default_taxonomy_whitelist;
0 ignored issues
show
Bug introduced by
The property default_taxonomy_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
843
		$this->is_multisite              = is_multisite();
844
845
		// theme mod varies from theme to theme.
846
		$this->options_whitelist[] = 'theme_mods_' . get_option( 'stylesheet' );
847
		if ( $this->is_multisite ) {
848
			$this->callable_whitelist = array_merge( Jetpack_Sync_Defaults::$default_callable_whitelist, Jetpack_Sync_Defaults::$default_multisite_callable_whitelist );
0 ignored issues
show
Bug introduced by
The property default_callable_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
Bug introduced by
The property default_multisite_callable_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
849
		} else {
850
			$this->callable_whitelist = Jetpack_Sync_Defaults::$default_callable_whitelist;
0 ignored issues
show
Bug introduced by
The property default_callable_whitelist cannot be accessed from this context as it is declared private in class Jetpack_Sync_Defaults.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
851
		}
852
	}
853
854
	function reset_data() {
855
		$this->reset_sync_queue();
856
	}
857
}
858