Completed
Push — update/sync-use-roles-package ( 2a2e96 )
by Marin
66:07 queued 56:05
created

Posts::estimate_full_sync_actions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 8
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Automattic\Jetpack\Sync\Modules;
4
5
use Automattic\Jetpack\Constants as Jetpack_Constants;
6
use Automattic\Jetpack\Roles;
7
use Automattic\Jetpack\Sync\Settings;
8
9
class Posts extends Module {
10
11
	private $just_published  = array();
12
	private $previous_status = array();
13
	private $action_handler;
14
	private $import_end = false;
15
16
	const DEFAULT_PREVIOUS_STATE = 'new';
17
18
	public function name() {
19
		return 'posts';
20
	}
21
22
	public function get_object_by_id( $object_type, $id ) {
23
		if ( $object_type === 'post' && $post = get_post( intval( $id ) ) ) {
24
			return $this->filter_post_content_and_add_links( $post );
25
		}
26
27
		return false;
28
	}
29
30
	public function init_listeners( $callable ) {
31
		$this->action_handler = $callable;
32
33
		add_action( 'wp_insert_post', array( $this, 'wp_insert_post' ), 11, 3 );
34
		add_action( 'jetpack_sync_save_post', $callable, 10, 4 );
35
36
		add_action( 'deleted_post', $callable, 10 );
37
		add_action( 'jetpack_published_post', $callable, 10, 2 );
38
39
		add_action( 'transition_post_status', array( $this, 'save_published' ), 10, 3 );
40
		add_filter( 'jetpack_sync_before_enqueue_jetpack_sync_save_post', array( $this, 'filter_blacklisted_post_types' ) );
41
42
		// listen for meta changes
43
		$this->init_listeners_for_meta_type( 'post', $callable );
44
		$this->init_meta_whitelist_handler( 'post', array( $this, 'filter_meta' ) );
45
46
		add_action( 'jetpack_daily_akismet_meta_cleanup_before', array( $this, 'daily_akismet_meta_cleanup_before' ) );
47
		add_action( 'jetpack_daily_akismet_meta_cleanup_after', array( $this, 'daily_akismet_meta_cleanup_after' ) );
48
		add_action( 'jetpack_post_meta_batch_delete', $callable, 10, 2 );
49
50
	}
51
52
	public function daily_akismet_meta_cleanup_before( $feedback_ids ) {
53
		remove_action( 'deleted_post_meta', $this->action_handler );
54
		/**
55
		 * Used for syncing deletion of batch post meta
56
		 *
57
		 * @since 6.1.0
58
		 *
59
		 * @module sync
60
		 *
61
		 * @param array $feedback_ids feedback post IDs
62
		 * @param string $meta_key to be deleted
63
		 */
64
		do_action( 'jetpack_post_meta_batch_delete', $feedback_ids, '_feedback_akismet_values' );
65
	}
66
67
	public function daily_akismet_meta_cleanup_after( $feedback_ids ) {
68
		add_action( 'deleted_post_meta', $this->action_handler );
69
	}
70
71
	public function init_full_sync_listeners( $callable ) {
72
		add_action( 'jetpack_full_sync_posts', $callable ); // also sends post meta
73
	}
74
75
	public function init_before_send() {
76
		add_filter( 'jetpack_sync_before_send_jetpack_sync_save_post', array( $this, 'expand_jetpack_sync_save_post' ) );
77
78
		// full sync
79
		add_filter( 'jetpack_sync_before_send_jetpack_full_sync_posts', array( $this, 'expand_post_ids' ) );
80
	}
81
82
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
83
		global $wpdb;
84
85
		return $this->enqueue_all_ids_as_action( 'jetpack_full_sync_posts', $wpdb->posts, 'ID', $this->get_where_sql( $config ), $max_items_to_enqueue, $state );
86
	}
87
88 View Code Duplication
	public function estimate_full_sync_actions( $config ) {
89
		global $wpdb;
90
91
		$query = "SELECT count(*) FROM $wpdb->posts WHERE " . $this->get_where_sql( $config );
92
		$count = $wpdb->get_var( $query );
93
94
		return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
95
	}
96
97 View Code Duplication
	private function get_where_sql( $config ) {
98
		$where_sql = Settings::get_blacklisted_post_types_sql();
99
100
		// config is a list of post IDs to sync
101
		if ( is_array( $config ) ) {
102
			$where_sql .= ' AND ID IN (' . implode( ',', array_map( 'intval', $config ) ) . ')';
103
		}
104
105
		return $where_sql;
106
	}
