]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/date.php
WordPress 3.8.1-scripts
[autoinstalls/wordpress.git] / wp-includes / date.php
1 <?php
2 /**
3  * WP_Date_Query will generate a MySQL WHERE clause for the specified date-based parameters.
4  *
5  * Initialize the class by passing an array of arrays of parameters.
6  *
7  * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page.
8  *
9  * @since 3.7.0
10  */
11 class WP_Date_Query {
12         /**
13          * List of date queries.
14          *
15          * @since 3.7.0
16          * @access public
17          * @var array
18          */
19         public $queries = array();
20
21         /**
22          * The relation between the queries. Can be either 'AND' or 'OR' and can be changed via the query arguments.
23          *
24          * @since 3.7.0
25          * @access public
26          * @var string
27          */
28         public $relation = 'AND';
29
30         /**
31          * The column to query against. Can be changed via the query arguments.
32          *
33          * @since 3.7.0
34          * @access public
35          * @var string
36          */
37         public $column = 'post_date';
38
39         /**
40          * The value comparison operator. Can be changed via the query arguments.
41          *
42          * @since 3.7.0
43          * @access public
44          * @var array
45          */
46         public $compare = '=';
47
48         /**
49          * Constructor.
50          *
51          * @param array $date_query {
52          *     One or more associative arrays of date query parameters.
53          *
54          *     @type array {
55          *         @type string $column   Optional. The column to query against. If undefined, inherits the value of
56          *                                the $default_column parameter. Default 'post_date'. Accepts 'post_date',
57          *                                'post_date_gmt', 'post_modified','post_modified_gmt', 'comment_date',
58          *                                'comment_date_gmt'.
59          *         @type string $compare  Optional. The comparison operator.
60          *                                Default '='. Accepts '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN',
61          *                                'BETWEEN', 'NOT BETWEEN'.
62          *         @type string $relation Optional. The boolean relationship between the date queryies.
63          *                                Default 'OR'. Accepts 'OR', 'AND'.
64          *         @type array {
65          *             @type string|array $before Optional. Date to retrieve posts before. Accepts strtotime()-compatible
66          *                                        string, or array of 'year', 'month', 'day' values. {
67          *
68          *                 @type string $year  The four-digit year. Default empty. Accepts any four-digit year.
69          *                 @type string $month Optional when passing array.The month of the year.
70          *                                     Default (string:empty)|(array:1). Accepts numbers 1-12.
71          *                 @type string $day   Optional when passing array.The day of the month.
72          *                                     Default (string:empty)|(array:1). Accepts numbers 1-31.
73          *             }
74          *             @type string|array $after Optional. Date to retrieve posts before. Accepts strtotime()-compatible
75          *                                       string, or array of 'year', 'month', 'day' values. {
76          *
77          *                 @type string $year  The four-digit year. Default empty. Accepts any four-digit year.
78          *                 @type string $month Optional when passing array.The month of the year.
79          *                                     Default (string:empty)|(array:12). Accepts numbers 1-12.
80          *                 @type string $day   Optional when passing array.The day of the month.
81          *                                     Default (string:empty)|(array:last day of month). Accepts numbers 1-31.
82          *             }
83          *             @type string       $column    Optional. Used to add a clause comparing a column other than the column
84          *                                           specified in the top-level $column paramater.  Default is the value
85          *                                           of top-level $column. Accepts 'post_date', 'post_date_gmt',
86          *                                           'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt'.
87          *             @type string       $compare   Optional. The comparison operator. Default '='. Accepts '=', '!=',
88          *                                           '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
89          *             @type bool         $inclusive Optional. Include results from dates specified in 'before' or 'after'.
90          *                                           Default. Accepts.
91          *             @type int          $year      Optional. The four-digit year number. Default empty. Accepts any
92          *                                           four-digit year.
93          *             @type int          $month     Optional. The two-digit month number. Default empty. Accepts numbers 1-12.
94          *             @type int          $week      Optional. The week number of the year. Default empty. Accepts numbers 0-53.
95          *             @type int          $dayofyear Optional. The day number of the year. Default empty. Accepts numbers 1-366.
96          *             @type int          $day       Optional. The day of the month. Default empty. Accepts numbers 1-31.
97          *             @type int          $dayofweek Optional. The day number of the week. Default empty. Accepts numbers 1-7.
98          *             @type int          $hour      Optional. The hour of the day. Default empty. Accepts numbers 0-23.
99          *             @type int          $minute    Optional. The minute of the hour. Default empty. Accepts numbers 0-60.
100          *             @type int          $second    Optional. The second of the minute. Default empty. Accepts numbers 0-60.
101          *         }
102          *     }
103          * }
104          * @param array $default_column Optional. Default column to query against. Default 'post_date'.
105          *                              Accepts 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt',
106          *                              'comment_date', 'comment_date_gmt'.
107          */
108         function __construct( $date_query, $default_column = 'post_date' ) {
109                 if ( empty( $date_query ) || ! is_array( $date_query ) )
110                         return;
111
112                 if ( isset( $date_query['relation'] ) && strtoupper( $date_query['relation'] ) == 'OR' )
113                         $this->relation = 'OR';
114                 else
115                         $this->relation = 'AND';
116
117                 if ( ! empty( $date_query['column'] ) )
118                         $this->column = esc_sql( $date_query['column'] );
119                 else
120                         $this->column = esc_sql( $default_column );
121
122                 $this->column = $this->validate_column( $this->column );
123
124                 $this->compare = $this->get_compare( $date_query );
125
126                 // If an array of arrays wasn't passed, fix it
127                 if ( ! isset( $date_query[0] ) )
128                         $date_query = array( $date_query );
129
130                 $this->queries = array();
131                 foreach ( $date_query as $key => $query ) {
132                         if ( ! is_array( $query ) )
133                                 continue;
134
135                         $this->queries[$key] = $query;
136                 }
137         }
138
139         /**
140          * Determines and validates what comparison operator to use.
141          *
142          * @since 3.7.0
143          * @access public
144          *
145          * @param array $query A date query or a date subquery
146          * @return string The comparison operator
147          */
148         public function get_compare( $query ) {
149                 if ( ! empty( $query['compare'] ) && in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
150                         return strtoupper( $query['compare'] );
151
152                 return $this->compare;
153         }
154
155         /**
156          * Validates a column name parameter.
157          *
158          * @since 3.7.0
159          * @access public
160          *
161          * @param string $column The user-supplied column name.
162          * @return string A validated column name value.
163          */
164         public function validate_column( $column ) {
165                 $valid_columns = array(
166                         'post_date', 'post_date_gmt', 'post_modified',
167                         'post_modified_gmt', 'comment_date', 'comment_date_gmt'
168                 );
169                 /**
170                  * Filter the list of valid date query columns.
171                  *
172                  * @since 3.7.0
173                  *
174                  * @param array $valid_columns An array of valid date query columns. Defaults are 'post_date', 'post_date_gmt',
175                  *                             'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt'
176                  */
177                 if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ) ) )
178                         $column = 'post_date';
179
180                 return $column;
181         }
182
183         /**
184          * Turns an array of date query parameters into a MySQL string.
185          *
186          * @since 3.7.0
187          * @access public
188          *
189          * @return string MySQL WHERE parameters
190          */
191         public function get_sql() {
192                 // The parts of the final query
193                 $where = array();
194
195                 foreach ( $this->queries as $key => $query ) {
196                         $where_parts = $this->get_sql_for_subquery( $query );
197                         if ( $where_parts ) {
198                                 // Combine the parts of this subquery into a single string
199                                 $where[ $key ] = '( ' . implode( ' AND ', $where_parts ) . ' )';
200                         }
201                 }
202
203                 // Combine the subquery strings into a single string
204                 if ( $where )
205                         $where = ' AND ( ' . implode( " {$this->relation} ", $where ) . ' )';
206                 else
207                         $where = '';
208
209                 /**
210                  * Filter the date query WHERE clause.
211                  *
212                  * @since 3.7.0
213                  *
214                  * @param string        $where WHERE clause of the date query.
215                  * @param WP_Date_Query $this  The WP_Date_Query instance.
216                  */
217                 return apply_filters( 'get_date_sql', $where, $this );
218         }
219
220         /**
221          * Turns a single date subquery into pieces for a WHERE clause.
222          *
223          * @since 3.7.0
224          * return array
225          */
226         protected function get_sql_for_subquery( $query ) {
227                 global $wpdb;
228
229                 // The sub-parts of a $where part
230                 $where_parts = array();
231
232                 $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
233
234                 $column = $this->validate_column( $column );
235
236                 $compare = $this->get_compare( $query );
237
238                 $lt = '<';
239                 $gt = '>';
240                 if ( ! empty( $query['inclusive'] ) ) {
241                         $lt .= '=';
242                         $gt .= '=';
243                 }
244
245                 // Range queries
246                 if ( ! empty( $query['after'] ) )
247                         $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], true ) );
248
249                 if ( ! empty( $query['before'] ) )
250                         $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], false ) );
251
252                 // Specific value queries
253
254                 if ( isset( $query['year'] ) && $value = $this->build_value( $compare, $query['year'] ) )
255                         $where_parts[] = "YEAR( $column ) $compare $value";
256
257                 if ( isset( $query['month'] ) && $value = $this->build_value( $compare, $query['month'] ) )
258                         $where_parts[] = "MONTH( $column ) $compare $value";
259
260                 // Legacy
261                 if ( isset( $query['monthnum'] ) && $value = $this->build_value( $compare, $query['monthnum'] ) )
262                         $where_parts[] = "MONTH( $column ) $compare $value";
263
264                 if ( isset( $query['week'] ) && false !== ( $value = $this->build_value( $compare, $query['week'] ) ) )
265                         $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
266
267                 // Legacy
268                 if ( isset( $query['w'] ) && false !== ( $value = $this->build_value( $compare, $query['w'] ) ) )
269                         $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
270
271                 if ( isset( $query['dayofyear'] ) && $value = $this->build_value( $compare, $query['dayofyear'] ) )
272                         $where_parts[] = "DAYOFYEAR( $column ) $compare $value";
273
274                 if ( isset( $query['day'] ) && $value = $this->build_value( $compare, $query['day'] ) )
275                         $where_parts[] = "DAYOFMONTH( $column ) $compare $value";
276
277                 if ( isset( $query['dayofweek'] ) && $value = $this->build_value( $compare, $query['dayofweek'] ) )
278                         $where_parts[] = "DAYOFWEEK( $column ) $compare $value";
279
280                 if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
281                         // Avoid notices
282                         foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
283                                 if ( ! isset( $query[$unit] ) ) {
284                                         $query[$unit] = null;
285                                 }
286                         }
287
288                         if ( $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ) ) {
289                                 $where_parts[] = $time_query;
290                         }
291                 }
292
293                 return $where_parts;
294         }
295
296         /**
297          * Builds and validates a value string based on the comparison operator.
298          *
299          * @since 3.7.0
300          * @access public
301          *
302          * @param string $compare The compare operator to use
303          * @param string|array $value The value
304          * @return string|int|false The value to be used in SQL or false on error.
305          */
306         public function build_value( $compare, $value ) {
307                 if ( ! isset( $value ) )
308                         return false;
309
310                 switch ( $compare ) {
311                         case 'IN':
312                         case 'NOT IN':
313                                 return '(' . implode( ',', array_map( 'intval', (array) $value ) ) . ')';
314
315                         case 'BETWEEN':
316                         case 'NOT BETWEEN':
317                                 if ( ! is_array( $value ) || 2 != count( $value ) || ! isset( $value[0] ) || ! isset( $value[1] ) )
318                                         $value = array( $value, $value );
319
320                                 $value = array_map( 'intval', $value );
321
322                                 return $value[0] . ' AND ' . $value[1];
323
324                         default;
325                                 return (int) $value;
326                 }
327         }
328
329         /**
330          * Builds a MySQL format date/time based on some query parameters.
331          *
332          * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
333          * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
334          * pass a string that that will be run through strtotime().
335          *
336          * @since 3.7.0
337          * @access public
338          *
339          * @param string|array $datetime An array of parameters or a strotime() string
340          * @param string $default_to Controls what values default to if they are missing from $datetime. Pass "min" or "max".
341          * @return string|false A MySQL format date/time or false on failure
342          */
343         public function build_mysql_datetime( $datetime, $default_to_max = false ) {
344                 $now = current_time( 'timestamp' );
345
346                 if ( ! is_array( $datetime ) ) {
347                         // @todo Timezone issues here possibly
348                         return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
349                 }
350
351                 $datetime = array_map( 'absint', $datetime );
352
353                 if ( ! isset( $datetime['year'] ) )
354                         $datetime['year'] = gmdate( 'Y', $now );
355
356                 if ( ! isset( $datetime['month'] ) )
357                         $datetime['month'] = ( $default_to_max ) ? 12 : 1;
358
359                 if ( ! isset( $datetime['day'] ) )
360                         $datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
361
362                 if ( ! isset( $datetime['hour'] ) )
363                         $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
364
365                 if ( ! isset( $datetime['minute'] ) )
366                         $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
367
368                 if ( ! isset( $datetime['second'] ) )
369                         $datetime['second'] = ( $default_to_max ) ? 59 : 0;
370
371                 return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
372         }
373
374         /**
375          * Builds a query string for comparing time values (hour, minute, second).
376          *
377          * If just hour, minute, or second is set than a normal comparison will be done.
378          * However if multiple values are passed, a pseudo-decimal time will be created
379          * in order to be able to accurately compare against.
380          *
381          * @since 3.7.0
382          * @access public
383          *
384          * @param string $column The column to query against. Needs to be pre-validated!
385          * @param string $compare The comparison operator. Needs to be pre-validated!
386          * @param int|null $hour Optional. An hour value (0-23).
387          * @param int|null $minute Optional. A minute value (0-59).
388          * @param int|null $second Optional. A second value (0-59).
389          * @return string|false A query part or false on failure.
390          */
391         public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
392                 global $wpdb;
393
394                 // Have to have at least one
395                 if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) )
396                         return false;
397
398                 // Complex combined queries aren't supported for multi-value queries
399                 if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
400                         $return = array();
401
402                         if ( isset( $hour ) && false !== ( $value = $this->build_value( $compare, $hour ) ) )
403                                 $return[] = "HOUR( $column ) $compare $value";
404
405                         if ( isset( $minute ) && false !== ( $value = $this->build_value( $compare, $minute ) ) )
406                                 $return[] = "MINUTE( $column ) $compare $value";
407
408                         if ( isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) )
409                                 $return[] = "SECOND( $column ) $compare $value";
410
411                         return implode( ' AND ', $return );
412                 }
413
414                 // Cases where just one unit is set
415                 if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $hour ) ) ) {
416                         return "HOUR( $column ) $compare $value";
417                 } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $minute ) ) ) {
418                         return "MINUTE( $column ) $compare $value";
419                 } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) ) {
420                         return "SECOND( $column ) $compare $value";
421                 }
422
423                 // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
424                 if ( ! isset( $minute ) )
425                         return false;
426
427                 $format = $time = '';
428
429                 // Hour
430                 if ( $hour ) {
431                         $format .= '%H.';
432                         $time   .= sprintf( '%02d', $hour ) . '.';
433                 } else {
434                         $format .= '0.';
435                         $time   .= '0.';
436                 }
437
438                 // Minute
439                 $format .= '%i';
440                 $time   .= sprintf( '%02d', $minute );
441
442                 if ( isset( $second ) ) {
443                         $format .= '%s';
444                         $time   .= sprintf( '%02d', $second );
445                 }
446
447                 return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );
448         }
449 }