Completed
Push — add/copy-a-post ( 5d5da0...5993aa )
by Kirk
06:36
created

Jetpack_Copy_Post::update_post_data()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 3
nop 3
dl 0
loc 39
rs 8.6737
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 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'] ) &&
34
			wp_verify_nonce( $_GET['_wpnonce'], 'jetpack-copy-post' ) &&
35
			'post-new.php' === $GLOBALS['pagenow'] ) {
36
			add_action( 'wp_insert_post', array( $this, 'update_post_data' ), 10, 3 );
37
		}
38
	}
39
40
	/**
41
	 * Update the new (target) post data with the source post data.
42
	 *
43
	 * @param int     $target_post_id Target post ID.
44
	 * @param WP_Post $post           Target post object (not used).
45
	 * @param bool    $update         Whether this is an existing post being updated or not.
46
	 * @return void
47
	 */
48
	public function update_post_data( $target_post_id, $post, $update ) {
49
		// This `$update` check avoids infinite loops of trying to update our updated post.
50
		if ( ! wp_verify_nonce( $_GET['_wpnonce'], 'jetpack-copy-post' ) || $update ) {
51
			return;
52
		}
53
54
		$source_post = get_post( $_GET['jetpack-copy'] );
55
		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...
56
			! $this->user_can_access_post( $source_post->ID ) ||
57
			! $this->validate_post_type( $source_post ) ) {
58
			return;
59
		}
60
61
		$update_results = array(
62
			'update_content'        => $this->update_content( $source_post, $target_post_id ),
63
			'update_featured_image' => $this->update_featured_image( $source_post, $target_post_id ),
64
			'update_post_format'    => $this->update_post_format( $source_post, $target_post_id ),
65
			'update_likes_sharing'  => $this->update_likes_sharing( $source_post, $target_post_id ),
66
		);
67
68
		// Required to satify get_default_post_to_edit(), which has these filters after post creation.
69
		add_filter( 'default_title', array( $this, 'filter_title' ), 10, 2 );
70
		add_filter( 'default_content', array( $this, 'filter_content' ), 10, 2 );
71
		add_filter( 'default_excerpt', array( $this, 'filter_excerpt' ), 10, 2 );
72
73
		/**
74
		 * Fires after all updates have been performed, and default content filters have been added.
75
		 * Allows for any cleanup or post operations, and default content filters can be removed or modified.
76
		 *
77
		 * @module copy-post
78
		 *
79
		 * @since 7.0
80
		 *
81
		 * @param WP_Post $source_post Post object that was copied.
82
		 * @param int     $target_post_id Target post ID.
83
		 * @param array   $update_results Results of the four update operations, allowing action to be taken.
84
		 */
85
		do_action( 'jetpack_copy_post', $source_post, $target_post_id, $update_results );
86
	}
87
88
	/**
89
	 * Determine if the current user has access to the source post.
90
	 *
91
	 * @param int $post_id Source post ID (the post being copied).
92
	 * @return bool True if user has the meta cap of `read_post` for the given post ID, false otherwise.
93
	 */
94
	protected function user_can_access_post( $post_id ) {
95
		return current_user_can( 'read_post', $post_id );
96
	}
97
98
	/**
99
	 * Update the target post's title, content, excerpt, categories, and tags.
100
	 *
101
	 * @param WP_Post $source_post Post object to be copied.
102
	 * @param int     $target_post_id Target post ID.
103
	 * @return int    0 on failure, or the updated post ID on success.
104
	 */
105
	protected function update_content( $source_post, $target_post_id ) {
106
		$data = array(
107
			'ID'             => $target_post_id,
108
			'post_title'     => $source_post->post_title,
109
			'post_content'   => $source_post->post_content,
110
			'post_excerpt'   => $source_post->post_excerpt,
111
			'comment_status' => $source_post->comment_status,
112
			'ping_status'    => $source_post->ping_status,
113
			'post_category'  => $source_post->post_category,
114
			'tags_input'     => $source_post->tags_input,
115
		);
116
117
		/**
118
		 * Fires just before the target post is updated with its new data.
119
		 * Allows for final data adjustments before updating the target post.
120
		 *
121
		 * @module copy-post
122
		 *
123
		 * @since 7.0
124
		 *
125
		 * @param array $data Post data with which to update the target (new) post.
126
		 * @param WP_Post $source_post Post object being copied.
127
		 * @param int     $target_post_id Target post ID.
128
		 */
129
		$data = apply_filters( 'jetpack_copy_post_data', $data, $source_post, $target_post_id );
130
		return wp_update_post( $data );
131
	}
132
133
	/**
134
	 * Update the target post's featured image.
135
	 *
136
	 * @param WP_Post $source_post Post object to be copied.
137
	 * @param int     $target_post_id Target post ID.
138
	 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
139
	 */
140
	protected function update_featured_image( $source_post, $target_post_id ) {
141
		$featured_image_id = get_post_thumbnail_id( $source_post );
142
		return update_post_meta( $target_post_id, '_thumbnail_id', $featured_image_id );
143
	}
144
145
	/**
146
	 * Update the target post's post format.
147
	 *
148
	 * @param WP_Post $source_post Post object to be copied.
149
	 * @param int     $target_post_id Target post ID.
150
	 * @return array|WP_Error|false WP_Error on error, array of affected term IDs on success.
151
	 */
