Completed
Push — update/dialogue-focus-on-conte... ( 9f1745...fa862f )
by
unknown
80:03 queued 71:18
created

class.wpcom-json-api-list-posts-v1-2-endpoint.php (3 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
new WPCOM_JSON_API_List_Posts_v1_2_Endpoint(
4
	array(
5
		'description'      => 'Get a list of matching posts.',
6
		'min_version'      => '1.2',
7
		'max_version'      => '1.2',
8
9
		'group'            => 'posts',
10
		'stat'             => 'posts',
11
12
		'method'           => 'GET',
13
		'path'             => '/sites/%s/posts/',
14
		'path_labels'      => array(
15
			'$site' => '(int|string) Site ID or domain',
16
		),
17
18
		'allow_fallback_to_jetpack_blog_token' => true,
19
20
		'query_parameters' => array(
21
			'number'                => '(int=20) The number of posts to return. Limit: 100.',
22
			'offset'                => '(int=0) 0-indexed offset.',
23
			'page'                  => '(int) Return the Nth 1-indexed page of posts. Takes precedence over the <code>offset</code> parameter.',
24
			'page_handle'           => '(string) A page handle, returned from a previous API call as a <code>meta.next_page</code> property. This is the most efficient way to fetch the next page of results.',
25
			'order'                 => array(
26
				'DESC' => 'Return posts in descending order. For dates, that means newest to oldest.',
27
				'ASC'  => 'Return posts in ascending order. For dates, that means oldest to newest.',
28
			),
29
			'order_by'              => array(
30
				'date'          => 'Order by the created time of each post.',
31
				'modified'      => 'Order by the modified time of each post.',
32
				'title'         => "Order lexicographically by the posts' titles.",
33
				'comment_count' => 'Order by the number of comments for each post.',
34
				'ID'            => 'Order by post ID.',
35
			),
36
			'after'                 => '(ISO 8601 datetime) Return posts dated after the specified datetime.',
37
			'before'                => '(ISO 8601 datetime) Return posts dated before the specified datetime.',
38
			'modified_after'        => '(ISO 8601 datetime) Return posts modified after the specified datetime.',
39
			'modified_before'       => '(ISO 8601 datetime) Return posts modified before the specified datetime.',
40
			'tag'                   => '(string) Specify the tag name or slug.',
41
			'category'              => '(string) Specify the category name or slug.',
42
			'term'                  => '(object:string) Specify comma-separated term slugs to search within, indexed by taxonomy slug.',
43
			'type'                  => "(string) Specify the post type. Defaults to 'post', use 'any' to query for both posts and pages. Post types besides post and page need to be whitelisted using the <code>rest_api_allowed_post_types</code> filter.",
44
			'exclude_private_types' => '(bool=false) Use this flag together with `type=any` to get only publicly accessible posts.',
45
			'parent_id'             => '(int) Returns only posts which are children of the specified post. Applies only to hierarchical post types.',
46
			'exclude'               => '(array:int|int) Excludes the specified post ID(s) from the response',
47
			'exclude_tree'          => '(int) Excludes the specified post and all of its descendants from the response. Applies only to hierarchical post types.',
48
			'status'                => '(string) Comma-separated list of statuses for which to query, including any of: "publish", "private", "draft", "pending", "future", and "trash", or simply "any". Defaults to "publish"',
49
			'sticky'                => array(
50
				'include' => 'Sticky posts are not excluded from the list.',
51
				'exclude' => 'Sticky posts are excluded from the list.',
52
				'require' => 'Only include sticky posts',
53
			),
54
			'author'                => "(int) Author's user ID",
55
			'search'                => '(string) Search query',
56
			'meta_key'              => '(string) Metadata key that the post should contain',
57
			'meta_value'            => '(string) Metadata value that the post should contain. Will only be applied if a `meta_key` is also given',
58
		),
59
60
		'example_request'  => 'https://public-api.wordpress.com/rest/v1.2/sites/en.blog.wordpress.com/posts/?number=2',
61
	)
62
);
63
64
class WPCOM_JSON_API_List_Posts_v1_2_Endpoint extends WPCOM_JSON_API_List_Posts_v1_1_Endpoint {
65
	// /sites/%s/posts/ -> $blog_id
66
	function callback( $path = '', $blog_id = 0 ) {
67
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
68
		if ( is_wp_error( $blog_id ) ) {
69
			return $blog_id;
70
		}
71
72
		$args                        = $this->query_args();
73
		$is_eligible_for_page_handle = true;
74
		$site                        = $this->get_platform()->get_site( $blog_id );
75
76
		if ( $args['number'] < 1 ) {
77
			$args['number'] = 20;
78
		} elseif ( 100 < $args['number'] ) {
79
			return new WP_Error( 'invalid_number', 'The NUMBER parameter must be less than or equal to 100.', 400 );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'invalid_number'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
80
		}
81
82
		if ( isset( $args['type'] ) ) {
83
			// load all types on WPCOM, unless only built-in ones are requested
84 View Code Duplication
			if ( defined( 'IS_WPCOM' ) && IS_WPCOM && ! in_array( $args['type'], array( 'post', 'revision', 'page' ) ) ) {
85
				$this->load_theme_functions();
86
			}
87
88
			if ( ! $site->is_post_type_allowed( $args['type'] ) ) {
89
				return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'unknown_post_type'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
90
			}
91
92
			// Normalize post_type
93
			if ( 'any' == $args['type'] ) {
94
				$whitelisted_post_types = $site->get_whitelisted_post_types();
95
96
				if ( isset( $args['exclude_private_types'] ) && $args['exclude_private_types'] == true ) {
97
					$public_post_types = get_post_types( array( 'public' => true ) );
98
					$args['type']      = array_intersect( $public_post_types, $whitelisted_post_types );
99
				} else {
100
					$args['type'] = $whitelisted_post_types;
101
				}
102
			}
103
		} else {
104
			// let's be explicit about defaulting to 'post'
105
			$args['type'] = 'post';
106
		}
107
108
		// make sure the user can read or edit the requested post type(s)
109 View Code Duplication
		if ( is_array( $args['type'] ) ) {
110
			$allowed_types = array();
111
			foreach ( $args['type'] as $post_type ) {
112
				if ( $site->current_user_can_access_post_type( $post_type, $args['context'] ) ) {
113
					$allowed_types[] = $post_type;
114
				}
115
			}
116
117
			if ( empty( $allowed_types ) ) {
118
				return array(
119
					'found' => 0,
120
					'posts' => array(),
121
				);
122
			}
123
			$args['type'] = $allowed_types;
124
		} else {
125
			if ( ! $site->current_user_can_access_post_type( $args['type'], $args['context'] ) ) {
126
				return array(
127
					'found' => 0,
128
					'posts' => array(),
129
				);
130
			}
131
		}
132
133
		// determine statuses
134
		$status = ( ! empty( $args['status'] ) ) ? explode( ',', $args['status'] ) : array( 'publish' );
135 View Code Duplication
		if ( is_user_logged_in() ) {
136
			$statuses_whitelist = array(
137
				'publish',
138
				'pending',
139
				'draft',
140
				'future',
141
				'private',
142
				'trash',
143
				'any',
144
			);
145
			$status             = array_intersect( $status, $statuses_whitelist );
146
		} else {
147
			// logged-out users can see only published posts
148
			$statuses_whitelist = array( 'publish', 'any' );
149
			$status             = array_intersect( $status, $statuses_whitelist );
150
151
			if ( empty( $status ) ) {
152
				// requested only protected statuses? nothing for you here
153
				return array(
154
					'found' => 0,
155
					'posts' => array(),
156
				);
157
			}
158
			// clear it (AKA published only) because "any" includes protected
159
			$status = array();
160
		}
161
162
		$query = array(
163
			'posts_per_page' => $args['number'],
164
			'order'          => $args['order'],
165
			'orderby'        => $args['order_by'],
166
			'post_type'      => $args['type'],
167
			'post_status'    => $status,
168
			'post_parent'    => isset( $args['parent_id'] ) ? $args['parent_id'] : null,
169
			'author'         => isset( $args['author'] ) && 0 < $args['author'] ? $args['author'] : null,
170
			's'              => isset( $args['search'] ) && '' !== $args['search'] ? $args['search'] : null,
171
			'fields'         => 'ids',
172
		);
173
174
		if ( ! is_user_logged_in() ) {
175
			$query['has_password'] = false;
176
		}
177
178 View Code Duplication
		if ( isset( $args['meta_key'] ) ) {
179
			$show = false;
180
			if ( WPCOM_JSON_API_Metadata::is_public( $args['meta_key'] ) ) {
181
				$show = true;
182
			}
183
			if ( current_user_can( 'edit_post_meta', $query['post_type'], $args['meta_key'] ) ) {
184
				$show = true;
185
			}
186
187
			if ( is_protected_meta( $args['meta_key'], 'post' ) && ! $show ) {
188
				return new WP_Error( 'invalid_meta_key', 'Invalid meta key', 404 );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'invalid_meta_key'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
189
			}
190
191
			$meta = array( 'key' => $args['meta_key'] );
192
			if ( isset( $args['meta_value'] ) ) {
193
				$meta['value'] = $args['meta_value'];
194
			}
195
196
			$query['meta_query'] = array( $meta );
197
		}
198
199 View Code Duplication
		if ( $args['sticky'] === 'include' ) {
200
			$query['ignore_sticky_posts'] = 1;
201
		} elseif ( $args['sticky'] === 'exclude' ) {
202
			$sticky = get_option( 'sticky_posts' );
203
			if ( is_array( $sticky ) ) {
204
				$query['post__not_in'] = $sticky;
205
			}
206
		} elseif ( $args['sticky'] === 'require' ) {
207
			$sticky = get_option( 'sticky_posts' );
208
			if ( is_array( $sticky ) && ! empty( $sticky ) ) {
209
				$query['post__in'] = $sticky;
210
			} else {
211
				// no sticky posts exist
212
				return array(
213
					'found' => 0,
214
					'posts' => array(),
215
				);
216
			}
217
		}
218
219 View Code Duplication
		if ( isset( $args['exclude'] ) ) {
220
			$excluded_ids          = (array) $args['exclude'];
221
			$query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $excluded_ids ) : $excluded_ids;
222
		}
223
224 View Code Duplication
		if ( isset( $args['exclude_tree'] ) && is_post_type_hierarchical( $args['type'] ) ) {
225
			// get_page_children is a misnomer; it supports all hierarchical post types
226
			$page_args        = array(
227
				'child_of'    => $args['exclude_tree'],
228
				'post_type'   => $args['type'],
229
				// since we're looking for things to exclude, be aggressive
230
				'post_status' => 'publish,draft,pending,private,future,trash',
231
			);
232
			$post_descendants = get_pages( $page_args );
233
234
			$exclude_tree = array( $args['exclude_tree'] );
235
			foreach ( $post_descendants as $child ) {
236
				$exclude_tree[] = $child->ID;
237
			}
238
239
			$query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $exclude_tree ) : $exclude_tree;
240
		}
241
242 View Code Duplication
		if ( isset( $args['category'] ) ) {
243
			$category = get_term_by( 'slug', $args['category'], 'category' );
244
			if ( $category === false ) {
245
				$query['category_name'] = $args['category'];
246
			} else {
247
				$query['cat'] = $category->term_id;
248
			}
249
		}
250
251
		if ( isset( $args['tag'] ) ) {
252
			$query['tag'] = $args['tag'];
253
		}
254
255 View Code Duplication
		if ( ! empty( $args['term'] ) ) {
256
			$query['tax_query'] = array();
257
			foreach ( $args['term'] as $taxonomy => $slug ) {
258
				$taxonomy_object = get_taxonomy( $taxonomy );
259
				if ( false === $taxonomy_object || ( ! $taxonomy_object->public &&
260
						! current_user_can( $taxonomy_object->cap->assign_terms ) ) ) {
261
					continue;
262
				}
263
264
				$query['tax_query'][] = array(
265
					'taxonomy' => $taxonomy,
266
					'field'    => 'slug',
267
					'terms'    => explode( ',', $slug ),
268
				);
269
			}
270
		}
271
272 View Code Duplication
		if ( isset( $args['page'] ) ) {
273
			if ( $args['page'] < 1 ) {
274
				$args['page'] = 1;
275
			}
276
277
			$query['paged'] = $args['page'];
278
			if ( $query['paged'] !== 1 ) {
279
				$is_eligible_for_page_handle = false;
280
			}
281
		} else {
282
			if ( $args['offset'] < 0 ) {
283
				$args['offset'] = 0;
284
			}
285
286
			$query['offset'] = $args['offset'];
287
			if ( $query['offset'] !== 0 ) {
288
				$is_eligible_for_page_handle = false;
289
			}
290
		}
291
292
		if ( isset( $args['before'] ) ) {
293
			$this->date_range['before'] = $args['before'];
294
		}
295
		if ( isset( $args['after'] ) ) {
296
			$this->date_range['after'] = $args['after'];
297
		}
298
299
		if ( isset( $args['modified_before_gmt'] ) ) {
300
			$this->modified_range['before'] = $args['modified_before_gmt'];
301
		}
302
		if ( isset( $args['modified_after_gmt'] ) ) {
303
			$this->modified_range['after'] = $args['modified_after_gmt'];
304
		}
305
306
		if ( $this->date_range ) {
307
			add_filter( 'posts_where', array( $this, 'handle_date_range' ) );
308
		}
309
310
		if ( $this->modified_range ) {
311
			add_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
312
		}
313
314 View Code Duplication
		if ( isset( $args['page_handle'] ) ) {
315
			$page_handle = wp_parse_args( $args['page_handle'] );
316
			if ( isset( $page_handle['value'] ) && isset( $page_handle['id'] ) ) {
317
				// we have a valid looking page handle
318
				$this->page_handle = $page_handle;
319
				add_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
320
			}
321
		}
322
323
		/**
324
		 * 'column' necessary for the me/posts endpoint (which extends sites/$site/posts).
325
		 * Would need to be added to the sites/$site/posts definition if we ever want to
326
		 * use it there.
327
		 */
328
		$column_whitelist = array( 'post_modified_gmt' );
329 View Code Duplication
		if ( isset( $args['column'] ) && in_array( $args['column'], $column_whitelist ) ) {
330
			$query['column'] = $args['column'];
331
		}
332
333
		$this->performed_query = $query;
334
		add_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
335
336
		$wp_query = new WP_Query( $query );
337
338
		remove_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
339
340
		if ( $this->date_range ) {
341
			remove_filter( 'posts_where', array( $this, 'handle_date_range' ) );
342
			$this->date_range = array();
343
		}
344
345
		if ( $this->modified_range ) {
346
			remove_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
347
			$this->modified_range = array();
348
		}
349
350
		if ( $this->page_handle ) {
351
			remove_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
352
353
		}
354
355
		$return         = array();
356
		$excluded_count = 0;
357 View Code Duplication
		foreach ( array_keys( $this->response_format ) as $key ) {
358
			switch ( $key ) {
359
				case 'found':
360
					$return[ $key ] = (int) $wp_query->found_posts;
361
					break;
362
				case 'posts':
363
					$posts = array();
364
					foreach ( $wp_query->posts as $post_ID ) {
365
						$the_post = $this->get_post_by( 'ID', $post_ID, $args['context'] );
366
						if ( $the_post && ! is_wp_error( $the_post ) ) {
367
							$posts[] = $the_post;
368
						} else {
369
							$excluded_count++;
370
						}
371
					}
372
373
					if ( $posts ) {
374
						/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
375
						do_action( 'wpcom_json_api_objects', 'posts', count( $posts ) );
376
					}
377
378
					$return[ $key ] = $posts;
379
					break;
380
381
				case 'meta':
382
					if ( ! is_array( $args['type'] ) ) {
383
						$return[ $key ] = (object) array(
384
							'links' => (object) array(
385
								'counts' => (string) $this->links->get_site_link( $blog_id, 'post-counts/' . $args['type'] ),
386
							),
387
						);
388
					}
389
390
					if ( $is_eligible_for_page_handle && $return['posts'] ) {
391
						$last_post = end( $return['posts'] );
392
						reset( $return['posts'] );
393
						if ( ( $return['found'] > count( $return['posts'] ) ) && $last_post ) {
394
							if ( ! isset( $return[ $key ] ) ) {
395
								$return[ $key ] = (object) array();
396
							}
397
398
							if ( isset( $last_post['ID'] ) ) {
399
								$return[ $key ]->next_page = $this->build_page_handle( $last_post, $query );
400
							}
401
						}
402
					}
403
404
					if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
405
						if ( ! isset( $return[ $key ] ) ) {
406
							$return[ $key ] = new stdClass();
407
						}
408
						$return[ $key ]->wpcom = true;
409
					}
410
411
					break;
412
			}
413
		}
