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


Generated : Sat Sep 5 08:20:28 2026 Cross-referenced by PHPXref