Completed
Push — branch-4.2 ( 75dc85...f982fc )
by Jeremy
17:06 queued 07:07
created

Jetpack_Sync_Client::send_checksum()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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