Completed
Push — add/test-ensures-non-site-user... ( 461723...7b3c57 )
by
unknown
203:20 queued 194:02
created

Jetpack_Sync_Client::reset_sync_queue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
require_once dirname( __FILE__ ) . '/class.jetpack-sync-json-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
87
		add_filter( 'jetpack_sync_before_send_wp_insert_comment', array( $this, 'expand_wp_insert_comment' ) );
88
89
		// even though it's messy, we implement these hooks because
90
		// the edit_comment hook doesn't include the data
91
		// so this saves us a DB read for every comment event
92
		foreach ( array( '', 'trackback', 'pingback' ) as $comment_type ) {
93
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
94
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
95
				add_action( $comment_action_name, $handler, 10, 2 );
96
				add_filter( 'jetpack_sync_before_send_' . $comment_action_name, array( $this, 'expand_wp_insert_comment' ) );
97
			}
98
		}
99
100
		// options
101
		add_action( 'added_option', $handler, 10, 2 );
102
		add_action( 'updated_option', $handler, 10, 3 );
103
		add_action( 'deleted_option', $handler, 10, 1 );
104
105
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
106
		add_action( 'add_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
107
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
108
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
109
110
		// wordpress version
111
		add_action( 'upgrader_process_complete', array( $this, 'send_wp_version' ), 10, 2 );
112
		add_action( 'jetpack_sync_wp_version', $handler );
113
114
		// themes
115
		add_action( 'switch_theme', array( $this, 'send_theme_info' ) );
116
		add_action( 'jetpack_sync_current_theme_support', $handler, 10 ); // custom hook, see meta-hooks below
117
118
		// post-meta, and in the future - other meta?
119
		foreach ( $this->meta_types as $meta_type ) {
120
			add_action( "added_{$meta_type}_meta", $handler, 10, 4 );
121
			add_action( "updated_{$meta_type}_meta", $handler, 10, 4 );
122
			add_action( "deleted_{$meta_type}_meta", $handler, 10, 4 );
123
		}
124
125
		// terms
126
		add_action( 'created_term', array( $this, 'save_term_handler' ), 10, 3 );
127
		add_action( 'edited_term', array( $this, 'save_term_handler' ), 10, 3 );
128
		add_action( 'jetpack_sync_save_term', $handler, 10, 4 );
129
		add_action( 'delete_term', $handler, 10, 4 );
130
		add_action( 'set_object_terms', $handler, 10, 6 );
131
		add_action( 'deleted_term_relationships', $handler, 10, 2 );
132
133
		// users
134
		add_action( 'user_register', array( $this, 'save_user_handler' ) );
135
		add_action( 'profile_update', array( $this, 'save_user_handler' ), 10, 2 );
136
		add_action( 'add_user_to_blog', array( $this, 'save_user_handler' ) );
137
		add_action( 'jetpack_sync_save_user', $handler, 10, 2 );
138
139
		add_action( 'deleted_user', $handler, 10, 2 );
140
		add_filter( 'jetpack_sync_before_send_jetpack_sync_save_user', array( $this, 'expand_user' ), 10, 2 );
141
		add_action( 'remove_user_from_blog', $handler, 10, 2 );
142
143
		// user roles
144
		add_action( 'add_user_role', array( $this, 'save_user_role_handler' ), 10, 2 );
145
		add_action( 'set_user_role', array( $this, 'save_user_role_handler' ), 10, 3 );
146
		add_action( 'remove_user_role', array( $this, 'save_user_role_handler' ), 10, 2 );
147
148
		// user capabilities
149
		add_action( 'added_user_meta', array( $this, 'save_user_cap_handler' ), 10, 4 );
150
		add_action( 'updated_user_meta', array( $this, 'save_user_cap_handler' ), 10, 4 );
151
		add_action( 'deleted_user_meta', array( $this, 'save_user_cap_handler' ), 10, 4 );
152
153
		// updates
154
		add_action( 'set_site_transient_update_plugins', $handler, 10, 1 );
155
		add_action( 'set_site_transient_update_themes', $handler, 10, 1 );
156
		add_action( 'set_site_transient_update_core', $handler, 10, 1 );
157
		add_filter( 'jetpack_sync_before_enqueue_set_site_transient_update_plugins', array( $this, 'filter_update_keys' ), 10, 2 );
158
159
		// plugins
160
		add_action( 'upgrader_process_complete', $handler, 10, 2 );
161
		add_filter( 'jetpack_sync_before_send_upgrader_process_complete', array( $this, 'expand_upgrader_process_complete' ) );
162
		add_action( 'deleted_plugin', $handler, 10, 2 );
163
		add_action( 'activated_plugin', $handler, 10, 2 );
164
		add_action( 'deactivated_plugin', $handler, 10, 2 );
165
166
167
		// multi site network options
168
		if ( $this->is_multisite ) {
169
			add_action( 'add_site_option', $handler, 10, 2 );
170
			add_action( 'update_site_option', $handler, 10, 3 );
171
			add_action( 'delete_site_option', $handler, 10, 1 );
172
		}
173
174
		// synthetic actions for full sync
175
		add_action( 'jetpack_full_sync_start', $handler );
176
		add_action( 'jetpack_full_sync_end', $handler );
177
		add_action( 'jetpack_full_sync_options', $handler );
178
		add_action( 'jetpack_full_sync_posts', $handler ); // also sends post meta
179
		add_action( 'jetpack_full_sync_comments', $handler ); // also send comments meta
180
		add_action( 'jetpack_full_sync_constants', $handler );
181
		add_action( 'jetpack_full_sync_callables', $handler );
182
		add_action( 'jetpack_full_sync_updates', $handler );
183
184
		add_action( 'jetpack_full_sync_users', $handler );
185
		add_action( 'jetpack_full_sync_terms', $handler, 10, 2 );
186
		if ( is_multisite() ) {
187
			add_action( 'jetpack_full_sync_network_options', $handler );
188
		}
189
190
		// Module Activation
191
		add_action( 'jetpack_activate_module', $handler );
192
		add_action( 'jetpack_deactivate_module', $handler );
193
194
		/**
195
		 * Sync all pending actions with server
196
		 */
197
		add_action( 'jetpack_sync_actions', array( $this, 'do_sync' ) );
198
	}
