[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Class for generating SQL clauses that filter a primary query according to date.
   4   *
   5   * WP_Date_Query is a helper that allows primary query classes, such as WP_Query, to filter
   6   * their results by date columns, by generating `WHERE` subclauses to be attached to the
   7   * primary SQL query string.
   8   *
   9   * Attempting to filter by an invalid date value (eg month=13) will generate SQL that will
  10   * return no results. In these cases, a _doing_it_wrong() error notice is also thrown.
  11   * See WP_Date_Query::validate_date_values().
  12   *
  13   * @link https://developer.wordpress.org/reference/classes/wp_query/
  14   *
  15   * @since 3.7.0
  16   */
  17  #[AllowDynamicProperties]
  18  class WP_Date_Query {
  19      /**
  20       * Array of date queries.
  21       *
  22       * See WP_Date_Query::__construct() for information on date query arguments.
  23       *
  24       * @since 3.7.0
  25       * @var array
  26       */
  27      public $queries = array();
  28  
  29      /**
  30       * The default relation between top-level queries. Can be either 'AND' or 'OR'.
  31       *
  32       * @since 3.7.0
  33       * @var string
  34       */
  35      public $relation = 'AND';
  36  
  37      /**
  38       * The column to query against. Can be changed via the query arguments.
  39       *
  40       * @since 3.7.0
  41       * @var string
  42       */
  43      public $column = 'post_date';
  44  
  45      /**
  46       * The value comparison operator. Can be changed via the query arguments.
  47       *
  48       * @since 3.7.0
  49       * @var string
  50       */
  51      public $compare = '=';
  52  
  53      /**
  54       * Supported time-related parameter keys.
  55       *
  56       * @since 4.1.0
  57       * @var string[]
  58       */
  59      public $time_keys = array( 'after', 'before', 'year', 'month', 'monthnum', 'week', 'w', 'dayofyear', 'day', 'dayofweek', 'dayofweek_iso', 'hour', 'minute', 'second' );
  60  
  61      /**
  62       * Constructor.
  63       *
  64       * Time-related parameters that normally require integer values ('year', 'month', 'week', 'dayofyear', 'day',
  65       * 'dayofweek', 'dayofweek_iso', 'hour', 'minute', 'second') accept arrays of integers for some values of
  66       * 'compare'. When 'compare' is 'IN' or 'NOT IN', arrays are accepted; when 'compare' is 'BETWEEN' or 'NOT
  67       * BETWEEN', arrays of two valid values are required. See individual argument descriptions for accepted values.
  68       *
  69       * @since 3.7.0
  70       * @since 4.0.0 The $inclusive logic was updated to include all times within the date range.
  71       * @since 4.1.0 Introduced 'dayofweek_iso' time type parameter.
  72       *
  73       * @param array  $date_query {
  74       *     Array of date query clauses.
  75       *
  76       *     @type array ...$0 {
  77       *         @type string $column   Optional. The column to query against. If undefined, inherits the value of
  78       *                                the `$default_column` parameter. See WP_Date_Query::validate_column() and
  79       *                                the {@see 'date_query_valid_columns'} filter for the list of accepted values.
  80       *                                Default 'post_date'.
  81       *         @type string $compare  Optional. The comparison operator. Accepts '=', '!=', '>', '>=', '<', '<=',
  82       *                                'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Default '='.
  83       *         @type string $relation Optional. The boolean relationship between the date queries. Accepts 'OR' or 'AND'.
  84       *                                Default 'OR'.
  85       *         @type array  ...$0 {
  86       *             Optional. An array of first-order clause parameters, or another fully-formed date query.
  87       *
  88       *             @type string|array $before {
  89       *                 Optional. Date to retrieve posts before. Accepts `strtotime()`-compatible string,
  90       *                 or array of 'year', 'month', 'day' values.
  91       *
  92       *                 @type string $year  The four-digit year. Default empty. Accepts any four-digit year.
  93       *                 @type string $month Optional when passing array. The month of the year.
  94       *                                     Default (string:empty)|(array:1). Accepts numbers 1-12.
  95       *                 @type string $day   Optional when passing array. The day of the month.
  96       *                                     Default (string:empty)|(array:1). Accepts numbers 1-31.
  97       *             }
  98       *             @type string|array $after {
  99       *                 Optional. Date to retrieve posts after. Accepts `strtotime()`-compatible string,
 100       *                 or array of 'year', 'month', 'day' values.
 101       *
 102       *                 @type string $year  The four-digit year. Accepts any four-digit year. Default empty.
 103       *                 @type string $month Optional when passing array. The month of the year. Accepts numbers 1-12.
 104       *                                     Default (string:empty)|(array:12).
 105       *                 @type string $day   Optional when passing array. The day of the month. Accepts numbers 1-31.
 106       *                                     Default (string:empty)|(array:last day of month).
 107       *             }
 108       *             @type string       $column        Optional. Used to add a clause comparing a column other than
 109       *                                               the column specified in the top-level `$column` parameter.
 110       *                                               See WP_Date_Query::validate_column() and
 111       *                                               the {@see 'date_query_valid_columns'} filter for the list
 112       *                                               of accepted values. Default is the value of top-level `$column`.
 113       *             @type string       $compare       Optional. The comparison operator. Accepts '=', '!=', '>', '>=',
 114       *                                               '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Comparisons
 115       *                                               support arrays in some time-related parameters. Default '='.
 116       *             @type bool         $inclusive     Optional. Include results from dates specified in 'before' or
 117       *                                               'after'. Default false.
 118       *             @type int|int[]    $year          Optional. The four-digit year number. Accepts any four-digit year
 119       *                                               or an array of years if `$compare` supports it. Default empty.
 120       *             @type int|int[]    $month         Optional. The two-digit month number. Accepts numbers 1-12 or an
 121       *                                               array of valid numbers if `$compare` supports it. Default empty.
 122       *             @type int|int[]    $week          Optional. The week number of the year. Accepts numbers 1-53 or an
 123       *                                               array of valid numbers if `$compare` supports it. Default empty.
 124       *             @type int|int[]    $dayofyear     Optional. The day number of the year. Accepts numbers 1-366 or an
 125       *                                               array of valid numbers if `$compare` supports it.
 126       *             @type int|int[]    $day           Optional. The day of the month. Accepts numbers 1-31 or an array
 127       *                                               of valid numbers if `$compare` supports it. Default empty.
 128       *             @type int|int[]    $dayofweek     Optional. The day number of the week. Accepts numbers 1-7 (1 is
 129       *                                               Sunday) or an array of valid numbers if `$compare` supports it.
 130       *                                               Default empty.
 131       *             @type int|int[]    $dayofweek_iso Optional. The day number of the week (ISO). Accepts numbers 1-7
 132       *                                               (1 is Monday) or an array of valid numbers if `$compare` supports it.
 133       *                                               Default empty.
 134       *             @type int|int[]    $hour          Optional. The hour of the day. Accepts numbers 0-23 or an array
 135       *                                               of valid numbers if `$compare` supports it. Default empty.
 136       *             @type int|int[]    $minute        Optional. The minute of the hour. Accepts numbers 0-59 or an array
 137       *                                               of valid numbers if `$compare` supports it. Default empty.
 138       *             @type int|int[]    $second        Optional. The second of the minute. Accepts numbers 0-59 or an
 139       *                                               array of valid numbers if `$compare` supports it. Default empty.
 140       *         }
 141       *     }
 142       * }
 143       * @param string $default_column Optional. Default column to query against. See WP_Date_Query::validate_column()
 144       *                               and the {@see 'date_query_valid_columns'} filter for the list of accepted values.
 145       *                               Default 'post_date'.
 146       */
 147  	public function __construct( $date_query, $default_column = 'post_date' ) {
 148          if ( empty( $date_query ) || ! is_array( $date_query ) ) {
 149              return;
 150          }
 151  
 152          if ( isset( $date_query['relation'] ) ) {
 153              $this->relation = $this->sanitize_relation( $date_query['relation'] );
 154          } else {
 155              $this->relation = 'AND';
 156          }
 157  
 158          // Support for passing time-based keys in the top level of the $date_query array.
 159          if ( ! isset( $date_query[0] ) ) {
 160              $date_query = array( $date_query );
 161          }
 162  
 163          if ( ! empty( $date_query['column'] ) ) {
 164              $date_query['column'] = esc_sql( $date_query['column'] );
 165          } else {
 166              $date_query['column'] = esc_sql( $default_column );
 167          }
 168  
 169          $this->column = $this->validate_column( $this->column );
 170  
 171          $this->compare = $this->get_compare( $date_query );
 172  
 173          $this->queries = $this->sanitize_query( $date_query );
 174      }
 175  
 176      /**
 177       * Recursive-friendly query sanitizer.
 178       *
 179       * Ensures that each query-level clause has a 'relation' key, and that
 180       * each first-order clause contains all the necessary keys from `$defaults`.
 181       *
 182       * @since 4.1.0
 183       *
 184       * @param array $queries
 185       * @param array $parent_query
 186       * @return array Sanitized queries.
 187       */
 188  	public function sanitize_query( $queries, $parent_query = null ) {
 189          $cleaned_query = array();
 190  
 191          $defaults = array(
 192              'column'   => 'post_date',
 193              'compare'  => '=',
 194              'relation' => 'AND',
 195          );
 196  
 197          // Numeric keys should always have array values.
 198          foreach ( $queries as $qkey => $qvalue ) {
 199              if ( is_numeric( $qkey ) && ! is_array( $qvalue ) ) {
 200                  unset( $queries[ $qkey ] );
 201              }
 202          }
 203  
 204          // Each query should have a value for each default key. Inherit from the parent when possible.
 205          foreach ( $defaults as $dkey => $dvalue ) {
 206              if ( isset( $queries[ $dkey ] ) ) {
 207                  continue;
 208              }
 209  
 210              $queries[ $dkey ] = $parent_query[ $dkey ] ?? $dvalue;
 211          }
 212  
 213          // Validate the dates passed in the query.
 214          if ( $this->is_first_order_clause( $queries ) ) {
 215              $this->validate_date_values( $queries );
 216          }
 217  
 218          // Sanitize the relation parameter.
 219          $queries['relation'] = $this->sanitize_relation( $queries['relation'] );
 220  
 221          foreach ( $queries as $key => $q ) {
 222              if ( ! is_array( $q ) || in_array( $key, $this->time_keys, true ) ) {
 223                  // This is a first-order query. Trust the values and sanitize when building SQL.
 224                  $cleaned_query[ $key ] = $q;
 225              } else {
 226                  // Any array without a time key is another query, so we recurse.
 227                  $cleaned_query[] = $this->sanitize_query( $q, $queries );
 228              }
 229          }
 230  
 231          return $cleaned_query;
 232      }
 233  
 234      /**
 235       * Determines whether this is a first-order clause.
 236       *
 237       * Checks to see if the current clause has any time-related keys.
 238       * If so, it's first-order.
 239       *
 240       * @since 4.1.0
 241       *
 242       * @param array $query Query clause.
 243       * @return bool True if this is a first-order clause.
 244       */
 245  	protected function is_first_order_clause( $query ) {
 246          $time_keys = array_intersect( $this->time_keys, array_keys( $query ) );
 247          return ! empty( $time_keys );
 248      }
 249  
 250      /**
 251       * Determines and validates what comparison operator to use.
 252       *
 253       * @since 3.7.0
 254       *
 255       * @param array $query A date query or a date subquery.
 256       * @return string The comparison operator.
 257       */
 258  	public function get_compare( $query ) {
 259          if ( ! empty( $query['compare'] )
 260              && in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true )
 261          ) {
 262              return strtoupper( $query['compare'] );
 263          }
 264  
 265          return $this->compare;
 266      }
 267  
 268      /**
 269       * Validates the given date_query values and triggers errors if something is not valid.
 270       *
 271       * Note that date queries with invalid date ranges are allowed to
 272       * continue (though of course no items will be found for impossible dates).
 273       * This method only generates debug notices for these cases.
 274       *
 275       * @since 4.1.0
 276       *
 277       * @param array $date_query The date_query array.
 278       * @return bool True if all values in the query are valid, false if one or more fail.
 279       */
 280  	public function validate_date_values( $date_query = array() ) {
 281          if ( empty( $date_query ) ) {
 282              return false;
 283          }
 284  
 285          $valid = true;
 286  
 287          /*
 288           * Validate 'before' and 'after' up front, then let the
 289           * validation routine continue to be sure that all invalid
 290           * values generate errors too.
 291           */
 292          if ( array_key_exists( 'before', $date_query ) && is_array( $date_query['before'] ) ) {
 293              $valid = $this->validate_date_values( $date_query['before'] );
 294          }
 295  
 296          if ( array_key_exists( 'after', $date_query ) && is_array( $date_query['after'] ) ) {
 297              $valid = $this->validate_date_values( $date_query['after'] );
 298          }
 299  
 300          // Array containing all min-max checks.
 301          $min_max_checks = array();
 302  
 303          // Days per year.
 304          if ( array_key_exists( 'year', $date_query ) ) {
 305              /*
 306               * If a year exists in the date query, we can use it to get the days.
 307               * If multiple years are provided (as in a BETWEEN), use the first one.
 308               */
 309              if ( is_array( $date_query['year'] ) ) {
 310                  $_year = reset( $date_query['year'] );
 311              } else {
 312                  $_year = $date_query['year'];
 313              }
 314  
 315              $max_days_of_year = (int) gmdate( 'z', mktime( 0, 0, 0, 12, 31, $_year ) ) + 1;
 316          } else {
 317              // Otherwise we use the max of 366 (leap-year).
 318              $max_days_of_year = 366;
 319          }
 320  
 321          $min_max_checks['dayofyear'] = array(
 322              'min' => 1,
 323              'max' => $max_days_of_year,
 324          );
 325  
 326          // Days per week.
 327          $min_max_checks['dayofweek'] = array(
 328              'min' => 1,
 329              'max' => 7,
 330          );
 331  
 332          // Days per week.
 333          $min_max_checks['dayofweek_iso'] = array(
 334              'min' => 1,
 335              'max' => 7,
 336          );
 337  
 338          // Months per year.
 339          $min_max_checks['month'] = array(
 340              'min' => 1,
 341              'max' => 12,
 342          );
 343  
 344          // Weeks per year.
 345          if ( isset( $_year ) ) {
 346              /*
 347               * If we have a specific year, use it to calculate number of weeks.
 348               * Note: the number of weeks in a year is the date in which Dec 28 appears.
 349               */
 350              $week_count = gmdate( 'W', mktime( 0, 0, 0, 12, 28, $_year ) );
 351  
 352          } else {
 353              // Otherwise set the week-count to a maximum of 53.
 354              $week_count = 53;
 355          }
 356  
 357          $min_max_checks['week'] = array(
 358              'min' => 1,
 359              'max' => $week_count,
 360          );
 361  
 362          // Days per month.
 363          $min_max_checks['day'] = array(
 364              'min' => 1,
 365              'max' => 31,
 366          );
 367  
 368          // Hours per day.
 369          $min_max_checks['hour'] = array(
 370              'min' => 0,
 371              'max' => 23,
 372          );
 373  
 374          // Minutes per hour.
 375          $min_max_checks['minute'] = array(
 376              'min' => 0,
 377              'max' => 59,
 378          );
 379  
 380          // Seconds per minute.
 381          $min_max_checks['second'] = array(
 382              'min' => 0,
 383              'max' => 59,
 384          );
 385  
 386          // Concatenate and throw a notice for each invalid value.
 387          foreach ( $min_max_checks as $key => $check ) {
 388              if ( ! array_key_exists( $key, $date_query ) ) {
 389                  continue;
 390              }
 391  
 392              // Throw a notice for each failing value.
 393              foreach ( (array) $date_query[ $key ] as $_value ) {
 394                  $is_between = $_value >= $check['min'] && $_value <= $check['max'];
 395  
 396                  if ( ! is_numeric( $_value ) || ! $is_between ) {
 397                      $error = sprintf(
 398                          /* translators: Date query invalid date message. 1: Invalid value, 2: Type of value, 3: Minimum valid value, 4: Maximum valid value. */
 399                          __( 'Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.' ),
 400                          '<code>' . esc_html( $_value ) . '</code>',
 401                          '<code>' . esc_html( $key ) . '</code>',
 402                          '<code>' . esc_html( $check['min'] ) . '</code>',
 403                          '<code>' . esc_html( $check['max'] ) . '</code>'
 404                      );
 405  
 406                      _doing_it_wrong( __CLASS__, $error, '4.1.0' );
 407  
 408                      $valid = false;
 409                  }
 410              }
 411          }
 412  
 413          // If we already have invalid date messages, don't bother running through checkdate().
 414          if ( ! $valid ) {
 415              return $valid;
 416          }
 417  
 418          $day_month_year_error_msg = '';
 419  
 420          $day_exists   = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] );
 421          $month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] );
 422          $year_exists  = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] );
 423  
 424          if ( $day_exists && $month_exists && $year_exists ) {
 425              // 1. Checking day, month, year combination.
 426              if ( ! wp_checkdate( $date_query['month'], $date_query['day'], $date_query['year'], sprintf( '%s-%s-%s', $date_query['year'], $date_query['month'], $date_query['day'] ) ) ) {
 427                  $day_month_year_error_msg = sprintf(
 428                      /* translators: 1: Year, 2: Month, 3: Day of month. */
 429                      __( 'The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.' ),
 430                      '<code>' . esc_html( $date_query['year'] ) . '</code>',
 431                      '<code>' . esc_html( $date_query['month'] ) . '</code>',
 432                      '<code>' . esc_html( $date_query['day'] ) . '</code>'
 433                  );
 434  
 435                  $valid = false;
 436              }
 437          } elseif ( $day_exists && $month_exists ) {
 438              /*
 439               * 2. checking day, month combination
 440               * We use 2012 because, as a leap year, it's the most permissive.
 441               */
 442              if ( ! wp_checkdate( $date_query['month'], $date_query['day'], 2012, sprintf( '2012-%s-%s', $date_query['month'], $date_query['day'] ) ) ) {
 443                  $day_month_year_error_msg = sprintf(
 444                      /* translators: 1: Month, 2: Day of month. */
 445                      __( 'The following values do not describe a valid date: month %1$s, day %2$s.' ),
 446                      '<code>' . esc_html( $date_query['month'] ) . '</code>',
 447                      '<code>' . esc_html( $date_query['day'] ) . '</code>'
 448                  );
 449  
 450                  $valid = false;
 451              }
 452          }
 453  
 454          if ( ! empty( $day_month_year_error_msg ) ) {
 455              _doing_it_wrong( __CLASS__, $day_month_year_error_msg, '4.1.0' );
 456          }
 457  
 458          return $valid;
 459      }
 460  
 461      /**
 462       * Validates a column name parameter.
 463       *
 464       * Column names without a table prefix (like 'post_date') are checked against a list of
 465       * allowed and known tables, and then, if found, have a table prefix (such as 'wp_posts.')
 466       * prepended. Prefixed column names (such as 'wp_posts.post_date') bypass this allowed
 467       * check, and are only sanitized to remove illegal characters.
 468       *
 469       * @since 3.7.0
 470       *
 471       * @global wpdb $wpdb WordPress database abstraction object.
 472       *
 473       * @param string $column The user-supplied column name.
 474       * @return string A validated column name value.
 475       */
 476  	public function validate_column( $column ) {
 477          global $wpdb;
 478  
 479          $valid_columns = array(
 480              'post_date',         // Part of $wpdb->posts.
 481              'post_date_gmt',     // Part of $wpdb->posts.
 482              'post_modified',     // Part of $wpdb->posts.
 483              'post_modified_gmt', // Part of $wpdb->posts.
 484              'comment_date',      // Part of $wpdb->comments.
 485              'comment_date_gmt',  // Part of $wpdb->comments.
 486              'user_registered',   // Part of $wpdb->users.
 487          );
 488  
 489          if ( is_multisite() ) {
 490              $valid_columns = array_merge(
 491                  $valid_columns,
 492                  array(
 493                      'registered',   // Part of $wpdb->blogs.
 494                      'last_updated', // Part of $wpdb->blogs.
 495                  )
 496              );
 497          }
 498  
 499          // Attempt to detect a table prefix.
 500          if ( ! str_contains( $column, '.' ) ) {
 501              /**
 502               * Filters the list of valid date query columns.
 503               *
 504               * @since 3.7.0
 505               * @since 4.1.0 Added 'user_registered' to the default recognized columns.
 506               * @since 4.6.0 Added 'registered' and 'last_updated' to the default recognized columns.
 507               *
 508               * @param string[] $valid_columns An array of valid date query columns. Defaults
 509               *                                are 'post_date', 'post_date_gmt', 'post_modified',
 510               *                                'post_modified_gmt', 'comment_date', 'comment_date_gmt',
 511               *                                'user_registered', 'registered', 'last_updated'.
 512               */
 513              if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ), true ) ) {
 514                  $column = 'post_date';
 515              }
 516  
 517              $known_columns = array(
 518                  $wpdb->posts    => array(
 519                      'post_date',
 520                      'post_date_gmt',
 521                      'post_modified',
 522                      'post_modified_gmt',
 523                  ),
 524                  $wpdb->comments => array(
 525                      'comment_date',
 526                      'comment_date_gmt',
 527                  ),
 528                  $wpdb->users    => array(
 529                      'user_registered',
 530                  ),
 531              );
 532  
 533              if ( is_multisite() ) {
 534                  $known_columns[ $wpdb->blogs ] = array(
 535                      'registered',
 536                      'last_updated',
 537                  );
 538              }
 539  
 540              // If it's a known column name, add the appropriate table prefix.
 541              foreach ( $known_columns as $table_name => $table_columns ) {
 542                  if ( in_array( $column, $table_columns, true ) ) {
 543                      $column = $table_name . '.' . $column;
 544                      break;
 545                  }
 546              }
 547          }
 548  
 549          // Remove unsafe characters.
 550          return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column );
 551      }
 552  
 553      /**
 554       * Generates WHERE clause to be appended to a main query.
 555       *
 556       * @since 3.7.0
 557       *
 558       * @return string MySQL WHERE clause.
 559       */
 560  	public function get_sql() {
 561          $sql = $this->get_sql_clauses();
 562  
 563          $where = $sql['where'];
 564  
 565          /**
 566           * Filters the date query WHERE clause.
 567           *
 568           * @since 3.7.0
 569           *
 570           * @param string        $where WHERE clause of the date query.
 571           * @param WP_Date_Query $query The WP_Date_Query instance.
 572           */
 573          return apply_filters( 'get_date_sql', $where, $this );
 574      }
 575  
 576      /**
 577       * Generates SQL clauses to be appended to a main query.
 578       *
 579       * Called by the public WP_Date_Query::get_sql(), this method is abstracted
 580       * out to maintain parity with the other Query classes.
 581       *
 582       * @since 4.1.0
 583       *
 584       * @return string[] {
 585       *     Array containing JOIN and WHERE SQL clauses to append to the main query.
 586       *
 587       *     @type string $join  SQL fragment to append to the main JOIN clause.
 588       *     @type string $where SQL fragment to append to the main WHERE clause.
 589       * }
 590       */
 591  	protected function get_sql_clauses() {
 592          $sql = $this->get_sql_for_query( $this->queries );
 593  
 594          if ( ! empty( $sql['where'] ) ) {
 595              $sql['where'] = ' AND ' . $sql['where'];
 596          }
 597  
 598          return $sql;
 599      }
 600  
 601      /**
 602       * Generates SQL clauses for a single query array.
 603       *
 604       * If nested subqueries are found, this method recurses the tree to
 605       * produce the properly nested SQL.
 606       *
 607       * @since 4.1.0
 608       *
 609       * @param array $query Query to parse.
 610       * @param int   $depth Optional. Number of tree levels deep we currently are.
 611       *                     Used to calculate indentation. Default 0.
 612       * @return array {
 613       *     Array containing JOIN and WHERE SQL clauses to append to a single query array.
 614       *
 615       *     @type string $join  SQL fragment to append to the main JOIN clause.
 616       *     @type string $where SQL fragment to append to the main WHERE clause.
 617       * }
 618       */
 619  	protected function get_sql_for_query( $query, $depth = 0 ) {
 620          $sql_chunks = array(
 621              'join'  => array(),
 622              'where' => array(),
 623          );
 624  
 625          $sql = array(
 626              'join'  => '',
 627              'where' => '',
 628          );
 629  
 630          $indent = '';
 631          for ( $i = 0; $i < $depth; $i++ ) {
 632              $indent .= '  ';
 633          }
 634  
 635          foreach ( $query as $key => $clause ) {
 636              if ( 'relation' === $key ) {
 637                  $relation = $query['relation'];
 638              } elseif ( is_array( $clause ) ) {
 639  
 640                  // This is a first-order clause.
 641                  if ( $this->is_first_order_clause( $clause ) ) {
 642                      $clause_sql = $this->get_sql_for_clause( $clause, $query );
 643  
 644                      $where_count = count( $clause_sql['where'] );
 645                      if ( ! $where_count ) {
 646                          $sql_chunks['where'][] = '';
 647                      } elseif ( 1 === $where_count ) {
 648                          $sql_chunks['where'][] = $clause_sql['where'][0];
 649                      } else {
 650                          $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
 651                      }
 652  
 653                      $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
 654                      // This is a subquery, so we recurse.
 655                  } else {
 656                      $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
 657  
 658                      $sql_chunks['where'][] = $clause_sql['where'];
 659                      $sql_chunks['join'][]  = $clause_sql['join'];
 660                  }
 661              }
 662          }
 663  
 664          // Filter to remove empties.
 665          $sql_chunks['join']  = array_filter( $sql_chunks['join'] );
 666          $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
 667  
 668          if ( empty( $relation ) ) {
 669              $relation = 'AND';
 670          }
 671  
 672          // Filter duplicate JOIN clauses and combine into a single string.
 673          if ( ! empty( $sql_chunks['join'] ) ) {
 674              $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
 675          }
 676  
 677          // Generate a single WHERE clause with proper brackets and indentation.
 678          if ( ! empty( $sql_chunks['where'] ) ) {
 679              $sql['where'] = '( ' . "\n  " . $indent . implode( ' ' . "\n  " . $indent . $relation . ' ' . "\n  " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
 680          }
 681  
 682          return $sql;
 683      }
 684  
 685      /**
 686       * Turns a single date clause into pieces for a WHERE clause.
 687       *
 688       * A wrapper for get_sql_for_clause(), included here for backward
 689       * compatibility while retaining the naming convention across Query classes.
 690       *
 691       * @since 3.7.0
 692       *
 693       * @param array $query Date query arguments.
 694       * @return array {
 695       *     Array containing JOIN and WHERE SQL clauses to append to the main query.
 696       *
 697       *     @type string[] $join  Array of SQL fragments to append to the main JOIN clause.
 698       *     @type string[] $where Array of SQL fragments to append to the main WHERE clause.
 699       * }
 700       */
 701  	protected function get_sql_for_subquery( $query ) {
 702          return $this->get_sql_for_clause( $query, '' );
 703      }
 704  
 705      /**
 706       * Turns a first-order date query into SQL for a WHERE clause.
 707       *
 708       * @since 4.1.0
 709       *
 710       * @global wpdb $wpdb WordPress database abstraction object.
 711       *
 712       * @param array $query        Date query clause.
 713       * @param array $parent_query Parent query of the current date query.
 714       * @return array {
 715       *     Array containing JOIN and WHERE SQL clauses to append to the main query.
 716       *
 717       *     @type string[] $join  Array of SQL fragments to append to the main JOIN clause.
 718       *     @type string[] $where Array of SQL fragments to append to the main WHERE clause.
 719       * }
 720       */
 721  	protected function get_sql_for_clause( $query, $parent_query ) {
 722          global $wpdb;
 723  
 724          // The sub-parts of a $where part.
 725          $where_parts = array();
 726  
 727          $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
 728  
 729          $column = $this->validate_column( $column );
 730  
 731          $compare = $this->get_compare( $query );
 732  
 733          $inclusive = ! empty( $query['inclusive'] );
 734  
 735          // Assign greater- and less-than values.
 736          $lt = '<';
 737          $gt = '>';
 738  
 739          if ( $inclusive ) {
 740              $lt .= '=';
 741              $gt .= '=';
 742          }
 743  
 744          // Range queries.
 745          if ( ! empty( $query['after'] ) ) {
 746              $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) );
 747          }
 748          if ( ! empty( $query['before'] ) ) {
 749              $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) );
 750          }
 751          // Specific value queries.
 752  
 753          $date_units = array(
 754              'YEAR'           => array( 'year' ),
 755              'MONTH'          => array( 'month', 'monthnum' ),
 756              '_wp_mysql_week' => array( 'week', 'w' ),
 757              'DAYOFYEAR'      => array( 'dayofyear' ),
 758              'DAYOFMONTH'     => array( 'day' ),
 759              'DAYOFWEEK'      => array( 'dayofweek' ),
 760              'WEEKDAY'        => array( 'dayofweek_iso' ),
 761          );
 762  
 763          // Check of the possible date units and add them to the query.
 764          foreach ( $date_units as $sql_part => $query_parts ) {
 765              foreach ( $query_parts as $query_part ) {
 766                  if ( isset( $query[ $query_part ] ) ) {
 767                      $value = $this->build_value( $compare, $query[ $query_part ] );
 768                      if ( $value ) {
 769                          switch ( $sql_part ) {
 770                              case '_wp_mysql_week':
 771                                  $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
 772                                  break;
 773                              case 'WEEKDAY':
 774                                  $where_parts[] = "$sql_part( $column ) + 1 $compare $value";
 775                                  break;
 776                              default:
 777                                  $where_parts[] = "$sql_part( $column ) $compare $value";
 778                          }
 779  
 780                          break;
 781                      }
 782                  }
 783              }
 784          }
 785  
 786          if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
 787              // Avoid notices.
 788              foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
 789                  if ( ! isset( $query[ $unit ] ) ) {
 790                      $query[ $unit ] = null;
 791                  }
 792              }
 793  
 794              $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] );
 795              if ( $time_query ) {
 796                  $where_parts[] = $time_query;
 797              }
 798          }
 799  
 800          /*
 801           * Return an array of 'join' and 'where' for compatibility
 802           * with other query classes.
 803           */
 804          return array(
 805              'where' => $where_parts,
 806              'join'  => array(),
 807          );
 808      }
 809  
 810      /**
 811       * Builds and validates a value string based on the comparison operator.
 812       *
 813       * @since 3.7.0
 814       *
 815       * @param string       $compare The compare operator to use.
 816       * @param string|array $value   The value.
 817       * @return string|false|int The value to be used in SQL or false on error.
 818       */
 819  	public function build_value( $compare, $value ) {
 820          if ( ! isset( $value ) ) {
 821              return false;
 822          }
 823  
 824          switch ( $compare ) {
 825              case 'IN':
 826              case 'NOT IN':
 827                  $value = (array) $value;
 828  
 829                  // Remove non-numeric values.
 830                  $value = array_filter( $value, 'is_numeric' );
 831  
 832                  if ( empty( $value ) ) {
 833                      return false;
 834                  }
 835  
 836                  return '(' . implode( ',', array_map( 'intval', $value ) ) . ')';
 837  
 838              case 'BETWEEN':
 839              case 'NOT BETWEEN':
 840                  if ( ! is_array( $value ) || 2 !== count( $value ) ) {
 841                      $value = array( $value, $value );
 842                  } else {
 843                      $value = array_values( $value );
 844                  }
 845  
 846                  // If either value is non-numeric, bail.
 847                  foreach ( $value as $v ) {
 848                      if ( ! is_numeric( $v ) ) {
 849                          return false;
 850                      }
 851                  }
 852  
 853                  $value = array_map( 'intval', $value );
 854  
 855                  return $value[0] . ' AND ' . $value[1];
 856  
 857              default:
 858                  if ( ! is_numeric( $value ) ) {
 859                      return false;
 860                  }
 861  
 862                  return (int) $value;
 863          }
 864      }
 865  
 866      /**
 867       * Builds a MySQL format date/time based on some query parameters.
 868       *
 869       * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
 870       * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
 871       * pass a string that will be passed to date_create().
 872       *
 873       * @since 3.7.0
 874       *
 875       * @param string|array $datetime       An array of parameters or a strtotime() string.
 876       * @param bool         $default_to_max Whether to round up incomplete dates. Supported by values
 877       *                                     of $datetime that are arrays, or string values that are a
 878       *                                     subset of MySQL date format ('Y', 'Y-m', 'Y-m-d', 'Y-m-d H:i').
 879       *                                     Default: false.
 880       * @return string|false A MySQL format date/time or false on failure.
 881       */
 882  	public function build_mysql_datetime( $datetime, $default_to_max = false ) {
 883          if ( ! is_array( $datetime ) ) {
 884  
 885              /*
 886               * Try to parse some common date formats, so we can detect
 887               * the level of precision and support the 'inclusive' parameter.
 888               */
 889              if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) {
 890                  // Y
 891                  $datetime = array(
 892                      'year' => (int) $matches[1],
 893                  );
 894  
 895              } elseif ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) {
 896                  // Y-m
 897                  $datetime = array(
 898                      'year'  => (int) $matches[1],
 899                      'month' => (int) $matches[2],
 900                  );
 901  
 902              } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) {
 903                  // Y-m-d
 904                  $datetime = array(
 905                      'year'  => (int) $matches[1],
 906                      'month' => (int) $matches[2],
 907                      'day'   => (int) $matches[3],
 908                  );
 909  
 910              } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) {
 911                  // Y-m-d H:i
 912                  $datetime = array(
 913                      'year'   => (int) $matches[1],
 914                      'month'  => (int) $matches[2],
 915                      'day'    => (int) $matches[3],
 916                      'hour'   => (int) $matches[4],
 917                      'minute' => (int) $matches[5],
 918                  );
 919              }
 920  
 921              // If no match is found, we don't support default_to_max.
 922              if ( ! is_array( $datetime ) ) {
 923                  $wp_timezone = wp_timezone();
 924  
 925                  // Assume local timezone if not provided.
 926                  $dt = date_create( $datetime, $wp_timezone );
 927  
 928                  if ( false === $dt ) {
 929                      return gmdate( 'Y-m-d H:i:s', false );
 930                  }
 931  
 932                  return $dt->setTimezone( $wp_timezone )->format( 'Y-m-d H:i:s' );
 933              }
 934          }
 935  
 936          $datetime = array_map( 'absint', $datetime );
 937  
 938          if ( ! isset( $datetime['year'] ) ) {
 939              $datetime['year'] = current_time( 'Y' );
 940          }
 941  
 942          if ( ! isset( $datetime['month'] ) ) {
 943              $datetime['month'] = ( $default_to_max ) ? 12 : 1;
 944          }
 945  
 946          if ( ! isset( $datetime['day'] ) ) {
 947              $datetime['day'] = ( $default_to_max ) ? (int) gmdate( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
 948          }
 949  
 950          if ( ! isset( $datetime['hour'] ) ) {
 951              $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
 952          }
 953  
 954          if ( ! isset( $datetime['minute'] ) ) {
 955              $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
 956          }
 957  
 958          if ( ! isset( $datetime['second'] ) ) {
 959              $datetime['second'] = ( $default_to_max ) ? 59 : 0;
 960          }
 961  
 962          return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
 963      }
 964  
 965      /**
 966       * Builds a query string for comparing time values (hour, minute, second).
 967       *
 968       * If just hour, minute, or second is set than a normal comparison will be done.
 969       * However if multiple values are passed, a pseudo-decimal time will be created
 970       * in order to be able to accurately compare against.
 971       *
 972       * @since 3.7.0
 973       *
 974       * @global wpdb $wpdb WordPress database abstraction object.
 975       *
 976       * @param string   $column  The column to query against. Needs to be pre-validated!
 977       * @param string   $compare The comparison operator. Needs to be pre-validated!
 978       * @param int|null $hour    Optional. An hour value (0-23).
 979       * @param int|null $minute  Optional. A minute value (0-59).
 980       * @param int|null $second  Optional. A second value (0-59).
 981       * @return string|false A query part or false on failure.
 982       */
 983  	public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
 984          global $wpdb;
 985  
 986          // Have to have at least one.
 987          if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) ) {
 988              return false;
 989          }
 990  
 991          // Complex combined queries aren't supported for multi-value queries.
 992          if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) {
 993              $return = array();
 994  
 995              $value = $this->build_value( $compare, $hour );
 996              if ( false !== $value ) {
 997                  $return[] = "HOUR( $column ) $compare $value";
 998              }
 999  
1000              $value = $this->build_value( $compare, $minute );
1001              if ( false !== $value ) {
1002                  $return[] = "MINUTE( $column ) $compare $value";
1003              }
1004  
1005              $value = $this->build_value( $compare, $second );
1006              if ( false !== $value ) {
1007                  $return[] = "SECOND( $column ) $compare $value";
1008              }
1009  
1010              return implode( ' AND ', $return );
1011          }
1012  
1013          // Cases where just one unit is set.
1014          if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) ) {
1015              $value = $this->build_value( $compare, $hour );
1016              if ( false !== $value ) {
1017                  return "HOUR( $column ) $compare $value";
1018              }
1019          } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) ) {
1020              $value = $this->build_value( $compare, $minute );
1021              if ( false !== $value ) {
1022                  return "MINUTE( $column ) $compare $value";
1023              }
1024          } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) ) {
1025              $value = $this->build_value( $compare, $second );
1026              if ( false !== $value ) {
1027                  return "SECOND( $column ) $compare $value";
1028              }
1029          }
1030  
1031          // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
1032          if ( ! isset( $minute ) ) {
1033              return false;
1034          }
1035  
1036          $format = '';
1037          $time   = '';
1038  
1039          // Hour.
1040          if ( null !== $hour ) {
1041              $format .= '%H.';
1042              $time   .= sprintf( '%02d', $hour ) . '.';
1043          } else {
1044              $format .= '0.';
1045              $time   .= '0.';
1046          }
1047  
1048          // Minute.
1049          $format .= '%i';
1050          $time   .= sprintf( '%02d', $minute );
1051  
1052          if ( isset( $second ) ) {
1053              $format .= '%s';
1054              $time   .= sprintf( '%02d', $second );
1055          }
1056  
1057          return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );
1058      }
1059  
1060      /**
1061       * Sanitizes a 'relation' operator.
1062       *
1063       * @since 6.0.3
1064       *
1065       * @param string $relation Raw relation key from the query argument.
1066       * @return string Sanitized relation. Either 'AND' or 'OR'.
1067       */
1068  	public function sanitize_relation( $relation ) {
1069          if ( 'OR' === strtoupper( $relation ) ) {
1070              return 'OR';
1071          } else {
1072              return 'AND';
1073          }
1074      }
1075  }


Generated : Sun Jun 14 08:20:09 2026 Cross-referenced by PHPXref