Completed
Push — update/editor-blocks-icon-colo... ( 093ab2...3cfb5e )
by
unknown
08:47
created

class.wpcom-json-api-list-posts-v1-1-endpoint.php (1 issue)

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_1_Endpoint(
4
	array(
5
		'description'      => 'Get a list of matching posts.',
6
		'min_version'      => '1.1',
7
		'max_version'      => '1.1',
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
		'query_parameters' => array(
19
			'number'          => '(int=20) The number of posts to return. Limit: 100.',
20
			'offset'          => '(int=0) 0-indexed offset.',
21
			'page'            => '(int) Return the Nth 1-indexed page of posts. Takes precedence over the <code>offset</code> parameter.',
22
			'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.',
23
			'order'           => array(
24
				'DESC' => 'Return posts in descending order. For dates, that means newest to oldest.',
25
				'ASC'  => 'Return posts in ascending order. For dates, that means oldest to newest.',
26
			),
27
			'order_by'        => array(
28
				'date'          => 'Order by the created time of each post.',
29
				'modified'      => 'Order by the modified time of each post.',
30
				'title'         => "Order lexicographically by the posts' titles.",
31
				'comment_count' => 'Order by the number of comments for each post.',
32
				'ID'            => 'Order by post ID.',
33
			),
34
			'after'           => '(ISO 8601 datetime) Return posts dated after the specified datetime.',
35
			'before'          => '(ISO 8601 datetime) Return posts dated before the specified datetime.',
36
			'modified_after'  => '(ISO 8601 datetime) Return posts modified after the specified datetime.',
37
			'modified_before' => '(ISO 8601 datetime) Return posts modified before the specified datetime.',
38
			'tag'             => '(string) Specify the tag name or slug.',
39
			'category'        => '(string) Specify the category name or slug.',
40
			'term'            => '(object:string) Specify comma-separated term slugs to search within, indexed by taxonomy slug.',
41
			'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.",
42
			'parent_id'       => '(int) Returns only posts which are children of the specified post. Applies only to hierarchical post types.',
43
			'exclude'         => '(array:int|int) Excludes the specified post ID(s) from the response',
44
			'exclude_tree'    => '(int) Excludes the specified post and all of its descendants from the response. Applies only to hierarchical post types.',
45
			'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"',
46
			'sticky'          => array(
47
				'include' => 'Sticky posts are not excluded from the list.',
48
				'exclude' => 'Sticky posts are excluded from the list.',
49
				'require' => 'Only include sticky posts',
50
			),
51
			'author'          => "(int) Author's user ID",
52
			'search'          => '(string) Search query',
53
			'meta_key'        => '(string) Metadata key that the post should contain',
54
			'meta_value'      => '(string) Metadata value that the post should contain. Will only be applied if a `meta_key` is also given',
55
		),
56
57
		'example_request'  => 'https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts/?number=2',
58
	)
59
);
60
61
class WPCOM_JSON_API_List_Posts_v1_1_Endpoint extends WPCOM_JSON_API_Post_v1_1_Endpoint {
62
	public $date_range      = array();
63
	public $modified_range  = array();
64
	public $page_handle     = array();
65
	public $performed_query = null;
66
67
	public $response_format = array(
68
		'found' => '(int) The total number of posts found that match the request (ignoring limits, offsets, and pagination).',
69
		'posts' => '(array:post) An array of post objects.',
70
		'meta'  => '(object) Meta data',
71
	);
72
73
	// /sites/%s/posts/ -> $blog_id
74
	function callback( $path = '', $blog_id = 0 ) {
75
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
76
		if ( is_wp_error( $blog_id ) ) {
77
			return $blog_id;
78
		}
79
80
		$args                        = $this->query_args();
81
		$is_eligible_for_page_handle = true;
82
		$site                        = $this->get_platform()->get_site( $blog_id );
83
84
		if ( $args['number'] < 1 ) {
85
			$args['number'] = 20;
86
		} elseif ( 100 < $args['number'] ) {
87
			return new WP_Error( 'invalid_number', 'The NUMBER parameter must be less than or equal to 100.', 400 );
88
		}
89
90 View Code Duplication
		if ( isset( $args['type'] ) &&
91
			   ! in_array( $args['type'], array( 'post', 'revision', 'page', 'any' ) ) &&
92
			   defined( 'IS_WPCOM' ) && IS_WPCOM ) {
93
			$this->load_theme_functions();
94
		}
95
96 View Code Duplication
		if ( isset( $args['type'] ) && ! $site->is_post_type_allowed( $args['type'] ) ) {
97
			return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
98
		}
99
100
		// Normalize post_type
101 View Code Duplication
		if ( isset( $args['type'] ) && 'any' == $args['type'] ) {
102
			if ( version_compare( $this->api->version, '1.1', '<' ) ) {
103
				$args['type'] = array( 'post', 'page' );
104
			} else { // 1.1+
105
				$args['type'] = $site->get_whitelisted_post_types();
106
			}
107
		}
108
109
		// determine statuses
110
		$status = ( ! empty( $args['status'] ) ) ? explode( ',', $args['status'] ) : array( 'publish' );
111 View Code Duplication
		if ( is_user_logged_in() ) {
112
			$statuses_whitelist = array(
113
				'publish',
114
				'pending',
115
				'draft',
116
				'future',
117
				'private',
118
				'trash',
119
				'any',
120
			);
121
			$status             = array_intersect( $status, $statuses_whitelist );
122
		} else {
123
			// logged-out users can see only published posts
124
			$statuses_whitelist = array( 'publish', 'any' );
125
			$status             = array_intersect( $status, $statuses_whitelist );
126
127
			if ( empty( $status ) ) {
128
				// requested only protected statuses? nothing for you here
129
				return array(
130
					'found' => 0,
131
					'posts' => array(),
132
				);
133
			}
134
			// clear it (AKA published only) because "any" includes protected
135
			$status = array();
136
		}
137
138
		// let's be explicit about defaulting to 'post'
139
		$args['type'] = isset( $args['type'] ) ? $args['type'] : 'post';
140
141
		// make sure the user can read or edit the requested post type(s)
142 View Code Duplication
		if ( is_array( $args['type'] ) ) {
143
			$allowed_types = array();
144
			foreach ( $args['type'] as $post_type ) {
145
				if ( $site->current_user_can_access_post_type( $post_type, $args['context'] ) ) {
146
					$allowed_types[] = $post_type;
147
				}
148
			}
149
150
			if ( empty( $allowed_types ) ) {
151
				return array(
152
					'found' => 0,
153
					'posts' => array(),
154
				);
155
			}
156
			$args['type'] = $allowed_types;
157
		} else {
158
			if ( ! $site->current_user_can_access_post_type( $args['type'], $args['context'] ) ) {
159
				return array(
160
					'found' => 0,
161
					'posts' => array(),
162
				);
163
			}
164
		}
165
166
		$query = array(
167
			'posts_per_page' => $args['number'],
168
			'order'          => $args['order'],
169
			'orderby'        => $args['order_by'],
170
			'post_type'      => $args['type'],
171
			'post_status'    => $status,
172
			'post_parent'    => isset( $args['parent_id'] ) ? $args['parent_id'] : null,
173
			'author'         => isset( $args['author'] ) && 0 < $args['author'] ? $args['author'] : null,
174
			's'              => isset( $args['search'] ) && '' !== $args['search'] ? $args['search'] : null,
175
			'fields'         => 'ids',
176
		);
177
178
		if ( ! is_user_logged_in() ) {
179
			$query['has_password'] = false;
180
		}
181
182 View Code Duplication
		if ( isset( $args['meta_key'] ) ) {
183
			$show = false;
184
			if ( WPCOM_JSON_API_Metadata::is_public( $args['meta_key'] ) ) {
185
				$show = true;
186
			}
187
			if ( current_user_can( 'edit_post_meta', $query['post_type'], $args['meta_key'] ) ) {
188
				$show = true;
189
			}
190
191
			if ( is_protected_meta( $args['meta_key'], 'post' ) && ! $show ) {
192
				return new WP_Error( 'invalid_meta_key', 'Invalid meta key', 404 );
193
			}
194
195
			$meta = array( 'key' => $args['meta_key'] );
196
			if ( isset( $args['meta_value'] ) ) {
197
				$meta['value'] = $args['meta_value'];
198
			}
199
200
			$query['meta_query'] = array( $meta );
201
		}
202
203 View Code Duplication
		if ( $args['sticky'] === 'include' ) {
204
			$query['ignore_sticky_posts'] = 1;
205
		} elseif ( $args['sticky'] === 'exclude' ) {
206
			$sticky = get_option( 'sticky_posts' );
207
			if ( is_array( $sticky ) ) {
208
				$query['post__not_in'] = $sticky;
209
			}
210
		} elseif ( $args['sticky'] === 'require' ) {
211
			$sticky = get_option( 'sticky_posts' );
212
			if ( is_array( $sticky ) && ! empty( $sticky ) ) {
213
				$query['post__in'] = $sticky;
214
			} else {
215
				// no sticky posts exist
216
				return array(
217
					'found' => 0,
218
					'posts' => array(),
219
				);
220
			}
221
		}
222
223 View Code Duplication
		if ( isset( $args['exclude'] ) ) {
224
			$excluded_ids          = (array) $args['exclude'];
225
			$query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $excluded_ids ) : $excluded_ids;
226
		}
227
228 View Code Duplication
		if ( isset( $args['exclude_tree'] ) && is_post_type_hierarchical( $args['type'] ) ) {
229
			// get_page_children is a misnomer; it supports all hierarchical post types
230
			$page_args        = array(
231
				'child_of'    => $args['exclude_tree'],
232
				'post_type'   => $args['type'],
233
				// since we're looking for things to exclude, be aggressive
234
				'post_status' => 'publish,draft,pending,private,future,trash',
235
			);
236
			$post_descendants = get_pages( $page_args );
237
238
			$exclude_tree = array( $args['exclude_tree'] );
239
			foreach ( $post_descendants as $child ) {
240
				$exclude_tree[] = $child->ID;
241
			}
242
243
			$query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $exclude_tree ) : $exclude_tree;
244
		}