199
200
	// removes unnecessary keys from synced updates data
201
	function filter_update_keys( $args ) {
202
		$updates = $args[0];
203
204
		if ( isset( $updates->no_update ) ) {
205
			unset( $updates->no_update );
206
		}
207
208
		return $args;
209
	}
210
211
	function set_options_whitelist( $options ) {
212
		$this->options_whitelist = $options;
213
	}
214
215
	function get_options_whitelist() {
216
		return $this->options_whitelist;
217
	}
218
219
	function set_constants_whitelist( $constants ) {
220
		$this->constants_whitelist = $constants;
221
	}
222
223
	function get_constants_whitelist() {
224
		return $this->constants_whitelist;
225
	}
226
227
	function set_callable_whitelist( $callables ) {
228
		$this->callable_whitelist = $callables;
229
	}
230
231
	function get_callable_whitelist() {
232
		return $this->callable_whitelist;
233
	}
234
235
	function set_network_options_whitelist( $options ) {
236
		$this->network_options_whitelist = $options;
237
	}
238
239
	function get_network_options_whitelist() {
240
		return $this->network_options_whitelist;
241
	}
242
243
	function set_dequeue_max_bytes( $size ) {
244
		$this->dequeue_max_bytes = $size;
245
	}
246
247
	// in bytes
248
	function set_upload_max_bytes( $max_bytes ) {
249
		$this->upload_max_bytes = $max_bytes;
250
	}
251
252
	// in rows
253
	function set_upload_max_rows( $max_rows ) {
254
		$this->upload_max_rows = $max_rows;
255
	}
256
257
	// in seconds
258
	function set_sync_wait_time( $seconds ) {
259
		update_option( self::SYNC_THROTTLE_OPTION_NAME, $seconds, true );
260
	}
261
262
	function get_sync_wait_time() {
263
		return get_option( self::SYNC_THROTTLE_OPTION_NAME );
264
	}
265
266
	private function get_last_sync_time() {
267
		return (double) get_option( self::LAST_SYNC_TIME_OPTION_NAME );
268
	}
269
270
	private function set_last_sync_time() {
271
		return update_option( self::LAST_SYNC_TIME_OPTION_NAME, microtime( true ), true );
272
	}
273
274
	function set_taxonomy_whitelist( $taxonomies ) {
275
		$this->taxonomy_whitelist = $taxonomies;
276
	}
277
278
	function is_whitelisted_option( $option ) {
279
		return in_array( $option, $this->options_whitelist );
280
	}
