-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathclass-es-wp-date-query.php
403 lines (353 loc) · 11.6 KB
/
class-es-wp-date-query.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
<?php
/**
* ES_WP_Query classes: ES_WP_Date_Query class
*
* @package ES_WP_Query
*/
/**
* Elasticsearch wrapper for WP_Meta_Query
*/
class ES_WP_Date_Query extends WP_Date_Query {
/**
* Turns an array of date query parameters into ES Query DSL.
*
* @param ES_WP_Query_Wrapper $es_query The query to filter.
* @access public
* @return array
*/
public function get_dsl( $es_query ) {
// The parts of the final query.
$filter = array();
foreach ( $this->queries as $query ) {
$filter_parts = $this->get_es_subquery( $query, $es_query );
if ( ! empty( $filter_parts ) ) {
// Combine the parts of this subquery.
if ( 1 === count( $filter_parts ) ) {
$filter[] = reset( $filter_parts );
} else {
$filter[] = array(
'bool' => array(
'filter' => $filter_parts,
),
);
}
}
}
// Combine the subqueries.
if ( 1 === count( $filter ) ) {
$filter = reset( $filter );
} elseif ( ! empty( $filter ) ) {
if ( 'or' === strtolower( $this->relation ) ) {
$relation = 'should';
} else {
$relation = 'filter';
}
$filter = array(
'bool' => array(
$relation => $filter,
),
);
} else {
$filter = array();
}
/**
* Filter the date query WHERE clause.
*
* @param string $where WHERE clause of the date query.
* @param WP_Date_Query $this The WP_Date_Query instance.
*/
return apply_filters( 'get_date_dsl', $filter, $this ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
}
/**
* Turns a single date subquery into elasticsearch filters.
*
* @param array $query The date subquery.
* @param ES_WP_Query_Wrapper $es_query The ES_WP_Query object.
* @access protected
* @return array
*/
protected function get_es_subquery( $query, $es_query ) {
// Ensure $query is an array before proceeding.
if ( ! is_array( $query ) ) {
return array();
}
// The sub-parts of a $where part.
$filter_parts = array();
$field = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
$field = $this->validate_column( $field );
// We don't actually want the mysql column here, so we'll remove it.
$field = preg_replace( '/^.*\./', '', $field );
$compare = $this->get_compare( $query );
// Range queries, we like range queries.
if ( ! empty( $query['after'] ) || ! empty( $query['before'] ) ) {
$inclusive = ! empty( $query['inclusive'] );
if ( $inclusive ) {
$lt = 'lte';
$gt = 'gte';
} else {
$lt = 'lt';
$gt = 'gt';
}
$range = array();
if ( ! empty( $query['after'] ) ) {
$range[ $gt ] = $this->build_datetime( $query['after'], ! $inclusive );
}
if ( ! empty( $query['before'] ) ) {
$range[ $lt ] = $this->build_datetime( $query['before'], $inclusive );
}
if ( ! empty( $range ) ) {
$filter_parts[] = $es_query->dsl_range( $es_query->es_map( $field ), $range );
}
unset( $range );
}
// Legacy support and field renaming.
if ( isset( $query['monthnum'] ) ) {
$query['month'] = $query['monthnum'];
}
if ( isset( $query['w'] ) ) {
$query['week'] = $query['w'];
}
if ( isset( $query['w'] ) ) {
$query['week'] = $query['w'];
}
if ( isset( $query['dayofyear'] ) ) {
$query['day_of_year'] = $query['dayofyear'];
}
if ( isset( $query['dayofweek'] ) ) {
// We encourage you to store the day_of_week according to ISO-8601 standards.
$day_of_week = 1 === $query['dayofweek'] ? 7 : $query['dayofweek'] - 1;
// This is, of course, optional. Use this filter to manipualte the value however you'd like.
$query['day_of_week'] = apply_filters( 'es_date_query_dayofweek', $day_of_week, $query['dayofweek'] );
}
foreach ( array( 'year', 'month', 'week', 'day', 'day_of_year', 'day_of_week' ) as $date_token ) {
if ( isset( $query[ $date_token ] ) ) {
$part = $this->build_dsl_part(
$es_query->es_map( "{$field}.{$date_token}" ),
$query[ $date_token ],
$compare
);
if ( false !== $part ) {
$filter_parts[] = $part;
}
}
}
// Avoid notices.
$query = wp_parse_args(
$query,
array(
'hour' => null,
'minute' => null,
'second' => null,
)
);
$time = $this->build_es_time( $compare, $query['hour'], $query['minute'], $query['second'] );
if ( false === $time ) {
foreach ( array( 'hour', 'minute', 'second' ) as $date_token ) {
if ( isset( $query[ $date_token ] ) ) {
$part = $this->build_dsl_part(
$es_query->es_map( "{$field}.{$date_token}" ),
$query[ $date_token ],
$compare
);
if ( false !== $part ) {
$filter_parts[] = $part;
}
}
}
} else {
if ( 1 > $time ) {
$filter_parts[] = $this->build_dsl_part( $es_query->es_map( "{$field}.seconds_from_hour" ), $time, $compare, 'floatval' );
} else {
$filter_parts[] = $this->build_dsl_part( $es_query->es_map( "{$field}.seconds_from_day" ), $time, $compare, 'floatval' );
}
}
return $filter_parts;
}
/**
* Builds a MySQL format date/time based on some query parameters.
*
* This is a clone of build_mysql_datetime, but specifically for static usage.
*
* You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
* either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
* pass a string that that will be run through strtotime().
*
* @static
* @access public
*
* @param string|array $datetime An array of parameters or a strotime() string.
* @param string|bool $default_to_max Controls what values default to if they are missing from $datetime. Pass "min" or "max".
* @return string|false A MySQL format date/time or false on failure
*/
public static function build_datetime( $datetime, $default_to_max = false ) {
$now = current_time( 'timestamp' );
if ( ! is_array( $datetime ) ) {
// @todo Timezone issues here possibly
return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
}
$datetime = array_map( 'absint', $datetime );
if ( ! isset( $datetime['year'] ) ) {
$datetime['year'] = gmdate( 'Y', $now );
}
if ( ! isset( $datetime['month'] ) ) {
$datetime['month'] = ( $default_to_max ) ? 12 : 1;
}
if ( ! isset( $datetime['day'] ) ) {
$datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
}
if ( ! isset( $datetime['hour'] ) ) {
$datetime['hour'] = ( $default_to_max ) ? 23 : 0;
}
if ( ! isset( $datetime['minute'] ) ) {
$datetime['minute'] = ( $default_to_max ) ? 59 : 0;
}
if ( ! isset( $datetime['second'] ) ) {
$datetime['second'] = ( $default_to_max ) ? 59 : 0;
}
return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
}
/**
* Given one or two dates and comparison operators for each, builds a date
* query that encompasses the requested range.
*
* @param string|array $date An array of parameters or a strotime() string.
* @param string $compare The comparison operator for the date.
* @param string|array|null $date2 Optional. An array of parameters or a strotime() string. Defaults to null.
* @param string|null $compare2 Optional. The comparison operator for the date. Defaults to null.
* @access public
* @return array
*/
public static function build_date_range( $date, $compare, $date2 = null, $compare2 = null ) {
// If we pass two dates, create a range for both.
if ( isset( $date2 ) && isset( $compare2 ) ) {
return array_merge( self::build_date_range( $date, $compare ), self::build_date_range( $date2, $compare2 ) );
}
// To improve readability.
$upper_edge = true;
$lower_edge = false;
switch ( $compare ) {
case '!=':
case '=':
return array(
'gte' => self::build_datetime( $date, $lower_edge ),
'lte' => self::build_datetime( $date, $upper_edge ),
);
case '>':
return array( 'gt' => self::build_datetime( $date, $upper_edge ) );
case '>=':
return array( 'gte' => self::build_datetime( $date, $lower_edge ) );
case '<':
return array( 'lt' => self::build_datetime( $date, $lower_edge ) );
case '<=':
return array( 'lte' => self::build_datetime( $date, $upper_edge ) );
}
}
/**
* Builds and validates a value string based on the comparison operator.
*
* @access public
*
* @param string $field The field name.
* @param string|array $value The value.
* @param string $compare The compare operator to use.
* @param string $sanitize Optional. The sanitization function to use. Defaults to 'intval'.
* @return string|int|false The value to be used in DSL or false on error.
*/
public function build_dsl_part( $field, $value, $compare, $sanitize = 'intval' ) {
if ( ! isset( $value ) ) {
return false;
}
$part = false;
switch ( $compare ) {
case 'IN':
case 'NOT IN':
$part = ES_WP_Query_Wrapper::dsl_terms( $field, array_map( $sanitize, (array) $value ) );
break;
case 'BETWEEN':
case 'NOT BETWEEN':
if ( ! is_array( $value ) ) {
$value = array( $value, $value );
} elseif ( count( $value ) >= 2 && ( ! isset( $value[0] ) || ! isset( $value[1] ) ) ) {
$value = array( array_shift( $value ), array_shift( $value ) );
} elseif ( count( $value ) ) {
$value = reset( $value );
$value = array( $value, $value );
}
if ( ! isset( $value[0] ) || ! isset( $value[1] ) ) {
return false;
}
$value = array_map( $sanitize, $value );
sort( $value );
$part = ES_WP_Query_Wrapper::dsl_range(
$field,
array(
'gte' => $value[0],
'lte' => $value[1],
)
);
break;
case '>':
case '>=':
case '<':
case '<=':
switch ( $compare ) {
case '>':
$operator = 'gt';
break;
case '>=':
$operator = 'gte';
break;
case '<':
$operator = 'lt';
break;
case '<=':
$operator = 'lte';
break;
}
$part = ES_WP_Query_Wrapper::dsl_range( $field, array( $operator => $sanitize( $value ) ) );
break;
default:
$part = ES_WP_Query_Wrapper::dsl_terms( $field, $sanitize( $value ) );
break;
}
if ( ! empty( $part ) && in_array( $compare, array( '!=', 'NOT IN', 'NOT BETWEEN' ), true ) ) {
return array(
'bool' => array(
'must_not' => $part,
),
);
} else {
return $part;
}
}
/**
* Builds a query string for comparing time values (hour, minute, second).
*
* If just hour, minute, or second is set than a normal comparison will be done.
* However if multiple values are passed, a pseudo-decimal time will be created
* in order to be able to accurately compare against.
*
* @access public
*
* @param string $compare The comparison operator. Needs to be pre-validated.
* @param int|null $hour Optional. An hour value (0-23).
* @param int|null $minute Optional. A minute value (0-59).
* @param int|null $second Optional. A second value (0-59).
* @return string|false A query part or false on failure.
*/
public function build_es_time( $compare, $hour = null, $minute = null, $second = null ) {
// Complex combined queries aren't supported for multi-value queries.
if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) {
return false;
}
// Lastly, ignore cases where just one unit is set or $minute is null.
if ( count( array_filter( array( $hour, $minute, $second ), 'is_null' ) ) > 1 || is_null( $minute ) ) {
return false;
}
// Hour.
if ( ! $hour ) {
$hour = 0;
}
return mktime( $hour, $minute, $second, 1, 1, 1970 );
}
}