Completed
Push — update/group-save-post-sync ( c97a0d )
by
unknown
38:18 queued 31:27
created

Posts::maybe_initialize_post_sync_item_referer()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
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
use Automattic\Jetpack\Sync\Item;
14
15
/**
16
 * Class to handle sync for posts.
17
 */
18
class Posts extends Module {
19
20
	/**
21
	 * Action handler callable.
22
	 *
23
	 * @access private
24
	 *
25
	 * @var callable
26
	 */
27
	private $action_handler;
28
29
	/**
30
	 * Import end.
31
	 *
32
	 * @access private
33
	 *
34
	 * @todo This appears to be unused - let's remove it.
35
	 *
36
	 * @var boolean
37
	 */
38
	private $import_end = false;
39
40
	/**
41
	 * Default previous post state.
42
	 * Used for default previous post status.
43
	 *
44
	 * @access public
45
	 *
46
	 * @var string
47
	 */
48
	const DEFAULT_PREVIOUS_STATE = 'new';
49
50
	/**
51
	 * Sync module name.
52
	 *
53
	 * @access public
54
	 *
55
	 * @return string
56
	 */
57
	public function name() {
58
		return 'posts';
59
	}
60
61
	/**
62
	 * The table in the database.
63
	 *
64
	 * @access public
65
	 *
66
	 * @return string
67
	 */
68
	public function table_name() {
69
		return 'posts';
70
	}
71
72
	/**
73
	 * Retrieve a post by its ID.
74
	 *
75
	 * @access public
76
	 *
77
	 * @param string $object_type Type of the sync object.
78
	 * @param int    $id          ID of the sync object.
79
	 * @return \WP_Post|bool Filtered \WP_Post object, or false if the object is not a post.
80
	 */
81
	public function get_object_by_id( $object_type, $id ) {
82
		if ( 'post' === $object_type ) {
83
			$post = get_post( intval( $id ) );
84
			if ( $post ) {
85
				return $this->filter_post_content_and_add_links( $post );
86
			}
87
		}
88
89
		return false;
90
	}
91
92
	/**
93
	 * Initialize posts action listeners.
94
	 *
95
	 * @access public
96
	 *
97
	 * @param callable $callable Action handler callable.
98
	 */
99
	public function init_listeners( $callable ) {
100
		$this->action_handler = $callable;
101
102
		// Our aim is to initialize `sync_items` as early as possible, so that other areas of the code base can know
103
		// that we are within a post-saving operation. `wp_insert_post_parent` happens early within the action stack.
104
		// And we can catch editpost actions early by hooking to `check_admin_referrer`.
105
		add_filter( 'wp_insert_post_parent', array( $this, 'maybe_initialize_post_sync_item' ), 10, 3 );
106
		add_action( 'check_admin_referer', array( $this, 'maybe_initialize_post_sync_item_referer' ), 10, 2 );
107
108
		add_action( 'wp_insert_post', array( $this, 'wp_insert_post' ), 11, 3 );
109
		add_action( 'jetpack_sync_save_post', $callable, 10, 4 );
110
111
		add_action( 'deleted_post', $callable, 10 );
112
		add_action( 'jetpack_published_post', $callable, 10, 2 );
113
114
		add_action( 'transition_post_status', array( $this, 'save_published' ), 10, 3 );
115
		add_filter( 'jetpack_sync_before_enqueue_jetpack_sync_save_post', array( $this, 'filter_blacklisted_post_types' ) );
116
117
		// Listen for meta changes.
118
		$this->init_listeners_for_meta_type( 'post', $callable );
119
		$this->init_meta_whitelist_handler( 'post', array( $this, 'filter_meta' ) );
120
121
		add_action( 'jetpack_daily_akismet_meta_cleanup_before', array( $this, 'daily_akismet_meta_cleanup_before' ) );
122
		add_action( 'jetpack_daily_akismet_meta_cleanup_after', array( $this, 'daily_akismet_meta_cleanup_after' ) );
123
		add_action( 'jetpack_post_meta_batch_delete', $callable, 10, 2 );
124
	}
125
126
	/**
127
	 * Initalizes the post sync item early.
128
	 *
129
	 * @param int   $post_parent Post Parent ID.
130
	 * @param int   $post_ID Post ID.
131
	 * @param array $args an Array containing post data.
132
	 *
133
	 * @return mixed
134
	 */
135
	public function maybe_initialize_post_sync_item( $post_parent, $post_ID, $args ) {
136
		if ( $post_ID ) {
137
			$this->set_post_sync_item( $post_ID );
138
		} elseif ( ! $this->is_attachment( $args ) ) {
139
			$this->set_post_sync_item( 'new' );
140
		}
141
		return $post_parent;
142
	}
143
144
	/**
145
	 * Initalizes the post sync item early.
146
	 *
147
	 * @param string $action Not used.
148
	 * @param array  $result Used to check if it is not tull.
149
	 */
150
	public function maybe_initialize_post_sync_item_referer( $action, $result ) {
151
		if ( ! $this->is_valid_editpost_action( $result ) ) {
0 ignored issues
show
Documentation introduced by
$result is of type array, but the function expects a boolean.

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...
152
			return;
153
		}
154
		$post_ID = $this->get_post_id_from_post_request();
155
		if ( ! $post_ID ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $post_ID of type null|integer is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
156
			return;
157
		}
158
		$this->set_post_sync_item( $post_ID );
159
	}
160
161
	/**
162
	 * Sets the post sync item.
163
	 *
164
	 * @param int|string $post_ID Key under which to store the Sync Item on.
165
	 *
166
	 * @return Item
167
	 */
168
	private function set_post_sync_item( $post_ID ) {
169
		if ( $this->has_sync_item( $post_ID ) ) {
170
			return;
171
		}
172
		if ( $this->has_sync_item( 'new' ) && 'new' !== $post_ID ) {
173
			$this->sync_items[ $post_ID ] = $this->sync_items['new'];
0 ignored issues
show
Bug introduced by
The property sync_items does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
174
			unset( $this->sync_items['new'] );
175
			return;
176
		}
177
		$this->sync_items[ $post_ID ] = new Item( 'save_post' );
178
	}
179
180
	/**
181
	 * Check if the post type is an attachment.
182
	 *
183
	 * @param array $args Post Arguments.
184
	 *
185
	 * @return bool
186
	 */
187
	private function is_attachment( $args ) {
188
		return ( isset( $args['post_type'] ) && 'attachment' === $args['post_type'] );
189
	}
190
191
	/**
192
	 * Checks if we already have a sync item with a particular post ID.
193
	 *
194
	 * @param string|int $post_ID Post Id.
195
	 *
196
	 * @return bool
197
	 */
198
	private function has_sync_item( $post_ID ) {
199
		return isset( $this->sync_items[ $post_ID ] );
200
	}
201
202
	/**
203
	 * Gets the post sync item.
204
	 *
205
	 * @param string|int $post_ID Post Id.
206
	 *
207
	 * @return Item
208
	 */
209
	private function get_post_sync_item( $post_ID ) {
210
		$this->set_post_sync_item( $post_ID );
211
		return $this->sync_items[ $post_ID ];
212
	}
213
214
	/**
215
	 * Checks if we area dealing with a valid post action.
216
	 *
217
	 * @param bool $result Result of the post edit action.
218
	 *
219
	 * @return bool
220
	 */
221
	private function is_valid_editpost_action( $result ) {
222
		if ( ! $result ) {
223
			return false;
224
		}
225
		if ( 'POST' !== $_SERVER['REQUEST_METHOD'] || ! isset( $_POST['action'] ) || ! isset( $_POST['post_ID'] ) ) {  // phpcs:ignore WordPress.Security.NonceVerification.Missing
226
			return false;
227
		}
228
		if ( 'editpost' !== $_POST['action'] ) {  // phpcs:ignore WordPress.Security.NonceVerification.Missing
229
			return false;
230
		}
231
		return true;
232
	}
233
234
	/**
235
	 * Gets the post ID from a post request.
236
	 *
237
	 * @return int|null Post Id.
238
	 */
239
	private function get_post_id_from_post_request() {
240
		if ( ! isset( $_POST['post_ID'] ) ) {  // phpcs:ignore WordPress.Security.NonceVerification.Missing
241
			return null;
242
		}
243
		return (int) $_POST['post_ID'];  // phpcs:ignore WordPress.Security.NonceVerification.Missing
244
	}
245
246
	/**
247
	 * Before Akismet's daily cleanup of spam detection metadata.
248
	 *
249
	 * @access public
250
	 *
251
	 * @param array $feedback_ids IDs of feedback posts.
252
	 */
253
	public function daily_akismet_meta_cleanup_before( $feedback_ids ) {
254
		remove_action( 'deleted_post_meta', $this->action_handler );
255
		/**
256
		 * Used for syncing deletion of batch post meta
257
		 *
258
		 * @since 6.1.0
259
		 *
260
		 * @module sync
261
		 *
262
		 * @param array $feedback_ids feedback post IDs
263
		 * @param string $meta_key to be deleted
264
		 */
265
		do_action( 'jetpack_post_meta_batch_delete', $feedback_ids, '_feedback_akismet_values' );
266
	}
267
268
	/**
269
	 * After Akismet's daily cleanup of spam detection metadata.
270
	 *
271
	 * @access public
272
	 *
273
	 * @param array $feedback_ids IDs of feedback posts.
274
	 */
275
	public function daily_akismet_meta_cleanup_after( $feedback_ids ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
276
		add_action( 'deleted_post_meta', $this->action_handler );
277
	}
278
279
	/**
280
	 * Initialize posts action listeners for full sync.
281
	 *
282
	 * @access public
283
	 *
284
	 * @param callable $callable Action handler callable.
285
	 */
286
	public function init_full_sync_listeners( $callable ) {
287
		add_action( 'jetpack_full_sync_posts', $callable ); // Also sends post meta.
288
	}
289
290
	/**
291
	 * Initialize the module in the sender.
292
	 *
293
	 * @access public
294
	 */
295
	public function init_before_send() {
296
		add_filter( 'jetpack_sync_before_send_jetpack_sync_save_post', array( $this, 'expand_jetpack_sync_save_post' ) );
297
298
		// Full sync.
299
		add_filter( 'jetpack_sync_before_send_jetpack_full_sync_posts', array( $this, 'expand_post_ids' ) );
300
	}
301
302
	/**
303
	 * Enqueue the posts actions for full sync.
304
	 *
305
	 * @access public
306
	 *
307
	 * @param array   $config               Full sync configuration for this sync module.
308
	 * @param int     $max_items_to_enqueue Maximum number of items to enqueue.
309
	 * @param boolean $state                True if full sync has finished enqueueing this module, false otherwise.
310
	 * @return array Number of actions enqueued, and next module state.
311
	 */
312
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
313
		global $wpdb;
314
315
		return $this->enqueue_all_ids_as_action( 'jetpack_full_sync_posts', $wpdb->posts, 'ID', $this->get_where_sql( $config ), $max_items_to_enqueue, $state );
316
	}
