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