Completed
Push — renovate/pin-dependencies ( 14fe97...989735 )
by
unknown
30:07 queued 20:05
created

Posts::trim_post_meta()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * Posts sync module.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync\Modules;
9
10
use Automattic\Jetpack\Constants as Jetpack_Constants;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Sync\Settings;
13
14
/**
15
 * Class to handle sync for posts.
16
 */
17
class Posts extends Module {
18
	/**
19
	 * The post IDs of posts that were just published but not synced yet.
20
	 *
21
	 * @access private
22
	 *
23
	 * @var array
24
	 */
25
	private $just_published = array();
26
27
	/**
28
	 * The previous status of posts that we use for calculating post status transitions.
29
	 *
30
	 * @access private
31
	 *
32
	 * @var array
33
	 */
34
	private $previous_status = array();
35
36
	/**
37
	 * Action handler callable.
38
	 *
39
	 * @access private
40
	 *
41
	 * @var callable
42
	 */
43
	private $action_handler;
44
45
	/**
46
	 * Import end.
47
	 *
48
	 * @access private
49
	 *
50
	 * @todo This appears to be unused - let's remove it.
51
	 *
52
	 * @var boolean
53
	 */
54
	private $import_end = false;
55
56
	/**
57
	 * Max bytes allowed for post_content => length.
58
	 * Current Setting : 5MB.
59
	 *
60
	 * @access public
61
	 *
62
	 * @var int
63
	 */
64
	const MAX_POST_CONTENT_LENGTH = 5000000;
65
66
	/**
67
	 * Max bytes allowed for post meta_value => length.
68
	 * Current Setting : 2MB.
69
	 *
70
	 * @access public
71
	 *
72
	 * @var int
73
	 */
74
	const MAX_POST_META_LENGTH = 2000000;
75
76
	/**
77
	 * Default previous post state.
78
	 * Used for default previous post status.
79
	 *
80
	 * @access public
81
	 *
82
	 * @var string
83
	 */
84
	const DEFAULT_PREVIOUS_STATE = 'new';
85
86
	/**
87
	 * Sync module name.
88
	 *
89
	 * @access public
90
	 *
91
	 * @return string
92
	 */
93
	public function name() {
94
		return 'posts';
95
	}
96
97
	/**
98
	 * The table in the database.
99
	 *
100
	 * @access public
101
	 *
102
	 * @return string
103
	 */
104
	public function table_name() {
105
		return 'posts';
106
	}
107
108
	/**
109
	 * Retrieve a post by its ID.
110
	 *
111
	 * @access public
112
	 *
113
	 * @param string $object_type Type of the sync object.
114
	 * @param int    $id          ID of the sync object.
115
	 * @return \WP_Post|bool Filtered \WP_Post object, or false if the object is not a post.
116
	 */
117
	public function get_object_by_id( $object_type, $id ) {
118
		if ( 'post' === $object_type ) {
119
			$post = get_post( (int) $id );
120
			if ( $post ) {
121
				return $this->filter_post_content_and_add_links( $post );
122
			}
123
		}
124
125
		return false;
126
	}
127
128
	/**
129
	 * Initialize posts action listeners.
130
	 *
131
	 * @access public
132
	 *
133
	 * @param callable $callable Action handler callable.
134
	 */
135
	public function init_listeners( $callable ) {
136
		$this->action_handler = $callable;
137
138
		add_action( 'wp_insert_post', array( $this, 'wp_insert_post' ), 11, 3 );
139
		add_action( 'wp_after_insert_post', array( $this, 'wp_after_insert_post' ), 11, 2 );
140
		add_action( 'jetpack_sync_save_post', $callable, 10, 4 );
141
142
		add_action( 'deleted_post', $callable, 10 );
143
		add_action( 'jetpack_published_post', $callable, 10, 2 );
144
		add_filter( 'jetpack_sync_before_enqueue_deleted_post', array( $this, 'filter_blacklisted_post_types_deleted' ) );
145
146
		add_action( 'transition_post_status', array( $this, 'save_published' ), 10, 3 );
147
		add_filter( 'jetpack_sync_before_enqueue_jetpack_sync_save_post', array( $this, 'filter_blacklisted_post_types' ) );
148
149
		// Listen for meta changes.
150
		$this->init_listeners_for_meta_type( 'post', $callable );
151
		$this->init_meta_whitelist_handler( 'post', array( $this, 'filter_meta' ) );
152
153
		add_action( 'jetpack_daily_akismet_meta_cleanup_before', array( $this, 'daily_akismet_meta_cleanup_before' ) );
154
		add_action( 'jetpack_daily_akismet_meta_cleanup_after', array( $this, 'daily_akismet_meta_cleanup_after' ) );
155
		add_action( 'jetpack_post_meta_batch_delete', $callable, 10, 2 );
156
	}
157
158
	/**
159
	 * Before Akismet's daily cleanup of spam detection metadata.
160
	 *
161
	 * @access public
162
	 *
163
	 * @param array $feedback_ids IDs of feedback posts.
164
	 */
165
	public function daily_akismet_meta_cleanup_before( $feedback_ids ) {
166
		remove_action( 'deleted_post_meta', $this->action_handler );
167
168
		if ( ! is_array( $feedback_ids ) || count( $feedback_ids ) < 1 ) {
169
			return;
170
		}
171
172
		$ids_chunks = array_chunk( $feedback_ids, 100, false );
173
		foreach ( $ids_chunks as $chunk ) {
174
			/**
175
			 * Used for syncing deletion of batch post meta
176
			 *
177
			 * @since 6.1.0
178
			 *
179
			 * @module sync
180
			 *
181
			 * @param array $feedback_ids feedback post IDs
182
			 * @param string $meta_key to be deleted
183
			 */
184
			do_action( 'jetpack_post_meta_batch_delete', $chunk, '_feedback_akismet_values' );
185
		}
186
	}
187
188
	/**
189
	 * After Akismet's daily cleanup of spam detection metadata.
190
	 *
191
	 * @access public
192
	 *
193
	 * @param array $feedback_ids IDs of feedback posts.
194
	 */
195
	public function daily_akismet_meta_cleanup_after( $feedback_ids ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
196
		add_action( 'deleted_post_meta', $this->action_handler );
197
	}
198
199
	/**
200
	 * Initialize posts action listeners for full sync.
201
	 *
202
	 * @access public
203
	 *
204
	 * @param callable $callable Action handler callable.
205
	 */
206
	public function init_full_sync_listeners( $callable ) {
207
		add_action( 'jetpack_full_sync_posts', $callable ); // Also sends post meta.
208
	}
209
210
	/**
211
	 * Initialize the module in the sender.
212
	 *
213
	 * @access public
214
	 */
215
	public function init_before_send() {
216
		add_filter( 'jetpack_sync_before_send_jetpack_sync_save_post', array( $this, 'expand_jetpack_sync_save_post' ) );
217
218
		// meta.
219
		add_filter( 'jetpack_sync_before_send_added_post_meta', array( $this, 'trim_post_meta' ) );
220
		add_filter( 'jetpack_sync_before_send_updated_post_meta', array( $this, 'trim_post_meta' ) );
221
		add_filter( 'jetpack_sync_before_send_deleted_post_meta', array( $this, 'trim_post_meta' ) );
222
223
		// Full sync.
224
		add_filter( 'jetpack_sync_before_send_jetpack_full_sync_posts', array( $this, 'expand_post_ids' ) );
225
	}
226
227
	/**
228
	 * Enqueue the posts actions for full sync.
229
	 *
230
	 * @access public
231
	 *
232
	 * @param array   $config               Full sync configuration for this sync module.
233
	 * @param int     $max_items_to_enqueue Maximum number of items to enqueue.
234
	 * @param boolean $state                True if full sync has finished enqueueing this module, false otherwise.
235
	 * @return array Number of actions enqueued, and next module state.
236
	 */
237
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
238
		global $wpdb;
239
240
		return $this->enqueue_all_ids_as_action( 'jetpack_full_sync_posts', $wpdb->posts, 'ID', $this->get_where_sql( $config ), $max_items_to_enqueue, $state );
241
	}
