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