date.php 35 KB

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