317
318
	/**
319
	 * Retrieve an estimated number of actions that will be enqueued.
320
	 *
321
	 * @access public
322
	 *
323
	 * @todo Use $wpdb->prepare for the SQL query.
324
	 *
325
	 * @param array $config Full sync configuration for this sync module.
326
	 * @return array Number of items yet to be enqueued.
327
	 */
328 View Code Duplication
	public function estimate_full_sync_actions( $config ) {
329
		global $wpdb;
330
331
		$query = "SELECT count(*) FROM $wpdb->posts WHERE " . $this->get_where_sql( $config );
332
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
333
		$count = $wpdb->get_var( $query );
334
335
		return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
336
	}
337
338
	/**
339
	 * Retrieve the WHERE SQL clause based on the module config.
340
	 *
341
	 * @access public
342
	 *
343
	 * @param array $config Full sync configuration for this sync module.
344
	 * @return string WHERE SQL clause, or `null` if no comments are specified in the module config.
345
	 */
346 View Code Duplication
	public function get_where_sql( $config ) {
347
		$where_sql = Settings::get_blacklisted_post_types_sql();
348
349
		// Config is a list of post IDs to sync.
350
		if ( is_array( $config ) ) {
351
			$where_sql .= ' AND ID IN (' . implode( ',', array_map( 'intval', $config ) ) . ')';
352
		}
353
354
		return $where_sql;
355
	}
