You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1177 lines
41 KiB

  1. <?php
  2. /**
  3. * Comment API: WP_Comment_Query class
  4. *
  5. * @package WordPress
  6. * @subpackage Comments
  7. * @since 4.4.0
  8. */
  9. /**
  10. * Core class used for querying comments.
  11. *
  12. * @since 3.1.0
  13. *
  14. * @see WP_Comment_Query::__construct() for accepted arguments.
  15. */
  16. class WP_Comment_Query {
  17. /**
  18. * SQL for database query.
  19. *
  20. * @since 4.0.1
  21. * @access public
  22. * @var string
  23. */
  24. public $request;
  25. /**
  26. * Metadata query container
  27. *
  28. * @since 3.5.0
  29. * @access public
  30. * @var object WP_Meta_Query
  31. */
  32. public $meta_query = false;
  33. /**
  34. * Metadata query clauses.
  35. *
  36. * @since 4.4.0
  37. * @access protected
  38. * @var array
  39. */
  40. protected $meta_query_clauses;
  41. /**
  42. * SQL query clauses.
  43. *
  44. * @since 4.4.0
  45. * @access protected
  46. * @var array
  47. */
  48. protected $sql_clauses = array(
  49. 'select' => '',
  50. 'from' => '',
  51. 'where' => array(),
  52. 'groupby' => '',
  53. 'orderby' => '',
  54. 'limits' => '',
  55. );
  56. /**
  57. * SQL WHERE clause.
  58. *
  59. * Stored after the {@see 'comments_clauses'} filter is run on the compiled WHERE sub-clauses.
  60. *
  61. * @since 4.4.2
  62. * @access protected
  63. * @var string
  64. */
  65. protected $filtered_where_clause;
  66. /**
  67. * Date query container
  68. *
  69. * @since 3.7.0
  70. * @access public
  71. * @var object WP_Date_Query
  72. */
  73. public $date_query = false;
  74. /**
  75. * Query vars set by the user.
  76. *
  77. * @since 3.1.0
  78. * @access public
  79. * @var array
  80. */
  81. public $query_vars;
  82. /**
  83. * Default values for query vars.
  84. *
  85. * @since 4.2.0
  86. * @access public
  87. * @var array
  88. */
  89. public $query_var_defaults;
  90. /**
  91. * List of comments located by the query.
  92. *
  93. * @since 4.0.0
  94. * @access public
  95. * @var array
  96. */
  97. public $comments;
  98. /**
  99. * The amount of found comments for the current query.
  100. *
  101. * @since 4.4.0
  102. * @access public
  103. * @var int
  104. */
  105. public $found_comments = 0;
  106. /**
  107. * The number of pages.
  108. *
  109. * @since 4.4.0
  110. * @access public
  111. * @var int
  112. */
  113. public $max_num_pages = 0;
  114. /**
  115. * Make private/protected methods readable for backward compatibility.
  116. *
  117. * @since 4.0.0
  118. * @access public
  119. *
  120. * @param callable $name Method to call.
  121. * @param array $arguments Arguments to pass when calling.
  122. * @return mixed|false Return value of the callback, false otherwise.
  123. */
  124. public function __call( $name, $arguments ) {
  125. if ( 'get_search_sql' === $name ) {
  126. return call_user_func_array( array( $this, $name ), $arguments );
  127. }
  128. return false;
  129. }
  130. /**
  131. * Constructor.
  132. *
  133. * Sets up the comment query, based on the query vars passed.
  134. *
  135. * @since 4.2.0
  136. * @since 4.4.0 `$parent__in` and `$parent__not_in` were added.
  137. * @since 4.4.0 Order by `comment__in` was added. `$update_comment_meta_cache`, `$no_found_rows`,
  138. * `$hierarchical`, and `$update_comment_post_cache` were added.
  139. * @since 4.5.0 Introduced the `$author_url` argument.
  140. * @since 4.6.0 Introduced the `$cache_domain` argument.
  141. * @access public
  142. *
  143. * @param string|array $query {
  144. * Optional. Array or query string of comment query parameters. Default empty.
  145. *
  146. * @type string $author_email Comment author email address. Default empty.
  147. * @type string $author_url Comment author URL. Default empty.
  148. * @type array $author__in Array of author IDs to include comments for. Default empty.
  149. * @type array $author__not_in Array of author IDs to exclude comments for. Default empty.
  150. * @type array $comment__in Array of comment IDs to include. Default empty.
  151. * @type array $comment__not_in Array of comment IDs to exclude. Default empty.
  152. * @type bool $count Whether to return a comment count (true) or array of
  153. * comment objects (false). Default false.
  154. * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
  155. * Default null.
  156. * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs
  157. * only or empty for all fields. Default empty.
  158. * @type int $ID Currently unused.
  159. * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved
  160. * comments will be returned by the query regardless of
  161. * `$status`. Default empty.
  162. * @type int $karma Karma score to retrieve matching comments for.
  163. * Default empty.
  164. * @type string $meta_key Include comments with a matching comment meta key.
  165. * Default empty.
  166. * @type string $meta_value Include comments with a matching comment meta value.
  167. * Requires `$meta_key` to be set. Default empty.
  168. * @type array $meta_query Meta query clauses to limit retrieved comments by.
  169. * See WP_Meta_Query. Default empty.
  170. * @type int $number Maximum number of comments to retrieve.
  171. * Default empty (no limit).
  172. * @type int $offset Number of comments to offset the query. Used to build
  173. * LIMIT clause. Default 0.
  174. * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
  175. * Default: true.
  176. * @type string|array $orderby Comment status or array of statuses. To use 'meta_value'
  177. * or 'meta_value_num', `$meta_key` must also be defined.
  178. * To sort by a specific `$meta_query` clause, use that
  179. * clause's array key. Accepts 'comment_agent',
  180. * 'comment_approved', 'comment_author',
  181. * 'comment_author_email', 'comment_author_IP',
  182. * 'comment_author_url', 'comment_content', 'comment_date',
  183. * 'comment_date_gmt', 'comment_ID', 'comment_karma',
  184. * 'comment_parent', 'comment_post_ID', 'comment_type',
  185. * 'user_id', 'comment__in', 'meta_value', 'meta_value_num',
  186. * the value of $meta_key, and the array keys of
  187. * `$meta_query`. Also accepts false, an empty array, or
  188. * 'none' to disable `ORDER BY` clause.
  189. * Default: 'comment_date_gmt'.
  190. * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
  191. * Default: 'DESC'.
  192. * @type int $parent Parent ID of comment to retrieve children of.
  193. * Default empty.
  194. * @type array $parent__in Array of parent IDs of comments to retrieve children for.
  195. * Default empty.
  196. * @type array $parent__not_in Array of parent IDs of comments *not* to retrieve
  197. * children for. Default empty.
  198. * @type array $post_author__in Array of author IDs to retrieve comments for.
  199. * Default empty.
  200. * @type array $post_author__not_in Array of author IDs *not* to retrieve comments for.
  201. * Default empty.
  202. * @type int $post_ID Currently unused.
  203. * @type int $post_id Limit results to those affiliated with a given post ID.
  204. * Default 0.
  205. * @type array $post__in Array of post IDs to include affiliated comments for.
  206. * Default empty.
  207. * @type array $post__not_in Array of post IDs to exclude affiliated comments for.
  208. * Default empty.
  209. * @type int $post_author Post author ID to limit results by. Default empty.
  210. * @type string|array $post_status Post status or array of post statuses to retrieve
  211. * affiliated comments for. Pass 'any' to match any value.
  212. * Default empty.
  213. * @type string $post_type Post type or array of post types to retrieve affiliated
  214. * comments for. Pass 'any' to match any value. Default empty.
  215. * @type string $post_name Post name to retrieve affiliated comments for.
  216. * Default empty.
  217. * @type int $post_parent Post parent ID to retrieve affiliated comments for.
  218. * Default empty.
  219. * @type string $search Search term(s) to retrieve matching comments for.
  220. * Default empty.
  221. * @type string $status Comment status to limit results by. Accepts 'hold'
  222. * (`comment_status=0`), 'approve' (`comment_status=1`),
  223. * 'all', or a custom comment status. Default 'all'.
  224. * @type string|array $type Include comments of a given type, or array of types.
  225. * Accepts 'comment', 'pings' (includes 'pingback' and
  226. * 'trackback'), or anycustom type string. Default empty.
  227. * @type array $type__in Include comments from a given array of comment types.
  228. * Default empty.
  229. * @type array $type__not_in Exclude comments from a given array of comment types.
  230. * Default empty.
  231. * @type int $user_id Include comments for a specific user ID. Default empty.
  232. * @type bool|string $hierarchical Whether to include comment descendants in the results.
  233. * 'threaded' returns a tree, with each comment's children
  234. * stored in a `children` property on the `WP_Comment`
  235. * object. 'flat' returns a flat array of found comments plus
  236. * their children. Pass `false` to leave out descendants.
  237. * The parameter is ignored (forced to `false`) when
  238. * `$fields` is 'ids' or 'counts'. Accepts 'threaded',
  239. * 'flat', or false. Default: false.
  240. * @type string $cache_domain Unique cache key to be produced when this query is stored in
  241. * an object cache. Default is 'core'.
  242. * @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments.
  243. * Default true.
  244. * @type bool $update_comment_post_cache Whether to prime the cache for comment posts.
  245. * Default false.
  246. * }
  247. */
  248. public function __construct( $query = '' ) {
  249. $this->query_var_defaults = array(
  250. 'author_email' => '',
  251. 'author_url' => '',
  252. 'author__in' => '',
  253. 'author__not_in' => '',
  254. 'include_unapproved' => '',
  255. 'fields' => '',
  256. 'ID' => '',
  257. 'comment__in' => '',
  258. 'comment__not_in' => '',
  259. 'karma' => '',
  260. 'number' => '',
  261. 'offset' => '',
  262. 'no_found_rows' => true,
  263. 'orderby' => '',
  264. 'order' => 'DESC',
  265. 'parent' => '',
  266. 'parent__in' => '',
  267. 'parent__not_in' => '',
  268. 'post_author__in' => '',
  269. 'post_author__not_in' => '',
  270. 'post_ID' => '',
  271. 'post_id' => 0,
  272. 'post__in' => '',
  273. 'post__not_in' => '',
  274. 'post_author' => '',
  275. 'post_name' => '',
  276. 'post_parent' => '',
  277. 'post_status' => '',
  278. 'post_type' => '',
  279. 'status' => 'all',
  280. 'type' => '',
  281. 'type__in' => '',
  282. 'type__not_in' => '',
  283. 'user_id' => '',
  284. 'search' => '',
  285. 'count' => false,
  286. 'meta_key' => '',
  287. 'meta_value' => '',
  288. 'meta_query' => '',
  289. 'date_query' => null, // See WP_Date_Query
  290. 'hierarchical' => false,
  291. 'cache_domain' => 'core',
  292. 'update_comment_meta_cache' => true,
  293. 'update_comment_post_cache' => false,
  294. );
  295. if ( ! empty( $query ) ) {
  296. $this->query( $query );
  297. }
  298. }
  299. /**
  300. * Parse arguments passed to the comment query with default query parameters.
  301. *
  302. * @since 4.2.0 Extracted from WP_Comment_Query::query().
  303. *
  304. * @access public
  305. *
  306. * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
  307. */
  308. public function parse_query( $query = '' ) {
  309. if ( empty( $query ) ) {
  310. $query = $this->query_vars;
  311. }
  312. $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
  313. /**
  314. * Fires after the comment query vars have been parsed.
  315. *
  316. * @since 4.2.0
  317. *
  318. * @param WP_Comment_Query &$this The WP_Comment_Query instance (passed by reference).
  319. */
  320. do_action_ref_array( 'parse_comment_query', array( &$this ) );
  321. }
  322. /**
  323. * Sets up the WordPress query for retrieving comments.
  324. *
  325. * @since 3.1.0
  326. * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
  327. * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
  328. * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
  329. * arguments to $query_vars.
  330. * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
  331. * @access public
  332. *
  333. * @param string|array $query Array or URL query string of parameters.
  334. * @return array|int List of comments, or number of comments when 'count' is passed as a query var.
  335. */
  336. public function query( $query ) {
  337. $this->query_vars = wp_parse_args( $query );
  338. return $this->get_comments();
  339. }
  340. /**
  341. * Get a list of comments matching the query vars.
  342. *
  343. * @since 4.2.0
  344. * @access public
  345. *
  346. * @global wpdb $wpdb WordPress database abstraction object.
  347. *
  348. * @return int|array List of comments or number of found comments if `$count` argument is true.
  349. */
  350. public function get_comments() {
  351. global $wpdb;
  352. $this->parse_query();
  353. // Parse meta query
  354. $this->meta_query = new WP_Meta_Query();
  355. $this->meta_query->parse_query_vars( $this->query_vars );
  356. /**
  357. * Fires before comments are retrieved.
  358. *
  359. * @since 3.1.0
  360. *
  361. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  362. */
  363. do_action_ref_array( 'pre_get_comments', array( &$this ) );
  364. // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
  365. $this->meta_query->parse_query_vars( $this->query_vars );
  366. if ( ! empty( $this->meta_query->queries ) ) {
  367. $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
  368. }
  369. // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
  370. $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
  371. $last_changed = wp_cache_get_last_changed( 'comment' );
  372. $cache_key = "get_comments:$key:$last_changed";
  373. $cache_value = wp_cache_get( $cache_key, 'comment' );
  374. if ( false === $cache_value ) {
  375. $comment_ids = $this->get_comment_ids();
  376. if ( $comment_ids ) {
  377. $this->set_found_comments();
  378. }
  379. $cache_value = array(
  380. 'comment_ids' => $comment_ids,
  381. 'found_comments' => $this->found_comments,
  382. );
  383. wp_cache_add( $cache_key, $cache_value, 'comment' );
  384. } else {
  385. $comment_ids = $cache_value['comment_ids'];
  386. $this->found_comments = $cache_value['found_comments'];
  387. }
  388. if ( $this->found_comments && $this->query_vars['number'] ) {
  389. $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] );
  390. }
  391. // If querying for a count only, there's nothing more to do.
  392. if ( $this->query_vars['count'] ) {
  393. // $comment_ids is actually a count in this case.
  394. return intval( $comment_ids );
  395. }
  396. $comment_ids = array_map( 'intval', $comment_ids );
  397. if ( 'ids' == $this->query_vars['fields'] ) {
  398. $this->comments = $comment_ids;
  399. return $this->comments;
  400. }
  401. _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] );
  402. // Fetch full comment objects from the primed cache.
  403. $_comments = array();
  404. foreach ( $comment_ids as $comment_id ) {
  405. if ( $_comment = get_comment( $comment_id ) ) {
  406. $_comments[] = $_comment;
  407. }
  408. }
  409. // Prime comment post caches.
  410. if ( $this->query_vars['update_comment_post_cache'] ) {
  411. $comment_post_ids = array();
  412. foreach ( $_comments as $_comment ) {
  413. $comment_post_ids[] = $_comment->comment_post_ID;
  414. }
  415. _prime_post_caches( $comment_post_ids, false, false );
  416. }
  417. /**
  418. * Filters the comment query results.
  419. *
  420. * @since 3.1.0
  421. *
  422. * @param array $results An array of comments.
  423. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  424. */
  425. $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
  426. // Convert to WP_Comment instances
  427. $comments = array_map( 'get_comment', $_comments );
  428. if ( $this->query_vars['hierarchical'] ) {
  429. $comments = $this->fill_descendants( $comments );
  430. }
  431. $this->comments = $comments;
  432. return $this->comments;
  433. }
  434. /**
  435. * Used internally to get a list of comment IDs matching the query vars.
  436. *
  437. * @since 4.4.0
  438. * @access protected
  439. *
  440. * @global wpdb $wpdb WordPress database abstraction object.
  441. */
  442. protected function get_comment_ids() {
  443. global $wpdb;
  444. // Assemble clauses related to 'comment_approved'.
  445. $approved_clauses = array();
  446. // 'status' accepts an array or a comma-separated string.
  447. $status_clauses = array();
  448. $statuses = $this->query_vars['status'];
  449. if ( ! is_array( $statuses ) ) {
  450. $statuses = preg_split( '/[\s,]+/', $statuses );
  451. }
  452. // 'any' overrides other statuses.
  453. if ( ! in_array( 'any', $statuses ) ) {
  454. foreach ( $statuses as $status ) {
  455. switch ( $status ) {
  456. case 'hold' :
  457. $status_clauses[] = "comment_approved = '0'";
  458. break;
  459. case 'approve' :
  460. $status_clauses[] = "comment_approved = '1'";
  461. break;
  462. case 'all' :
  463. case '' :
  464. $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
  465. break;
  466. default :
  467. $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
  468. break;
  469. }
  470. }
  471. if ( ! empty( $status_clauses ) ) {
  472. $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
  473. }
  474. }
  475. // User IDs or emails whose unapproved comments are included, regardless of $status.
  476. if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
  477. $include_unapproved = $this->query_vars['include_unapproved'];
  478. // Accepts arrays or comma-separated strings.
  479. if ( ! is_array( $include_unapproved ) ) {
  480. $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
  481. }
  482. $unapproved_ids = $unapproved_emails = array();
  483. foreach ( $include_unapproved as $unapproved_identifier ) {
  484. // Numeric values are assumed to be user ids.
  485. if ( is_numeric( $unapproved_identifier ) ) {
  486. $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
  487. // Otherwise we match against email addresses.
  488. } else {
  489. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
  490. }
  491. }
  492. }
  493. // Collapse comment_approved clauses into a single OR-separated clause.
  494. if ( ! empty( $approved_clauses ) ) {
  495. if ( 1 === count( $approved_clauses ) ) {
  496. $this->sql_clauses['where']['approved'] = $approved_clauses[0];
  497. } else {
  498. $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
  499. }
  500. }
  501. $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
  502. // Disable ORDER BY with 'none', an empty array, or boolean false.
  503. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
  504. $orderby = '';
  505. } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
  506. $ordersby = is_array( $this->query_vars['orderby'] ) ?
  507. $this->query_vars['orderby'] :
  508. preg_split( '/[,\s]/', $this->query_vars['orderby'] );
  509. $orderby_array = array();
  510. $found_orderby_comment_ID = false;
  511. foreach ( $ordersby as $_key => $_value ) {
  512. if ( ! $_value ) {
  513. continue;
  514. }
  515. if ( is_int( $_key ) ) {
  516. $_orderby = $_value;
  517. $_order = $order;
  518. } else {
  519. $_orderby = $_key;
  520. $_order = $_value;
  521. }
  522. if ( ! $found_orderby_comment_ID && in_array( $_orderby, array( 'comment_ID', 'comment__in' ) ) ) {
  523. $found_orderby_comment_ID = true;
  524. }
  525. $parsed = $this->parse_orderby( $_orderby );
  526. if ( ! $parsed ) {
  527. continue;
  528. }
  529. if ( 'comment__in' === $_orderby ) {
  530. $orderby_array[] = $parsed;
  531. continue;
  532. }
  533. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  534. }
  535. // If no valid clauses were found, order by comment_date_gmt.
  536. if ( empty( $orderby_array ) ) {
  537. $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
  538. }
  539. // To ensure determinate sorting, always include a comment_ID clause.
  540. if ( ! $found_orderby_comment_ID ) {
  541. $comment_ID_order = '';
  542. // Inherit order from comment_date or comment_date_gmt, if available.
  543. foreach ( $orderby_array as $orderby_clause ) {
  544. if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
  545. $comment_ID_order = $match[1];
  546. break;
  547. }
  548. }
  549. // If no date-related order is available, use the date from the first available clause.
  550. if ( ! $comment_ID_order ) {
  551. foreach ( $orderby_array as $orderby_clause ) {
  552. if ( false !== strpos( 'ASC', $orderby_clause ) ) {
  553. $comment_ID_order = 'ASC';
  554. } else {
  555. $comment_ID_order = 'DESC';
  556. }
  557. break;
  558. }
  559. }
  560. // Default to DESC.
  561. if ( ! $comment_ID_order ) {
  562. $comment_ID_order = 'DESC';
  563. }
  564. $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
  565. }
  566. $orderby = implode( ', ', $orderby_array );
  567. } else {
  568. $orderby = "$wpdb->comments.comment_date_gmt $order";
  569. }
  570. $number = absint( $this->query_vars['number'] );
  571. $offset = absint( $this->query_vars['offset'] );
  572. if ( ! empty( $number ) ) {
  573. if ( $offset ) {
  574. $limits = 'LIMIT ' . $offset . ',' . $number;
  575. } else {
  576. $limits = 'LIMIT ' . $number;
  577. }
  578. }
  579. if ( $this->query_vars['count'] ) {
  580. $fields = 'COUNT(*)';
  581. } else {
  582. $fields = "$wpdb->comments.comment_ID";
  583. }
  584. $post_id = absint( $this->query_vars['post_id'] );
  585. if ( ! empty( $post_id ) ) {
  586. $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
  587. }
  588. // Parse comment IDs for an IN clause.
  589. if ( ! empty( $this->query_vars['comment__in'] ) ) {
  590. $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
  591. }
  592. // Parse comment IDs for a NOT IN clause.
  593. if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
  594. $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
  595. }
  596. // Parse comment parent IDs for an IN clause.
  597. if ( ! empty( $this->query_vars['parent__in'] ) ) {
  598. $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
  599. }
  600. // Parse comment parent IDs for a NOT IN clause.
  601. if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
  602. $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
  603. }
  604. // Parse comment post IDs for an IN clause.
  605. if ( ! empty( $this->query_vars['post__in'] ) ) {
  606. $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
  607. }
  608. // Parse comment post IDs for a NOT IN clause.
  609. if ( ! empty( $this->query_vars['post__not_in'] ) ) {
  610. $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
  611. }
  612. if ( '' !== $this->query_vars['author_email'] ) {
  613. $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
  614. }
  615. if ( '' !== $this->query_vars['author_url'] ) {
  616. $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] );
  617. }
  618. if ( '' !== $this->query_vars['karma'] ) {
  619. $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
  620. }
  621. // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
  622. $raw_types = array(
  623. 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
  624. 'NOT IN' => (array) $this->query_vars['type__not_in'],
  625. );
  626. $comment_types = array();
  627. foreach ( $raw_types as $operator => $_raw_types ) {
  628. $_raw_types = array_unique( $_raw_types );
  629. foreach ( $_raw_types as $type ) {
  630. switch ( $type ) {
  631. // An empty translates to 'all', for backward compatibility
  632. case '':
  633. case 'all' :
  634. break;
  635. case 'comment':
  636. case 'comments':
  637. $comment_types[ $operator ][] = "''";
  638. break;
  639. case 'pings':
  640. $comment_types[ $operator ][] = "'pingback'";
  641. $comment_types[ $operator ][] = "'trackback'";
  642. break;
  643. default:
  644. $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
  645. break;
  646. }
  647. }
  648. if ( ! empty( $comment_types[ $operator ] ) ) {
  649. $types_sql = implode( ', ', $comment_types[ $operator ] );
  650. $this->sql_clauses['where']['comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
  651. }
  652. }
  653. $parent = $this->query_vars['parent'];
  654. if ( $this->query_vars['hierarchical'] && ! $parent ) {
  655. $parent = 0;
  656. }
  657. if ( '' !== $parent ) {
  658. $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent );
  659. }
  660. if ( is_array( $this->query_vars['user_id'] ) ) {
  661. $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
  662. } elseif ( '' !== $this->query_vars['user_id'] ) {
  663. $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
  664. }
  665. // Falsy search strings are ignored.
  666. if ( strlen( $this->query_vars['search'] ) ) {
  667. $search_sql = $this->get_search_sql(
  668. $this->query_vars['search'],
  669. array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
  670. );
  671. // Strip leading 'AND'.
  672. $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
  673. }
  674. // If any post-related query vars are passed, join the posts table.
  675. $join_posts_table = false;
  676. $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
  677. $post_fields = array_filter( $plucked );
  678. if ( ! empty( $post_fields ) ) {
  679. $join_posts_table = true;
  680. foreach ( $post_fields as $field_name => $field_value ) {
  681. // $field_value may be an array.
  682. $esses = array_fill( 0, count( (array) $field_value ), '%s' );
  683. $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
  684. }
  685. }
  686. // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'.
  687. foreach ( array( 'post_status', 'post_type' ) as $field_name ) {
  688. $q_values = array();
  689. if ( ! empty( $this->query_vars[ $field_name ] ) ) {
  690. $q_values = $this->query_vars[ $field_name ];
  691. if ( ! is_array( $q_values ) ) {
  692. $q_values = explode( ',', $q_values );
  693. }
  694. // 'any' will cause the query var to be ignored.
  695. if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) {
  696. continue;
  697. }
  698. $join_posts_table = true;
  699. $esses = array_fill( 0, count( $q_values ), '%s' );
  700. $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ")", $q_values );
  701. }
  702. }
  703. // Comment author IDs for an IN clause.
  704. if ( ! empty( $this->query_vars['author__in'] ) ) {
  705. $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
  706. }
  707. // Comment author IDs for a NOT IN clause.
  708. if ( ! empty( $this->query_vars['author__not_in'] ) ) {
  709. $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
  710. }
  711. // Post author IDs for an IN clause.
  712. if ( ! empty( $this->query_vars['post_author__in'] ) ) {
  713. $join_posts_table = true;
  714. $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
  715. }
  716. // Post author IDs for a NOT IN clause.
  717. if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
  718. $join_posts_table = true;
  719. $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
  720. }
  721. $join = '';
  722. if ( $join_posts_table ) {
  723. $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
  724. }
  725. if ( ! empty( $this->meta_query_clauses ) ) {
  726. $join .= $this->meta_query_clauses['join'];
  727. // Strip leading 'AND'.
  728. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
  729. if ( ! $this->query_vars['count'] ) {
  730. $groupby = "{$wpdb->comments}.comment_ID";
  731. }
  732. }
  733. if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
  734. $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
  735. $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
  736. }
  737. $where = implode( ' AND ', $this->sql_clauses['where'] );
  738. $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
  739. /**
  740. * Filters the comment query clauses.
  741. *
  742. * @since 3.1.0
  743. *
  744. * @param array $pieces A compacted array of comment query clauses.
  745. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  746. */
  747. $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
  748. $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
  749. $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
  750. $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
  751. $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
  752. $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
  753. $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
  754. $this->filtered_where_clause = $where;
  755. if ( $where ) {
  756. $where = 'WHERE ' . $where;
  757. }
  758. if ( $groupby ) {
  759. $groupby = 'GROUP BY ' . $groupby;
  760. }
  761. if ( $orderby ) {
  762. $orderby = "ORDER BY $orderby";
  763. }
  764. $found_rows = '';
  765. if ( ! $this->query_vars['no_found_rows'] ) {
  766. $found_rows = 'SQL_CALC_FOUND_ROWS';
  767. }
  768. $this->sql_clauses['select'] = "SELECT $found_rows $fields";
  769. $this->sql_clauses['from'] = "FROM $wpdb->comments $join";
  770. $this->sql_clauses['groupby'] = $groupby;
  771. $this->sql_clauses['orderby'] = $orderby;
  772. $this->sql_clauses['limits'] = $limits;
  773. $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
  774. if ( $this->query_vars['count'] ) {
  775. return intval( $wpdb->get_var( $this->request ) );
  776. } else {
  777. $comment_ids = $wpdb->get_col( $this->request );
  778. return array_map( 'intval', $comment_ids );
  779. }
  780. }
  781. /**
  782. * Populates found_comments and max_num_pages properties for the current
  783. * query if the limit clause was used.
  784. *
  785. * @since 4.6.0
  786. * @access private
  787. *
  788. * @global wpdb $wpdb WordPress database abstraction object.
  789. */
  790. private function set_found_comments() {
  791. global $wpdb;
  792. if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
  793. /**
  794. * Filters the query used to retrieve found comment count.
  795. *
  796. * @since 4.4.0
  797. *
  798. * @param string $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
  799. * @param WP_Comment_Query $comment_query The `WP_Comment_Query` instance.
  800. */
  801. $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
  802. $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
  803. }
  804. }
  805. /**
  806. * Fetch descendants for located comments.
  807. *
  808. * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
  809. * the descendant trees for all matched top-level comments.
  810. *
  811. * @since 4.4.0
  812. *
  813. * @param array $comments Array of top-level comments whose descendants should be filled in.
  814. * @return array
  815. */
  816. protected function fill_descendants( $comments ) {
  817. global $wpdb;
  818. $levels = array(
  819. 0 => wp_list_pluck( $comments, 'comment_ID' ),
  820. );
  821. /*
  822. * The WHERE clause for the descendant query is the same as for the top-level
  823. * query, minus the `parent`, `parent__in`, and `parent__not_in` sub-clauses.
  824. */
  825. $_where = $this->filtered_where_clause;
  826. $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
  827. foreach ( $exclude_keys as $exclude_key ) {
  828. if ( isset( $this->sql_clauses['where'][ $exclude_key ] ) ) {
  829. $clause = $this->sql_clauses['where'][ $exclude_key ];
  830. // Strip the clause as well as any adjacent ANDs.
  831. $pattern = '|(?:AND)?\s*' . $clause . '\s*(?:AND)?|';
  832. $_where_parts = preg_split( $pattern, $_where );
  833. // Remove empties.
  834. $_where_parts = array_filter( array_map( 'trim', $_where_parts ) );
  835. // Reassemble with an AND.
  836. $_where = implode( ' AND ', $_where_parts );
  837. }
  838. }
  839. $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
  840. $last_changed = wp_cache_get_last_changed( 'comment' );
  841. // Fetch an entire level of the descendant tree at a time.
  842. $level = 0;
  843. do {
  844. // Parent-child relationships may be cached. Only query for those that are not.
  845. $child_ids = $uncached_parent_ids = array();
  846. $_parent_ids = $levels[ $level ];
  847. foreach ( $_parent_ids as $parent_id ) {
  848. $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
  849. $parent_child_ids = wp_cache_get( $cache_key, 'comment' );
  850. if ( false !== $parent_child_ids ) {
  851. $child_ids = array_merge( $child_ids, $parent_child_ids );
  852. } else {
  853. $uncached_parent_ids[] = $parent_id;
  854. }
  855. }
  856. if ( $uncached_parent_ids ) {
  857. // Fetch this level of comments.
  858. $parent_query_args = $this->query_vars;
  859. foreach ( $exclude_keys as $exclude_key ) {
  860. $parent_query_args[ $exclude_key ] = '';
  861. }
  862. $parent_query_args['parent__in'] = $uncached_parent_ids;
  863. $parent_query_args['no_found_rows'] = true;
  864. $parent_query_args['hierarchical'] = false;
  865. $parent_query_args['offset'] = 0;
  866. $parent_query_args['number'] = 0;
  867. $level_comments = get_comments( $parent_query_args );
  868. // Cache parent-child relationships.
  869. $parent_map = array_fill_keys( $uncached_parent_ids, array() );
  870. foreach ( $level_comments as $level_comment ) {
  871. $parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID;
  872. $child_ids[] = $level_comment->comment_ID;
  873. }
  874. foreach ( $parent_map as $parent_id => $children ) {
  875. $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
  876. wp_cache_set( $cache_key, $children, 'comment' );
  877. }
  878. }
  879. $level++;
  880. $levels[ $level ] = $child_ids;
  881. } while ( $child_ids );
  882. // Prime comment caches for non-top-level comments.
  883. $descendant_ids = array();
  884. for ( $i = 1, $c = count( $levels ); $i < $c; $i++ ) {
  885. $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
  886. }
  887. _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
  888. // Assemble a flat array of all comments + descendants.
  889. $all_comments = $comments;
  890. foreach ( $descendant_ids as $descendant_id ) {
  891. $all_comments[] = get_comment( $descendant_id );
  892. }
  893. // If a threaded representation was requested, build the tree.
  894. if ( 'threaded' === $this->query_vars['hierarchical'] ) {
  895. $threaded_comments = $ref = array();
  896. foreach ( $all_comments as $k => $c ) {
  897. $_c = get_comment( $c->comment_ID );
  898. // If the comment isn't in the reference array, it goes in the top level of the thread.
  899. if ( ! isset( $ref[ $c->comment_parent ] ) ) {
  900. $threaded_comments[ $_c->comment_ID ] = $_c;
  901. $ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
  902. // Otherwise, set it as a child of its parent.
  903. } else {
  904. $ref[ $_c->comment_parent ]->add_child( $_c );
  905. $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
  906. }
  907. }
  908. // Set the 'populated_children' flag, to ensure additional database queries aren't run.
  909. foreach ( $ref as $_ref ) {
  910. $_ref->populated_children( true );
  911. }
  912. $comments = $threaded_comments;
  913. } else {
  914. $comments = $all_comments;
  915. }
  916. return $comments;
  917. }
  918. /**
  919. * Used internally to generate an SQL string for searching across multiple columns
  920. *
  921. * @since 3.1.0
  922. * @access protected
  923. *
  924. * @global wpdb $wpdb WordPress database abstraction object.
  925. *
  926. * @param string $string
  927. * @param array $cols
  928. * @return string
  929. */
  930. protected function get_search_sql( $string, $cols ) {
  931. global $wpdb;
  932. $like = '%' . $wpdb->esc_like( $string ) . '%';
  933. $searches = array();
  934. foreach ( $cols as $col ) {
  935. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  936. }
  937. return ' AND (' . implode(' OR ', $searches) . ')';
  938. }
  939. /**
  940. * Parse and sanitize 'orderby' keys passed to the comment query.
  941. *
  942. * @since 4.2.0
  943. * @access protected
  944. *
  945. * @global wpdb $wpdb WordPress database abstraction object.
  946. *
  947. * @param string $orderby Alias for the field to order by.
  948. * @return string|false Value to used in the ORDER clause. False otherwise.
  949. */
  950. protected function parse_orderby( $orderby ) {
  951. global $wpdb;
  952. $allowed_keys = array(
  953. 'comment_agent',
  954. 'comment_approved',
  955. 'comment_author',
  956. 'comment_author_email',
  957. 'comment_author_IP',
  958. 'comment_author_url',
  959. 'comment_content',
  960. 'comment_date',
  961. 'comment_date_gmt',
  962. 'comment_ID',
  963. 'comment_karma',
  964. 'comment_parent',
  965. 'comment_post_ID',
  966. 'comment_type',
  967. 'user_id',
  968. );
  969. if ( ! empty( $this->query_vars['meta_key'] ) ) {
  970. $allowed_keys[] = $this->query_vars['meta_key'];
  971. $allowed_keys[] = 'meta_value';
  972. $allowed_keys[] = 'meta_value_num';
  973. }
  974. $meta_query_clauses = $this->meta_query->get_clauses();
  975. if ( $meta_query_clauses ) {
  976. $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
  977. }
  978. $parsed = false;
  979. if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
  980. $parsed = "$wpdb->commentmeta.meta_value";
  981. } elseif ( $orderby == 'meta_value_num' ) {
  982. $parsed = "$wpdb->commentmeta.meta_value+0";
  983. } elseif ( $orderby == 'comment__in' ) {
  984. $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
  985. $parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
  986. } elseif ( in_array( $orderby, $allowed_keys ) ) {
  987. if ( isset( $meta_query_clauses[ $orderby ] ) ) {
  988. $meta_clause = $meta_query_clauses[ $orderby ];
  989. $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
  990. } else {
  991. $parsed = "$wpdb->comments.$orderby";
  992. }
  993. }
  994. return $parsed;
  995. }
  996. /**
  997. * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
  998. *
  999. * @since 4.2.0
  1000. * @access protected
  1001. *
  1002. * @param string $order The 'order' query variable.
  1003. * @return string The sanitized 'order' query variable.
  1004. */
  1005. protected function parse_order( $order ) {
  1006. if ( ! is_string( $order ) || empty( $order ) ) {
  1007. return 'DESC';
  1008. }
  1009. if ( 'ASC' === strtoupper( $order ) ) {
  1010. return 'ASC';
  1011. } else {
  1012. return 'DESC';
  1013. }
  1014. }
  1015. }