[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-comment-query.php (source)

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


Generated : Fri Jun 27 08:20:01 2025 Cross-referenced by PHPXref