Completed
Push — master-stable ( 53f101...a82972 )
by
unknown
86:26 queued 76:28
created

class.wpcom-json-api-list-posts-v1-2-endpoint.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/*
3
 * WARNING: This file is distributed verbatim in Jetpack.
4
 * There should be nothing WordPress.com specific in this file.
5
 *
6
 * @hide-in-jetpack
7
 */
8
9
class WPCOM_JSON_API_List_Posts_v1_2_Endpoint extends WPCOM_JSON_API_List_Posts_v1_1_Endpoint {
10
	// /sites/%s/posts/ -> $blog_id
11
	function callback( $path = '', $blog_id = 0 ) {
12
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
13
		if ( is_wp_error( $blog_id ) ) {
14
			return $blog_id;
15
		}
16
17
		$args = $this->query_args();
18
		$is_eligible_for_page_handle = true;
19
		$site = $this->get_platform()->get_site( $blog_id );
20
21
		if ( $args['number'] < 1 ) {
22
			$args['number'] = 20;
23
		} elseif ( 100 < $args['number'] ) {
24
			return new WP_Error( 'invalid_number',  'The NUMBER parameter must be less than or equal to 100.', 400 );
25
		}
26
27
		if ( isset( $args['type'] ) ) {
28
			// load all types on WPCOM, unless only built-in ones are requested
29 View Code Duplication
			if ( defined( 'IS_WPCOM' ) && IS_WPCOM && ! in_array( $args['type'], array( 'post', 'revision', 'page' ) ) ) {
30
				$this->load_theme_functions();
31
			}
32
33
			if ( ! $site->is_post_type_allowed( $args['type'] ) ) {
34
				return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
35
			}
36
37
			// Normalize post_type
38
			if ( 'any' == $args['type'] ) {
39
				$whitelisted_post_types = $site->get_whitelisted_post_types();
40
41
				if ( isset( $args['exclude_private_types'] ) && $args['exclude_private_types'] == true ) {
42
					$public_post_types = get_post_types( array( 'public' => true ) );
43
					$args['type'] = array_intersect( $public_post_types, $whitelisted_post_types );
44
				} else {
45
					$args['type'] = $whitelisted_post_types;
46
				}
47
			}
48
		} else {
49
			// let's be explicit about defaulting to 'post'
50
			$args['type'] = 'post';
51
		}
52
53
		// make sure the user can read or edit the requested post type(s)
54 View Code Duplication
		if ( is_array( $args['type'] ) ) {
55
			$allowed_types = array();
56
			foreach ( $args['type'] as $post_type ) {
57
				if ( $site->current_user_can_access_post_type( $post_type, $args['context'] ) ) {
58
					$allowed_types[] = $post_type;
59
				}
60
			}
61
62
			if ( empty( $allowed_types ) ) {
63
				return array( 'found' => 0, 'posts' => array() );
64
			}
65
			$args['type'] = $allowed_types;
66
		}
67
		else {
68
			if ( ! $site->current_user_can_access_post_type( $args['type'], $args['context'] ) ) {
69
				return array( 'found' => 0, 'posts' => array() );
70
			}
71
		}
72
73
		// determine statuses
74
		$status = ( ! empty( $args['status'] ) ) ? explode( ',', $args['status'] ) : array( 'publish' );
75 View Code Duplication
		if ( is_user_logged_in() ) {
76
			$statuses_whitelist = array(
77
				'publish',
78
				'pending',
79
				'draft',
80
				'future',
81
				'private',
82
				'trash',
83
				'any',
84
			);
85
			$status = array_intersect( $status, $statuses_whitelist );
86
		} else {
87
			// logged-out users can see only published posts
88
			$statuses_whitelist = array( 'publish', 'any' );
89
			$status = array_intersect( $status, $statuses_whitelist );
90
91
			if ( empty( $status ) ) {
92
				// requested only protected statuses? nothing for you here
93
				return array( 'found' => 0, 'posts' => array() );
94
			}
95
			// clear it (AKA published only) because "any" includes protected
96
			$status = array();
97
		}
98
99
		$query = array(
100
			'posts_per_page' => $args['number'],
101
			'order'          => $args['order'],
102
			'orderby'        => $args['order_by'],
103
			'post_type'      => $args['type'],
104
			'post_status'    => $status,
105
			'post_parent'    => isset( $args['parent_id'] ) ? $args['parent_id'] : null,
106
			'author'         => isset( $args['author'] ) && 0 < $args['author'] ? $args['author'] : null,
107
			's'              => isset( $args['search'] ) ? $args['search'] : null,
108
			'fields'         => 'ids',
109
		);
110
111
		if ( ! is_user_logged_in () ) {
112
			$query['has_password'] = false;
113
		}
114
115
		if ( isset( $args['meta_key'] ) ) {
116
			$show = false;
117
			if ( WPCOM_JSON_API_Metadata::is_public( $args['meta_key'] ) )
118
				$show = true;
119
			if ( current_user_can( 'edit_post_meta', $query['post_type'], $args['meta_key'] ) )
120
				$show = true;
121
122
			if ( is_protected_meta( $args['meta_key'], 'post' ) && ! $show )
123
				return new WP_Error( 'invalid_meta_key', 'Invalid meta key', 404 );
124
125
			$meta = array( 'key' => $args['meta_key'] );
126
			if ( isset( $args['meta_value'] ) )
127
				$meta['value'] = $args['meta_value'];
128
129
			$query['meta_query'] = array( $meta );
130
		}
131
132 View Code Duplication
		if ( $args['sticky'] === 'include' ) {
133
			$query['ignore_sticky_posts'] = 1;
134
		} else if ( $args['sticky'] === 'exclude' ) {
135
			$sticky = get_option( 'sticky_posts' );
136
			if ( is_array( $sticky ) ) {
137
				$query['post__not_in'] = $sticky;
138
			}
139
		} else if ( $args['sticky'] === 'require' ) {
140
			$sticky = get_option( 'sticky_posts' );
141
			if ( is_array( $sticky ) && ! empty( $sticky ) ) {
142
				$query['post__in'] = $sticky;
143
			} else {
144
				// no sticky posts exist
145
				return array( 'found' => 0, 'posts' => array() );
146
			}
147
		}
148
149 View Code Duplication
		if ( isset( $args['exclude'] ) ) {
150
			$excluded_ids = (array) $args['exclude'];
151
			$query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $excluded_ids ) : $excluded_ids;
152
		}
153
154 View Code Duplication
		if ( isset( $args['exclude_tree'] ) && is_post_type_hierarchical( $args['type'] ) ) {
155
			// get_page_children is a misnomer; it supports all hierarchical post types
156
			$page_args = array(
157
					'child_of' => $args['exclude_tree'],
158
					'post_type' => $args['type'],
159
					// since we're looking for things to exclude, be aggressive
160
					'post_status' => 'publish,draft,pending,private,future,trash',
161
				);
162
			$post_descendants = get_pages( $page_args );
163
164
			$exclude_tree = array( $args['exclude_tree'] );
165
			foreach ( $post_descendants as $child ) {
166
				$exclude_tree[] = $child->ID;
167
			}
168
169
			$query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $exclude_tree ) : $exclude_tree;
170
		}