356
357
	/**
358
	 * Retrieve the actions that will be sent for this module during a full sync.
359
	 *
360
	 * @access public
361
	 *
362
	 * @return array Full sync actions of this module.
363
	 */
364
	public function get_full_sync_actions() {
365
		return array( 'jetpack_full_sync_posts' );
366
	}
367
368
	/**
369
	 * Process content before send.
370
	 *
371
	 * @param array $args Arguments of the `wp_insert_post` hook.
372
	 *
373
	 * @return array
374
	 */
375
	public function expand_jetpack_sync_save_post( $args ) {
376
		list( $post_id, $post, $update, $previous_state ) = $args;
377
		return array( $post_id, $this->filter_post_content_and_add_links( $post ), $update, $previous_state );
378
	}
379
380
	/**
381
	 * Filter all blacklisted post types.
382
	 *
383
	 * @param array $args Hook arguments.
384
	 * @return array|false Hook arguments, or false if the post type is a blacklisted one.
385
	 */
386
	public function filter_blacklisted_post_types( $args ) {
387
		$post = $args[1];
388
389
		if ( in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true ) ) {
390
			return false;
391
		}
392
393
		return $args;
394
	}
395
396
	/**
397
	 * Filter all meta that is not blacklisted, or is stored for a disallowed post type.
398
	 *
399
	 * @param array $args Hook arguments.
400
	 * @return array|false Hook arguments, or false if meta was filtered.
401
	 */