107
108
	function get_full_sync_actions() {
109
		return array( 'jetpack_full_sync_posts' );
110
	}
111
112
	/**
113
	 * Process content before send
114
	 *
115
	 * @param array $args wp_insert_post arguments
116
	 *
117
	 * @return array
118
	 */
119
	function expand_jetpack_sync_save_post( $args ) {
120
		list( $post_id, $post, $update, $previous_state ) = $args;
121
		return array( $post_id, $this->filter_post_content_and_add_links( $post ), $update, $previous_state );
122
	}
123
124
	function filter_blacklisted_post_types( $args ) {
125
		$post = $args[1];
126
127
		if ( in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ) ) ) {
128
			return false;
129
		}
130
131
		return $args;
132
	}
133
134
	// Meta
135
	function filter_meta( $args ) {
136
		if ( $this->is_post_type_allowed( $args[1] ) && $this->is_whitelisted_post_meta( $args[2] ) ) {
137
			return $args;
138
		}
139
140
		return false;
141
	}
142
143
	function is_whitelisted_post_meta( $meta_key ) {
144
		// _wpas_skip_ is used by publicize
145
		return in_array( $meta_key, Settings::get_setting( 'post_meta_whitelist' ) ) || wp_startswith( $meta_key, '_wpas_skip_' );
146
	}
147
148
	function is_post_type_allowed( $post_id ) {
149
		$post = get_post( intval( $post_id ) );
150
		if ( $post->post_type ) {
151
			return ! in_array( $post->post_type, Settings::get_setting( 'post_types_blacklist' ) );
152
		}
153
		return false;
154
	}
155
156 View Code Duplication
	function remove_embed() {
157
		global $wp_embed;
158
		remove_filter( 'the_content', array( $wp_embed, 'run_shortcode' ), 8 );
159
		// remove the embed shortcode since we would do the part later.
160
		remove_shortcode( 'embed' );
161
		// Attempts to embed all URLs in a post
162
		remove_filter( 'the_content', array( $wp_embed, 'autoembed' ), 8 );
163
	}
164
165 View Code Duplication
	function add_embed() {
166
		global $wp_embed;
167
		add_filter( 'the_content', array( $wp_embed, 'run_shortcode' ), 8 );
168
		// Shortcode placeholder for strip_shortcodes()
169
		add_shortcode( 'embed', '__return_false' );
170
		// Attempts to embed all URLs in a post
171
		add_filter( 'the_content', array( $wp_embed, 'autoembed' ), 8 );
172
	}
173
174
	// Expands wp_insert_post to include filtered content