242
243
	/**
244
	 * Retrieve an estimated number of actions that will be enqueued.
245
	 *
246
	 * @access public
247
	 *
248
	 * @todo Use $wpdb->prepare for the SQL query.
249
	 *
250
	 * @param array $config Full sync configuration for this sync module.
251
	 * @return array Number of items yet to be enqueued.
252
	 */
253 View Code Duplication
	public function estimate_full_sync_actions( $config ) {
254
		global $wpdb;
255
256
		$query = "SELECT count(*) FROM $wpdb->posts WHERE " . $this->get_where_sql( $config );
257
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
258
		$count = $wpdb->get_var( $query );
259
260
		return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
261
	}
262
263
	/**
264
	 * Retrieve the WHERE SQL clause based on the module config.
265
	 *
266
	 * @access public
267
	 *
268
	 * @param array $config Full sync configuration for this sync module.
269
	 * @return string WHERE SQL clause, or `null` if no comments are specified in the module config.
270
	 */
271 View Code Duplication
	public function get_where_sql( $config ) {
272
		$where_sql = Settings::get_blacklisted_post_types_sql();
273
274
		// Config is a list of post IDs to sync.
275
		if ( is_array( $config ) ) {
276
			$where_sql .= ' AND ID IN (' . implode( ',', array_map( 'intval', $config ) ) . ')';
277
		}
278
279
		return $where_sql;
280
	}