281
282
	function is_whitelisted_network_option( $option ) {
283
		return $this->is_multisite && in_array( $option, $this->network_options_whitelist );
284
	}
285
286
	function set_codec( iJetpack_Sync_Codec $codec ) {
287
		$this->codec = $codec;
288
	}
289
290
	function get_codec() {
291
		return $this->codec;
292
	}
293
294
	function set_full_sync_client( $full_sync_client ) {
295
		if ( $this->full_sync_client ) {
296
			remove_action( 'jetpack_sync_full', array( $this->full_sync_client, 'start' ) );
297
		}
298
299
		$this->full_sync_client = $full_sync_client;
300
301
		/**
302
		 * Sync all objects in the database with the server
303
		 */
304
		add_action( 'jetpack_sync_full', array( $this->full_sync_client, 'start' ) );
305
	}
306
307
	function get_full_sync_client() {
308
		return $this->full_sync_client;
309
	}
310
311
	function action_handler() {
312
		$current_filter = current_filter();
313
		$args           = func_get_args();
314
		if ( in_array( $current_filter, array( 'deleted_option', 'added_option', 'updated_option' ) )
315
		     &&
316
		     ! $this->is_whitelisted_option( $args[0] )
317
		) {
318
			return;
319
		}
320
321
		if ( in_array( $current_filter, array( 'delete_site_option', 'add_site_option', 'update_site_option' ) )
322
		     &&
323
		     ! $this->is_whitelisted_network_option( $args[0] )
324
		) {
325
			return;
326
		}
327
		
328
		if ( $current_filter == 'upgrader_process_complete' ) {
329
			array_shift( $args );
330
		}
331
332
		// don't sync private meta
333
		if ( preg_match( '/^(added|updated|deleted)_.*_meta$/', $current_filter )
334
		     && $args[2][0] === '_'
335
		     && ! 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...
336
		) {
337
			return;
338
		}
339
340
		/**
341
		 * Modify the data within an action before it is enqueued locally.
342
		 *
343
		 * @since 4.2.0
344
		 *
345
		 * @param array The action parameters
346
		 */
347
		$args = apply_filters( "jetpack_sync_before_enqueue_$current_filter", $args );
348
349
		// if we add any items to the queue, we should 
350
		// try to ensure that our script can't be killed before
351
		// they are sent
352
		if ( function_exists( 'ignore_user_abort' ) ) {
353
			ignore_user_abort( true );
354
		}
355
356
		$this->sync_queue->add( array(
357
			$current_filter,
358
			$args,
359
			get_current_user_id(),
360
			microtime( true )
361
		) );
362
	}
363
364
	function send_theme_info() {
365
		global $_wp_theme_features;
366
367
		$theme_support = array();
368
369
		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...
370
			$has_support = current_theme_supports( $theme_feature );
371
			if ( $has_support ) {
372
				$theme_support[ $theme_feature ] = $_wp_theme_features[ $theme_feature ];
373
			}
374
375
		}
376
377
		/**
378
		 * Fires when the client needs to sync theme support info
379
		 * Only sends theme support attributes whitelisted in Jetpack_Sync_Defaults::$default_theme_support_whitelist
380
		 *
381
		 * @since 4.2.0
382
		 *
383
		 * @param object the theme support hash
384
		 */
385
		do_action( 'jetpack_sync_current_theme_support', $theme_support );
386
		return 1; // The number of actions enqueued
387
	}
388
389
	function send_wp_version( $update, $meta_data ) {
390
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
391
			$this->force_sync_callables();
392
		}
393
	}
394
395
	function save_term_handler( $term_id, $tt_id, $taxonomy ) {
396
		if ( class_exists( 'WP_Term' ) ) {
397
			$term_object = WP_Term::get_instance( $term_id, $taxonomy );
398
		} else {
399
			$term_object = get_term_by( 'id', $term_id, $taxonomy );
400
		}
401
402
		/**
403
		 * Fires when the client needs to sync a new term
404
		 *
405
		 * @since 4.2.0
406
		 *
407
		 * @param object the Term object
408
		 */
409
		do_action( 'jetpack_sync_save_term', $term_object );
410
	}
411
412
	function send_attachment_info( $attachment_id ) {
413
		$attachment = get_post( $attachment_id );
414
415
		/**
416
		 * Fires when the client needs to sync an attachment for a post
417
		 *
418
		 * @since 4.2.0
419
		 *
420
		 * @param int The attachment ID
421
		 * @param object The attachment
422
		 */
423
		do_action( 'jetpack_sync_save_add_attachment', $attachment_id, $attachment );
424
	}
