summaryrefslogtreecommitdiff
blob: e956748cd900d38442799cd6b8a41f7a40a78193 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
<?php
/**
 * Comments sync module.
 *
 * @package automattic/jetpack-sync
 */

namespace Automattic\Jetpack\Sync\Modules;

use Automattic\Jetpack\Sync\Settings;

/**
 * Class to handle sync for comments.
 */
class Comments extends Module {
	/**
	 * Sync module name.
	 *
	 * @access public
	 *
	 * @return string
	 */
	public function name() {
		return 'comments';
	}

	/**
	 * The id field in the database.
	 *
	 * @access public
	 *
	 * @return string
	 */
	public function id_field() {
		return 'comment_ID';
	}

	/**
	 * The table in the database.
	 *
	 * @access public
	 *
	 * @return string
	 */
	public function table_name() {
		return 'comments';
	}

	/**
	 * Retrieve a comment by its ID.
	 *
	 * @access public
	 *
	 * @param string $object_type Type of the sync object.
	 * @param int    $id          ID of the sync object.
	 * @return \WP_Comment|bool Filtered \WP_Comment object, or false if the object is not a comment.
	 */
	public function get_object_by_id( $object_type, $id ) {
		$comment_id = intval( $id );
		if ( 'comment' === $object_type ) {
			$comment = get_comment( $comment_id );
			if ( $comment ) {
				return $this->filter_comment( $comment );
			}
		}

		return false;
	}

	/**
	 * Initialize comments action listeners.
	 * Also responsible for initializing comment meta listeners.
	 *
	 * @access public
	 *
	 * @param callable $callable Action handler callable.
	 */
	public function init_listeners( $callable ) {
		add_action( 'wp_insert_comment', $callable, 10, 2 );
		add_action( 'deleted_comment', $callable );
		add_action( 'trashed_comment', $callable );
		add_action( 'spammed_comment', $callable );
		add_action( 'trashed_post_comments', $callable, 10, 2 );
		add_action( 'untrash_post_comments', $callable );
		add_action( 'comment_approved_to_unapproved', $callable );
		add_action( 'comment_unapproved_to_approved', $callable );
		add_action( 'jetpack_modified_comment_contents', $callable, 10, 2 );
		add_action( 'untrashed_comment', $callable, 10, 2 );
		add_action( 'unspammed_comment', $callable, 10, 2 );
		add_filter( 'wp_update_comment_data', array( $this, 'handle_comment_contents_modification' ), 10, 3 );
		add_filter( 'jetpack_sync_before_enqueue_wp_insert_comment', array( $this, 'only_allow_white_listed_comment_types' ) );

		/**
		 * Even though it's messy, we implement these hooks because
		 * the edit_comment hook doesn't include the data
		 * so this saves us a DB read for every comment event.
		 */
		foreach ( $this->get_whitelisted_comment_types() as $comment_type ) {
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
				add_action( $comment_action_name, $callable, 10, 2 );
			}
		}