281
282
	/**
283
	 * Retrieve the actions that will be sent for this module during a full sync.
284
	 *
285
	 * @access public
286
	 *
287
	 * @return array Full sync actions of this module.
288
	 */
289
	public function get_full_sync_actions() {
290
		return array( 'jetpack_full_sync_posts' );
291
	}
292
293
	/**
294
	 * Filter meta arguments so that we don't sync meta_values over MAX_POST_META_LENGTH.
295
	 *
296
	 * @param array $args action arguments.
297
	 *
298
	 * @return array filtered action arguments.
299
	 */
300
	public function trim_post_meta( $args ) {
301
		list( $meta_id, $object_id, $meta_key, $meta_value ) = $args;
302
		// Explicitly truncate meta_value when it exceeds limit.
303
		// Large content will cause OOM issues and break Sync.
304
		$serialized_value = maybe_serialize( $meta_value );
305
		if ( strlen( $serialized_value ) >= self::MAX_POST_META_LENGTH ) {
306
			$meta_value = '';
307
		}
308
		return array( $meta_id, $object_id, $meta_key, $meta_value );
309
	}
310
311
	/**
312
	 * Process content before send.
313
	 *
314
	 * @param array $args Arguments of the `wp_insert_post` hook.
315
	 *
316
	 * @return array
317
	 */
318
	public function expand_jetpack_sync_save_post( $args ) {
319
		list( $post_id, $post, $update, $previous_state ) = $args;
320
		return array( $post_id, $this->filter_post_content_and_add_links( $post ), $update, $previous_state );
321
	}
322
323
	/**
324
	 * Filter all blacklisted post types.
325
	 *
326
	 * @param array $args Hook arguments.
327
	 * @return array|false Hook arguments, or false if the post type is a blacklisted one.
328
	 */
329
	public function filter_blacklisted_post_types_deleted( $args ) {
330
331
		// deleted_post is called after the SQL delete but before cache cleanup.
332
		// There is the potential we can't detect post_type at this point.
333
		if ( ! $this->is_post_type_allowed( $args[0] ) ) {
334
			return false;
335
		}
336
337
		return $args;
338
	}
339
340
	/**
341
	 * Filter all blacklisted post types.
342
	 *
343
	 * @param array $args Hook arguments.
344
	 * @return array|false Hook arguments, or false if the post type is a blacklisted one.
345
	 */
346
	public function filter_blacklisted_post_types( $args ) {
347
		$post = $args[1];
348
349
		if ( in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true ) ) {
350
			return false;
351
		}
352
353
		return $args;
354
	}
355
356
	/**
357
	 * Filter all meta that is not blacklisted, or is stored for a disallowed post type.
358
	 *
359
	 * @param array $args Hook arguments.
360
	 * @return array|false Hook arguments, or false if meta was filtered.
361
	 */
