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