Completed
Push — fix/11256-post-format-handling ( db1887 )
by Kirk
06:43
created

Jetpack_Copy_Post::update_post_data()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 3
nop 3
dl 0
loc 43
rs 8.9208
c 0
b 0
f 0
1
<?php
2
/**
3
 * Module Name: Copy Post
4
 * Module Description: Copy an existing post's content into a new draft post.
5
 * Jumpstart Description: Copy an existing post's content into a new post.
6
 * Sort Order: 15
7
 * First Introduced: 7.0
8
 * Requires Connection: No
9
 * Auto Activate: No
10
 * Module Tags: Writing
11
 * Feature: Writing
12
 * Additional Search Queries: copy, duplicate
13
 */
14
15
/**
16
 * Copy Post class.
17
 */
18
class Jetpack_Copy_Post {
19
	/**
20
	 * Jetpack_Copy_Post_By_Param constructor.
21
	 * Add row actions to post/page/CPT listing screens.
22
	 * Process any `?copy` param if on a create new post/page/CPT screen.
23
	 *
24
	 * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
25
	 */
26
	public function __construct() {
27
		if ( 'edit.php' === $GLOBALS['pagenow'] ) {
28
			add_filter( 'post_row_actions', array( $this, 'add_row_action' ), 10, 2 );
29
			add_filter( 'page_row_actions', array( $this, 'add_row_action' ), 10, 2 );
30
			return;
31
		}
32
33
		if ( ! empty( $_GET['jetpack-copy'] ) && 'post-new.php' === $GLOBALS['pagenow'] ) {
34
			add_action( 'wp_insert_post', array( $this, 'update_post_data' ), 10, 3 );
35
		}
36
	}
37
38
	/**
39
	 * Update the new (target) post data with the source post data.
40
	 *
41
	 * @param int     $target_post_id Target post ID.
42
	 * @param WP_Post $post           Target post object (not used).
43
	 * @param bool    $update         Whether this is an existing post being updated or not.
44
	 * @return void
45
	 */
46
	public function update_post_data( $target_post_id, $post, $update ) {
47
		// This `$update` check avoids infinite loops of trying to update our updated post.
48
		if ( $update ) {
49
			return;
50
		}
51
52
		$source_post = get_post( $_GET['jetpack-copy'] );
53
		if ( ! $source_post instanceof WP_Post ||
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
54
			! $this->user_can_access_post( $source_post->ID ) ||
55
			! $this->validate_post_type( $source_post ) ) {
56
			return;
57
		}
58
59
		$update_results = array(
60
			'update_content'         => $this->update_content( $source_post, $target_post_id ),
61
			'update_featured_image'  => $this->update_featured_image( $source_post, $target_post_id ),
62
			'update_post_format'     => $this->update_post_format( $source_post, $target_post_id ),
63
			'update_likes_sharing'   => $this->update_likes_sharing( $source_post, $target_post_id ),
64
			'update_post_type_terms' => $this->update_post_type_terms( $source_post, $target_post_id ),
65
		);
66
67
		// Required to satisfy get_default_post_to_edit(), which has these filters after post creation.
68
		add_filter( 'default_title', array( $this, 'filter_title' ), 10, 2 );
69
		add_filter( 'default_content', array( $this, 'filter_content' ), 10, 2 );
70
		add_filter( 'default_excerpt', array( $this, 'filter_excerpt' ), 10, 2 );
71
72
		// Required to avoid the block editor from adding default blocks according to post format.
73
		add_filter( 'block_editor_settings', array( $this, 'remove_post_format_template' ) );
74
75
		/**
76
		 * Fires after all updates have been performed, and default content filters have been added.
77
		 * Allows for any cleanup or post operations, and default content filters can be removed or modified.
78
		 *
79
		 * @module copy-post
80
		 *
81
		 * @since 7.0.0
82
		 *
83
		 * @param WP_Post $source_post Post object that was copied.
84
		 * @param int     $target_post_id Target post ID.
85
		 * @param array   $update_results Results of all update operations, allowing action to be taken.
86
		 */
87
		do_action( 'jetpack_copy_post', $source_post, $target_post_id, $update_results );
88
	}
89
90
	/**
91
	 * Determine if the current user has edit access to the source post.
92
	 *
93
	 * @param int $post_id Source post ID (the post being copied).
94
	 * @return bool True if user has the meta cap of `edit_post` for the given post ID, false otherwise.
95
	 */
96
	protected function user_can_access_post( $post_id ) {
97
		return current_user_can( 'edit_post', $post_id );
98
	}
99
100
	/**
101
	 * Update the target post's title, content, excerpt, categories, and tags.
102
	 *
103
	 * @param WP_Post $source_post Post object to be copied.
104
	 * @param int     $target_post_id Target post ID.
105
	 * @return int    0 on failure, or the updated post ID on success.
106
	 */
107
	protected function update_content( $source_post, $target_post_id ) {
108
		$data = array(
109
			'ID'             => $target_post_id,
110
			'post_title'     => $source_post->post_title,
111
			'post_content'   => $source_post->post_content,
112
			'post_excerpt'   => $source_post->post_excerpt,
113
			'comment_status' => $source_post->comment_status,
114
			'ping_status'    => $source_post->ping_status,
115
			'post_category'  => $source_post->post_category,
116
			'post_password'  => $source_post->post_password,
117
			'tags_input'     => $source_post->tags_input,
118
		);
119
120
		/**
121
		 * Fires just before the target post is updated with its new data.
122
		 * Allows for final data adjustments before updating the target post.
123
		 *
124
		 * @module copy-post
125
		 *
126
		 * @since 7.0.0
127
		 *
128
		 * @param array $data Post data with which to update the target (new) post.
129
		 * @param WP_Post $source_post Post object being copied.
130
		 * @param int     $target_post_id Target post ID.
131
		 */
132
		$data = apply_filters( 'jetpack_copy_post_data', $data, $source_post, $target_post_id );
133
		return wp_update_post( $data );
134
	}
135
136
	/**
137
	 * Update terms for post types.
138
	 *
139
	 * @param WP_Post $source_post Post object to be copied.
140
	 * @param int     $target_post_id Target post ID.
141
	 * @return array Results of attempts to set each term to the target (new) post.
142
	 */
143
	protected function update_post_type_terms( $source_post, $target_post_id ) {
144
		$results = array();
145
146
		$bypassed_post_types = apply_filters( 'jetpack_copy_post_bypassed_post_types', array( 'post', 'page' ), $source_post, $target_post_id );
147
		if ( in_array( $source_post->post_type, $bypassed_post_types, true ) ) {
148
			return $results;
149
		}
150
151
		$taxonomies = get_object_taxonomies( $source_post, 'objects' );
152
		foreach ( $taxonomies as $taxonomy ) {
153
			$terms     = wp_get_post_terms( $source_post->ID, $taxonomy->name, array( 'fields' => 'ids' ) );
154
			$results[] = wp_set_post_terms( $target_post_id, $terms, $taxonomy->name );
155
		}
156
157
		return $results;
158
	}
159
160
	/**
161
	 * Update the target post's featured image.
162
	 *
163
	 * @param WP_Post $source_post Post object to be copied.
164
	 * @param int     $target_post_id Target post ID.
165
	 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
166
	 */
167
	protected function update_featured_image( $source_post, $target_post_id ) {
168
		$featured_image_id = get_post_thumbnail_id( $source_post );
169
		return update_post_meta( $target_post_id, '_thumbnail_id', $featured_image_id );
170
	}
171
172
	/**
173
	 * Update the target post's post format.
174
	 *
175
	 * @param WP_Post $source_post Post object to be copied.
176
	 * @param int     $target_post_id Target post ID.
177
	 * @return array|WP_Error|false WP_Error on error, array of affected term IDs on success.
178
	 */
179
	protected function update_post_format( $source_post, $target_post_id ) {
180
		$post_format = get_post_format( $source_post );
181
		return set_post_format( $target_post_id, $post_format );
182
	}
183
184
	/**
185
	 * Update the target post's post format.
186
	 *
187
	 * @param array $settings Settings to be passed into the block editor.
188
	 * @return array Settings with any `template` key removed.
189
	 */
190
	public function remove_post_format_template( $settings ) {
191
		unset( $settings['template'] );
192
		return $settings;
193
	}
194
195
	/**
196
	 * Update the target post's Likes and Sharing statuses.
197
	 *
198
	 * @param WP_Post $source_post Post object to be copied.
199
	 * @param int     $target_post_id Target post ID.
200
	 * @return array Array with the results of each update action.
201
	 */
202
	protected function update_likes_sharing( $source_post, $target_post_id ) {
203
		$likes          = get_post_meta( $source_post->ID, 'switch_like_status', true );
204
		$sharing        = get_post_meta( $source_post->ID, 'sharing_disabled', false );
205
		$likes_result   = update_post_meta( $target_post_id, 'switch_like_status', $likes );
206
		$sharing_result = update_post_meta( $target_post_id, 'sharing_disabled', $sharing );
207
		return array(
208
			'likes'   => $likes_result,
209
			'sharing' => $sharing_result,
210
		);
211
	}
212
213
	/**
214
	 * Update the target post's title.
215
	 *
216
	 * @param string  $post_title Post title determined by `get_default_post_to_edit()`.
217
	 * @param WP_Post $post       Post object of newly-inserted post.
218
	 * @return string             Updated post title from source post.
219
	 */
220
	public function filter_title( $post_title, $post ) {
221
		return $post->post_title;
222
	}
223
224
	/**
225
	 * Update the target post's content (`post_content`).
226
	 *
227
	 * @param string  $post_content Post content determined by `get_default_post_to_edit()`.
228
	 * @param WP_Post $post         Post object of newly-inserted post.
229
	 * @return string               Updated post content from source post.
230
	 */
231
	public function filter_content( $post_content, $post ) {
232
		return $post->post_content;
233
	}
234
235
	/**
236
	 * Update the target post's excerpt.
237
	 *
238
	 * @param string  $post_excerpt Post excerpt determined by `get_default_post_to_edit()`.
239
	 * @param WP_Post $post         Post object of newly-inserted post.
240
	 * @return string               Updated post excerpt from source post.
241
	 */
242
	public function filter_excerpt( $post_excerpt, $post ) {
243
		return $post->post_excerpt;
244
	}
245
246
	/**
247
	 * Validate the post type to be used for the target post.
248
	 *
249
	 * @param WP_Post $post Post object of current post in listing.
250
	 * @return bool True if the post type is in a list of supported psot types; false otherwise.
251
	 */
252
	protected function validate_post_type( $post ) {
253
		/**
254
		 * Fires when determining if the "Copy" row action should be made available.
255
		 * Allows overriding supported post types.
256
		 *
257
		 * @module copy-post
258
		 *
259
		 * @since 7.0.0
260
		 *
261
		 * @param array   Post types supported by default.
262
		 * @param WP_Post $post Post object of current post in listing.
263
		 */
264
		$valid_post_types = apply_filters(
265
			'jetpack_copy_post_post_types',
266
			array(
267
				'post',
268
				'page',
269
				'jetpack-testimonial',
270
				'jetpack-portfolio',
271
			),
272
			$post
273
		);
274
		return in_array( $post->post_type, $valid_post_types, true );
275
	}
276
277
	/**
278
	 * Add a "Copy" row action to supported posts/pages/CPTs on list views.
279
	 *
280
	 * @param array   $actions Existing actions.
281
	 * @param WP_Post $post    Post object of current post in list.
282
	 * @return array           Array of updated row actions.
283
	 */
284
	public function add_row_action( $actions, $post ) {
285
		if ( ! $this->user_can_access_post( $post->ID ) ||
286
			! $post instanceof WP_Post ||
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
287
			! $this->validate_post_type( $post ) ) {
288
			return $actions;
289
		}
290
291
		$edit_url    = add_query_arg(
292
			array(
293
				'post_type'    => $post->post_type,
294
				'jetpack-copy' => $post->ID,
295
			),
296
			admin_url( 'post-new.php' )
297
		);
298
		$edit_action = array(
299
			'jetpack-copy' => sprintf(
300
				'<a href="%s" aria-label="%s">%s</a>',
301
				esc_url( $edit_url ),
302
				esc_attr__( 'Copy this post.', 'jetpack' ),
303
				esc_html__( 'Copy', 'jetpack' )
304
			),
305
		);
306
307
		// Insert the Copy action before the Trash action.
308
		$edit_offset = array_search( 'trash', array_keys( $actions ), true );
309
		$updated_actions     = array_merge(
310
			array_slice( $actions, 0, $edit_offset ),
311
			$edit_action,
312
			array_slice( $actions, $edit_offset )
313
		);
314
315
		/**
316
		 * Fires after the new Copy action has been added to the row actions.
317
		 * Allows changes to the action presentation, or other final checks.
318
		 *
319
		 * @module copy-post
320
		 *
321
		 * @since 7.0.0
322
		 *
323
		 * @param array   $updated_actions Updated row actions with the Copy Post action.
324
		 * @param array   $actions Original row actions passed to this filter.
325
		 * @param WP_Post $post Post object of current post in listing.
326
		 */
327
		return apply_filters( 'jetpack_copy_post_row_actions', $updated_actions, $actions, $post );
328
	}
329
}
330
331
/**
332
 * Instantiate an instance of Jetpack_Copy_Post on the `admin_init` hook.
333
 */
334
function jetpack_copy_post_init() {
335
	new Jetpack_Copy_Post();
336
}
337
add_action( 'admin_init', 'jetpack_copy_post_init' );
338