class-wp-comment-query.php 41 KB

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