Completed
Push — add/sync-checksum-to-heartbeat ( 97b1a9...4bf518 )
by
unknown
54:22 queued 44:54
created

Jetpack_Sync_Client::reset_data()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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