class-wp-date-query.php 35 KB

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