Няма описание

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

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