245
246 View Code Duplication
		if ( isset( $args['category'] ) ) {
247
			$category = get_term_by( 'slug', $args['category'], 'category' );
248
			if ( $category === false ) {
249
				$query['category_name'] = $args['category'];
250
			} else {
251
				$query['cat'] = $category->term_id;
252
			}
253
		}
254
255
		if ( isset( $args['tag'] ) ) {
256
			$query['tag'] = $args['tag'];
257
		}
258
259 View Code Duplication
		if ( ! empty( $args['term'] ) ) {
260
			$query['tax_query'] = array();
261
			foreach ( $args['term'] as $taxonomy => $slug ) {
262
				$taxonomy_object = get_taxonomy( $taxonomy );
263
				if ( false === $taxonomy_object || ( ! $taxonomy_object->public &&
264
						! current_user_can( $taxonomy_object->cap->assign_terms ) ) ) {
265
					continue;
266
				}
267
268
				$query['tax_query'][] = array(
269
					'taxonomy' => $taxonomy,
270
					'field'    => 'slug',
271
					'terms'    => explode( ',', $slug ),
272
				);
273
			}
274
		}
275
276 View Code Duplication
		if ( isset( $args['page'] ) ) {
277
			if ( $args['page'] < 1 ) {
278
				$args['page'] = 1;
279
			}
280
281
			$query['paged'] = $args['page'];
282
			if ( $query['paged'] !== 1 ) {
283
				$is_eligible_for_page_handle = false;
284
			}
285
		} else {
286
			if ( $args['offset'] < 0 ) {
287
				$args['offset'] = 0;
288
			}
289
290
			$query['offset'] = $args['offset'];
291
			if ( $query['offset'] !== 0 ) {
292
				$is_eligible_for_page_handle = false;
293
			}
294
		}
