Completed
Push — improving-sync-with-enej ( 131777...2efaa3 )
by
unknown
10:50
created

Jetpack_Sync_Module_Posts   F

Complexity

Total Complexity 72

Size/Duplication

Total Lines 439
Duplicated Lines 12.07 %

Coupling/Cohesion

Components 5
Dependencies 4

Importance

Changes 0
Metric Value
dl 53
loc 439
rs 2.5423
c 0
b 0
f 0
wmc 72
lcom 5
cbo 4

29 Methods

Rating   Name   Duplication   Size   Complexity  
A expand_post_ids() 0 13 1
A name() 0 3 1
A get_object_by_id() 0 7 3
A set_defaults() 0 3 1
B init_listeners() 0 34 2
A set_object_terms() 0 6 2
A wp_insert_post_parent() 0 4 1
A is_saving_post() 0 3 1
A sync_import_done() 0 18 2
C sync_import_end() 0 26 7
A get_importer_name() 0 4 2
A is_importer() 0 9 3
A init_full_sync_listeners() 0 3 1
A init_before_send() 0 6 1
A enqueue_full_sync_actions() 0 5 1
A estimate_full_sync_actions() 8 8 1
A get_where_sql() 10 10 2
A get_full_sync_actions() 0 3 1
A expand_jetpack_sync_save_post() 0 4 1
A filter_blacklisted_post_types() 0 9 2
A filter_meta() 0 7 3
A is_whitelisted_post_meta() 0 4 2
A is_post_type_allowed() 0 5 1
A remove_embed() 8 8 1
A add_embed() 8 8 1
D filter_post_content_and_add_links() 19 94 13
A save_published() 0 4 2
C wp_insert_post() 0 58 10
B send_published() 0 26 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_Sync_Module_Posts often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Sync_Module_Posts, and based on these observations, apply Extract Interface, too.

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