425
426
	function save_user_handler( $user_id, $old_user_data = null ) {
427
428
		// ensure we only sync users who are members of the current blog
429
		if ( ! is_user_member_of_blog( $user_id, get_current_blog_id() ) ) {
430
			return;
431
		}
432
433
		$user = $this->sanitize_user( get_user_by( 'id', $user_id ) );
434
435
		// Older versions of WP don't pass the old_user_data in ->data
436
		if ( isset( $old_user_data->data ) ) {
437
			$old_user = $old_user_data->data;
438
		} else {
439
			$old_user = $old_user_data;
440
		}
441
442
		if ( $old_user !== null ) {
443
			unset( $old_user->user_pass );
444
			if ( serialize( $old_user ) === serialize( $user->data ) ) {
445
				return;
446
			}
447
		}
448
		/**
449
		 * Fires when the client needs to sync an updated user
450
		 *
451
		 * @since 4.2.0
452
		 *
453
		 * @param object The WP_User object
454
		 */
455
		do_action( 'jetpack_sync_save_user', $user );
456
	}
457
458
	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...
459
		$user = $this->sanitize_user( get_user_by( 'id', $user_id ) );
460
461
		/**
462
		 * Fires when the client needs to sync an updated user
463
		 *
464
		 * @since 4.2.0
465
		 *
466
		 * @param object The WP_User object
467
		 */
468
		do_action( 'jetpack_sync_save_user', $user );
469
	}
470
471
	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...
472
473
		// if a user is currently being removed as a member of this blog, we don't fire the event
474
		if ( current_filter() === 'deleted_user_meta' 
475
		&&
476
			preg_match( '/capabilities|user_level/', $meta_key )
477
		&& 
478
			! is_user_member_of_blog( $user_id, get_current_blog_id() ) ) {
479
			return;
480
		}
481
482
		$user = $this->sanitize_user( get_user_by( 'id', $user_id ) );
483
		if ( $meta_key === $user->cap_key ) {
484
			/**
485
			 * Fires when the client needs to sync an updated user
486
			 *
487
			 * @since 4.2.0
488
			 *
489
			 * @param object The WP_User object
490
			 */
491
			do_action( 'jetpack_sync_save_user', $user );
492
		}
493
	}
494
495
	public function sanitize_user( $user ) {
496
		unset( $user->data->user_pass );
497
		return $user;
498
	}
499
500
	public function sanitize_user_and_expand( $user ) {
501
		$user = $this->sanitize_user( $user );
502
		return $this->add_to_user( $user );
503
	}
504
505
	public function add_to_user( $user ) {
506
		$user->allowed_mime_types = get_allowed_mime_types( $user );
507
		return $user;
508
	}
509
510
	public function expand_user( $args ) {
511
		list( $user ) = $args;
512
		return array( $this->add_to_user( $user ) );
513
	}
514
515
	function do_sync() {
516
		// don't sync if importing
517
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
518
			$this->schedule_sync( "+1 minute" );
519
520
			return false;
521
		}
522
523
		// don't sync if we are throttled
524
		$sync_wait = $this->get_sync_wait_time();
525
		$last_sync = $this->get_last_sync_time();
526
527
		if ( $last_sync && $sync_wait && $last_sync + $sync_wait > microtime( true ) ) {
528
			return false;
529
		}
530
531
		$this->set_last_sync_time();
532
		$this->maybe_sync_constants();
533
		$this->maybe_sync_callables();
534
535
		if ( $this->sync_queue->size() === 0 ) {
536
			return false;
537
		}
538
539
		// now that we're sure we are about to sync, try to
540
		// ignore user abort so we can avoid getting into a
541
		// bad state
542
		if ( function_exists( 'ignore_user_abort' ) ) {
543
			ignore_user_abort( true );
544
		}
545
546
		$buffer = $this->sync_queue->checkout_with_memory_limit( $this->dequeue_max_bytes, $this->upload_max_rows );
547
548
		if ( ! $buffer ) {
549
			// buffer has no items
550
			return false;
551
		}
552
553
		if ( is_wp_error( $buffer ) ) {
554
			// another buffer is currently sending
555
			return false;
556
		}
557
558
		$upload_size   = 0;
559
		$items_to_send = array();