362
	public function filter_meta( $args ) {
363
		if ( $this->is_post_type_allowed( $args[1] ) && $this->is_whitelisted_post_meta( $args[2] ) ) {
364
			return $args;
365
		}
366
367
		return false;
368
	}
369
370
	/**
371
	 * Whether a post meta key is whitelisted.
372
	 *
373
	 * @param string $meta_key Meta key.
374
	 * @return boolean Whether the post meta key is whitelisted.
375
	 */
376
	public function is_whitelisted_post_meta( $meta_key ) {
377
		// The _wpas_skip_ meta key is used by Publicize.
378
		return in_array( $meta_key, Settings::get_setting( 'post_meta_whitelist' ), true ) || ( 0 === strpos( $meta_key, '_wpas_skip_' ) );
379
	}
380
381
	/**
382
	 * Whether a post type is allowed.
383
	 * A post type will be disallowed if it's present in the post type blacklist.
384
	 *
385
	 * @param int $post_id ID of the post.
386
	 * @return boolean Whether the post type is allowed.
387
	 */
388
	public function is_post_type_allowed( $post_id ) {
389
		$post = get_post( (int) $post_id );
390
391
		if ( isset( $post->post_type ) ) {
392
			return ! in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true );
393
		}
394
		return false;
395
	}
396
397
	/**
398
	 * Remove the embed shortcode.
399
	 *
400
	 * @global $wp_embed
401
	 */
402 View Code Duplication
	public function remove_embed() {
403
		global $wp_embed;
404
		remove_filter( 'the_content', array( $wp_embed, 'run_shortcode' ), 8 );
405
		// remove the embed shortcode since we would do the part later.
406
		remove_shortcode( 'embed' );
407
		// Attempts to embed all URLs in a post.
408
		remove_filter( 'the_content', array( $wp_embed, 'autoembed' ), 8 );
409
	}
410
411
	/**
412
	 * Add the embed shortcode.
413
	 *
414
	 * @global $wp_embed
415
	 */
416 View Code Duplication
	public function add_embed() {
417
		global $wp_embed;
418
		add_filter( 'the_content', array( $wp_embed, 'run_shortcode' ), 8 );
419
		// Shortcode placeholder for strip_shortcodes().
420
		add_shortcode( 'embed', '__return_false' );
421
		// Attempts to embed all URLs in a post.
422
		add_filter( 'the_content', array( $wp_embed, 'autoembed' ), 8 );
423
	}
424
425
	/**
426
	 * Expands wp_insert_post to include filtered content
427
	 *
428
	 * @param \WP_Post $post_object Post object.
429
	 */
