[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sat Apr 20 01:00:03 2024 Cross-referenced by PHPXref 0.7.1