171
172
		if ( isset( $args['category'] ) ) {
173
			$category = get_term_by( 'slug', $args['category'], 'category' );
174
			if ( $category === false) {
175
				$query['category_name'] = $args['category'];
176
			} else {
177
				$query['cat'] = $category->term_id;
178
			}
179
		}
180
181
		if ( isset( $args['tag'] ) ) {
182
			$query['tag'] = $args['tag'];
183
		}
184
185 View Code Duplication
		if ( ! empty( $args['term'] ) ) {
186
			$query['tax_query'] = array();
187
			foreach ( $args['term'] as $taxonomy => $slug ) {
188
				$taxonomy_object = get_taxonomy( $taxonomy );
189
				if ( false === $taxonomy_object || ( ! $taxonomy_object->public &&
190
						! current_user_can( $taxonomy_object->cap->assign_terms ) ) ) {
191
					continue;
192
				}
193
194
				$query['tax_query'][] = array(
195
					'taxonomy' => $taxonomy,
196
					'field' => 'slug',
197
					'terms' => explode( ',', $slug )
198
				);
199
			}
200
		}
201
202 View Code Duplication
		if ( isset( $args['page'] ) ) {
203
			if ( $args['page'] < 1 ) {
204
				$args['page'] = 1;
205
			}
206
207
			$query['paged'] = $args['page'];
208
			if ( $query['paged'] !== 1 ) {
209
				$is_eligible_for_page_handle = false;
210
			}
211
		} else {
212
			if ( $args['offset'] < 0 ) {
213
				$args['offset'] = 0;
214
			}
215
216
			$query['offset'] = $args['offset'];
217
			if ( $query['offset'] !== 0 ) {
218
				$is_eligible_for_page_handle = false;
219
			}
220
		}
221
222
		if ( isset( $args['before'] ) ) {
223
			$this->date_range['before'] = $args['before'];
224
		}
225
		if ( isset( $args['after'] ) ) {
226
			$this->date_range['after'] = $args['after'];
227
		}
228
229
		if ( isset( $args['modified_before_gmt'] ) ) {
230
			$this->modified_range['before'] = $args['modified_before_gmt'];
231
		}
232
		if ( isset( $args['modified_after_gmt'] ) ) {
233
			$this->modified_range['after'] = $args['modified_after_gmt'];
234
		}