402
	public function filter_meta( $args ) {
403
		if ( $this->is_post_type_allowed( $args[1] ) && $this->is_whitelisted_post_meta( $args[2] ) ) {
404
			return $args;
405
		}
406
407
		return false;
408
	}
409
410
	/**
411
	 * Whether a post meta key is whitelisted.
412
	 *
413
	 * @param string $meta_key Meta key.
414
	 * @return boolean Whether the post meta key is whitelisted.
415
	 */
416
	public function is_whitelisted_post_meta( $meta_key ) {
417
		// The _wpas_skip_ meta key is used by Publicize.
418
		return in_array( $meta_key, Settings::get_setting( 'post_meta_whitelist' ), true ) || wp_startswith( $meta_key, '_wpas_skip_' );
419
	}
420
421
	/**
422
	 * Whether a post type is allowed.
423
	 * A post type will be disallowed if it's present in the post type blacklist.
424
	 *
425
	 * @param int $post_id ID of the post.
426
	 * @return boolean Whether the post type is allowed.
427
	 */
428
	public function is_post_type_allowed( $post_id ) {
429
		$post = get_post( intval( $post_id ) );
430
431
		if ( isset( $post->post_type ) ) {
432
			return ! in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ), true );
433
		}
434
		return false;
435
	}
436
437
	/**
438
	 * Remove the embed shortcode.
439
	 *
440
	 * @global $wp_embed
441
	 */
442 View Code Duplication
	public function remove_embed() {
443
		global $wp_embed;
444
		remove_filter( 'the_content', array( $wp_embed, 'run_shortcode' ), 8 );
445
		// remove the embed shortcode since we would do the part later.
446
		remove_shortcode( 'embed' );
447
		// Attempts to embed all URLs in a post.
448
		remove_filter( 'the_content', array( $wp_embed, 'autoembed' ), 8 );
449
	}
450
451
	/**
452
	 * Add the embed shortcode.
453
	 *
454
	 * @global $wp_embed
455
	 */
456 View Code Duplication
	public function add_embed() {
457
		global $wp_embed;
458
		add_filter( 'the_content', array( $wp_embed, 'run_shortcode' ), 8 );
459
		// Shortcode placeholder for strip_shortcodes().
460
		add_shortcode( 'embed', '__return_false' );
461
		// Attempts to embed all URLs in a post.
462
		add_filter( 'the_content', array( $wp_embed, 'autoembed' ), 8 );
463
	}
464
465
	/**
466
	 * Expands wp_insert_post to include filtered content
467
	 *
468
	 * @param \WP_Post $post_object Post object.
469
	 */
