Completed
Push — improving-sync-with-enej ( b87d5b...ed4a48 )
by
unknown
08:43
created

Jetpack_Sync_Module_Posts   F

Complexity

Total Complexity 73

Size/Duplication

Total Lines 450
Duplicated Lines 11.78 %

Coupling/Cohesion

Components 5
Dependencies 4

Importance

Changes 0
Metric Value
dl 53
loc 450
rs 2.459
c 0
b 0
f 0
wmc 73
lcom 5
cbo 4

30 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A get_object_by_id() 0 7 3
A set_defaults() 0 3 1
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
B init_listeners() 0 36 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
A init_before_send() 0 7 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 expand_jetpack_published_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 61 10
B send_published() 0 26 3
A expand_post_ids() 0 13 1

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