235
236
		if ( $this->date_range ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->date_range of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
237
			add_filter( 'posts_where', array( $this, 'handle_date_range' ) );
238
		}
239
240
		if ( $this->modified_range ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->modified_range of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
241
			add_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
242
		}
243
244
		if ( isset( $args['page_handle'] ) ) {
245
			$page_handle = wp_parse_args( $args['page_handle'] );
246
			if ( isset( $page_handle['value'] ) && isset( $page_handle['id'] ) ) {
247
				// we have a valid looking page handle
248
				$this->page_handle = $page_handle;
249
				add_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
250
			}
251
		}
252
253
		/**
254
		 * 'column' necessary for the me/posts endpoint (which extends sites/$site/posts).
255
		 * Would need to be added to the sites/$site/posts definition if we ever want to
256
		 * use it there.
257
		 */
258
		$column_whitelist = array( 'post_modified_gmt' );
259 View Code Duplication
		if ( isset( $args['column'] ) && in_array( $args['column'], $column_whitelist ) ) {
260
			$query['column'] = $args['column'];
261
		}
262
263
		$this->performed_query = $query;
264
		add_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
265
266
		$wp_query = new WP_Query( $query );
267
268
		remove_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
269
270
		if ( $this->date_range ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->date_range of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
271
			remove_filter( 'posts_where', array( $this, 'handle_date_range' ) );
272
			$this->date_range = array();
273
		}
274
275
		if ( $this->modified_range ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->modified_range of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
276
			remove_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
277
			$this->modified_range = array();
278
		}
279
280
		if ( $this->page_handle ) {
281
			remove_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
282
283
		}
284
285
		$return = array();
286
		$excluded_count = 0;
287 View Code Duplication
		foreach ( array_keys( $this->response_format ) as $key ) {
288
			switch ( $key ) {
289
			case 'found' :
290
				$return[$key] = (int) $wp_query->found_posts;
291
				break;
292
			case 'posts' :
293
				$posts = array();
294
				foreach ( $wp_query->posts as $post_ID ) {
295
					$the_post = $this->get_post_by( 'ID', $post_ID, $args['context'] );
296
					if ( $the_post && ! is_wp_error( $the_post ) ) {
297
						$posts[] = $the_post;
298
					} else {
299
						$excluded_count++;
300
					}
301
				}
302
303
				if ( $posts ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $posts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
304
					/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
305
					do_action( 'wpcom_json_api_objects', 'posts', count( $posts ) );
306
				}
307
308
				$return[$key] = $posts;
309
				break;
310
311
			case 'meta' :
312
				if ( ! is_array( $args['type'] ) ) {
313
					$return[$key] = (object) array(
314
						'links' => (object) array(
315
							'counts' => (string) $this->links->get_site_link( $blog_id, 'post-counts/' . $args['type'] ),
316
						)
317
					);
318
				}
319
320
				if ( $is_eligible_for_page_handle && $return['posts'] ) {
321
					$last_post = end( $return['posts'] );
322
					reset( $return['posts'] );
323
					if ( ( $return['found'] > count( $return['posts'] ) ) && $last_post ) {
324
						if ( ! isset( $return[$key] ) ) {
325
							$return[$key] = (object) array();
326
						}
327
						$return[$key]->next_page = $this->build_page_handle( $last_post, $query );
328
					}
329
				}
330
331
				if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
332
					if ( !isset( $return[$key] ) )
333
						$return[$key] = new stdClass;
334
					$return[$key]->wpcom = true;
335
				}
336
337
				break;
338
			}
339
		}
340
341
		$return['found'] -= $excluded_count;
342
343
		return $return;
344
	}
345
346 View Code Duplication
	function build_page_handle( $post, $query ) {
347
		$column = $query['orderby'];
348
		if ( ! $column ) {
349
			$column = 'date';
350
		}
351
		return build_query( array( 'value' => urlencode($post[$column]), 'id' => $post['ID'] ) );
352
	}
353
354 View Code Duplication
	function _build_date_range_query( $column, $range, $where ) {
355
		global $wpdb;
356
357
		switch ( count( $range ) ) {
358
			case 2 :
359
				$where .= $wpdb->prepare(
360
					" AND `$wpdb->posts`.$column >= CAST( %s AS DATETIME ) AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
361
					$range['after'],
362
					$range['before']
363
				);
364
				break;
365
			case 1 :
366
				if ( isset( $range['before'] ) ) {
367
					$where .= $wpdb->prepare(
368
						" AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
369
						$range['before']
370
					);
371
				} else {
372
					$where .= $wpdb->prepare(
373
						" AND `$wpdb->posts`.$column > CAST( %s AS DATETIME ) ",
374
						$range['after']
375
					);
376
				}
377
				break;
378
		}
379
380
		return $where;
381
	}
382
}
383