470
	public function filter_post_content_and_add_links( $post_object ) {
471
		global $post;
472
		// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
473
		$post = $post_object;
474
475
		// Return non existant post.
476
		$post_type = get_post_type_object( $post->post_type );
477 View Code Duplication
		if ( empty( $post_type ) || ! is_object( $post_type ) ) {
478
			$non_existant_post                    = new \stdClass();
479
			$non_existant_post->ID                = $post->ID;
480
			$non_existant_post->post_modified     = $post->post_modified;
481
			$non_existant_post->post_modified_gmt = $post->post_modified_gmt;
482
			$non_existant_post->post_status       = 'jetpack_sync_non_registered_post_type';
483
			$non_existant_post->post_type         = $post->post_type;
484
485
			return $non_existant_post;
486
		}
487
		/**
488
		 * Filters whether to prevent sending post data to .com
489
		 *
490
		 * Passing true to the filter will prevent the post data from being sent
491
		 * to the WordPress.com.
492
		 * Instead we pass data that will still enable us to do a checksum against the
493
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
494
		 * other services.
495
		 *
496
		 * @since 4.2.0
497
		 *
498
		 * @param boolean false prevent post data from being synced to WordPress.com
499
		 * @param mixed $post \WP_Post object
500
		 */
501 View Code Duplication
		if ( apply_filters( 'jetpack_sync_prevent_sending_post_data', false, $post ) ) {
502
			// We only send the bare necessary object to be able to create a checksum.
503
			$blocked_post                    = new \stdClass();
504
			$blocked_post->ID                = $post->ID;
505
			$blocked_post->post_modified     = $post->post_modified;
506
			$blocked_post->post_modified_gmt = $post->post_modified_gmt;
507
			$blocked_post->post_status       = 'jetpack_sync_blocked';
508
			$blocked_post->post_type         = $post->post_type;
509
510
			return $blocked_post;
511
		}
512
513
		// lets not do oembed just yet.
514
		$this->remove_embed();
515
516
		if ( 0 < strlen( $post->post_password ) ) {
517
			$post->post_password = 'auto-' . wp_generate_password( 10, false );
518
		}
519
520
		/** This filter is already documented in core. wp-includes/post-template.php */
521
		if ( Settings::get_setting( 'render_filtered_content' ) && $post_type->public ) {
522
			global $shortcode_tags;
523
			/**
524
			 * Filter prevents some shortcodes from expanding.
525
			 *
526
			 * Since we can can expand some type of shortcode better on the .com side and make the
527
			 * expansion more relevant to contexts. For example [galleries] and subscription emails
528
			 *
529
			 * @since 4.5.0
530
			 *
531
			 * @param array of shortcode tags to remove.
532
			 */
533
			$shortcodes_to_remove        = apply_filters(
534
				'jetpack_sync_do_not_expand_shortcodes',
535
				array(
536
					'gallery',
537
					'slideshow',
538
				)
539
			);
540
			$removed_shortcode_callbacks = array();
541
			foreach ( $shortcodes_to_remove as $shortcode ) {
542
				if ( isset( $shortcode_tags[ $shortcode ] ) ) {
543
					$removed_shortcode_callbacks[ $shortcode ] = $shortcode_tags[ $shortcode ];
544
				}
545
			}
546
547
			array_map( 'remove_shortcode', array_keys( $removed_shortcode_callbacks ) );
548
549
			$post->post_content_filtered = apply_filters( 'the_content', $post->post_content );
550
			$post->post_excerpt_filtered = apply_filters( 'the_excerpt', $post->post_excerpt );
551
552
			foreach ( $removed_shortcode_callbacks as $shortcode => $callback ) {
553
				add_shortcode( $shortcode, $callback );
554
			}
555
		}
556
557
		$this->add_embed();
558
559
		if ( has_post_thumbnail( $post->ID ) ) {
560
			$image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
561
			if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) {
562
				$post->featured_image = $image_attributes[0];
563
			}
564
		}
565
566
		$post->permalink = get_permalink( $post->ID );
567
		$post->shortlink = wp_get_shortlink( $post->ID );
568
569
		if ( function_exists( 'amp_get_permalink' ) ) {
570
			$post->amp_permalink = amp_get_permalink( $post->ID );
571
		}
572
573
		return $post;
574
	}