430
	public function filter_post_content_and_add_links( $post_object ) {
431
		global $post;
432
		// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
433
		$post = $post_object;
434
435
		// Return non existant post.
436
		$post_type = get_post_type_object( $post->post_type );
437 View Code Duplication
		if ( empty( $post_type ) || ! is_object( $post_type ) ) {
438
			$non_existant_post                    = new \stdClass();
439
			$non_existant_post->ID                = $post->ID;
440
			$non_existant_post->post_modified     = $post->post_modified;
441
			$non_existant_post->post_modified_gmt = $post->post_modified_gmt;
442
			$non_existant_post->post_status       = 'jetpack_sync_non_registered_post_type';
443
			$non_existant_post->post_type         = $post->post_type;
444
445
			return $non_existant_post;
446
		}
447
		/**
448
		 * Filters whether to prevent sending post data to .com
449
		 *
450
		 * Passing true to the filter will prevent the post data from being sent
451
		 * to the WordPress.com.
452
		 * Instead we pass data that will still enable us to do a checksum against the
453
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
454
		 * other services.
455
		 *
456
		 * @since 4.2.0
457
		 *
458
		 * @param boolean false prevent post data from being synced to WordPress.com
459
		 * @param mixed $post \WP_Post object
460
		 */
461 View Code Duplication
		if ( apply_filters( 'jetpack_sync_prevent_sending_post_data', false, $post ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $post.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
462
			// We only send the bare necessary object to be able to create a checksum.
463
			$blocked_post                    = new \stdClass();
464
			$blocked_post->ID                = $post->ID;
465
			$blocked_post->post_modified     = $post->post_modified;
466
			$blocked_post->post_modified_gmt = $post->post_modified_gmt;
467
			$blocked_post->post_status       = 'jetpack_sync_blocked';
468
			$blocked_post->post_type         = $post->post_type;
469
470
			return $blocked_post;
471
		}
472
473
		// lets not do oembed just yet.
474
		$this->remove_embed();
475
476
		if ( 0 < strlen( $post->post_password ) ) {
477
			$post->post_password = 'auto-' . wp_generate_password( 10, false );
478
		}
479
480
		// Explicitly omit post_content when it exceeds limit.
481
		// Large content will cause OOM issues and break Sync.
482
		if ( strlen( $post->post_content ) >= self::MAX_POST_CONTENT_LENGTH ) {
483
			$post->post_content = '';
484
		}
485
486
		/** This filter is already documented in core. wp-includes/post-template.php */
487
		if ( Settings::get_setting( 'render_filtered_content' ) && $post_type->public ) {
488
			global $shortcode_tags;
489
			/**
490
			 * Filter prevents some shortcodes from expanding.
491
			 *
492
			 * Since we can can expand some type of shortcode better on the .com side and make the
493
			 * expansion more relevant to contexts. For example [galleries] and subscription emails
494
			 *
495
			 * @since 4.5.0
496
			 *
497
			 * @param array of shortcode tags to remove.
498
			 */
499
			$shortcodes_to_remove        = apply_filters(
500
				'jetpack_sync_do_not_expand_shortcodes',
501
				array(
502
					'gallery',
503
					'slideshow',
504
				)
505
			);
506
			$removed_shortcode_callbacks = array();
507
			foreach ( $shortcodes_to_remove as $shortcode ) {
508
				if ( isset( $shortcode_tags[ $shortcode ] ) ) {
509
					$removed_shortcode_callbacks[ $shortcode ] = $shortcode_tags[ $shortcode ];
510
				}
511
			}
512
513
			array_map( 'remove_shortcode', array_keys( $removed_shortcode_callbacks ) );
514
515
			$post->post_content_filtered = apply_filters( 'the_content', $post->post_content );
516
			$post->post_excerpt_filtered = apply_filters( 'the_excerpt', $post->post_excerpt );
517
518
			foreach ( $removed_shortcode_callbacks as $shortcode => $callback ) {
519
				add_shortcode( $shortcode, $callback );
520
			}
521
		}
522
523
		$this->add_embed();
524
525
		if ( has_post_thumbnail( $post->ID ) ) {
526
			$image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
527
			if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) {
528
				$post->featured_image = $image_attributes[0];
529
			}
530
		}
531
532
		$post->permalink = get_permalink( $post->ID );
533
		$post->shortlink = wp_get_shortlink( $post->ID );
534
535
		if ( function_exists( 'amp_get_permalink' ) ) {
536
			$post->amp_permalink = amp_get_permalink( $post->ID );
537
		}
538
539
		return $post;
540
	}
541
542
	/**
543
	 * Handle transition from another post status to a published one.
544
	 *
545
	 * @param string   $new_status New post status.
546
	 * @param string   $old_status Old post status.
547
	 * @param \WP_Post $post       Post object.
548
	 */
549
	public function save_published( $new_status, $old_status, $post ) {
550
		if ( 'publish' === $new_status && 'publish' !== $old_status ) {
551
			$this->just_published[ $post->ID ] = true;
552
		}
553
554
		$this->previous_status[ $post->ID ] = $old_status;
555
	}
556
557
	/**
558
	 * When publishing or updating a post, the Gutenberg editor sends two requests:
559
	 * 1. sent to WP REST API endpoint `wp-json/wp/v2/posts/$id`
560
	 * 2. sent to wp-admin/post.php `?post=$id&action=edit&classic-editor=1&meta_box=1`
561
	 *
562
	 * The 2nd request is to update post meta, which is not supported on WP REST API.
563
	 * When syncing post data, we will include if this was a meta box update.
564
	 *
565
	 * @todo Implement nonce verification.
566
	 *
567
	 * @return boolean Whether this is a Gutenberg meta box update.
568
	 */
