Nenhuma Descrição

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

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