560
		$actions_to_send = array();
561
		// we estimate the total encoded size as we go by encoding each item individually
562
		// this is expensive, but the only way to really know :/
563
		foreach ( $buffer->get_items() as $key => $item ) {
564
			/**
565
			 * Modify the data within an action before it is serialized and sent to the server
566
			 * For example, during full sync this expands Post ID's into full Post objects,
567
			 * so that we don't have to serialize the whole object into the queue.
568
			 *
569
			 * @since 4.2.0
570
			 *
571
			 * @param array The action parameters
572
			 */
573
			$item[1] = apply_filters( "jetpack_sync_before_send_" . $item[0], $item[1] );
574
575
			$encoded_item = $this->codec->encode( $item );
576
577
			$upload_size += strlen( $encoded_item );
578
579
			if ( $upload_size > $this->upload_max_bytes && count( $items_to_send ) > 0 ) {
580
				break;
581
			}
582
583
			$items_to_send[ $key ] = $encoded_item;
584
			$actions_to_send[ $key ] = $item[0];
585
		}
586
587
		/**
588
		 * Fires when data is ready to send to the server.
589
		 * Return false or WP_Error to abort the sync (e.g. if there's an error)
590
		 * The items will be automatically re-sent later
591
		 *
592
		 * @since 4.2.0
593
		 *
594
		 * @param array $data The action buffer
595
		 */
596
		$result = apply_filters( 'jetpack_sync_client_send_data', $items_to_send, $this->codec->name() );
597
598
		if ( ! $result || is_wp_error( $result ) ) {
599
			$result = $this->sync_queue->checkin( $buffer );
600
601
			if ( is_wp_error( $result ) ) {
602
				error_log( "Error checking in buffer: " . $result->get_error_message() );
603
				$this->sync_queue->force_checkin();
604
			}
605
			// try again in 1 minute
606
			$this->schedule_sync( "+1 minute" );
607
		} else {
608
			$processed_actions = array();
609
			foreach( $result as $result_id ) {
610
				if ( isset( $actions_to_send[ $result_id ] ) ) {
611
					$processed_actions[] =  $actions_to_send[ $result_id ];
612
				}
613
			}
614
615
			/**
616
			 * Allows us to keep track of all the actions that have been sent.
617
			 * Allows us to calculate the progress of specific actions.
618
			 *
619
			 * @since 4.2.0
620
			 *
621
			 * @param array $processed_actions The actions that we send successfully.
622
			 */
623
			do_action( 'jetpack_sync_processed_actions', $processed_actions );
624
625
626
			$this->sync_queue->close( $buffer, $result );
627
			// check if there are any more events in the buffer
628
			// if so, schedule a cron job to happen soon
629
			if ( $this->sync_queue->has_any_items() ) {
630
				$this->schedule_sync( "+1 minute" );
631
			}
632
		}
633
	}
634
635
	function expand_wp_insert_post( $args ) {
636
		return array( $args[0], $this->filter_post_content_and_add_links( $args[1] ), $args[2] );
637
	}
638
639
	function expand_upgrader_process_complete( $args ) {
640
		list( $process ) = $args;
641
		if ( isset( $process['type'] ) && $process['type'] === 'plugin' ) {
642
			return array( $process, get_plugins() );
643
		}
644
		return $args;
645
	}
646
647
	// Expands wp_insert_post to include filtered content
648
	function filter_post_content_and_add_links( $post ) {
649
650
		/**
651
		 * Filters whether to prevent sending post data to .com
652
		 *
653
		 * Passing true to the filter will prevent the post data from being sent
654
		 * to the WordPress.com.
655
		 * Instead we pass data that will still enable us to do a checksum against the
656
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
657
		 * other services.
658
		 * @since 4.2.0
659
		 *
660
		 * @param boolean false prevent post data from bing sycned to WordPress.com
661
		 * @param mixed $post WP_POST object
662
		 */
663
		if ( apply_filters( 'jetpack_sync_prevent_sending_post_data', false, $post ) ) {
664
			// We only send the bare necessery object to be able to create a checksum.
665
			$blocked_post = new stdClass();
666
			$blocked_post->ID = $post->ID;
667
			$blocked_post->post_modified = $post->post_modified;
668
			$blocked_post->post_modified_gmt = $post->post_modified_gmt;
669
			$blocked_post->post_status = 'jetpack_sync_blocked';
670
			return $blocked_post;
671
		}
672
673
		if ( 0 < strlen( $post->post_password ) ) {
674
			$post->post_password = 'auto-' . wp_generate_password( 10, false );
675
		}
676
		/** This filter is already documented in core. wp-includes/post-template.php */
677
		$post->post_content_filtered   = apply_filters( 'the_content', $post->post_content );
678
		$post->post_excerpt_filtered   = apply_filters( 'the_content', $post->post_excerpt );
679
		$post->permalink               = get_permalink( $post->ID );
680
		$post->shortlink               = wp_get_shortlink( $post->ID );
681
		$post->dont_email_post_to_subs = get_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', true );
682
683
		return $post;
684
	}
