[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sat May 30 01:00:03 2020 Cross-referenced by PHPXref 0.7.1