Açıklama Yok

class-wp-date-query.php 34KB

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