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