295
296
		if ( isset( $args['before_gmt'] ) ) {
297
			$this->date_range['before'] = $args['before_gmt'];
298
		}
299
		if ( isset( $args['after_gmt'] ) ) {
300
			$this->date_range['after'] = $args['after_gmt'];
301
		}
302
303
		if ( isset( $args['modified_before_gmt'] ) ) {
304
			$this->modified_range['before'] = $args['modified_before_gmt'];
305
		}
306
		if ( isset( $args['modified_after_gmt'] ) ) {
307
			$this->modified_range['after'] = $args['modified_after_gmt'];
308
		}
309
310
		if ( $this->date_range ) {
311
			add_filter( 'posts_where', array( $this, 'handle_date_range' ) );
312
		}
313
314
		if ( $this->modified_range ) {
315
			add_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
316
		}
317
318 View Code Duplication
		if ( isset( $args['page_handle'] ) ) {
319
			$page_handle = wp_parse_args( $args['page_handle'] );
320
			if ( isset( $page_handle['value'] ) && isset( $page_handle['id'] ) ) {
321
				// we have a valid looking page handle
322
				$this->page_handle = $page_handle;
323
				add_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
324
			}
325
		}
326
327
		/**
328
		 * 'column' necessary for the me/posts endpoint (which extends sites/$site/posts).
329
		 * Would need to be added to the sites/$site/posts definition if we ever want to
330
		 * use it there.
331
		 */
