選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 

1018 行
34 KiB

  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. * @param array $query Query clause.
  234. * @return bool True if this is a first-order clause.
  235. */
  236. protected function is_first_order_clause( $query ) {
  237. $time_keys = array_intersect( $this->time_keys, array_keys( $query ) );
  238. return ! empty( $time_keys );
  239. }
  240. /**
  241. * Determines and validates what comparison operator to use.
  242. *
  243. * @since 3.7.0
  244. * @access public
  245. *
  246. * @param array $query A date query or a date subquery.
  247. * @return string The comparison operator.
  248. */
  249. public function get_compare( $query ) {
  250. if ( ! empty( $query['compare'] ) && in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
  251. return strtoupper( $query['compare'] );
  252. return $this->compare;
  253. }
  254. /**
  255. * Validates the given date_query values and triggers errors if something is not valid.
  256. *
  257. * Note that date queries with invalid date ranges are allowed to
  258. * continue (though of course no items will be found for impossible dates).
  259. * This method only generates debug notices for these cases.
  260. *
  261. * @since 4.1.0
  262. * @access public
  263. *
  264. * @param array $date_query The date_query array.
  265. * @return bool True if all values in the query are valid, false if one or more fail.
  266. */
  267. public function validate_date_values( $date_query = array() ) {
  268. if ( empty( $date_query ) ) {
  269. return false;
  270. }
  271. $valid = true;
  272. /*
  273. * Validate 'before' and 'after' up front, then let the
  274. * validation routine continue to be sure that all invalid
  275. * values generate errors too.
  276. */
  277. if ( array_key_exists( 'before', $date_query ) && is_array( $date_query['before'] ) ){
  278. $valid = $this->validate_date_values( $date_query['before'] );
  279. }
  280. if ( array_key_exists( 'after', $date_query ) && is_array( $date_query['after'] ) ){
  281. $valid = $this->validate_date_values( $date_query['after'] );
  282. }
  283. // Array containing all min-max checks.
  284. $min_max_checks = array();
  285. // Days per year.
  286. if ( array_key_exists( 'year', $date_query ) ) {
  287. /*
  288. * If a year exists in the date query, we can use it to get the days.
  289. * If multiple years are provided (as in a BETWEEN), use the first one.
  290. */
  291. if ( is_array( $date_query['year'] ) ) {
  292. $_year = reset( $date_query['year'] );
  293. } else {
  294. $_year = $date_query['year'];
  295. }
  296. $max_days_of_year = date( 'z', mktime( 0, 0, 0, 12, 31, $_year ) ) + 1;
  297. } else {
  298. // otherwise we use the max of 366 (leap-year)
  299. $max_days_of_year = 366;
  300. }
  301. $min_max_checks['dayofyear'] = array(
  302. 'min' => 1,
  303. 'max' => $max_days_of_year
  304. );
  305. // Days per week.
  306. $min_max_checks['dayofweek'] = array(
  307. 'min' => 1,
  308. 'max' => 7
  309. );
  310. // Days per week.
  311. $min_max_checks['dayofweek_iso'] = array(
  312. 'min' => 1,
  313. 'max' => 7
  314. );
  315. // Months per year.
  316. $min_max_checks['month'] = array(
  317. 'min' => 1,
  318. 'max' => 12
  319. );
  320. // Weeks per year.
  321. if ( isset( $_year ) ) {
  322. /*
  323. * If we have a specific year, use it to calculate number of weeks.
  324. * Note: the number of weeks in a year is the date in which Dec 28 appears.
  325. */
  326. $week_count = date( 'W', mktime( 0, 0, 0, 12, 28, $_year ) );
  327. } else {
  328. // Otherwise set the week-count to a maximum of 53.
  329. $week_count = 53;
  330. }
  331. $min_max_checks['week'] = array(
  332. 'min' => 1,
  333. 'max' => $week_count
  334. );
  335. // Days per month.
  336. $min_max_checks['day'] = array(
  337. 'min' => 1,
  338. 'max' => 31
  339. );
  340. // Hours per day.
  341. $min_max_checks['hour'] = array(
  342. 'min' => 0,
  343. 'max' => 23
  344. );
  345. // Minutes per hour.
  346. $min_max_checks['minute'] = array(
  347. 'min' => 0,
  348. 'max' => 59
  349. );
  350. // Seconds per minute.
  351. $min_max_checks['second'] = array(
  352. 'min' => 0,
  353. 'max' => 59
  354. );
  355. // Concatenate and throw a notice for each invalid value.
  356. foreach ( $min_max_checks as $key => $check ) {
  357. if ( ! array_key_exists( $key, $date_query ) ) {
  358. continue;
  359. }
  360. // Throw a notice for each failing value.
  361. foreach ( (array) $date_query[ $key ] as $_value ) {
  362. $is_between = $_value >= $check['min'] && $_value <= $check['max'];
  363. if ( ! is_numeric( $_value ) || ! $is_between ) {
  364. $error = sprintf(
  365. /* translators: Date query invalid date message: 1: invalid value, 2: type of value, 3: minimum valid value, 4: maximum valid value */
  366. __( 'Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.' ),
  367. '<code>' . esc_html( $_value ) . '</code>',
  368. '<code>' . esc_html( $key ) . '</code>',
  369. '<code>' . esc_html( $check['min'] ) . '</code>',
  370. '<code>' . esc_html( $check['max'] ) . '</code>'
  371. );
  372. _doing_it_wrong( __CLASS__, $error, '4.1.0' );
  373. $valid = false;
  374. }
  375. }
  376. }
  377. // If we already have invalid date messages, don't bother running through checkdate().
  378. if ( ! $valid ) {
  379. return $valid;
  380. }
  381. $day_month_year_error_msg = '';
  382. $day_exists = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] );
  383. $month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] );
  384. $year_exists = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] );
  385. if ( $day_exists && $month_exists && $year_exists ) {
  386. // 1. Checking day, month, year combination.
  387. 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'] ) ) ) {
  388. /* translators: 1: year, 2: month, 3: day of month */
  389. $day_month_year_error_msg = sprintf(
  390. __( 'The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.' ),
  391. '<code>' . esc_html( $date_query['year'] ) . '</code>',
  392. '<code>' . esc_html( $date_query['month'] ) . '</code>',
  393. '<code>' . esc_html( $date_query['day'] ) . '</code>'
  394. );
  395. $valid = false;
  396. }
  397. } elseif ( $day_exists && $month_exists ) {
  398. /*
  399. * 2. checking day, month combination
  400. * We use 2012 because, as a leap year, it's the most permissive.
  401. */
  402. if ( ! wp_checkdate( $date_query['month'], $date_query['day'], 2012, sprintf( '2012-%s-%s', $date_query['month'], $date_query['day'] ) ) ) {
  403. /* translators: 1: month, 2: day of month */
  404. $day_month_year_error_msg = sprintf(
  405. __( 'The following values do not describe a valid date: month %1$s, day %2$s.' ),
  406. '<code>' . esc_html( $date_query['month'] ) . '</code>',
  407. '<code>' . esc_html( $date_query['day'] ) . '</code>'
  408. );
  409. $valid = false;
  410. }
  411. }
  412. if ( ! empty( $day_month_year_error_msg ) ) {
  413. _doing_it_wrong( __CLASS__, $day_month_year_error_msg, '4.1.0' );
  414. }
  415. return $valid;
  416. }
  417. /**
  418. * Validates a column name parameter.
  419. *
  420. * Column names without a table prefix (like 'post_date') are checked against a whitelist of
  421. * known tables, and then, if found, have a table prefix (such as 'wp_posts.') prepended.
  422. * Prefixed column names (such as 'wp_posts.post_date') bypass this whitelist check,
  423. * and are only sanitized to remove illegal characters.
  424. *
  425. * @since 3.7.0
  426. * @access public
  427. *
  428. * @param string $column The user-supplied column name.
  429. * @return string A validated column name value.
  430. */
  431. public function validate_column( $column ) {
  432. global $wpdb;
  433. $valid_columns = array(
  434. 'post_date', 'post_date_gmt', 'post_modified',
  435. 'post_modified_gmt', 'comment_date', 'comment_date_gmt',
  436. 'user_registered', 'registered', 'last_updated',
  437. );
  438. // Attempt to detect a table prefix.
  439. if ( false === strpos( $column, '.' ) ) {
  440. /**
  441. * Filters the list of valid date query columns.
  442. *
  443. * @since 3.7.0
  444. * @since 4.1.0 Added 'user_registered' to the default recognized columns.
  445. *
  446. * @param array $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'
  450. */
  451. if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ) ) ) {
  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 ) ) {
  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. * Generate WHERE clause to be appended to a main query.
  486. *
  487. * @since 3.7.0
  488. * @access public
  489. *
  490. * @return string MySQL WHERE clause.
  491. */
  492. public function get_sql() {
  493. $sql = $this->get_sql_clauses();
  494. $where = $sql['where'];
  495. /**
  496. * Filters the date query WHERE clause.
  497. *
  498. * @since 3.7.0
  499. *
  500. * @param string $where WHERE clause of the date query.
  501. * @param WP_Date_Query $this The WP_Date_Query instance.
  502. */
  503. return apply_filters( 'get_date_sql', $where, $this );
  504. }
  505. /**
  506. * Generate SQL clauses to be appended to a main query.
  507. *
  508. * Called by the public WP_Date_Query::get_sql(), this method is abstracted
  509. * out to maintain parity with the other Query classes.
  510. *
  511. * @since 4.1.0
  512. * @access protected
  513. *
  514. * @return array {
  515. * Array containing JOIN and WHERE SQL clauses to append to the main query.
  516. *
  517. * @type string $join SQL fragment to append to the main JOIN clause.
  518. * @type string $where SQL fragment to append to the main WHERE clause.
  519. * }
  520. */
  521. protected function get_sql_clauses() {
  522. $sql = $this->get_sql_for_query( $this->queries );
  523. if ( ! empty( $sql['where'] ) ) {
  524. $sql['where'] = ' AND ' . $sql['where'];
  525. }
  526. return $sql;
  527. }
  528. /**
  529. * Generate SQL clauses for a single query array.
  530. *
  531. * If nested subqueries are found, this method recurses the tree to
  532. * produce the properly nested SQL.
  533. *
  534. * @since 4.1.0
  535. * @access protected
  536. *
  537. * @param array $query Query to parse.
  538. * @param int $depth Optional. Number of tree levels deep we currently are.
  539. * Used to calculate indentation. Default 0.
  540. * @return array {
  541. * Array containing JOIN and WHERE SQL clauses to append to a single query array.
  542. *
  543. * @type string $join SQL fragment to append to the main JOIN clause.
  544. * @type string $where SQL fragment to append to the main WHERE clause.
  545. * }
  546. */
  547. protected function get_sql_for_query( $query, $depth = 0 ) {
  548. $sql_chunks = array(
  549. 'join' => array(),
  550. 'where' => array(),
  551. );
  552. $sql = array(
  553. 'join' => '',
  554. 'where' => '',
  555. );
  556. $indent = '';
  557. for ( $i = 0; $i < $depth; $i++ ) {
  558. $indent .= " ";
  559. }
  560. foreach ( $query as $key => $clause ) {
  561. if ( 'relation' === $key ) {
  562. $relation = $query['relation'];
  563. } elseif ( is_array( $clause ) ) {
  564. // This is a first-order clause.
  565. if ( $this->is_first_order_clause( $clause ) ) {
  566. $clause_sql = $this->get_sql_for_clause( $clause, $query );
  567. $where_count = count( $clause_sql['where'] );
  568. if ( ! $where_count ) {
  569. $sql_chunks['where'][] = '';
  570. } elseif ( 1 === $where_count ) {
  571. $sql_chunks['where'][] = $clause_sql['where'][0];
  572. } else {
  573. $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
  574. }
  575. $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
  576. // This is a subquery, so we recurse.
  577. } else {
  578. $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
  579. $sql_chunks['where'][] = $clause_sql['where'];
  580. $sql_chunks['join'][] = $clause_sql['join'];
  581. }
  582. }
  583. }
  584. // Filter to remove empties.
  585. $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
  586. $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
  587. if ( empty( $relation ) ) {
  588. $relation = 'AND';
  589. }
  590. // Filter duplicate JOIN clauses and combine into a single string.
  591. if ( ! empty( $sql_chunks['join'] ) ) {
  592. $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
  593. }
  594. // Generate a single WHERE clause with proper brackets and indentation.
  595. if ( ! empty( $sql_chunks['where'] ) ) {
  596. $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
  597. }
  598. return $sql;
  599. }
  600. /**
  601. * Turns a single date clause into pieces for a WHERE clause.
  602. *
  603. * A wrapper for get_sql_for_clause(), included here for backward
  604. * compatibility while retaining the naming convention across Query classes.
  605. *
  606. * @since 3.7.0
  607. * @access protected
  608. *
  609. * @param array $query Date query arguments.
  610. * @return array {
  611. * Array containing JOIN and WHERE SQL clauses to append to the main query.
  612. *
  613. * @type string $join SQL fragment to append to the main JOIN clause.
  614. * @type string $where SQL fragment to append to the main WHERE clause.
  615. * }
  616. */
  617. protected function get_sql_for_subquery( $query ) {
  618. return $this->get_sql_for_clause( $query, '' );
  619. }
  620. /**
  621. * Turns a first-order date query into SQL for a WHERE clause.
  622. *
  623. * @since 4.1.0
  624. * @access protected
  625. *
  626. * @param array $query Date query clause.
  627. * @param array $parent_query Parent query of the current date query.
  628. * @return array {
  629. * Array containing JOIN and WHERE SQL clauses to append to the main query.
  630. *
  631. * @type string $join SQL fragment to append to the main JOIN clause.
  632. * @type string $where SQL fragment to append to the main WHERE clause.
  633. * }
  634. */
  635. protected function get_sql_for_clause( $query, $parent_query ) {
  636. global $wpdb;
  637. // The sub-parts of a $where part.
  638. $where_parts = array();
  639. $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
  640. $column = $this->validate_column( $column );
  641. $compare = $this->get_compare( $query );
  642. $inclusive = ! empty( $query['inclusive'] );
  643. // Assign greater- and less-than values.
  644. $lt = '<';
  645. $gt = '>';
  646. if ( $inclusive ) {
  647. $lt .= '=';
  648. $gt .= '=';
  649. }
  650. // Range queries.
  651. if ( ! empty( $query['after'] ) ) {
  652. $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) );
  653. }
  654. if ( ! empty( $query['before'] ) ) {
  655. $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) );
  656. }
  657. // Specific value queries.
  658. if ( isset( $query['year'] ) && $value = $this->build_value( $compare, $query['year'] ) )
  659. $where_parts[] = "YEAR( $column ) $compare $value";
  660. if ( isset( $query['month'] ) && $value = $this->build_value( $compare, $query['month'] ) ) {
  661. $where_parts[] = "MONTH( $column ) $compare $value";
  662. } elseif ( isset( $query['monthnum'] ) && $value = $this->build_value( $compare, $query['monthnum'] ) ) {
  663. $where_parts[] = "MONTH( $column ) $compare $value";
  664. }
  665. if ( isset( $query['week'] ) && false !== ( $value = $this->build_value( $compare, $query['week'] ) ) ) {
  666. $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
  667. } elseif ( isset( $query['w'] ) && false !== ( $value = $this->build_value( $compare, $query['w'] ) ) ) {
  668. $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
  669. }
  670. if ( isset( $query['dayofyear'] ) && $value = $this->build_value( $compare, $query['dayofyear'] ) )
  671. $where_parts[] = "DAYOFYEAR( $column ) $compare $value";
  672. if ( isset( $query['day'] ) && $value = $this->build_value( $compare, $query['day'] ) )
  673. $where_parts[] = "DAYOFMONTH( $column ) $compare $value";
  674. if ( isset( $query['dayofweek'] ) && $value = $this->build_value( $compare, $query['dayofweek'] ) )
  675. $where_parts[] = "DAYOFWEEK( $column ) $compare $value";
  676. if ( isset( $query['dayofweek_iso'] ) && $value = $this->build_value( $compare, $query['dayofweek_iso'] ) )
  677. $where_parts[] = "WEEKDAY( $column ) + 1 $compare $value";
  678. if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
  679. // Avoid notices.
  680. foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
  681. if ( ! isset( $query[ $unit ] ) ) {
  682. $query[ $unit ] = null;
  683. }
  684. }
  685. if ( $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ) ) {
  686. $where_parts[] = $time_query;
  687. }
  688. }
  689. /*
  690. * Return an array of 'join' and 'where' for compatibility
  691. * with other query classes.
  692. */
  693. return array(
  694. 'where' => $where_parts,
  695. 'join' => array(),
  696. );
  697. }
  698. /**
  699. * Builds and validates a value string based on the comparison operator.
  700. *
  701. * @since 3.7.0
  702. * @access public
  703. *
  704. * @param string $compare The compare operator to use
  705. * @param string|array $value The value
  706. * @return string|false|int The value to be used in SQL or false on error.
  707. */
  708. public function build_value( $compare, $value ) {
  709. if ( ! isset( $value ) )
  710. return false;
  711. switch ( $compare ) {
  712. case 'IN':
  713. case 'NOT IN':
  714. $value = (array) $value;
  715. // Remove non-numeric values.
  716. $value = array_filter( $value, 'is_numeric' );
  717. if ( empty( $value ) ) {
  718. return false;
  719. }
  720. return '(' . implode( ',', array_map( 'intval', $value ) ) . ')';
  721. case 'BETWEEN':
  722. case 'NOT BETWEEN':
  723. if ( ! is_array( $value ) || 2 != count( $value ) ) {
  724. $value = array( $value, $value );
  725. } else {
  726. $value = array_values( $value );
  727. }
  728. // If either value is non-numeric, bail.
  729. foreach ( $value as $v ) {
  730. if ( ! is_numeric( $v ) ) {
  731. return false;
  732. }
  733. }
  734. $value = array_map( 'intval', $value );
  735. return $value[0] . ' AND ' . $value[1];
  736. default;
  737. if ( ! is_numeric( $value ) ) {
  738. return false;
  739. }
  740. return (int) $value;
  741. }
  742. }
  743. /**
  744. * Builds a MySQL format date/time based on some query parameters.
  745. *
  746. * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
  747. * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
  748. * pass a string that will be run through strtotime().
  749. *
  750. * @since 3.7.0
  751. * @access public
  752. *
  753. * @param string|array $datetime An array of parameters or a strotime() string
  754. * @param bool $default_to_max Whether to round up incomplete dates. Supported by values
  755. * of $datetime that are arrays, or string values that are a
  756. * subset of MySQL date format ('Y', 'Y-m', 'Y-m-d', 'Y-m-d H:i').
  757. * Default: false.
  758. * @return string|false A MySQL format date/time or false on failure
  759. */
  760. public function build_mysql_datetime( $datetime, $default_to_max = false ) {
  761. $now = current_time( 'timestamp' );
  762. if ( ! is_array( $datetime ) ) {
  763. /*
  764. * Try to parse some common date formats, so we can detect
  765. * the level of precision and support the 'inclusive' parameter.
  766. */
  767. if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) {
  768. // Y
  769. $datetime = array(
  770. 'year' => intval( $matches[1] ),
  771. );
  772. } elseif ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) {
  773. // Y-m
  774. $datetime = array(
  775. 'year' => intval( $matches[1] ),
  776. 'month' => intval( $matches[2] ),
  777. );
  778. } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) {
  779. // Y-m-d
  780. $datetime = array(
  781. 'year' => intval( $matches[1] ),
  782. 'month' => intval( $matches[2] ),
  783. 'day' => intval( $matches[3] ),
  784. );
  785. } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) {
  786. // Y-m-d H:i
  787. $datetime = array(
  788. 'year' => intval( $matches[1] ),
  789. 'month' => intval( $matches[2] ),
  790. 'day' => intval( $matches[3] ),
  791. 'hour' => intval( $matches[4] ),
  792. 'minute' => intval( $matches[5] ),
  793. );
  794. }
  795. // If no match is found, we don't support default_to_max.
  796. if ( ! is_array( $datetime ) ) {
  797. // @todo Timezone issues here possibly
  798. return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
  799. }
  800. }
  801. $datetime = array_map( 'absint', $datetime );
  802. if ( ! isset( $datetime['year'] ) )
  803. $datetime['year'] = gmdate( 'Y', $now );
  804. if ( ! isset( $datetime['month'] ) )
  805. $datetime['month'] = ( $default_to_max ) ? 12 : 1;
  806. if ( ! isset( $datetime['day'] ) )
  807. $datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
  808. if ( ! isset( $datetime['hour'] ) )
  809. $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
  810. if ( ! isset( $datetime['minute'] ) )
  811. $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
  812. if ( ! isset( $datetime['second'] ) )
  813. $datetime['second'] = ( $default_to_max ) ? 59 : 0;
  814. return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
  815. }
  816. /**
  817. * Builds a query string for comparing time values (hour, minute, second).
  818. *
  819. * If just hour, minute, or second is set than a normal comparison will be done.
  820. * However if multiple values are passed, a pseudo-decimal time will be created
  821. * in order to be able to accurately compare against.
  822. *
  823. * @since 3.7.0
  824. * @access public
  825. *
  826. * @param string $column The column to query against. Needs to be pre-validated!
  827. * @param string $compare The comparison operator. Needs to be pre-validated!
  828. * @param int|null $hour Optional. An hour value (0-23).
  829. * @param int|null $minute Optional. A minute value (0-59).
  830. * @param int|null $second Optional. A second value (0-59).
  831. * @return string|false A query part or false on failure.
  832. */
  833. public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
  834. global $wpdb;
  835. // Have to have at least one
  836. if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) )
  837. return false;
  838. // Complex combined queries aren't supported for multi-value queries
  839. if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
  840. $return = array();
  841. if ( isset( $hour ) && false !== ( $value = $this->build_value( $compare, $hour ) ) )
  842. $return[] = "HOUR( $column ) $compare $value";
  843. if ( isset( $minute ) && false !== ( $value = $this->build_value( $compare, $minute ) ) )
  844. $return[] = "MINUTE( $column ) $compare $value";
  845. if ( isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) )
  846. $return[] = "SECOND( $column ) $compare $value";
  847. return implode( ' AND ', $return );
  848. }
  849. // Cases where just one unit is set
  850. if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $hour ) ) ) {
  851. return "HOUR( $column ) $compare $value";
  852. } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $minute ) ) ) {
  853. return "MINUTE( $column ) $compare $value";
  854. } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) ) {
  855. return "SECOND( $column ) $compare $value";
  856. }
  857. // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
  858. if ( ! isset( $minute ) )
  859. return false;
  860. $format = $time = '';
  861. // Hour
  862. if ( null !== $hour ) {
  863. $format .= '%H.';
  864. $time .= sprintf( '%02d', $hour ) . '.';
  865. } else {
  866. $format .= '0.';
  867. $time .= '0.';
  868. }
  869. // Minute
  870. $format .= '%i';
  871. $time .= sprintf( '%02d', $minute );
  872. if ( isset( $second ) ) {
  873. $format .= '%s';
  874. $time .= sprintf( '%02d', $second );
  875. }
  876. return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );
  877. }
  878. }