414
415
		$return['found'] -= $excluded_count;
416
417
		return $return;
418
	}
419
420 View Code Duplication
	function build_page_handle( $post, $query ) {
421
		$column = $query['orderby'];
422
		if ( ! $column ) {
423
			$column = 'date';
424
		}
425
		return build_query(
426
			array(
427
				'value' => urlencode( $post[ $column ] ),
428
				'id'    => $post['ID'],
429
			)
430
		);
431
	}
432
433 View Code Duplication
	function _build_date_range_query( $column, $range, $where ) {
434
		global $wpdb;
435
436
		switch ( count( $range ) ) {
437
			case 2:
438
				$where .= $wpdb->prepare(
439
					" AND `$wpdb->posts`.$column >= CAST( %s AS DATETIME ) AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
440
					$range['after'],
441
					$range['before']
442
				);
443
				break;
444
			case 1:
445
				if ( isset( $range['before'] ) ) {
446
					$where .= $wpdb->prepare(
447
						" AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
448
						$range['before']
449
					);
450
				} else {
451
					$where .= $wpdb->prepare(
452
						" AND `$wpdb->posts`.$column > CAST( %s AS DATETIME ) ",
453
						$range['after']
454
					);
455
				}
456
				break;
457
		}
458
459
		return $where;
460
	}
461
}
462