569
	public function is_gutenberg_meta_box_update() {
570
		// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
571
		return (
572
			isset( $_POST['action'], $_GET['classic-editor'], $_GET['meta_box'] ) &&
573
			'editpost' === $_POST['action'] &&
574
			'1' === $_GET['classic-editor'] &&
575
			'1' === $_GET['meta_box']
576
			// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
577
		);
578
	}
579
580
	/**
581
	 * Handler for the wp_insert_post hook.
582
	 * Called upon creation of a new post.
583
	 *
584
	 * @param int      $post_ID Post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $post not be \WP_Post|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
585
	 * @param \WP_Post $post    Post object.
586
	 * @param boolean  $update  Whether this is an existing post being updated or not.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $update not be boolean|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
587
	 */
588
	public function wp_insert_post( $post_ID, $post = null, $update = null ) {
589
		if ( ! is_numeric( $post_ID ) || is_null( $post ) ) {
590
			return;
591
		}
592
593
		// Workaround for https://github.com/woocommerce/woocommerce/issues/18007.
594
		if ( $post && 'shop_order' === $post->post_type ) {
595
			$post = get_post( $post_ID );
596
		}
597
598
		$previous_status = isset( $this->previous_status[ $post_ID ] ) ? $this->previous_status[ $post_ID ] : self::DEFAULT_PREVIOUS_STATE;
599
600
		$just_published = isset( $this->just_published[ $post_ID ] ) ? $this->just_published[ $post_ID ] : false;
601
602
		$state = array(
603
			'is_auto_save'                 => (bool) Jetpack_Constants::get_constant( 'DOING_AUTOSAVE' ),
604
			'previous_status'              => $previous_status,
605
			'just_published'               => $just_published,
606
			'is_gutenberg_meta_box_update' => $this->is_gutenberg_meta_box_update(),
607
		);
608
		/**
609
		 * Filter that is used to add to the post flags ( meta data ) when a post gets published
610
		 *
611
		 * @since 5.8.0
612
		 *
613
		 * @param int $post_ID the post ID
614
		 * @param mixed $post \WP_Post object
615
		 * @param bool $update Whether this is an existing post being updated or not.
616
		 * @param mixed $state state
617
		 *
618
		 * @module sync
619
		 */
620
		do_action( 'jetpack_sync_save_post', $post_ID, $post, $update, $state );
621
		unset( $this->previous_status[ $post_ID ] );
622
	}
623
624
	/**
625
	 * Handler for the wp_after_insert_post hook.
626
	 * Called after creation/update of a new post.
627
	 *
628
	 * @param int      $post_ID Post ID.
629
	 * @param \WP_Post $post    Post object.
630
	 **/
631
	public function wp_after_insert_post( $post_ID, $post ) {
632
		if ( ! is_numeric( $post_ID ) || is_null( $post ) ) {
633
			return;
634
		}
635
636
		// Workaround for https://github.com/woocommerce/woocommerce/issues/18007.
637
		if ( $post && 'shop_order' === $post->post_type ) {
638
			$post = get_post( $post_ID );
639
		}
640
641
		$this->send_published( $post_ID, $post );
642
	}
643
644
	/**
645
	 * Send a published post for sync.
646
	 *
647
	 * @param int      $post_ID Post ID.
648
	 * @param \WP_Post $post    Post object.
649
	 */
