]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/date.php
WordPress 4.1.1
[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                         /*
309                          * If a year exists in the date query, we can use it to get the days.
310                          * If multiple years are provided (as in a BETWEEN), use the first one.
311                          */
312                         if ( is_array( $date_query['year'] ) ) {
313                                 $_year = reset( $date_query['year'] );
314                         } else {
315                                 $_year = $date_query['year'];
316                         }
317
318                         $max_days_of_year = date( 'z', mktime( 0, 0, 0, 12, 31, $_year ) ) + 1;
319                 } else {
320                         // otherwise we use the max of 366 (leap-year)
321                         $max_days_of_year = 366;
322                 }
323
324                 $min_max_checks['dayofyear'] = array(
325                         'min' => 1,
326                         'max' => $max_days_of_year
327                 );
328
329                 // Days per week.
330                 $min_max_checks['dayofweek'] = array(
331                         'min' => 1,
332                         'max' => 7
333                 );
334
335                 // Days per week.
336                 $min_max_checks['dayofweek_iso'] = array(
337                         'min' => 1,
338                         'max' => 7
339                 );
340
341                 // Months per year.
342                 $min_max_checks['month'] = array(
343                         'min' => 1,
344                         'max' => 12
345                 );
346
347                 // Weeks per year.
348                 if ( isset( $_year ) ) {
349                         // If we have a specific year, use it to calculate number of weeks.
350                         $date = new DateTime();
351                         $date->setISODate( $_year, 53 );
352                         $week_count = $date->format( "W" ) === "53" ? 53 : 52;
353
354                 } else {
355                         // Otherwise set the week-count to a maximum of 53.
356                         $week_count = 53;
357                 }
358
359                 $min_max_checks['week'] = array(
360                         'min' => 1,
361                         'max' => $week_count
362                 );
363
364                 // Days per month.
365                 $min_max_checks['day'] = array(
366                         'min' => 1,
367                         'max' => 31
368                 );
369
370                 // Hours per day.
371                 $min_max_checks['hour'] = array(
372                         'min' => 0,
373                         'max' => 23
374                 );
375
376                 // Minutes per hour.
377                 $min_max_checks['minute'] = array(
378                         'min' => 0,
379                         'max' => 59
380                 );
381
382                 // Seconds per minute.
383                 $min_max_checks['second'] = array(
384                         'min' => 0,
385                         'max' => 59
386                 );
387
388                 // Concatenate and throw a notice for each invalid value.
389                 foreach ( $min_max_checks as $key => $check ) {
390                         if ( ! array_key_exists( $key, $date_query ) ) {
391                                 continue;
392                         }
393
394                         // Throw a notice for each failing value.
395                         $is_between = true;
396                         foreach ( (array) $date_query[ $key ] as $_value ) {
397                                 $is_between = $_value >= $check['min'] && $_value <= $check['max'];
398
399                                 if ( ! is_numeric( $_value ) || ! $is_between ) {
400                                         $error = sprintf(
401                                                 /* translators: Date query invalid date message: 1: invalid value, 2: type of value, 3: minimum valid value, 4: maximum valid value */
402                                                 __( 'Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.' ),
403                                                 '<code>' . esc_html( $_value ) . '</code>',
404                                                 '<code>' . esc_html( $key ) . '</code>',
405                                                 '<code>' . esc_html( $check['min'] ) . '</code>',
406                                                 '<code>' . esc_html( $check['max'] ) . '</code>'
407                                         );
408
409                                         _doing_it_wrong( __CLASS__, $error, '4.1.0' );
410
411                                         $valid = false;
412                                 }
413                         }
414                 }
415
416                 // If we already have invalid date messages, don't bother running through checkdate().
417                 if ( ! $valid ) {
418                         return $valid;
419                 }
420
421                 $day_month_year_error_msg = '';
422
423                 $day_exists   = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] );
424                 $month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] );
425                 $year_exists  = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] );
426
427                 if ( $day_exists && $month_exists && $year_exists ) {
428                         // 1. Checking day, month, year combination.
429                         if ( ! wp_checkdate( $date_query['month'], $date_query['day'], $date_query['year'], sprintf( '%s-%s-%s', $date_query['year'], $date_query['month'], $date_query['day'] ) ) ) {
430                                 /* translators: 1: year, 2: month, 3: day of month */
431                                 $day_month_year_error_msg = sprintf(
432                                         __( 'The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.' ),
433                                         '<code>' . esc_html( $date_query['year'] ) . '</code>',
434                                         '<code>' . esc_html( $date_query['month'] ) . '</code>',
435                                         '<code>' . esc_html( $date_query['day'] ) . '</code>'
436                                 );
437
438                                 $valid = false;
439                         }
440
441                 } else if ( $day_exists && $month_exists ) {
442                         /*
443                          * 2. checking day, month combination
444                          * We use 2012 because, as a leap year, it's the most permissive.
445                          */
446                         if ( ! wp_checkdate( $date_query['month'], $date_query['day'], 2012, sprintf( '2012-%s-%s', $date_query['month'], $date_query['day'] ) ) ) {
447                                 /* translators: 1: month, 2: day of month */
448                                 $day_month_year_error_msg = sprintf(
449                                         __( 'The following values do not describe a valid date: month %1$s, day %2$s.' ),
450                                         '<code>' . esc_html( $date_query['month'] ) . '</code>',
451                                         '<code>' . esc_html( $date_query['day'] ) . '</code>'
452                                 );
453
454                                 $valid = false;
455                         }
456                 }
457
458                 if ( ! empty( $day_month_year_error_msg ) ) {
459                         _doing_it_wrong( __CLASS__, $day_month_year_error_msg, '4.1.0' );
460                 }
461
462                 return $valid;
463         }
464
465         /**
466          * Validates a column name parameter.
467          *
468          * Column names without a table prefix (like 'post_date') are checked against a whitelist of
469          * known tables, and then, if found, have a table prefix (such as 'wp_posts.') prepended.
470          * Prefixed column names (such as 'wp_posts.post_date') bypass this whitelist check,
471          * and are only sanitized to remove illegal characters.
472          *
473          * @since 3.7.0
474          * @access public
475          *
476          * @param string $column The user-supplied column name.
477          * @return string A validated column name value.
478          */
479         public function validate_column( $column ) {
480                 global $wpdb;
481
482                 $valid_columns = array(
483                         'post_date', 'post_date_gmt', 'post_modified',
484                         'post_modified_gmt', 'comment_date', 'comment_date_gmt',
485                         'user_registered',
486                 );
487
488                 // Attempt to detect a table prefix.
489                 if ( false === strpos( $column, '.' ) ) {
490                         /**
491                          * Filter the list of valid date query columns.
492                          *
493                          * @since 3.7.0
494                          * @since 4.1.0 Added 'user_registered' to the default recognized columns.
495                          *
496                          * @param array $valid_columns An array of valid date query columns. Defaults
497                          *                             are 'post_date', 'post_date_gmt', 'post_modified',
498                          *                             'post_modified_gmt', 'comment_date', 'comment_date_gmt',
499                          *                                 'user_registered'
500                          */
501                         if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ) ) ) {
502                                 $column = 'post_date';
503                         }
504
505                         $known_columns = array(
506                                 $wpdb->posts => array(
507                                         'post_date',
508                                         'post_date_gmt',
509                                         'post_modified',
510                                         'post_modified_gmt',
511                                 ),
512                                 $wpdb->comments => array(
513                                         'comment_date',
514                                         'comment_date_gmt',
515                                 ),
516                                 $wpdb->users => array(
517                                         'user_registered',
518                                 ),
519                         );
520
521                         // If it's a known column name, add the appropriate table prefix.
522                         foreach ( $known_columns as $table_name => $table_columns ) {
523                                 if ( in_array( $column, $table_columns ) ) {
524                                         $column = $table_name . '.' . $column;
525                                         break;
526                                 }
527                         }
528
529                 }
530
531                 // Remove unsafe characters.
532                 return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column );
533         }
534
535         /**
536          * Generate WHERE clause to be appended to a main query.
537          *
538          * @since 3.7.0
539          * @access public
540          *
541          * @return string MySQL WHERE clause.
542          */
543         public function get_sql() {
544                 $sql = $this->get_sql_clauses();
545
546                 $where = $sql['where'];
547
548                 /**
549                  * Filter the date query WHERE clause.
550                  *
551                  * @since 3.7.0
552                  *
553                  * @param string        $where WHERE clause of the date query.
554                  * @param WP_Date_Query $this  The WP_Date_Query instance.
555                  */
556                 return apply_filters( 'get_date_sql', $where, $this );
557         }
558
559         /**
560          * Generate SQL clauses to be appended to a main query.
561          *
562          * Called by the public {@see WP_Date_Query::get_sql()}, this method
563          * is abstracted out to maintain parity with the other Query classes.
564          *
565          * @since 4.1.0
566          * @access protected
567          *
568          * @return array {
569          *     Array containing JOIN and WHERE SQL clauses to append to the main query.
570          *
571          *     @type string $join  SQL fragment to append to the main JOIN clause.
572          *     @type string $where SQL fragment to append to the main WHERE clause.
573          * }
574          */
575         protected function get_sql_clauses() {
576                 $sql = $this->get_sql_for_query( $this->queries );
577
578                 if ( ! empty( $sql['where'] ) ) {
579                         $sql['where'] = ' AND ' . $sql['where'];
580                 }
581
582                 return $sql;
583         }
584
585         /**
586          * Generate SQL clauses for a single query array.
587          *
588          * If nested subqueries are found, this method recurses the tree to
589          * produce the properly nested SQL.
590          *
591          * @since 4.1.0
592          * @access protected
593          *
594          * @param array $query Query to parse.
595          * @param int   $depth Optional. Number of tree levels deep we currently are.
596          *                     Used to calculate indentation. Default 0.
597          * @return array {
598          *     Array containing JOIN and WHERE SQL clauses to append to a single query array.
599          *
600          *     @type string $join  SQL fragment to append to the main JOIN clause.
601          *     @type string $where SQL fragment to append to the main WHERE clause.
602          * }
603          */
604         protected function get_sql_for_query( $query, $depth = 0 ) {
605                 $sql_chunks = array(
606                         'join'  => array(),
607                         'where' => array(),
608                 );
609
610                 $sql = array(
611                         'join'  => '',
612                         'where' => '',
613                 );
614
615                 $indent = '';
616                 for ( $i = 0; $i < $depth; $i++ ) {
617                         $indent .= "  ";
618                 }
619
620                 foreach ( $query as $key => $clause ) {
621                         if ( 'relation' === $key ) {
622                                 $relation = $query['relation'];
623                         } else if ( is_array( $clause ) ) {
624
625                                 // This is a first-order clause.
626                                 if ( $this->is_first_order_clause( $clause ) ) {
627                                         $clause_sql = $this->get_sql_for_clause( $clause, $query );
628
629                                         $where_count = count( $clause_sql['where'] );
630                                         if ( ! $where_count ) {
631                                                 $sql_chunks['where'][] = '';
632                                         } else if ( 1 === $where_count ) {
633                                                 $sql_chunks['where'][] = $clause_sql['where'][0];
634                                         } else {
635                                                 $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
636                                         }
637
638                                         $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
639                                 // This is a subquery, so we recurse.
640                                 } else {
641                                         $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
642
643                                         $sql_chunks['where'][] = $clause_sql['where'];
644                                         $sql_chunks['join'][]  = $clause_sql['join'];
645                                 }
646                         }
647                 }
648
649                 // Filter to remove empties.
650                 $sql_chunks['join']  = array_filter( $sql_chunks['join'] );
651                 $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
652
653                 if ( empty( $relation ) ) {
654                         $relation = 'AND';
655                 }
656
657                 // Filter duplicate JOIN clauses and combine into a single string.
658                 if ( ! empty( $sql_chunks['join'] ) ) {
659                         $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
660                 }
661
662                 // Generate a single WHERE clause with proper brackets and indentation.
663                 if ( ! empty( $sql_chunks['where'] ) ) {
664                         $sql['where'] = '( ' . "\n  " . $indent . implode( ' ' . "\n  " . $indent . $relation . ' ' . "\n  " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
665                 }
666
667                 return $sql;
668         }
669
670         /**
671          * Turns a single date clause into pieces for a WHERE clause.
672          *
673          * A wrapper for get_sql_for_clause(), included here for backward
674          * compatibility while retaining the naming convention across Query classes.
675          *
676          * @since  3.7.0
677          * @access protected
678          *
679          * @param  array $query Date query arguments.
680          * @return array {
681          *     Array containing JOIN and WHERE SQL clauses to append to the main query.
682          *
683          *     @type string $join  SQL fragment to append to the main JOIN clause.
684          *     @type string $where SQL fragment to append to the main WHERE clause.
685          * }
686          */
687         protected function get_sql_for_subquery( $query ) {
688                 return $this->get_sql_for_clause( $query, '' );
689         }
690
691         /**
692          * Turns a first-order date query into SQL for a WHERE clause.
693          *
694          * @since  4.1.0
695          * @access protected
696          *
697          * @param  array $query        Date query clause.
698          * @param  array $parent_query Parent query of the current date query.
699          * @return array {
700          *     Array containing JOIN and WHERE SQL clauses to append to the main query.
701          *
702          *     @type string $join  SQL fragment to append to the main JOIN clause.
703          *     @type string $where SQL fragment to append to the main WHERE clause.
704          * }
705          */
706         protected function get_sql_for_clause( $query, $parent_query ) {
707                 global $wpdb;
708
709                 // The sub-parts of a $where part.
710                 $where_parts = array();
711
712                 $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
713
714                 $column = $this->validate_column( $column );
715
716                 $compare = $this->get_compare( $query );
717
718                 $inclusive = ! empty( $query['inclusive'] );
719
720                 // Assign greater- and less-than values.
721                 $lt = '<';
722                 $gt = '>';
723
724                 if ( $inclusive ) {
725                         $lt .= '=';
726                         $gt .= '=';
727                 }
728
729                 // Range queries.
730                 if ( ! empty( $query['after'] ) )
731                         $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) );
732
733                 if ( ! empty( $query['before'] ) )
734                         $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) );
735
736                 // Specific value queries.
737
738                 if ( isset( $query['year'] ) && $value = $this->build_value( $compare, $query['year'] ) )
739                         $where_parts[] = "YEAR( $column ) $compare $value";
740
741                 if ( isset( $query['month'] ) && $value = $this->build_value( $compare, $query['month'] ) )
742                         $where_parts[] = "MONTH( $column ) $compare $value";
743                 else if ( isset( $query['monthnum'] ) && $value = $this->build_value( $compare, $query['monthnum'] ) )
744                         $where_parts[] = "MONTH( $column ) $compare $value";
745
746                 if ( isset( $query['week'] ) && false !== ( $value = $this->build_value( $compare, $query['week'] ) ) )
747                         $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
748                 else if ( isset( $query['w'] ) && false !== ( $value = $this->build_value( $compare, $query['w'] ) ) )
749                         $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
750
751                 if ( isset( $query['dayofyear'] ) && $value = $this->build_value( $compare, $query['dayofyear'] ) )
752                         $where_parts[] = "DAYOFYEAR( $column ) $compare $value";
753
754                 if ( isset( $query['day'] ) && $value = $this->build_value( $compare, $query['day'] ) )
755                         $where_parts[] = "DAYOFMONTH( $column ) $compare $value";
756
757                 if ( isset( $query['dayofweek'] ) && $value = $this->build_value( $compare, $query['dayofweek'] ) )
758                         $where_parts[] = "DAYOFWEEK( $column ) $compare $value";
759
760                 if ( isset( $query['dayofweek_iso'] ) && $value = $this->build_value( $compare, $query['dayofweek_iso'] ) )
761                         $where_parts[] = "WEEKDAY( $column ) + 1 $compare $value";
762
763                 if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
764                         // Avoid notices.
765                         foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
766                                 if ( ! isset( $query[ $unit ] ) ) {
767                                         $query[ $unit ] = null;
768                                 }
769                         }
770
771                         if ( $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ) ) {
772                                 $where_parts[] = $time_query;
773                         }
774                 }
775
776                 /*
777                  * Return an array of 'join' and 'where' for compatibility
778                  * with other query classes.
779                  */
780                 return array(
781                         'where' => $where_parts,
782                         'join'  => array(),
783                 );
784         }
785
786         /**
787          * Builds and validates a value string based on the comparison operator.
788          *
789          * @since 3.7.0
790          * @access public
791          *
792          * @param string $compare The compare operator to use
793          * @param string|array $value The value
794          * @return string|false|int The value to be used in SQL or false on error.
795          */
796         public function build_value( $compare, $value ) {
797                 if ( ! isset( $value ) )
798                         return false;
799
800                 switch ( $compare ) {
801                         case 'IN':
802                         case 'NOT IN':
803                                 $value = (array) $value;
804
805                                 // Remove non-numeric values.
806                                 $value = array_filter( $value, 'is_numeric' );
807
808                                 if ( empty( $value ) ) {
809                                         return false;
810                                 }
811
812                                 return '(' . implode( ',', array_map( 'intval', $value ) ) . ')';
813
814                         case 'BETWEEN':
815                         case 'NOT BETWEEN':
816                                 if ( ! is_array( $value ) || 2 != count( $value ) ) {
817                                         $value = array( $value, $value );
818                                 } else {
819                                         $value = array_values( $value );
820                                 }
821
822                                 // If either value is non-numeric, bail.
823                                 foreach ( $value as $v ) {
824                                         if ( ! is_numeric( $v ) ) {
825                                                 return false;
826                                         }
827                                 }
828
829                                 $value = array_map( 'intval', $value );
830
831                                 return $value[0] . ' AND ' . $value[1];
832
833                         default;
834                                 if ( ! is_numeric( $value ) ) {
835                                         return false;
836                                 }
837
838                                 return (int) $value;
839                 }
840         }
841
842         /**
843          * Builds a MySQL format date/time based on some query parameters.
844          *
845          * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
846          * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
847          * pass a string that that will be run through strtotime().
848          *
849          * @since 3.7.0
850          * @access public
851          *
852          * @param string|array $datetime       An array of parameters or a strotime() string
853          * @param bool         $default_to_max Whether to round up incomplete dates. Supported by values
854          *                                     of $datetime that are arrays, or string values that are a
855          *                                     subset of MySQL date format ('Y', 'Y-m', 'Y-m-d', 'Y-m-d H:i').
856          *                                     Default: false.
857          * @return string|false A MySQL format date/time or false on failure
858          */
859         public function build_mysql_datetime( $datetime, $default_to_max = false ) {
860                 $now = current_time( 'timestamp' );
861
862                 if ( ! is_array( $datetime ) ) {
863
864                         /*
865                          * Try to parse some common date formats, so we can detect
866                          * the level of precision and support the 'inclusive' parameter.
867                          */
868                         if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) {
869                                 // Y
870                                 $datetime = array(
871                                         'year' => intval( $matches[1] ),
872                                 );
873
874                         } else if ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) {
875                                 // Y-m
876                                 $datetime = array(
877                                         'year'  => intval( $matches[1] ),
878                                         'month' => intval( $matches[2] ),
879                                 );
880
881                         } else if ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) {
882                                 // Y-m-d
883                                 $datetime = array(
884                                         'year'  => intval( $matches[1] ),
885                                         'month' => intval( $matches[2] ),
886                                         'day'   => intval( $matches[3] ),
887                                 );
888
889                         } else if ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) {
890                                 // Y-m-d H:i
891                                 $datetime = array(
892                                         'year'   => intval( $matches[1] ),
893                                         'month'  => intval( $matches[2] ),
894                                         'day'    => intval( $matches[3] ),
895                                         'hour'   => intval( $matches[4] ),
896                                         'minute' => intval( $matches[5] ),
897                                 );
898                         }
899
900                         // If no match is found, we don't support default_to_max.
901                         if ( ! is_array( $datetime ) ) {
902                                 // @todo Timezone issues here possibly
903                                 return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
904                         }
905                 }
906
907                 $datetime = array_map( 'absint', $datetime );
908
909                 if ( ! isset( $datetime['year'] ) )
910                         $datetime['year'] = gmdate( 'Y', $now );
911
912                 if ( ! isset( $datetime['month'] ) )
913                         $datetime['month'] = ( $default_to_max ) ? 12 : 1;
914
915                 if ( ! isset( $datetime['day'] ) )
916                         $datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
917
918                 if ( ! isset( $datetime['hour'] ) )
919                         $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
920
921                 if ( ! isset( $datetime['minute'] ) )
922                         $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
923
924                 if ( ! isset( $datetime['second'] ) )
925                         $datetime['second'] = ( $default_to_max ) ? 59 : 0;
926
927                 return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
928         }
929
930         /**
931          * Builds a query string for comparing time values (hour, minute, second).
932          *
933          * If just hour, minute, or second is set than a normal comparison will be done.
934          * However if multiple values are passed, a pseudo-decimal time will be created
935          * in order to be able to accurately compare against.
936          *
937          * @since 3.7.0
938          * @access public
939          *
940          * @param string $column The column to query against. Needs to be pre-validated!
941          * @param string $compare The comparison operator. Needs to be pre-validated!
942          * @param int|null $hour Optional. An hour value (0-23).
943          * @param int|null $minute Optional. A minute value (0-59).
944          * @param int|null $second Optional. A second value (0-59).
945          * @return string|false A query part or false on failure.
946          */
947         public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
948                 global $wpdb;
949
950                 // Have to have at least one
951                 if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) )
952                         return false;
953
954                 // Complex combined queries aren't supported for multi-value queries
955                 if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
956                         $return = array();
957
958                         if ( isset( $hour ) && false !== ( $value = $this->build_value( $compare, $hour ) ) )
959                                 $return[] = "HOUR( $column ) $compare $value";
960
961                         if ( isset( $minute ) && false !== ( $value = $this->build_value( $compare, $minute ) ) )
962                                 $return[] = "MINUTE( $column ) $compare $value";
963
964                         if ( isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) )
965                                 $return[] = "SECOND( $column ) $compare $value";
966
967                         return implode( ' AND ', $return );
968                 }
969
970                 // Cases where just one unit is set
971                 if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $hour ) ) ) {
972                         return "HOUR( $column ) $compare $value";
973                 } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $minute ) ) ) {
974                         return "MINUTE( $column ) $compare $value";
975                 } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) ) {
976                         return "SECOND( $column ) $compare $value";
977                 }
978
979                 // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
980                 if ( ! isset( $minute ) )
981                         return false;
982
983                 $format = $time = '';
984
985                 // Hour
986                 if ( $hour ) {
987                         $format .= '%H.';
988                         $time   .= sprintf( '%02d', $hour ) . '.';
989                 } else {
990                         $format .= '0.';
991                         $time   .= '0.';
992                 }
993
994                 // Minute
995                 $format .= '%i';
996                 $time   .= sprintf( '%02d', $minute );
997
998                 if ( isset( $second ) ) {
999                         $format .= '%s';
1000                         $time   .= sprintf( '%02d', $second );
1001                 }
1002
1003                 return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );
1004         }
1005 }