575
576
	/**
577
	 * Handle transition from another post status to a published one.
578
	 *
579
	 * @param string   $new_status New post status.
580
	 * @param string   $old_status Old post status.
581
	 * @param \WP_Post $post       Post object.
582
	 */
583
	public function save_published( $new_status, $old_status, $post ) {
584
		$sync_item         = $this->get_post_sync_item( $post->ID );
585
		$is_just_published = 'publish' === $new_status && 'publish' !== $old_status;
586
		$sync_item->add_state_value( 'just_published', $is_just_published );
587
		$sync_item->add_state_value( 'previous_status', $old_status );
588
	}
589
590
	/**
591
	 * When publishing or updating a post, the Gutenberg editor sends two requests:
592
	 * 1. sent to WP REST API endpoint `wp-json/wp/v2/posts/$id`
593
	 * 2. sent to wp-admin/post.php `?post=$id&action=edit&classic-editor=1&meta_box=1`
594
	 *
595
	 * The 2nd request is to update post meta, which is not supported on WP REST API.
596
	 * When syncing post data, we will include if this was a meta box update.
597
	 *
598
	 * @todo Implement nonce verification.
599
	 *
600
	 * @return boolean Whether this is a Gutenberg meta box update.
601
	 */
602
	public function is_gutenberg_meta_box_update() {
603
		// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
604
		return (
605
			isset( $_POST['action'], $_GET['classic-editor'], $_GET['meta_box'] ) &&
606
			'editpost' === $_POST['action'] &&
607
			'1' === $_GET['classic-editor'] &&
608
			'1' === $_GET['meta_box']
609
			// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
610
		);
611
	}
612
613
	/**
614
	 * Handler for the wp_insert_post hook.
615
	 * Called upon creation of a new post.
616
	 *
617
	 * @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...
618
	 * @param \WP_Post $post    Post object.
619
	 * @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...
620
	 */
621
	public function wp_insert_post( $post_ID, $post = null, $update = null ) {
622
		if ( ! is_numeric( $post_ID ) || is_null( $post ) ) {
623
			return;
624
		}
625
626
		// Workaround for https://github.com/woocommerce/woocommerce/issues/18007.
627
		if ( $post && 'shop_order' === $post->post_type ) {
628
			$post = get_post( $post_ID );
629
		}
630
631
		$sync_item = $this->set_post_sync_item( $post_ID );
632
633
		if ( ! $sync_item->has_state( 'previous_status' ) ) {
634
			$sync_item->add_state_value( 'previous_status', self::DEFAULT_PREVIOUS_STATE );
635
		}
636
637
		$sync_item->add_state_value( 'is_auto_save', (bool) Jetpack_Constants::get_constant( 'DOING_AUTOSAVE' ) );
638
		$sync_item->add_state_value( 'is_gutenberg_meta_box_update', $this->is_gutenberg_meta_box_update() );
639
		/**
640
		 * Filter that is used to add to the post flags ( meta data ) when a post gets published
641
		 *
642
		 * @since 5.8.0
643
		 *
644
		 * @param int $post_ID the post ID
645
		 * @param mixed $post \WP_Post object
646
		 * @param bool  $update Whether this is an existing post being updated or not.
647
		 * @param mixed $state state
648
		 *
649
		 * @module sync
650
		 */
651
		do_action( 'jetpack_sync_save_post', $post_ID, $post, $update, $sync_item->get_state() );
652
		$sync_item->unset_state( 'previous_status' );
653
		$this->send_published( $post_ID, $post, $sync_item );
0 ignored issues
show
Bug introduced by
It seems like $sync_item defined by $this->set_post_sync_item($post_ID) on line 631 can be null; however, Automattic\Jetpack\Sync\...Posts::send_published() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
654
	}
655
656
	/**
657
	 * Send a published post for sync.
658
	 *
659
	 * @param int      $post_ID Post ID.
660
	 * @param \WP_Post $post    Post object.
661
	 * @param Item     $sync_item   Sync Item Object.
662
	 */
