Completed
Push — update/sync-comment-whitelisti... ( 936bd0...c347b8 )
by
unknown
08:03
created

Comments::estimate_full_sync_actions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 16
loc 16
rs 9.7333
c 0
b 0
f 0
1
<?php
2
/**
3
 * Comments sync module.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync\Modules;
9
10
use Automattic\Jetpack\Sync\Settings;
11
use Automattic\Jetpack\Sync\Modules;
12
13
/**
14
 * Class to handle sync for comments.
15
 */
16
class Comments extends Module {
17
	/**
18
	 * Sync module name.
19
	 *
20
	 * @access public
21
	 *
22
	 * @return string
23
	 */
24
	public function name() {
25
		return 'comments';
26
	}
27
28
	/**
29
	 * The id field in the database.
30
	 *
31
	 * @access public
32
	 *
33
	 * @return string
34
	 */
35
	public function id_field() {
36
		return 'comment_ID';
37
	}
38
39
	/**
40
	 * The table in the database.
41
	 *
42
	 * @access public
43
	 *
44
	 * @return string
45
	 */
46
	public function table_name() {
47
		return 'comments';
48
	}
49
50
	/**
51
	 * Retrieve a comment by its ID.
52
	 *
53
	 * @access public
54
	 *
55
	 * @param string $object_type Type of the sync object.
56
	 * @param int    $id          ID of the sync object.
57
	 * @return \WP_Comment|bool Filtered \WP_Comment object, or false if the object is not a comment.
58
	 */
59
	public function get_object_by_id( $object_type, $id ) {
60
		$comment_id = intval( $id );
61
		if ( 'comment' === $object_type ) {
62
			$comment = get_comment( $comment_id );
63
			if ( $comment ) {
64
				return $this->filter_comment( $comment );
65
			}
66
		}
67
68
		return false;
69
	}
70
71
	/**
72
	 * Initialize comments action listeners.
73
	 * Also responsible for initializing comment meta listeners.
74
	 *
75
	 * @access public
76
	 *
77
	 * @param callable $callable Action handler callable.
78
	 */
79
	public function init_listeners( $callable ) {
80
		add_action( 'wp_insert_comment', $callable, 10, 2 );
81
		add_action( 'deleted_comment', $callable );
82
		add_action( 'trashed_comment', $callable );
83
		add_action( 'spammed_comment', $callable );
84
		add_action( 'trashed_post_comments', $callable, 10, 2 );
85
		add_action( 'untrash_post_comments', $callable );
86
		add_action( 'comment_approved_to_unapproved', $callable );
87
		add_action( 'comment_unapproved_to_approved', $callable );
88
		add_action( 'jetpack_modified_comment_contents', $callable, 10, 2 );
89
		add_action( 'untrashed_comment', $callable, 10, 2 );
90
		add_action( 'unspammed_comment', $callable, 10, 2 );
91
		add_filter( 'wp_update_comment_data', array( $this, 'handle_comment_contents_modification' ), 10, 3 );
92
93
		// comment actions.
94
		add_filter( 'jetpack_sync_before_enqueue_wp_insert_comment', array( $this, 'only_allow_white_listed_comment_types' ) );
95
		add_filter( 'jetpack_sync_before_enqueue_deleted_comment', array( $this, 'only_allow_white_listed_comment_types' ) );
96
		add_filter( 'jetpack_sync_before_enqueue_trashed_comment', array( $this, 'only_allow_white_listed_comment_types' ) );
97
		add_filter( 'jetpack_sync_before_enqueue_untrashed_comment', array( $this, 'only_allow_white_listed_comment_types' ) );
98
		add_filter( 'jetpack_sync_before_enqueue_spammed_comment', array( $this, 'only_allow_white_listed_comment_types' ) );
99
		add_filter( 'jetpack_sync_before_enqueue_unspammed_comment', array( $this, 'only_allow_white_listed_comment_types' ) );
100
101
		// comment status transitions.
102
		add_filter( 'jetpack_sync_before_enqueue_comment_approved_to_unapproved', array( $this, 'only_allow_white_listed_comment_type_transitions' ) );
103
		add_filter( 'jetpack_sync_before_enqueue_comment_unapproved_to_approved', array( $this, 'only_allow_white_listed_comment_type_transitions' ) );
104
105
		// Post Actions.
106
		add_filter( 'jetpack_sync_before_enqueue_trashed_post_comments', array( $this, 'filter_blacklisted_post_types' ) );
107
		add_filter( 'jetpack_sync_before_enqueue_untrash_post_comments', array( $this, 'filter_blacklisted_post_types' ) );
108
109
		/**
110
		 * Even though it's messy, we implement these hooks because
111
		 * the edit_comment hook doesn't include the data
112
		 * so this saves us a DB read for every comment event.
113
		 */
114
		foreach ( $this->get_whitelisted_comment_types() as $comment_type ) {
115
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
116
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
117
				add_action( $comment_action_name, $callable, 10, 2 );
118
			}
119
		}
120
121
		// Listen for meta changes.
122
		$this->init_listeners_for_meta_type( 'comment', $callable );
123
		$this->init_meta_whitelist_handler( 'comment', array( $this, 'filter_meta' ) );
124
	}
