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