685
686
687
	function expand_wp_comment_status_change( $args ) {
688
		return array( $args[0], $this->filter_comment( $args[1] ) );
689
	}
690
691
	function expand_wp_insert_comment( $args ) {
692
		return array( $args[0], $this->filter_comment( $args[1] ) );
693
	}
694
695
	function filter_comment( $comment ) {
696
		/**
697
		 * Filters whether to prevent sending comment data to .com
698
		 *
699
		 * Passing true to the filter will prevent the comment data from being sent
700
		 * to the WordPress.com.
701
		 * Instead we pass data that will still enable us to do a checksum against the
702
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
703
		 * other services.
704
		 * @since 4.2.0
705
		 *
706
		 * @param boolean false prevent post data from bing sycned to WordPress.com
707
		 * @param mixed $comment WP_COMMENT object
708
		 */
709
		if ( apply_filters( 'jetpack_sync_prevent_sending_comment_data', false, $comment ) ) {
710
			$blocked_comment = new stdClass();
711
			$blocked_comment->comment_ID = $comment->comment_ID;
712
			$blocked_comment->comment_date = $comment->comment_date;
713
			$blocked_comment->comment_date_gmt = $comment->comment_date_gmt;
714
			$blocked_comment->comment_approved = 'jetpack_sync_blocked';
715
			return $blocked_comment;
716
		}
717
718
		return $comment;
719
	}
720
721
	private function schedule_sync( $when ) {
722
		wp_schedule_single_event( strtotime( $when ), 'jetpack_sync_actions' );
723
	}
724
725
	function force_sync_constants() {
726
		delete_option( self::CONSTANTS_CHECKSUM_OPTION_NAME );
727
		delete_transient( self::CONSTANTS_AWAIT_TRANSIENT_NAME );
728
		$this->maybe_sync_constants();
729
730
	}
731
732
	function full_sync_constants() {
733
		/**
734
		 * Tells the client to sync all constants to the server
735
		 *
736
		 * @since 4.1
737
		 *
738
		 * @param boolean Whether to expand constants (should always be true)
739
		 */
740
		do_action( 'jetpack_full_sync_constants', true );
741
		return 1; // The number of actions enqueued
742
	}
743
744
	function force_sync_options() {
745
		/**
746
		 * Tells the client to sync all options to the server
747
		 *
748
		 * @since 4.2.0
749
		 *
750
		 * @param boolean Whether to expand options (should always be true)
751
		 */
752
		do_action( 'jetpack_full_sync_options', true );
753
		return 1; // The number of actions enqueued
754
	}
755
756
	function force_sync_network_options() {
757
		/**
758
		 * Tells the client to sync all network options to the server
759
		 *
760
		 * @since 4.2.0
761
		 *
762
		 * @param boolean Whether to expand options (should always be true)
763
		 */
764
		do_action( 'jetpack_full_sync_network_options', true );
765
		return 1; // The number of actions enqueued
766
	}
767
768
	public function full_sync_callables() {
769
		/**
770
		 * Tells the client to sync all callables to the server
771
		 *
772
		 * @since 4.1
773
		 *
774
		 * @param boolean Whether to expand callables (should always be true)
775
		 */
776
		do_action( 'jetpack_full_sync_callables', true );
777
		return 1; // The number of actions enqueued
778
	}
779
780
	public function full_sync_updates() {
781
		/**
782
		 * Tells the client to sync all updates to the server
783
		 *
784
		 * @since 4.1
785
		 *
786
		 * @param boolean Whether to expand callables (should always be true)
787
		 */
788
		do_action( 'jetpack_full_sync_updates', true );
789
		return 1; // The number of actions enqueued
790
	}