125
126
	/**
127
	 * Handler for any comment content updates.
128
	 *
129
	 * @access public
130
	 *
131
	 * @param array $new_comment              The new, processed comment data.
132
	 * @param array $old_comment              The old, unslashed comment data.
133
	 * @param array $new_comment_with_slashes The new, raw comment data.
134
	 * @return array The new, processed comment data.
135
	 */
136
	public function handle_comment_contents_modification( $new_comment, $old_comment, $new_comment_with_slashes ) {
137
		$changes        = array();
138
		$content_fields = array(
139
			'comment_author',
140
			'comment_author_email',
141
			'comment_author_url',
142
			'comment_content',
143
		);
144
		foreach ( $content_fields as $field ) {
145
			if ( $new_comment_with_slashes[ $field ] !== $old_comment[ $field ] ) {
146
				$changes[ $field ] = array( $new_comment[ $field ], $old_comment[ $field ] );
147
			}
148
		}
149
150
		if ( ! empty( $changes ) ) {
151
			/**
152
			 * Signals to the sync listener that this comment's contents were modified and a sync action
153
			 * reflecting the change(s) to the content should be sent
154
			 *
155
			 * @since 4.9.0
156
			 *
157
			 * @param int $new_comment['comment_ID'] ID of comment whose content was modified
158
			 * @param mixed $changes Array of changed comment fields with before and after values
159
			 */
160
			do_action( 'jetpack_modified_comment_contents', $new_comment['comment_ID'], $changes );
161
		}
162
		return $new_comment;
163
	}
164
165
	/**
166
	 * Initialize comments action listeners for full sync.
167
	 *
168
	 * @access public
169
	 *
170
	 * @param callable $callable Action handler callable.
171
	 */
172
	public function init_full_sync_listeners( $callable ) {
173
		add_action( 'jetpack_full_sync_comments', $callable ); // Also send comments meta.
174
	}
175
176
	/**
177
	 * Gets a filtered list of comment types that sync can hook into.
178
	 *
179
	 * @access public
180
	 *
181
	 * @return array Defaults to [ '', 'trackback', 'pingback' ].
182
	 */
183
	public function get_whitelisted_comment_types() {
184
		/**
185
		 * Comment types present in this list will sync their status changes to WordPress.com.
186
		 *
187
		 * @since 7.6.0
188
		 *
189
		 * @param array A list of comment types.
190
		 */
191
		return apply_filters(
192
			'jetpack_sync_whitelisted_comment_types',
193
			array( '', 'comment', 'trackback', 'pingback' )
194
		);
195
	}
196
197
	/**
198
	 * Prevents any comment types that are not in the whitelist from being enqueued and sent to WordPress.com.
199
	 *
200
	 * @param array $args Arguments passed to wp_insert_comment, deleted_comment, spammed_comment, etc.
201
	 *
202
	 * @return bool or array $args Arguments passed to wp_insert_comment, deleted_comment, spammed_comment, etc.
203
	 */
204
	public function only_allow_white_listed_comment_types( $args ) {
205
		$comment = false;
206
207
		if ( isset( $args[1] ) ) {
208
			// comment object is available.
209
			$comment = $args[1];
210
		} elseif ( is_numeric( $args[0] ) ) {
211
			// comment_id is available.
212
			$comment = get_comment( $args[0] );
213
		}
214
215
		if ( false !== $comment && ! in_array( $comment->comment_type, $this->get_whitelisted_comment_types(), true ) ) {
216
			return false;
217
		}
218
219
		return $args;
220
	}