175
	function filter_post_content_and_add_links( $post_object ) {
176
		global $post;
177
		$post = $post_object;
178
179
		// return non existant post
180
		$post_type = get_post_type_object( $post->post_type );
181 View Code Duplication
		if ( empty( $post_type ) || ! is_object( $post_type ) ) {
182
			$non_existant_post                    = new \stdClass();
183
			$non_existant_post->ID                = $post->ID;
184
			$non_existant_post->post_modified     = $post->post_modified;
185
			$non_existant_post->post_modified_gmt = $post->post_modified_gmt;
186
			$non_existant_post->post_status       = 'jetpack_sync_non_registered_post_type';
187
			$non_existant_post->post_type         = $post->post_type;
188
189
			return $non_existant_post;
190
		}
191
		/**
192
		 * Filters whether to prevent sending post data to .com
193
		 *
194
		 * Passing true to the filter will prevent the post data from being sent
195
		 * to the WordPress.com.
196
		 * Instead we pass data that will still enable us to do a checksum against the
197
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
198
		 * other services.
199
		 *
200
		 * @since 4.2.0
201
		 *
202
		 * @param boolean false prevent post data from being synced to WordPress.com
203
		 * @param mixed $post WP_POST object
204
		 */
205 View Code Duplication
		if ( apply_filters( 'jetpack_sync_prevent_sending_post_data', false, $post ) ) {
206
			// We only send the bare necessary object to be able to create a checksum.
207
			$blocked_post                    = new \stdClass();
208
			$blocked_post->ID                = $post->ID;
209
			$blocked_post->post_modified     = $post->post_modified;
210
			$blocked_post->post_modified_gmt = $post->post_modified_gmt;
211
			$blocked_post->post_status       = 'jetpack_sync_blocked';
212
			$blocked_post->post_type         = $post->post_type;
213
214
			return $blocked_post;
215
		}
216
217
		// lets not do oembed just yet.
218
		$this->remove_embed();
219
220
		if ( 0 < strlen( $post->post_password ) ) {
221
			$post->post_password = 'auto-' . wp_generate_password( 10, false );
222
		}
223
224
		/** This filter is already documented in core. wp-includes/post-template.php */
225
		if ( Settings::get_setting( 'render_filtered_content' ) && $post_type->public ) {
226
			global $shortcode_tags;
227
			/**
228
			 * Filter prevents some shortcodes from expanding.
229
			 *
230
			 * Since we can can expand some type of shortcode better on the .com side and make the
231
			 * expansion more relevant to contexts. For example [galleries] and subscription emails
232
			 *
233
			 * @since 4.5.0
234
			 *
235
			 * @param array of shortcode tags to remove.
236
			 */
237
			$shortcodes_to_remove        = apply_filters(
238
				'jetpack_sync_do_not_expand_shortcodes',
239
				array(
240
					'gallery',
241
					'slideshow',
242
				)
243
			);
244
			$removed_shortcode_callbacks = array();
245
			foreach ( $shortcodes_to_remove as $shortcode ) {
246
				if ( isset( $shortcode_tags[ $shortcode ] ) ) {
247
					$removed_shortcode_callbacks[ $shortcode ] = $shortcode_tags[ $shortcode ];
248
				}
249
			}
250
251
			array_map( 'remove_shortcode', array_keys( $removed_shortcode_callbacks ) );
252
253
			$post->post_content_filtered = apply_filters( 'the_content', $post->post_content );
254
			$post->post_excerpt_filtered = apply_filters( 'the_excerpt', $post->post_excerpt );
255
256
			foreach ( $removed_shortcode_callbacks as $shortcode => $callback ) {
257
				add_shortcode( $shortcode, $callback );
258
			}
259
		}
260
261
		$this->add_embed();
262
263
		if ( has_post_thumbnail( $post->ID ) ) {
264
			$image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
265
			if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) {
266
				$post->featured_image = $image_attributes[0];
267
			}
268
		}
269
270
		$post->permalink = get_permalink( $post->ID );
271
		$post->shortlink = wp_get_shortlink( $post->ID );
272
273
		if ( function_exists( 'amp_get_permalink' ) ) {
274
			$post->amp_permalink = amp_get_permalink( $post->ID );
275
		}
276
277
		return $post;
278
	}
279
280
	public function save_published( $new_status, $old_status, $post ) {
281
		if ( 'publish' === $new_status && 'publish' !== $old_status ) {
282
			$this->just_published[ $post->ID ] = true;
283
		}
284
285
		$this->previous_status[ $post->ID ] = $old_status;
286
	}
287
288
	/*
289
	 * When publishing or updating a post, the Gutenberg editor sends two requests:
290
	 * 1. sent to WP REST API endpoint `wp-json/wp/v2/posts/$id`
291
	 * 2. sent to wp-admin/post.php `?post=$id&action=edit&classic-editor=1&meta_box=1`
292
	 *
293
	 * The 2nd request is to update post meta, which is not supported on WP REST API.
294
	 * When syncing post data, we will include if this was a meta box update.
295
	 */
296
	public function is_gutenberg_meta_box_update() {
297
		return (
298
			isset( $_POST['action'], $_GET['classic-editor'], $_GET['meta_box'] ) &&
299
			'editpost' === $_POST['action'] &&
300
			'1' === $_GET['classic-editor'] &&
301
			'1' === $_GET['meta_box']
302
		);
303
	}