332
		$column_whitelist = array( 'post_modified_gmt' );
333 View Code Duplication
		if ( isset( $args['column'] ) && in_array( $args['column'], $column_whitelist ) ) {
334
			$query['column'] = $args['column'];
335
		}
336
337
		$this->performed_query = $query;
338
		add_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
339
340
		$wp_query = new WP_Query( $query );
341
342
		remove_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
343
344
		if ( $this->date_range ) {
345
			remove_filter( 'posts_where', array( $this, 'handle_date_range' ) );
346
			$this->date_range = array();
347
		}
348
349
		if ( $this->modified_range ) {
350
			remove_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
351
			$this->modified_range = array();
352
		}
353
354
		if ( $this->page_handle ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->page_handle 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...
355
			remove_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
356
357
		}
358
359
		$return         = array();
360
		$excluded_count = 0;
361 View Code Duplication
		foreach ( array_keys( $this->response_format ) as $key ) {
362
			switch ( $key ) {
363
				case 'found':
364
					$return[ $key ] = (int) $wp_query->found_posts;
365
					break;
366
				case 'posts':
367
					$posts = array();
368
					foreach ( $wp_query->posts as $post_ID ) {
369
						$the_post = $this->get_post_by( 'ID', $post_ID, $args['context'] );
370
						if ( $the_post && ! is_wp_error( $the_post ) ) {
371
							$posts[] = $the_post;
372
						} else {
373
							$excluded_count++;
374
						}
375
					}
376
377
					if ( $posts ) {
378
						/** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
379
						do_action( 'wpcom_json_api_objects', 'posts', count( $posts ) );
380
					}
381
382
					$return[ $key ] = $posts;
383
					break;
384
385
				case 'meta':
386
					if ( ! is_array( $args['type'] ) ) {
387
						$return[ $key ] = (object) array(
388
							'links' => (object) array(
389
								'counts' => (string) $this->links->get_site_link( $blog_id, 'post-counts/' . $args['type'] ),
390
							),
391
						);
392
					}
393
394
					if ( $is_eligible_for_page_handle && $return['posts'] ) {
395
						$last_post = end( $return['posts'] );
396
						reset( $return['posts'] );
397
						if ( ( $return['found'] > count( $return['posts'] ) ) && $last_post ) {
398
							if ( ! isset( $return[ $key ] ) ) {
399
								$return[ $key ] = (object) array();
400
							}
401
							if ( isset( $last_post['ID'] ) ) {
402
								$return[ $key ]->next_page = $this->build_page_handle( $last_post, $query );
403
							}
404
						}
405
					}
406
407
					if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
408
						if ( ! isset( $return[ $key ] ) ) {
409
							$return[ $key ] = new stdClass();
410
						}
411
						$return[ $key ]->wpcom = true;
412
					}
413
414
					break;
415
			}
416
		}
417
418
		$return['found'] -= $excluded_count;
419
420
		return $return;
421
	}
422
423 View Code Duplication
	function build_page_handle( $post, $query ) {
424
		$column = $query['orderby'];
425
		if ( ! $column ) {
426
			$column = 'date';
427
		}
428
		return build_query(
429
			array(
430
				'value' => urlencode( $post[ $column ] ),
431
				'id'    => $post['ID'],
432
			)
433
		);
434
	}
435
436 View Code Duplication
	function _build_date_range_query( $column, $range, $where ) {
437
		global $wpdb;
438
439
		switch ( count( $range ) ) {
440
			case 2:
441
				$where .= $wpdb->prepare(
442
					" AND `$wpdb->posts`.$column >= CAST( %s AS DATETIME ) AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
443
					$range['after'],
444
					$range['before']
445
				);
446
				break;
447
			case 1:
448
				if ( isset( $range['before'] ) ) {
449
					$where .= $wpdb->prepare(
450
						" AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
451
						$range['before']
452
					);
453
				} else {
454
					$where .= $wpdb->prepare(
455
						" AND `$wpdb->posts`.$column > CAST( %s AS DATETIME ) ",
456
						$range['after']
457
					);
458
				}
459
				break;
460
		}
461
462
		return $where;
463
	}
464
465
	function handle_date_range( $where ) {
466
		return $this->_build_date_range_query( 'post_date_gmt', $this->date_range, $where );
467
	}
468
469
	function handle_modified_range( $where ) {
470
		return $this->_build_date_range_query( 'post_modified_gmt', $this->modified_range, $where );
471
	}
472
473 View Code Duplication
	function handle_where_for_page_handle( $where ) {
474
		global $wpdb;
475
476
		$column = $this->performed_query['orderby'];
477
		if ( ! $column ) {
478
			$column = 'date';
479
		}
480
		$order = $this->performed_query['order'];
481
		if ( ! $order ) {
482
			$order = 'DESC';
483
		}
484
485
		if ( ! in_array( $column, array( 'ID', 'title', 'date', 'modified', 'comment_count' ) ) ) {
486
			return $where;
487
		}
488
489
		if ( ! in_array( $order, array( 'DESC', 'ASC' ) ) ) {
490
			return $where;
491
		}
492
493
		$db_column = '';
494
		$db_value  = '';
495
		switch ( $column ) {
496
			case 'ID':
497
				$db_column = 'ID';
498
				$db_value  = '%d';
499
				break;
500
			case 'title':
501
				$db_column = 'post_title';
502
				$db_value  = '%s';
503
				break;
504
			case 'date':
505
				$db_column = 'post_date';
506
				$db_value  = 'CAST( %s as DATETIME )';
507
				break;
508
			case 'modified':
509
				$db_column = 'post_modified';
510
				$db_value  = 'CAST( %s as DATETIME )';
511
				break;
512
			case 'comment_count':
513
				$db_column = 'comment_count';
514
				$db_value  = '%d';
515
				break;
516
		}
517
518
		if ( 'DESC' === $order ) {
519
			$db_order = '<';
520
		} else {
521
			$db_order = '>';
522
		}
523
524
		// Add a clause that limits the results to items beyond the passed item, or equivalent to the passed item
525
		// but with an ID beyond the passed item. When we're ordering by the ID already, we only ask for items
526
		// beyond the passed item.
527
		$where .= $wpdb->prepare( " AND ( ( `$wpdb->posts`.`$db_column` $db_order $db_value ) ", $this->page_handle['value'] );
528
		if ( $db_column !== 'ID' ) {
529
			$where .= $wpdb->prepare( "OR ( `$wpdb->posts`.`$db_column` = $db_value AND `$wpdb->posts`.ID $db_order %d )", $this->page_handle['value'], $this->page_handle['id'] );
530
		}
531
		$where .= ' )';
532
533
		return $where;
534
	}
535
536 View Code Duplication
	function handle_orderby_for_page_handle( $orderby ) {
537
		global $wpdb;
538
		if ( $this->performed_query['orderby'] === 'ID' ) {
539
			// bail if we're already ordering by ID
540
			return $orderby;
541
		}
542
543
		if ( $orderby ) {
544
			$orderby .= ' ,';
545
		}
546
		$order = $this->performed_query['order'];
547
		if ( ! $order ) {
548
			$order = 'DESC';
549
		}
550
		$orderby .= " `$wpdb->posts`.ID $order";
551
		return $orderby;
552
	}
553
}
554