221
222
	/**
223
	 * Filter all blacklisted post types.
224
	 *
225
	 * @param array $args Hook arguments.
226
	 * @return array|false Hook arguments, or false if the post type is a blacklisted one.
227
	 */
228
	public function filter_blacklisted_post_types( $args ) {
229
		$post_id      = $args[0];
230
		$posts_module = Modules::get_module( 'posts' );
231
232
		if ( false !== $posts_module && ! $posts_module->is_post_type_allowed( $post_id ) ) {
233
			return false;
234
		}
235
236
		return $args;
237
	}
238
239
	/**
240
	 * Prevents any comment types that are not in the whitelist from being enqueued and sent to WordPress.com.
241
	 *
242
	 * @param array $args Arguments passed to wp_{old_status}_to_{new_status}.
243
	 *
244
	 * @return bool or array $args Arguments passed to wp_{old_status}_to_{new_status}
245
	 */
246
	public function only_allow_white_listed_comment_type_transitions( $args ) {
247
		$comment = $args[0];
248
249
		if ( ! in_array( $comment->comment_type, $this->get_whitelisted_comment_types(), true ) ) {
250
			return false;
251
		}
252
253
		return $args;
254
	}
255
256
	/**
257
	 * Initialize the module in the sender.
258
	 *
259
	 * @access public
260
	 */
261
	public function init_before_send() {
262
		add_filter( 'jetpack_sync_before_send_wp_insert_comment', array( $this, 'expand_wp_insert_comment' ) );
263
264
		foreach ( $this->get_whitelisted_comment_types() as $comment_type ) {
265
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
266
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
267
				add_filter(
268
					'jetpack_sync_before_send_' . $comment_action_name,
269
					array(
270
						$this,
271
						'expand_wp_insert_comment',
272
					)
273
				);
274
			}
275
		}
276
277
		// Full sync.
278
		add_filter( 'jetpack_sync_before_send_jetpack_full_sync_comments', array( $this, 'expand_comment_ids' ) );
279
	}
280
281
	/**
282
	 * Enqueue the comments actions for full sync.
283
	 *
284
	 * @access public
285
	 *
286
	 * @param array   $config               Full sync configuration for this sync module.
287
	 * @param int     $max_items_to_enqueue Maximum number of items to enqueue.
288
	 * @param boolean $state                True if full sync has finished enqueueing this module, false otherwise.
289
	 * @return array Number of actions enqueued, and next module state.
290
	 */
291
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
292
		global $wpdb;
293
		return $this->enqueue_all_ids_as_action( 'jetpack_full_sync_comments', $wpdb->comments, 'comment_ID', $this->get_where_sql( $config ), $max_items_to_enqueue, $state );
294
	}
295
296
	/**
297
	 * Retrieve an estimated number of actions that will be enqueued.
298
	 *
299
	 * @access public
300
	 *
301
	 * @param array $config Full sync configuration for this sync module.
302
	 * @return int Number of items yet to be enqueued.
303
	 */
304 View Code Duplication
	public function estimate_full_sync_actions( $config ) {
305
		global $wpdb;
306
307
		$query = "SELECT count(*) FROM $wpdb->comments";
308
309
		$where_sql = $this->get_where_sql( $config );
310
		if ( $where_sql ) {
311
			$query .= ' WHERE ' . $where_sql;
312
		}
313
314
		// TODO: Call $wpdb->prepare on the following query.
315
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
316
		$count = $wpdb->get_var( $query );
317
318
		return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
319
	}
320
321
	/**
322
	 * Retrieve the WHERE SQL clause based on the module config.
323
	 *
324
	 * @access public
325
	 *
326
	 * @param array $config Full sync configuration for this sync module.
327
	 * @return string WHERE SQL clause, or `null` if no comments are specified in the module config.
328
	 */
329
	public function get_where_sql( $config ) {
330
		if ( is_array( $config ) ) {
331
			return 'comment_ID IN (' . implode( ',', array_map( 'intval', $config ) ) . ')';
332
		}
333
334
		return '1=1';
335
	}
336
337
	/**
338
	 * Retrieve the actions that will be sent for this module during a full sync.
339
	 *
340
	 * @access public
341
	 *
342
	 * @return array Full sync actions of this module.
343
	 */
344
	public function get_full_sync_actions() {
345
		return array( 'jetpack_full_sync_comments' );
346
	}