304
305
	public function wp_insert_post( $post_ID, $post = null, $update = null ) {
306
		if ( ! is_numeric( $post_ID ) || is_null( $post ) ) {
307
			return;
308
		}
309
310
		// workaround for https://github.com/woocommerce/woocommerce/issues/18007
311
		if ( $post && 'shop_order' === $post->post_type ) {
312
			$post = get_post( $post_ID );
313
		}
314
315
		$previous_status = isset( $this->previous_status[ $post_ID ] ) ?
316
			$this->previous_status[ $post_ID ] :
317
			self::DEFAULT_PREVIOUS_STATE;
318
319
		$just_published = isset( $this->just_published[ $post_ID ] ) ?
320
			$this->just_published[ $post_ID ] :
321
			false;
322
323
		$state = array(
324
			'is_auto_save'                 => (bool) Jetpack_Constants::get_constant( 'DOING_AUTOSAVE' ),
325
			'previous_status'              => $previous_status,
326
			'just_published'               => $just_published,
327
			'is_gutenberg_meta_box_update' => $this->is_gutenberg_meta_box_update(),
328
		);
329
		/**
330
		 * Filter that is used to add to the post flags ( meta data ) when a post gets published
331
		 *
332
		 * @since 5.8.0
333
		 *
334
		 * @param int $post_ID the post ID
335
		 * @param mixed $post WP_POST object
336
		 * @param bool  $update Whether this is an existing post being updated or not.
337
		 * @param mixed $state state
338
		 *
339
		 * @module sync
340
		 */
341
		do_action( 'jetpack_sync_save_post', $post_ID, $post, $update, $state );
342
		unset( $this->previous_status[ $post_ID ] );
343
		$this->send_published( $post_ID, $post );
344
	}
345
346
	public function send_published( $post_ID, $post ) {
347
		if ( ! isset( $this->just_published[ $post_ID ] ) ) {
348
			return;
349
		}
350
351
		// Post revisions cause race conditions where this send_published add the action before the actual post gets synced
352
		if ( wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
353
			return;
354
		}
355
356
		$post_flags = array(
357
			'post_type' => $post->post_type,
358
		);
359
360
		$author_user_object = get_user_by( 'id', $post->post_author );
361
		if ( $author_user_object ) {
362
			$roles = new Roles();
363
364
			$post_flags['author'] = array(
365
				'id'              => $post->post_author,
366
				'wpcom_user_id'   => get_user_meta( $post->post_author, 'wpcom_user_id', true ),
367
				'display_name'    => $author_user_object->display_name,
368
				'email'           => $author_user_object->user_email,
369
				'translated_role' => $roles->translate_user_to_role( $author_user_object ),
370
			);
371
		}
372
373
		/**
374
		 * Filter that is used to add to the post flags ( meta data ) when a post gets published
375
		 *
376
		 * @since 4.4.0
377
		 *
378
		 * @param mixed array post flags that are added to the post
379
		 * @param mixed $post WP_POST object
380
		 */
381
		$flags = apply_filters( 'jetpack_published_post_flags', $post_flags, $post );
382
383
		/**
384
		 * Action that gets synced when a post type gets published.
385
		 *
386
		 * @since 4.4.0
387
		 *
388
		 * @param int $post_ID
389
		 * @param mixed array $flags post flags that are added to the post
390
		 */
391
		do_action( 'jetpack_published_post', $post_ID, $flags );
392
		unset( $this->just_published[ $post_ID ] );
393
394
		/**
395
		 * Send additional sync action for Activity Log when post is a Customizer publish
396
		 */
397
		if ( 'customize_changeset' == $post->post_type ) {
398
			$post_content = json_decode( $post->post_content, true );
399
			foreach ( $post_content as $key => $value ) {
400
				// Skip if it isn't a widget
401
				if ( 'widget_' != substr( $key, 0, strlen( 'widget_' ) ) ) {
402
					continue;
403
				}
404
				// Change key from "widget_archives[2]" to "archives-2"
405
				$key = str_replace( 'widget_', '', $key );
406
				$key = str_replace( '[', '-', $key );
407
				$key = str_replace( ']', '', $key );
408
409
				global $wp_registered_widgets;
410
				if ( isset( $wp_registered_widgets[ $key ] ) ) {
411
					$widget_data = array(
412
						'name'  => $wp_registered_widgets[ $key ]['name'],
413
						'id'    => $key,
414
						'title' => $value['value']['title'],
415
					);
416
					do_action( 'jetpack_widget_edited', $widget_data );
417
				}
418
			}
419
		}
420
	}
421
422
	public function expand_post_ids( $args ) {
423
		list( $post_ids, $previous_interval_end) = $args;
424
425
		$posts = array_filter( array_map( array( 'WP_Post', 'get_instance' ), $post_ids ) );
426
		$posts = array_map( array( $this, 'filter_post_content_and_add_links' ), $posts );
427
		$posts = array_values( $posts ); // reindex in case posts were deleted
428
429
		return array(
430
			$posts,
431
			$this->get_metadata( $post_ids, 'post', Settings::get_setting( 'post_meta_whitelist' ) ),
432
			$this->get_term_relationships( $post_ids ),
433
			$previous_interval_end,
434
		);
435
	}
436
}
437