		// Listen for meta changes.
		$this->init_listeners_for_meta_type( 'comment', $callable );
		$this->init_meta_whitelist_handler( 'comment', array( $this, 'filter_meta' ) );
	}

	/**
	 * Handler for any comment content updates.
	 *
	 * @access public
	 *
	 * @param array $new_comment              The new, processed comment data.
	 * @param array $old_comment              The old, unslashed comment data.
	 * @param array $new_comment_with_slashes The new, raw comment data.
	 * @return array The new, processed comment data.
	 */
	public function handle_comment_contents_modification( $new_comment, $old_comment, $new_comment_with_slashes ) {
		$changes        = array();
		$content_fields = array(
			'comment_author',
			'comment_author_email',
			'comment_author_url',
			'comment_content',
		);
		foreach ( $content_fields as $field ) {
			if ( $new_comment_with_slashes[ $field ] !== $old_comment[ $field ] ) {
				$changes[ $field ] = array( $new_comment[ $field ], $old_comment[ $field ] );
			}
		}

		if ( ! empty( $changes ) ) {
			/**
			 * Signals to the sync listener that this comment's contents were modified and a sync action
			 * reflecting the change(s) to the content should be sent
			 *
			 * @since 4.9.0
			 *
			 * @param int $new_comment['comment_ID'] ID of comment whose content was modified
			 * @param mixed $changes Array of changed comment fields with before and after values
			 */
			do_action( 'jetpack_modified_comment_contents', $new_comment['comment_ID'], $changes );
		}
		return $new_comment;
	}

	/**
	 * Initialize comments action listeners for full sync.
	 *
	 * @access public
	 *
	 * @param callable $callable Action handler callable.
	 */
	public function init_full_sync_listeners( $callable ) {
		add_action( 'jetpack_full_sync_comments', $callable ); // Also send comments meta.
	}

	/**
	 * Gets a filtered list of comment types that sync can hook into.
	 *
	 * @access public
	 *
	 * @return array Defaults to [ '', 'trackback', 'pingback' ].
	 */
	public function get_whitelisted_comment_types() {
		/**
		 * Comment types present in this list will sync their status changes to WordPress.com.
		 *
		 * @since 7.6.0
		 *
		 * @param array A list of comment types.
		 */
		return apply_filters(
			'jetpack_sync_whitelisted_comment_types',
			array( '', 'trackback', 'pingback' )
		);
	}

	/**
	 * Prevents any comment types that are not in the whitelist from being enqueued and sent to WordPress.com.
	 *
	 * @param array $args Arguments passed to wp_insert_comment.
	 *
	 * @return bool or array $args Arguments passed to wp_insert_comment
	 */
	public function only_allow_white_listed_comment_types( $args ) {
		$comment = $args[1];

		if ( ! in_array( $comment->comment_type, $this->get_whitelisted_comment_types(), true ) ) {
			return false;
		}

		return $args;
	}

	/**
	 * Initialize the module in the sender.
	 *
	 * @access public
	 */
	public function init_before_send() {
		add_filter( 'jetpack_sync_before_send_wp_insert_comment', array( $this, 'expand_wp_insert_comment' ) );

		foreach ( $this->get_whitelisted_comment_types() as $comment_type ) {
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
				add_filter(
					'jetpack_sync_before_send_' . $comment_action_name,
					array(
						$this,
						'expand_wp_insert_comment',
					)
				);
			}
		}

		// Full sync.
		add_filter( 'jetpack_sync_before_send_jetpack_full_sync_comments', array( $this, 'expand_comment_ids' ) );
	}

	/**
	 * Enqueue the comments actions for full sync.
	 *
	 * @access public
	 *
	 * @param array   $config               Full sync configuration for this sync module.
	 * @param int     $max_items_to_enqueue Maximum number of items to enqueue.
	 * @param boolean $state                True if full sync has finished enqueueing this module, false otherwise.
	 * @return array Number of actions enqueued, and next module state.
	 */
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
		global $wpdb;
		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 );
	}

	/**
	 * Retrieve an estimated number of actions that will be enqueued.
	 *
	 * @access public
	 *
	 * @param array $config Full sync configuration for this sync module.
	 * @return int Number of items yet to be enqueued.
	 */
	public function estimate_full_sync_actions( $config ) {
		global $wpdb;

		$query = "SELECT count(*) FROM $wpdb->comments";

		$where_sql = $this->get_where_sql( $config );
		if ( $where_sql ) {
			$query .= ' WHERE ' . $where_sql;
		}

		// TODO: Call $wpdb->prepare on the following query.
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$count = $wpdb->get_var( $query );

		return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
	}

	/**
	 * Retrieve the WHERE SQL clause based on the module config.
	 *
	 * @access public
	 *
	 * @param array $config Full sync configuration for this sync module.
	 * @return string WHERE SQL clause, or `null` if no comments are specified in the module config.
	 */
	public function get_where_sql( $config ) {
		if ( is_array( $config ) ) {
			return 'comment_ID IN (' . implode( ',', array_map( 'intval', $config ) ) . ')';
		}

		return null;
	}

	/**
	 * Retrieve the actions that will be sent for this module during a full sync.
	 *
	 * @access public
	 *
	 * @return array Full sync actions of this module.
	 */
	public function get_full_sync_actions() {
		return array( 'jetpack_full_sync_comments' );
	}

	/**
	 * Count all the actions that are going to be sent.
	 *
	 * @access public
	 *
	 * @param array $action_names Names of all the actions that will be sent.
	 * @return int Number of actions.
	 */
	public function count_full_sync_actions( $action_names ) {
		return $this->count_actions( $action_names, array( 'jetpack_full_sync_comments' ) );
	}

	/**
	 * Expand the comment status change before the data is serialized and sent to the server.
	 *
	 * @access public
	 * @todo This is not used currently - let's implement it.
	 *
	 * @param array $args The hook parameters.
	 * @return array The expanded hook parameters.
	 */
	public function expand_wp_comment_status_change( $args ) {
		return array( $args[0], $this->filter_comment( $args[1] ) );
	}

	/**
	 * Expand the comment creation before the data is serialized and sent to the server.
	 *
	 * @access public
	 *
	 * @param array $args The hook parameters.
	 * @return array The expanded hook parameters.
	 */
	public function expand_wp_insert_comment( $args ) {
		return array( $args[0], $this->filter_comment( $args[1] ) );
	}

	/**
	 * Filter a comment object to the fields we need.
	 *
	 * @access public
	 *
	 * @param \WP_Comment $comment The unfiltered comment object.
	 * @return \WP_Comment Filtered comment object.
	 */
	public function filter_comment( $comment ) {
		/**
		 * Filters whether to prevent sending comment data to .com
		 *
		 * Passing true to the filter will prevent the comment data from being sent
		 * to the WordPress.com.
		 * Instead we pass data that will still enable us to do a checksum against the
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
		 * other services.
		 *
		 * @since 4.2.0
		 *
		 * @param boolean false prevent post data from bing synced to WordPress.com
		 * @param mixed $comment WP_COMMENT object
		 */
		if ( apply_filters( 'jetpack_sync_prevent_sending_comment_data', false, $comment ) ) {
			$blocked_comment                   = new \stdClass();
			$blocked_comment->comment_ID       = $comment->comment_ID;
			$blocked_comment->comment_date     = $comment->comment_date;
			$blocked_comment->comment_date_gmt = $comment->comment_date_gmt;
			$blocked_comment->comment_approved = 'jetpack_sync_blocked';
			return $blocked_comment;
		}

		return $comment;
	}

	/**
	 * Whether a certain comment meta key is whitelisted for sync.
	 *
	 * @access public
	 *
	 * @param string $meta_key Comment meta key.
	 * @return boolean Whether the meta key is whitelisted.
	 */
	public function is_whitelisted_comment_meta( $meta_key ) {
		return in_array( $meta_key, Settings::get_setting( 'comment_meta_whitelist' ), true );
	}

	/**
	 * Handler for filtering out non-whitelisted comment meta.
	 *
	 * @access public
	 *
	 * @param array $args Hook args.
	 * @return array|boolean False if not whitelisted, the original hook args otherwise.
	 */
	public function filter_meta( $args ) {
		return ( $this->is_whitelisted_comment_meta( $args[2] ) ? $args : false );
	}

	/**
	 * Expand the comment IDs to comment objects and meta before being serialized and sent to the server.
	 *
	 * @access public
	 *
	 * @param array $args The hook parameters.
	 * @return array The expanded hook parameters.
	 */
	public function expand_comment_ids( $args ) {
		list( $comment_ids, $previous_interval_end ) = $args;
		$comments                                    = get_comments(
			array(
				'include_unapproved' => true,
				'comment__in'        => $comment_ids,
				'orderby'            => 'comment_ID',
				'order'              => 'DESC',
			)
		);

		return array(
			$comments,
			$this->get_metadata( $comment_ids, 'comment', Settings::get_setting( 'comment_meta_whitelist' ) ),
			$previous_interval_end,
		);
	}
}