152
	protected function update_post_format( $source_post, $target_post_id ) {
153
		$post_format = get_post_format( $source_post );
154
		return set_post_format( $target_post_id, $post_format );
155
	}
156
157
	/**
158
	 * Update the target post's Likes and Sharing statuses.
159
	 *
160
	 * @param WP_Post $source_post Post object to be copied.
161
	 * @param int     $target_post_id Target post ID.
162
	 * @return array Array with the results of each update action.
163
	 */
164
	protected function update_likes_sharing( $source_post, $target_post_id ) {
165
		$likes          = get_post_meta( $source_post->ID, 'switch_like_status', true );
166
		$sharing        = get_post_meta( $source_post->ID, 'sharing_disabled', false );
167
		$likes_result   = update_post_meta( $target_post_id, 'switch_like_status', $likes );
168
		$sharing_result = update_post_meta( $target_post_id, 'sharing_disabled', $sharing );
169
		return array(
170
			'likes'   => $likes_result,
171
			'sharing' => $sharing_result,
172
		);
173
	}
174
175
	/**
176
	 * Update the target post's title.
177
	 *
178
	 * @param string  $post_title Post title determined by `get_default_post_to_edit()`.
179
	 * @param WP_Post $post       Post object of newly-inserted post.
180
	 * @return string             Updated post title from source post.
181
	 */
182
	public function filter_title( $post_title, $post ) {
183
		return $post->post_title;
184
	}
185
186
	/**
187
	 * Update the target post's content (`post_content`).
188
	 *
189
	 * @param string  $post_content Post content determined by `get_default_post_to_edit()`.
190
	 * @param WP_Post $post         Post object of newly-inserted post.
191
	 * @return string               Updated post content from source post.
192
	 */
193
	public function filter_content( $post_content, $post ) {
194
		return $post->post_content;
195
	}
196
197
	/**
198
	 * Update the target post's excerpt.
199
	 *
200
	 * @param string  $post_excerpt Post excerpt determined by `get_default_post_to_edit()`.
201
	 * @param WP_Post $post         Post object of newly-inserted post.
202
	 * @return string               Updated post excerpt from source post.
203
	 */
204
	public function filter_excerpt( $post_excerpt, $post ) {
205
		return $post->post_excerpt;
206
	}
207
208
	/**
209
	 * Validate the post type to be used for the target post.
210
	 *
211
	 * @param WP_Post $post Post object of current post in listing.
212
	 * @return bool True if the post type is in a list of supported psot types; false otherwise.
213
	 */
214
	protected function validate_post_type( $post ) {
215
		$valid_post_types    = array(
216
			'post',
217
			'page',
218
			'jetpack-testimonial',
219
			'jetpack-portfolio',
220
		);
221
		$post_type_supported = in_array( $post->post_type, $valid_post_types, true );
222
223
		/**
224
		 * Fires when determining if the "Copy" row action should be made available.
225
		 * Allows overriding supported post types.
226
		 *
227
		 * @module copy-post
228
		 *
229
		 * @since 7.0
230
		 *
231
		 * @param bool  $post_type_supported If the given post type is a valid supported psot type.
232
		 * @param array $valid_post_types Supported post types.
233
		 * @param WP_Post $post Post object of current post in listing.
234
		 */
235
		return apply_filters( 'jetpack_copy_post_post_types', $post_type_supported, $valid_post_types, $post );
236
	}
237
238
	/**
239
	 * Add a "Copy" row action to supported posts/pages/CPTs on list views.
240
	 *
241
	 * @param array   $actions Existing actions.
242
	 * @param WP_Post $post    Post object of current post in list.
243
	 * @return array           Array of updated row actions.
244
	 */
245
	public function add_row_action( $actions, $post ) {
246
		if ( ! $this->user_can_access_post( $post->ID ) ||
247
			! $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...
248
			! $this->validate_post_type( $post ) ) {
249
			return $actions;
250
		}
251
252
		$edit_url    = add_query_arg(
253
			array(
254
				'post_type'    => $post->post_type,
255
				'jetpack-copy' => $post->ID,
256
				'_wpnonce'     => wp_create_nonce( 'jetpack-copy-post' ),
257
			),
258
			admin_url( 'post-new.php' )
259
		);
260
		$edit_action = array(
261
			'jetpack-copy' => sprintf(
262
				'<a href="%s" aria-label="%s">%s</a>',
263
				esc_url( $edit_url ),
264
				esc_attr__( 'Copy this post.', 'jetpack' ),
265
				esc_html__( 'Copy', 'jetpack' )
266
			),
267
		);
268
269
		// Insert the Copy action before the Trash action.
270
		$edit_offset = array_search( 'trash', array_keys( $actions ), true );
271
		$actions     = array_merge(
272
			array_slice( $actions, 0, $edit_offset ),
273
			$edit_action,
274
			array_slice( $actions, $edit_offset )
275
		);
276
277
		return $actions;
278
	}
279
}
280
281
/**
282
 * Instantiate an instance of Jetpack_Copy_Post on the `admin_init` hook.
283
 */
284
function jetpack_copy_post_init() {
285
	new Jetpack_Copy_Post();
286
}
287
add_action( 'admin_init', 'jetpack_copy_post_init' );
288