class.wpcom-json-api-list-posts-endpoint.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. <?php
  2. new WPCOM_JSON_API_List_Posts_Endpoint( array(
  3. 'description' => 'Get a list of matching posts.',
  4. 'new_version' => '1.1',
  5. 'max_version' => '1',
  6. 'group' => 'posts',
  7. 'stat' => 'posts',
  8. 'method' => 'GET',
  9. 'path' => '/sites/%s/posts/',
  10. 'path_labels' => array(
  11. '$site' => '(int|string) Site ID or domain',
  12. ),
  13. 'query_parameters' => array(
  14. 'number' => '(int=20) The number of posts to return. Limit: 100.',
  15. 'offset' => '(int=0) 0-indexed offset.',
  16. 'page' => '(int) Return the Nth 1-indexed page of posts. Takes precedence over the <code>offset</code> parameter.',
  17. 'order' => array(
  18. 'DESC' => 'Return posts in descending order. For dates, that means newest to oldest.',
  19. 'ASC' => 'Return posts in ascending order. For dates, that means oldest to newest.',
  20. ),
  21. 'order_by' => array(
  22. 'date' => 'Order by the created time of each post.',
  23. 'modified' => 'Order by the modified time of each post.',
  24. 'title' => "Order lexicographically by the posts' titles.",
  25. 'comment_count' => 'Order by the number of comments for each post.',
  26. 'ID' => 'Order by post ID.',
  27. ),
  28. 'after' => '(ISO 8601 datetime) Return posts dated on or after the specified datetime.',
  29. 'before' => '(ISO 8601 datetime) Return posts dated on or before the specified datetime.',
  30. 'tag' => '(string) Specify the tag name or slug.',
  31. 'category' => '(string) Specify the category name or slug.',
  32. 'term' => '(object:string) Specify comma-separated term slugs to search within, indexed by taxonomy slug.',
  33. '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.",
  34. 'parent_id' => '(int) Returns only posts which are children of the specified post. Applies only to hierarchical post types.',
  35. 'exclude' => '(array:int|int) Excludes the specified post ID(s) from the response',
  36. 'exclude_tree' => '(int) Excludes the specified post and all of its descendants from the response. Applies only to hierarchical post types.',
  37. 'status' => array(
  38. 'publish' => 'Return only published posts.',
  39. 'private' => 'Return only private posts.',
  40. 'draft' => 'Return only draft posts.',
  41. 'pending' => 'Return only posts pending editorial approval.',
  42. 'future' => 'Return only posts scheduled for future publishing.',
  43. 'trash' => 'Return only posts in the trash.',
  44. 'any' => 'Return all posts regardless of status.',
  45. ),
  46. 'sticky' => array(
  47. 'false' => 'Post is not marked as sticky.',
  48. 'true' => 'Stick the post to the front page.',
  49. ),
  50. 'author' => "(int) Author's user ID",
  51. 'search' => '(string) Search query',
  52. 'meta_key' => '(string) Metadata key that the post should contain',
  53. 'meta_value' => '(string) Metadata value that the post should contain. Will only be applied if a `meta_key` is also given',
  54. ),
  55. 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/posts/?number=5'
  56. ) );
  57. class WPCOM_JSON_API_List_Posts_Endpoint extends WPCOM_JSON_API_Post_Endpoint {
  58. public $date_range = array();
  59. public $response_format = array(
  60. 'found' => '(int) The total number of posts found that match the request (ignoring limits, offsets, and pagination).',
  61. 'posts' => '(array:post) An array of post objects.',
  62. );
  63. // /sites/%s/posts/ -> $blog_id
  64. function callback( $path = '', $blog_id = 0 ) {
  65. $blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
  66. if ( is_wp_error( $blog_id ) ) {
  67. return $blog_id;
  68. }
  69. $args = $this->query_args();
  70. if ( $args['number'] < 1 ) {
  71. $args['number'] = 20;
  72. } elseif ( 100 < $args['number'] ) {
  73. return new WP_Error( 'invalid_number', 'The NUMBER parameter must be less than or equal to 100.', 400 );
  74. }
  75. if ( isset( $args['type'] ) && ! $this->is_post_type_allowed( $args['type'] ) ) {
  76. return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
  77. }
  78. // Normalize post_type
  79. if ( isset( $args['type'] ) && 'any' == $args['type'] ) {
  80. if ( version_compare( $this->api->version, '1.1', '<' ) ) {
  81. $args['type'] = array( 'post', 'page' );
  82. } else { // 1.1+
  83. $args['type'] = $this->_get_whitelisted_post_types();
  84. }
  85. }
  86. // determine statuses
  87. $status = $args['status'];
  88. $status = ( $status ) ? explode( ',', $status ) : array( 'publish' );
  89. if ( is_user_logged_in() ) {
  90. $statuses_whitelist = array(
  91. 'publish',
  92. 'pending',
  93. 'draft',
  94. 'future',
  95. 'private',
  96. 'trash',
  97. 'any',
  98. );
  99. $status = array_intersect( $status, $statuses_whitelist );
  100. } else {
  101. // logged-out users can see only published posts
  102. $statuses_whitelist = array( 'publish', 'any' );
  103. $status = array_intersect( $status, $statuses_whitelist );
  104. if ( empty( $status ) ) {
  105. // requested only protected statuses? nothing for you here
  106. return array( 'found' => 0, 'posts' => array() );
  107. }
  108. // clear it (AKA published only) because "any" includes protected
  109. $status = array();
  110. }
  111. // let's be explicit about defaulting to 'post'
  112. $args['type'] = isset( $args['type'] ) ? $args['type'] : 'post';
  113. // make sure the user can read or edit the requested post type(s)
  114. if ( is_array( $args['type'] ) ) {
  115. $allowed_types = array();
  116. foreach ( $args['type'] as $post_type ) {
  117. if ( $this->current_user_can_access_post_type( $post_type, $args['context'] ) ) {
  118. $allowed_types[] = $post_type;
  119. }
  120. }
  121. if ( empty( $allowed_types ) ) {
  122. return array( 'found' => 0, 'posts' => array() );
  123. }
  124. $args['type'] = $allowed_types;
  125. }
  126. else {
  127. if ( ! $this->current_user_can_access_post_type( $args['type'], $args['context'] ) ) {
  128. return array( 'found' => 0, 'posts' => array() );
  129. }
  130. }
  131. $query = array(
  132. 'posts_per_page' => $args['number'],
  133. 'order' => $args['order'],
  134. 'orderby' => $args['order_by'],
  135. 'post_type' => $args['type'],
  136. 'post_status' => $status,
  137. 'post_parent' => isset( $args['parent_id'] ) ? $args['parent_id'] : null,
  138. 'author' => isset( $args['author'] ) && 0 < $args['author'] ? $args['author'] : null,
  139. 's' => isset( $args['search'] ) ? $args['search'] : null,
  140. 'fields' => 'ids',
  141. );
  142. if ( ! is_user_logged_in () ) {
  143. $query['has_password'] = false;
  144. }
  145. if ( isset( $args['meta_key'] ) ) {
  146. $show = false;
  147. if ( WPCOM_JSON_API_Metadata::is_public( $args['meta_key'] ) )
  148. $show = true;
  149. if ( current_user_can( 'edit_post_meta', $query['post_type'], $args['meta_key'] ) )
  150. $show = true;
  151. if ( is_protected_meta( $args['meta_key'], 'post' ) && ! $show )
  152. return new WP_Error( 'invalid_meta_key', 'Invalid meta key', 404 );
  153. $meta = array( 'key' => $args['meta_key'] );
  154. if ( isset( $args['meta_value'] ) )
  155. $meta['value'] = $args['meta_value'];
  156. $query['meta_query'] = array( $meta );
  157. }
  158. if (
  159. isset( $args['sticky'] )
  160. &&
  161. ( $sticky = get_option( 'sticky_posts' ) )
  162. &&
  163. is_array( $sticky )
  164. ) {
  165. if ( $args['sticky'] ) {
  166. $query['post__in'] = $sticky;
  167. } else {
  168. $query['post__not_in'] = $sticky;
  169. $query['ignore_sticky_posts'] = 1;
  170. }
  171. } else {
  172. $query['post__not_in'] = $sticky;
  173. $query['ignore_sticky_posts'] = 1;
  174. }
  175. if ( isset( $args['exclude'] ) ) {
  176. $query['post__not_in'] = array_merge( $query['post__not_in'], (array) $args['exclude'] );
  177. }
  178. if ( isset( $args['exclude_tree'] ) && is_post_type_hierarchical( $args['type'] ) ) {
  179. // get_page_children is a misnomer; it supports all hierarchical post types
  180. $page_args = array(
  181. 'child_of' => $args['exclude_tree'],
  182. 'post_type' => $args['type'],
  183. // since we're looking for things to exclude, be aggressive
  184. 'post_status' => 'publish,draft,pending,private,future,trash',
  185. );
  186. $post_descendants = get_pages( $page_args );
  187. $exclude_tree = array( $args['exclude_tree'] );
  188. foreach ( $post_descendants as $child ) {
  189. $exclude_tree[] = $child->ID;
  190. }
  191. $query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $exclude_tree ) : $exclude_tree;
  192. }
  193. if ( isset( $args['category'] ) ) {
  194. $category = get_term_by( 'slug', $args['category'], 'category' );
  195. if ( $category === false) {
  196. $query['category_name'] = $args['category'];
  197. } else {
  198. $query['cat'] = $category->term_id;
  199. }
  200. }
  201. if ( isset( $args['tag'] ) ) {
  202. $query['tag'] = $args['tag'];
  203. }
  204. if ( ! empty( $args['term'] ) ) {
  205. $query['tax_query'] = array();
  206. foreach ( $args['term'] as $taxonomy => $slug ) {
  207. $taxonomy_object = get_taxonomy( $taxonomy );
  208. if ( false === $taxonomy_object || ( ! $taxonomy_object->public &&
  209. ! current_user_can( $taxonomy_object->cap->assign_terms ) ) ) {
  210. continue;
  211. }
  212. $query['tax_query'][] = array(
  213. 'taxonomy' => $taxonomy,
  214. 'field' => 'slug',
  215. 'terms' => explode( ',', $slug )
  216. );
  217. }
  218. }
  219. if ( isset( $args['page'] ) ) {
  220. if ( $args['page'] < 1 ) {
  221. $args['page'] = 1;
  222. }
  223. $query['paged'] = $args['page'];
  224. } else {
  225. if ( $args['offset'] < 0 ) {
  226. $args['offset'] = 0;
  227. }
  228. $query['offset'] = $args['offset'];
  229. }
  230. if ( isset( $args['before'] ) ) {
  231. $this->date_range['before'] = $args['before'];
  232. }
  233. if ( isset( $args['after'] ) ) {
  234. $this->date_range['after'] = $args['after'];
  235. }
  236. if ( $this->date_range ) {
  237. add_filter( 'posts_where', array( $this, 'handle_date_range' ) );
  238. }
  239. /**
  240. * 'column' necessary for the me/posts endpoint (which extends sites/$site/posts).
  241. * Would need to be added to the sites/$site/posts definition if we ever want to
  242. * use it there.
  243. */
  244. $column_whitelist = array( 'post_modified_gmt' );
  245. if ( isset( $args['column'] ) && in_array( $args['column'], $column_whitelist ) ) {
  246. $query['column'] = $args['column'];
  247. }
  248. $wp_query = new WP_Query( $query );
  249. if ( $this->date_range ) {
  250. remove_filter( 'posts_where', array( $this, 'handle_date_range' ) );
  251. $this->date_range = array();
  252. }
  253. $return = array();
  254. $excluded_count = 0;
  255. foreach ( array_keys( $this->response_format ) as $key ) {
  256. switch ( $key ) {
  257. case 'found' :
  258. $return[$key] = (int) $wp_query->found_posts;
  259. break;
  260. case 'posts' :
  261. $posts = array();
  262. foreach ( $wp_query->posts as $post_ID ) {
  263. $the_post = $this->get_post_by( 'ID', $post_ID, $args['context'] );
  264. if ( $the_post && ! is_wp_error( $the_post ) ) {
  265. $posts[] = $the_post;
  266. } else {
  267. $excluded_count++;
  268. }
  269. }
  270. if ( $posts ) {
  271. /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
  272. do_action( 'wpcom_json_api_objects', 'posts', count( $posts ) );
  273. }
  274. $return[$key] = $posts;
  275. break;
  276. }
  277. }
  278. $return['found'] -= $excluded_count;
  279. return $return;
  280. }
  281. function handle_date_range( $where ) {
  282. global $wpdb;
  283. switch ( count( $this->date_range ) ) {
  284. case 2 :
  285. $where .= $wpdb->prepare(
  286. " AND `$wpdb->posts`.post_date BETWEEN CAST( %s AS DATETIME ) AND CAST( %s AS DATETIME ) ",
  287. $this->date_range['after'],
  288. $this->date_range['before']
  289. );
  290. break;
  291. case 1 :
  292. if ( isset( $this->date_range['before'] ) ) {
  293. $where .= $wpdb->prepare(
  294. " AND `$wpdb->posts`.post_date <= CAST( %s AS DATETIME ) ",
  295. $this->date_range['before']
  296. );
  297. } else {
  298. $where .= $wpdb->prepare(
  299. " AND `$wpdb->posts`.post_date >= CAST( %s AS DATETIME ) ",
  300. $this->date_range['after']
  301. );
  302. }
  303. break;
  304. }
  305. return $where;
  306. }
  307. }