791
792 View Code Duplication
	private function maybe_sync_constants() {
793
		if ( get_transient( self::CONSTANTS_AWAIT_TRANSIENT_NAME ) ) {
794
			return;
795
		}
796
797
		$constants = $this->get_all_constants();
798
		if ( empty( $constants ) ) {
799
			return;
800
		}
801
802
		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...
803
		$constants_checksums = get_option( self::CONSTANTS_CHECKSUM_OPTION_NAME, array() );
804
		// only send the constants that have changed
805
		foreach ( $constants as $name => $value ) {
806
			$checksum = $this->get_check_sum( $value );
807
808
			// explicitly not using Identical comparison as get_option returns a string
809
			if ( ! $this->still_valid_checksum( $constants_checksums, $name, $checksum ) ) {
810
				/**
811
				 * Tells the client to sync a constant to the server
812
				 *
813
				 * @since 4.2.0
814
				 *
815
				 * @param string The name of the constant
816
				 * @param mixed The value of the constant
817
				 */
818
				do_action( 'jetpack_sync_constant', $name, $value );
819
				$constants_checksums[ $name ] = $checksum;
820
			}
821
		}
822
823
		update_option( self::CONSTANTS_CHECKSUM_OPTION_NAME, $constants_checksums );
824
	}
825
	// public so that we don't have to store an option for each constant
826
	function get_all_constants() {
827
		return array_combine(
828
			$this->constants_whitelist,
829
			array_map( array( $this, 'get_constant' ), $this->constants_whitelist )
830
		);
831
	}
832
833
	private function get_constant( $constant ) {
834
		return ( defined( $constant ) ) ?
835
			constant( $constant ) 
836
			: null;
837
	}
838
839
	public function get_all_updates() {
840
		return array(
841
			'core' => get_site_transient( 'update_core' ),
842
			'plugins' => get_site_transient( 'update_plugins' ),
843
			'themes' => get_site_transient( 'update_themes' ),
844
		);
845
	}
846
847
	public function force_sync_callables() {
848
		delete_option( self::CALLABLES_CHECKSUM_OPTION_NAME );
849
		delete_transient( self::CALLABLES_AWAIT_TRANSIENT_NAME );
850
		$this->maybe_sync_callables();
851
	}
852
853 View Code Duplication
	private function maybe_sync_callables() {
854
		if ( get_transient( self::CALLABLES_AWAIT_TRANSIENT_NAME ) ) {
855
			return;
856
		}
857
858
		$callables = $this->get_all_callables();
859
		if ( empty( $callables ) ) {
860
			return;
861
		}
862
863
		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...
864
865
		$callable_checksums = get_option( self::CALLABLES_CHECKSUM_OPTION_NAME , array() );
866
867
		// only send the callables that have changed
868
		foreach ( $callables as $name => $value ) {
869
			$checksum = $this->get_check_sum( $value );
870
			// explicitly not using Identical comparison as get_option returns a string
871
			if ( ! $this->still_valid_checksum( $callable_checksums, $name, $checksum ) ) {
872
				/**
873
				 * Tells the client to sync a callable (aka function) to the server
874
				 *
875
				 * @since 4.2.0
876
				 *
877
				 * @param string The name of the callable
878
				 * @param mixed The value of the callable
879
				 */
880
				do_action( 'jetpack_sync_callable', $name, $value );
881
				$callable_checksums[ $name ] = $checksum;
882
			}
883
		}
884
		update_option( self::CALLABLES_CHECKSUM_OPTION_NAME , $callable_checksums );
885
	}
886
887
	private function still_valid_checksum( $sums_to_check, $name, $new_sum ) {
888
		if ( isset( $sums_to_check[ $name ] ) && $sums_to_check[ $name ] === $new_sum ) {
889
			return true;
890
		}
891
		return false;
892
	}
893
894
	public function get_all_callables() {
895
		return array_combine(
896
			array_keys( $this->callable_whitelist ),
897
			array_map( array( $this, 'get_callable' ), array_values( $this->callable_whitelist ) )
898
		);
899
	}
900
901
	private function get_callable( $callable ) {
902
		return call_user_func( $callable );
903
	}
904
905
	// Is public so that we don't have to store so much data all the options twice.
906
	function get_all_options() {
907
		$options = array();
908
		foreach ( $this->options_whitelist as $option ) {
909
			$options[ $option ] = get_option( $option );
910
		}
911
912
		return $options;
913
	}
