class.wpcom-json-api-list-posts-v1-1-endpoint.php 17 KB

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