class.wpcom-json-api-list-posts-v1-2-endpoint.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. new WPCOM_JSON_API_List_Posts_v1_2_Endpoint( array(
  3. 'description' => 'Get a list of matching posts.',
  4. 'min_version' => '1.2',
  5. 'max_version' => '1.2',
  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. '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.',
  18. 'order' => array(
  19. 'DESC' => 'Return posts in descending order. For dates, that means newest to oldest.',
  20. 'ASC' => 'Return posts in ascending order. For dates, that means oldest to newest.',
  21. ),
  22. 'order_by' => array(
  23. 'date' => 'Order by the created time of each post.',
  24. 'modified' => 'Order by the modified time of each post.',
  25. 'title' => "Order lexicographically by the posts' titles.",
  26. 'comment_count' => 'Order by the number of comments for each post.',
  27. 'ID' => 'Order by post ID.',
  28. ),
  29. 'after' => '(ISO 8601 datetime) Return posts dated after the specified datetime.',
  30. 'before' => '(ISO 8601 datetime) Return posts dated before the specified datetime.',
  31. 'modified_after' => '(ISO 8601 datetime) Return posts modified after the specified datetime.',
  32. 'modified_before' => '(ISO 8601 datetime) Return posts modified before the specified datetime.',
  33. 'tag' => '(string) Specify the tag name or slug.',
  34. 'category' => '(string) Specify the category name or slug.',
  35. 'term' => '(object:string) Specify comma-separated term slugs to search within, indexed by taxonomy slug.',
  36. '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.",
  37. 'exclude_private_types' => '(bool=false) Use this flag together with `type=any` to get only publicly accessible posts.',
  38. 'parent_id' => '(int) Returns only posts which are children of the specified post. Applies only to hierarchical post types.',
  39. 'exclude' => '(array:int|int) Excludes the specified post ID(s) from the response',
  40. 'exclude_tree' => '(int) Excludes the specified post and all of its descendants from the response. Applies only to hierarchical post types.',
  41. '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"',
  42. 'sticky' => array(
  43. 'include' => 'Sticky posts are not excluded from the list.',
  44. 'exclude' => 'Sticky posts are excluded from the list.',
  45. 'require' => 'Only include sticky posts',
  46. ),
  47. 'author' => "(int) Author's user ID",
  48. 'search' => '(string) Search query',
  49. 'meta_key' => '(string) Metadata key that the post should contain',
  50. 'meta_value' => '(string) Metadata value that the post should contain. Will only be applied if a `meta_key` is also given',
  51. ),
  52. 'example_request' => 'https://public-api.wordpress.com/rest/v1.2/sites/en.blog.wordpress.com/posts/?number=2'
  53. ) );
  54. class WPCOM_JSON_API_List_Posts_v1_2_Endpoint extends WPCOM_JSON_API_List_Posts_v1_1_Endpoint {
  55. // /sites/%s/posts/ -> $blog_id
  56. function callback( $path = '', $blog_id = 0 ) {
  57. $blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
  58. if ( is_wp_error( $blog_id ) ) {
  59. return $blog_id;
  60. }
  61. $args = $this->query_args();
  62. $is_eligible_for_page_handle = true;
  63. $site = $this->get_platform()->get_site( $blog_id );
  64. if ( $args['number'] < 1 ) {
  65. $args['number'] = 20;
  66. } elseif ( 100 < $args['number'] ) {
  67. return new WP_Error( 'invalid_number', 'The NUMBER parameter must be less than or equal to 100.', 400 );
  68. }
  69. if ( isset( $args['type'] ) ) {
  70. // load all types on WPCOM, unless only built-in ones are requested
  71. if ( defined( 'IS_WPCOM' ) && IS_WPCOM && ! in_array( $args['type'], array( 'post', 'revision', 'page' ) ) ) {
  72. $this->load_theme_functions();
  73. }
  74. if ( ! $site->is_post_type_allowed( $args['type'] ) ) {
  75. return new WP_Error( 'unknown_post_type', 'Unknown post type', 404 );
  76. }
  77. // Normalize post_type
  78. if ( 'any' == $args['type'] ) {
  79. $whitelisted_post_types = $site->get_whitelisted_post_types();
  80. if ( isset( $args['exclude_private_types'] ) && $args['exclude_private_types'] == true ) {
  81. $public_post_types = get_post_types( array( 'public' => true ) );
  82. $args['type'] = array_intersect( $public_post_types, $whitelisted_post_types );
  83. } else {
  84. $args['type'] = $whitelisted_post_types;
  85. }
  86. }
  87. } else {
  88. // let's be explicit about defaulting to 'post'
  89. $args['type'] = 'post';
  90. }
  91. // make sure the user can read or edit the requested post type(s)
  92. if ( is_array( $args['type'] ) ) {
  93. $allowed_types = array();
  94. foreach ( $args['type'] as $post_type ) {
  95. if ( $site->current_user_can_access_post_type( $post_type, $args['context'] ) ) {
  96. $allowed_types[] = $post_type;
  97. }
  98. }
  99. if ( empty( $allowed_types ) ) {
  100. return array( 'found' => 0, 'posts' => array() );
  101. }
  102. $args['type'] = $allowed_types;
  103. }
  104. else {
  105. if ( ! $site->current_user_can_access_post_type( $args['type'], $args['context'] ) ) {
  106. return array( 'found' => 0, 'posts' => array() );
  107. }
  108. }
  109. // determine statuses
  110. $status = ( ! empty( $args['status'] ) ) ? explode( ',', $args['status'] ) : array( 'publish' );
  111. 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. if ( empty( $status ) ) {
  127. // requested only protected statuses? nothing for you here
  128. return array( 'found' => 0, 'posts' => array() );
  129. }
  130. // clear it (AKA published only) because "any" includes protected
  131. $status = array();
  132. }
  133. $query = array(
  134. 'posts_per_page' => $args['number'],
  135. 'order' => $args['order'],
  136. 'orderby' => $args['order_by'],
  137. 'post_type' => $args['type'],
  138. 'post_status' => $status,
  139. 'post_parent' => isset( $args['parent_id'] ) ? $args['parent_id'] : null,
  140. 'author' => isset( $args['author'] ) && 0 < $args['author'] ? $args['author'] : null,
  141. 's' => isset( $args['search'] ) ? $args['search'] : null,
  142. 'fields' => 'ids',
  143. );
  144. if ( ! is_user_logged_in () ) {
  145. $query['has_password'] = false;
  146. }
  147. if ( isset( $args['meta_key'] ) ) {
  148. $show = false;
  149. if ( WPCOM_JSON_API_Metadata::is_public( $args['meta_key'] ) )
  150. $show = true;
  151. if ( current_user_can( 'edit_post_meta', $query['post_type'], $args['meta_key'] ) )
  152. $show = true;
  153. if ( is_protected_meta( $args['meta_key'], 'post' ) && ! $show )
  154. return new WP_Error( 'invalid_meta_key', 'Invalid meta key', 404 );
  155. $meta = array( 'key' => $args['meta_key'] );
  156. if ( isset( $args['meta_value'] ) )
  157. $meta['value'] = $args['meta_value'];
  158. $query['meta_query'] = array( $meta );
  159. }
  160. if ( $args['sticky'] === 'include' ) {
  161. $query['ignore_sticky_posts'] = 1;
  162. } else if ( $args['sticky'] === 'exclude' ) {
  163. $sticky = get_option( 'sticky_posts' );
  164. if ( is_array( $sticky ) ) {
  165. $query['post__not_in'] = $sticky;
  166. }
  167. } else if ( $args['sticky'] === 'require' ) {
  168. $sticky = get_option( 'sticky_posts' );
  169. if ( is_array( $sticky ) && ! empty( $sticky ) ) {
  170. $query['post__in'] = $sticky;
  171. } else {
  172. // no sticky posts exist
  173. return array( 'found' => 0, 'posts' => array() );
  174. }
  175. }
  176. if ( isset( $args['exclude'] ) ) {
  177. $excluded_ids = (array) $args['exclude'];
  178. $query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $excluded_ids ) : $excluded_ids;
  179. }
  180. if ( isset( $args['exclude_tree'] ) && is_post_type_hierarchical( $args['type'] ) ) {
  181. // get_page_children is a misnomer; it supports all hierarchical post types
  182. $page_args = array(
  183. 'child_of' => $args['exclude_tree'],
  184. 'post_type' => $args['type'],
  185. // since we're looking for things to exclude, be aggressive
  186. 'post_status' => 'publish,draft,pending,private,future,trash',
  187. );
  188. $post_descendants = get_pages( $page_args );
  189. $exclude_tree = array( $args['exclude_tree'] );
  190. foreach ( $post_descendants as $child ) {
  191. $exclude_tree[] = $child->ID;
  192. }
  193. $query['post__not_in'] = isset( $query['post__not_in'] ) ? array_merge( $query['post__not_in'], $exclude_tree ) : $exclude_tree;
  194. }
  195. if ( isset( $args['category'] ) ) {
  196. $category = get_term_by( 'slug', $args['category'], 'category' );
  197. if ( $category === false) {
  198. $query['category_name'] = $args['category'];
  199. } else {
  200. $query['cat'] = $category->term_id;
  201. }
  202. }
  203. if ( isset( $args['tag'] ) ) {
  204. $query['tag'] = $args['tag'];
  205. }
  206. if ( ! empty( $args['term'] ) ) {
  207. $query['tax_query'] = array();
  208. foreach ( $args['term'] as $taxonomy => $slug ) {
  209. $taxonomy_object = get_taxonomy( $taxonomy );
  210. if ( false === $taxonomy_object || ( ! $taxonomy_object->public &&
  211. ! current_user_can( $taxonomy_object->cap->assign_terms ) ) ) {
  212. continue;
  213. }
  214. $query['tax_query'][] = array(
  215. 'taxonomy' => $taxonomy,
  216. 'field' => 'slug',
  217. 'terms' => explode( ',', $slug )
  218. );
  219. }
  220. }
  221. if ( isset( $args['page'] ) ) {
  222. if ( $args['page'] < 1 ) {
  223. $args['page'] = 1;
  224. }
  225. $query['paged'] = $args['page'];
  226. if ( $query['paged'] !== 1 ) {
  227. $is_eligible_for_page_handle = false;
  228. }
  229. } else {
  230. if ( $args['offset'] < 0 ) {
  231. $args['offset'] = 0;
  232. }
  233. $query['offset'] = $args['offset'];
  234. if ( $query['offset'] !== 0 ) {
  235. $is_eligible_for_page_handle = false;
  236. }
  237. }
  238. if ( isset( $args['before'] ) ) {
  239. $this->date_range['before'] = $args['before'];
  240. }
  241. if ( isset( $args['after'] ) ) {
  242. $this->date_range['after'] = $args['after'];
  243. }
  244. if ( isset( $args['modified_before_gmt'] ) ) {
  245. $this->modified_range['before'] = $args['modified_before_gmt'];
  246. }
  247. if ( isset( $args['modified_after_gmt'] ) ) {
  248. $this->modified_range['after'] = $args['modified_after_gmt'];
  249. }
  250. if ( $this->date_range ) {
  251. add_filter( 'posts_where', array( $this, 'handle_date_range' ) );
  252. }
  253. if ( $this->modified_range ) {
  254. add_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
  255. }
  256. if ( isset( $args['page_handle'] ) ) {
  257. $page_handle = wp_parse_args( $args['page_handle'] );
  258. if ( isset( $page_handle['value'] ) && isset( $page_handle['id'] ) ) {
  259. // we have a valid looking page handle
  260. $this->page_handle = $page_handle;
  261. add_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
  262. }
  263. }
  264. /**
  265. * 'column' necessary for the me/posts endpoint (which extends sites/$site/posts).
  266. * Would need to be added to the sites/$site/posts definition if we ever want to
  267. * use it there.
  268. */
  269. $column_whitelist = array( 'post_modified_gmt' );
  270. if ( isset( $args['column'] ) && in_array( $args['column'], $column_whitelist ) ) {
  271. $query['column'] = $args['column'];
  272. }
  273. $this->performed_query = $query;
  274. add_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
  275. $wp_query = new WP_Query( $query );
  276. remove_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );
  277. if ( $this->date_range ) {
  278. remove_filter( 'posts_where', array( $this, 'handle_date_range' ) );
  279. $this->date_range = array();
  280. }
  281. if ( $this->modified_range ) {
  282. remove_filter( 'posts_where', array( $this, 'handle_modified_range' ) );
  283. $this->modified_range = array();
  284. }
  285. if ( $this->page_handle ) {
  286. remove_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
  287. }
  288. $return = array();
  289. $excluded_count = 0;
  290. foreach ( array_keys( $this->response_format ) as $key ) {
  291. switch ( $key ) {
  292. case 'found' :
  293. $return[$key] = (int) $wp_query->found_posts;
  294. break;
  295. case 'posts' :
  296. $posts = array();
  297. foreach ( $wp_query->posts as $post_ID ) {
  298. $the_post = $this->get_post_by( 'ID', $post_ID, $args['context'] );
  299. if ( $the_post && ! is_wp_error( $the_post ) ) {
  300. $posts[] = $the_post;
  301. } else {
  302. $excluded_count++;
  303. }
  304. }
  305. if ( $posts ) {
  306. /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */
  307. do_action( 'wpcom_json_api_objects', 'posts', count( $posts ) );
  308. }
  309. $return[$key] = $posts;
  310. break;
  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. if ( $is_eligible_for_page_handle && $return['posts'] ) {
  320. $last_post = end( $return['posts'] );
  321. reset( $return['posts'] );
  322. if ( ( $return['found'] > count( $return['posts'] ) ) && $last_post ) {
  323. if ( ! isset( $return[$key] ) ) {
  324. $return[$key] = (object) array();
  325. }
  326. $return[$key]->next_page = $this->build_page_handle( $last_post, $query );
  327. }
  328. }
  329. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  330. if ( !isset( $return[$key] ) )
  331. $return[$key] = new stdClass;
  332. $return[$key]->wpcom = true;
  333. }
  334. break;
  335. }
  336. }
  337. $return['found'] -= $excluded_count;
  338. return $return;
  339. }
  340. function build_page_handle( $post, $query ) {
  341. $column = $query['orderby'];
  342. if ( ! $column ) {
  343. $column = 'date';
  344. }
  345. return build_query( array( 'value' => urlencode($post[$column]), 'id' => $post['ID'] ) );
  346. }
  347. function _build_date_range_query( $column, $range, $where ) {
  348. global $wpdb;
  349. switch ( count( $range ) ) {
  350. case 2 :
  351. $where .= $wpdb->prepare(
  352. " AND `$wpdb->posts`.$column >= CAST( %s AS DATETIME ) AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
  353. $range['after'],
  354. $range['before']
  355. );
  356. break;
  357. case 1 :
  358. if ( isset( $range['before'] ) ) {
  359. $where .= $wpdb->prepare(
  360. " AND `$wpdb->posts`.$column < CAST( %s AS DATETIME ) ",
  361. $range['before']
  362. );
  363. } else {
  364. $where .= $wpdb->prepare(
  365. " AND `$wpdb->posts`.$column > CAST( %s AS DATETIME ) ",
  366. $range['after']
  367. );
  368. }
  369. break;
  370. }
  371. return $where;
  372. }
  373. }