914
915
	function get_all_network_options() {
916
		$options = array();
917
		foreach ( $this->network_options_whitelist as $option ) {
918
			$options[ $option ] = get_site_option( $option );
919
		}
920
921
		return $options;
922
	}
923
924
	private function get_check_sum( $values ) {
925
		return crc32( json_encode( $values ) );
926
	}
927
928
	function jetpack_sync_core_icon() {
929
		if ( function_exists( 'get_site_icon_url' ) ) {
930
			$url = get_site_icon_url();
931
		} else {
932
			return;
933
		}
934
935
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
936
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
937
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
938
			// This is the option that is synced with dotcom
939
			Jetpack_Options::update_option( 'site_icon_url', $url );
940
		} else if ( empty( $url ) ) {
941
			Jetpack_Options::delete_option( 'site_icon_url' );
942
		}
943
	}
944
945
	function get_sync_queue() {
946
		return $this->sync_queue;
947
	}
948
949
	function reset_sync_queue() {
950
		$this->sync_queue->reset();
951
	}
952
953
	function get_settings() {
954
		$settings = array();
955
		foreach( array_keys( self::$valid_settings ) as $setting ) {
956
			$default_name = "default_$setting"; // e.g. default_dequeue_max_bytes
957
			$settings[ $setting ] = (int) get_option( self::SETTINGS_OPTION_PREFIX.$setting, Jetpack_Sync_Defaults::$$default_name );
958
		}
959
		return $settings;
960
	}
961
962
	function update_settings( $new_settings ) {
963
		$validated_settings = array_intersect_key( $new_settings, self::$valid_settings );
964
		foreach( $validated_settings as $setting => $value ) {
965
			update_option( self::SETTINGS_OPTION_PREFIX.$setting, $value, true );
966
		}
967
	}
968
969
	function update_options_whitelist() {
970
		/** This filter is already documented in json-endpoints/jetpack/class.wpcom-json-api-get-option-endpoint.php */
971
		$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...
972
	}
973
974
	function set_defaults() {
975
		$this->sync_queue = new Jetpack_Sync_Queue( 'sync' );
976
977
		// saved settings
978
		$settings = $this->get_settings();
979
		$this->set_dequeue_max_bytes( $settings['dequeue_max_bytes'] );
980
		$this->set_upload_max_bytes( $settings['upload_max_bytes'] );
981
		$this->set_upload_max_rows( $settings['upload_max_rows'] );
982
		$this->set_sync_wait_time( $settings['sync_wait_time'] );
983
984
		$this->set_full_sync_client( Jetpack_Sync_Full::getInstance() );
985
		$this->codec                     = new Jetpack_Sync_JSON_Deflate_Codec();
986
		$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...
987
		$this->update_options_whitelist();
988
		$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...
989
		$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...
990
		$this->is_multisite              = is_multisite();
991
992
		// theme mod varies from theme to theme.
993
		$this->options_whitelist[] = 'theme_mods_' . get_option( 'stylesheet' );
994
		if ( $this->is_multisite ) {
995
			$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...
996
		} else {
997
			$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...
998
		}
999
	}
1000
1001
	function reset_data() {
1002
		$this->reset_sync_queue();
1003
1004
1005
		delete_option( self::CONSTANTS_CHECKSUM_OPTION_NAME );
1006
		delete_option( self::CALLABLES_CHECKSUM_OPTION_NAME );
1007
1008
		delete_transient( self::CALLABLES_AWAIT_TRANSIENT_NAME );
1009
		delete_transient( self::CONSTANTS_AWAIT_TRANSIENT_NAME );
1010
1011
		delete_option( self::SYNC_THROTTLE_OPTION_NAME );
1012
		delete_option( self::LAST_SYNC_TIME_OPTION_NAME );
1013
1014
		$valid_settings  = self::$valid_settings;
1015
		$settings_prefix =  self::SETTINGS_OPTION_PREFIX;
1016
		foreach ( $valid_settings as $option => $value ) {
1017
			delete_option( $settings_prefix . $option );
1018
		}
1019
	}
1020
1021
	function uninstall() {
1022
		// Lets delete all the other fun stuff like transient and option and the sync queue
1023
		$this->reset_data();
1024
1025
		// delete the full sync status
1026
		delete_option( 'jetpack_full_sync_status' );
1027
1028
		// clear the sync cron.
1029
		wp_clear_scheduled_hook( 'jetpack_sync_actions' );
1030
	}
1031
}
1032