663
	public function send_published( $post_ID, $post, $sync_item ) {
664
665
		if ( ! $sync_item->is_state_value_true( 'just_published' ) ) {
666
			return;
667
		}
668
669
		// Post revisions cause race conditions where this send_published add the action before the actual post gets synced.
670
		if ( wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
671
			return;
672
		}
673
674
		$post_flags = array(
675
			'post_type' => $post->post_type,
676
		);
677
678
		$author_user_object = get_user_by( 'id', $post->post_author );
679
		if ( $author_user_object ) {
680
			$roles                = new Roles();
681
			$post_flags['author'] = array(
682
				'id'              => $post->post_author,
683
				'wpcom_user_id'   => get_user_meta( $post->post_author, 'wpcom_user_id', true ),
684
				'display_name'    => $author_user_object->display_name,
685
				'email'           => $author_user_object->user_email,
686
				'translated_role' => $roles->translate_user_to_role( $author_user_object ),
687
			);
688
		}
689
690
		/**
691
		 * Filter that is used to add to the post flags ( meta data ) when a post gets published
692
		 *
693
		 * @since 4.4.0
694
		 *
695
		 * @param mixed array post flags that are added to the post
696
		 * @param mixed $post \WP_Post object
697
		 */
698
		$flags = apply_filters( 'jetpack_published_post_flags', $post_flags, $post );
699
700
		/**
701
		 * Action that gets synced when a post type gets published.
702
		 *
703
		 * @since 4.4.0
704
		 *
705
		 * @param int $post_ID
706
		 * @param mixed array $flags post flags that are added to the post
707
		 */
708
		do_action( 'jetpack_published_post', $post_ID, $flags );
709
		$sync_item->unset_state( 'just_published' );
710
711
		/**
712
		 * Send additional sync action for Activity Log when post is a Customizer publish
713
		 */
714
		if ( 'customize_changeset' === $post->post_type ) {
715
			$post_content = json_decode( $post->post_content, true );
716
			foreach ( $post_content as $key => $value ) {
717
				// Skip if it isn't a widget.
718
				if ( 'widget_' !== substr( $key, 0, strlen( 'widget_' ) ) ) {
719
					continue;
720
				}
721
				// Change key from "widget_archives[2]" to "archives-2".
722
				$key = str_replace( 'widget_', '', $key );
723
				$key = str_replace( '[', '-', $key );
724
				$key = str_replace( ']', '', $key );
725
726
				global $wp_registered_widgets;
727
				if ( isset( $wp_registered_widgets[ $key ] ) ) {
728
					$widget_data = array(
729
						'name'  => $wp_registered_widgets[ $key ]['name'],
730
						'id'    => $key,
731
						'title' => $value['value']['title'],
732
					);
733
					do_action( 'jetpack_widget_edited', $widget_data );
734
				}
735
			}
736
		}
737
	}
738
739
	/**
740
	 * Expand post IDs to post objects within a hook before they are serialized and sent to the server.
741
	 *
742
	 * @access public
743
	 *
744
	 * @param array $args The hook parameters.
745
	 * @return array $args The expanded hook parameters.
746
	 */
747
	public function expand_post_ids( $args ) {
748
		list( $post_ids, $previous_interval_end) = $args;
749
750
		$posts = array_filter( array_map( array( 'WP_Post', 'get_instance' ), $post_ids ) );
751
		$posts = array_map( array( $this, 'filter_post_content_and_add_links' ), $posts );
752
		$posts = array_values( $posts ); // Reindex in case posts were deleted.
753
754
		return array(
755
			$posts,
756
			$this->get_metadata( $post_ids, 'post', Settings::get_setting( 'post_meta_whitelist' ) ),
757
			$this->get_term_relationships( $post_ids ),
758
			$previous_interval_end,
759
		);
760
	}
761
762
	/**
763
	 * Gets a list of minimum and maximum object ids for each batch based on the given batch size.
764
	 *
765
	 * @access public
766
	 *
767
	 * @param int         $batch_size The batch size for objects.
768
	 * @param string|bool $where_sql  The sql where clause minus 'WHERE', or false if no where clause is needed.
769
	 *
770
	 * @return array|bool An array of min and max ids for each batch. FALSE if no table can be found.
771
	 */
772
	public function get_min_max_object_ids_for_batches( $batch_size, $where_sql = false ) {
773
		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...
774
	}
775
}
776