650
	public function send_published( $post_ID, $post ) {
651
		if ( ! isset( $this->just_published[ $post_ID ] ) ) {
652
			return;
653
		}
654
655
		// Post revisions cause race conditions where this send_published add the action before the actual post gets synced.
656
		if ( wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
657
			return;
658
		}
659
660
		$post_flags = array(
661
			'post_type' => $post->post_type,
662
		);
663
664
		$author_user_object = get_user_by( 'id', $post->post_author );
665
		if ( $author_user_object ) {
666
			$roles = new Roles();
667
668
			$post_flags['author'] = array(
669
				'id'              => $post->post_author,
670
				'wpcom_user_id'   => get_user_meta( $post->post_author, 'wpcom_user_id', true ),
671
				'display_name'    => $author_user_object->display_name,
672
				'email'           => $author_user_object->user_email,
673
				'translated_role' => $roles->translate_user_to_role( $author_user_object ),
674
			);
675
		}
676
677
		/**
678
		 * Filter that is used to add to the post flags ( meta data ) when a post gets published
679
		 *
680
		 * @since 4.4.0
681
		 *
682
		 * @param mixed array post flags that are added to the post
683
		 * @param mixed $post \WP_Post object
684
		 */
685
		$flags = apply_filters( 'jetpack_published_post_flags', $post_flags, $post );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $post.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
686
687
		// Only Send Pulished Post event if post_type is not blacklisted.
688
		if ( ! in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true ) ) {
689
			/**
690
			 * Action that gets synced when a post type gets published.
691
			 *
692
			 * @since 4.4.0
693
			 *
694
			 * @param int $post_ID
695
			 * @param mixed array $flags post flags that are added to the post
696
			 */
697
			do_action( 'jetpack_published_post', $post_ID, $flags );
698
		}
699
		unset( $this->just_published[ $post_ID ] );
700
701
		/**
702
		 * Send additional sync action for Activity Log when post is a Customizer publish
703
		 */
704
		if ( 'customize_changeset' === $post->post_type ) {
705
			$post_content = json_decode( $post->post_content, true );
706
			foreach ( $post_content as $key => $value ) {
707
				// Skip if it isn't a widget.
708
				if ( 'widget_' !== substr( $key, 0, strlen( 'widget_' ) ) ) {
709
					continue;
710
				}
711
				// Change key from "widget_archives[2]" to "archives-2".
712
				$key = str_replace( 'widget_', '', $key );
713
				$key = str_replace( '[', '-', $key );
714
				$key = str_replace( ']', '', $key );
715
716
				global $wp_registered_widgets;
717
				if ( isset( $wp_registered_widgets[ $key ] ) ) {
718
					$widget_data = array(
719
						'name'  => $wp_registered_widgets[ $key ]['name'],
720
						'id'    => $key,
721
						'title' => $value['value']['title'],
722
					);
723
					do_action( 'jetpack_widget_edited', $widget_data );
724
				}
725
			}
726
		}
727
	}
728
729
	/**
730
	 * Expand post IDs to post objects within a hook before they are serialized and sent to the server.
731
	 *
732
	 * @access public
733
	 *
734
	 * @param array $args The hook parameters.
735
	 * @return array $args The expanded hook parameters.
736
	 */
737
	public function expand_post_ids( $args ) {
738
		list( $post_ids, $previous_interval_end) = $args;
739
740
		$posts = array_filter( array_map( array( 'WP_Post', 'get_instance' ), $post_ids ) );
741
		$posts = array_map( array( $this, 'filter_post_content_and_add_links' ), $posts );
742
		$posts = array_values( $posts ); // Reindex in case posts were deleted.
743
744
		return array(
745
			$posts,
746
			$this->get_metadata( $post_ids, 'post', Settings::get_setting( 'post_meta_whitelist' ) ),
747
			$this->get_term_relationships( $post_ids ),
748
			$previous_interval_end,
749
		);
750
	}
751
752
	/**
753
	 * Gets a list of minimum and maximum object ids for each batch based on the given batch size.
754
	 *
755
	 * @access public
756
	 *
757
	 * @param int         $batch_size The batch size for objects.
758
	 * @param string|bool $where_sql  The sql where clause minus 'WHERE', or false if no where clause is needed.
759
	 *
760
	 * @return array|bool An array of min and max ids for each batch. FALSE if no table can be found.
761
	 */
762
	public function get_min_max_object_ids_for_batches( $batch_size, $where_sql = false ) {
763
		return parent::get_min_max_object_ids_for_batches( $batch_size, $this->get_where_sql( $where_sql ) );
0 ignored issues
show
Documentation introduced by
$where_sql is of type string|boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
764
	}
765
}
766