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