347
348
	/**
349
	 * Count all the actions that are going to be sent.
350
	 *
351
	 * @access public
352
	 *
353
	 * @param array $action_names Names of all the actions that will be sent.
354
	 * @return int Number of actions.
355
	 */
356
	public function count_full_sync_actions( $action_names ) {
357
		return $this->count_actions( $action_names, array( 'jetpack_full_sync_comments' ) );
358
	}
359
360
	/**
361
	 * Expand the comment status change before the data is serialized and sent to the server.
362
	 *
363
	 * @access public
364
	 * @todo This is not used currently - let's implement it.
365
	 *
366
	 * @param array $args The hook parameters.
367
	 * @return array The expanded hook parameters.
368
	 */
369
	public function expand_wp_comment_status_change( $args ) {
370
		return array( $args[0], $this->filter_comment( $args[1] ) );
371
	}
372
373
	/**
374
	 * Expand the comment creation before the data is serialized and sent to the server.
375
	 *
376
	 * @access public
377
	 *
378
	 * @param array $args The hook parameters.
379
	 * @return array The expanded hook parameters.
380
	 */
381
	public function expand_wp_insert_comment( $args ) {
382
		return array( $args[0], $this->filter_comment( $args[1] ) );
383
	}
384
385
	/**
386
	 * Filter a comment object to the fields we need.
387
	 *
388
	 * @access public
389
	 *
390
	 * @param \WP_Comment $comment The unfiltered comment object.
391
	 * @return \WP_Comment Filtered comment object.
392
	 */
393
	public function filter_comment( $comment ) {
394
		/**
395
		 * Filters whether to prevent sending comment data to .com
396
		 *
397
		 * Passing true to the filter will prevent the comment data from being sent
398
		 * to the WordPress.com.
399
		 * Instead we pass data that will still enable us to do a checksum against the
400
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
401
		 * other services.
402
		 *
403
		 * @since 4.2.0
404
		 *
405
		 * @param boolean false prevent post data from bing synced to WordPress.com
406
		 * @param mixed $comment WP_COMMENT object
407
		 */
408
		if ( apply_filters( 'jetpack_sync_prevent_sending_comment_data', false, $comment ) ) {
409
			$blocked_comment                   = new \stdClass();
410
			$blocked_comment->comment_ID       = $comment->comment_ID;
411
			$blocked_comment->comment_date     = $comment->comment_date;
412
			$blocked_comment->comment_date_gmt = $comment->comment_date_gmt;
413
			$blocked_comment->comment_approved = 'jetpack_sync_blocked';
414
			return $blocked_comment;
415
		}
416
417
		return $comment;
418
	}
419
420
	/**
421
	 * Whether a certain comment meta key is whitelisted for sync.
422
	 *
423
	 * @access public
424
	 *
425
	 * @param string $meta_key Comment meta key.
426
	 * @return boolean Whether the meta key is whitelisted.
427
	 */
428
	public function is_whitelisted_comment_meta( $meta_key ) {
429
		return in_array( $meta_key, Settings::get_setting( 'comment_meta_whitelist' ), true );
430
	}
431
432
	/**
433
	 * Handler for filtering out non-whitelisted comment meta.
434
	 *
435
	 * @access public
436
	 *
437
	 * @param array $args Hook args.
438
	 * @return array|boolean False if not whitelisted, the original hook args otherwise.
439
	 */
440
	public function filter_meta( $args ) {
441
		return ( $this->is_whitelisted_comment_meta( $args[2] ) ? $args : false );
442
	}
443
444
	/**
445
	 * Expand the comment IDs to comment objects and meta before being serialized and sent to the server.
446
	 *
447
	 * @access public
448
	 *
449
	 * @param array $args The hook parameters.
450
	 * @return array The expanded hook parameters.
451
	 */
452
	public function expand_comment_ids( $args ) {
453
		list( $comment_ids, $previous_interval_end ) = $args;
454
		$comments                                    = get_comments(
455
			array(
456
				'include_unapproved' => true,
457
				'comment__in'        => $comment_ids,
458
				'orderby'            => 'comment_ID',
459
				'order'              => 'DESC',
460
			)
461
		);
462
463
		return array(
464
			$comments,
465
			$this->get_metadata( $comment_ids, 'comment', Settings::get_setting( 'comment_meta_whitelist' ) ),
466
			$previous_interval_end,
467
		);
468
	}
469
}
470