class-wp-meta-query.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. <?php
  2. /**
  3. * Meta API: WP_Meta_Query class
  4. *
  5. * @package WordPress
  6. * @subpackage Meta
  7. * @since 4.4.0
  8. */
  9. /**
  10. * Core class used to implement meta queries for the Meta API.
  11. *
  12. * Used for generating SQL clauses that filter a primary query according to metadata keys and values.
  13. *
  14. * WP_Meta_Query is a helper that allows primary query classes, such as WP_Query and WP_User_Query,
  15. *
  16. * to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
  17. * to the primary SQL query string.
  18. *
  19. * @since 3.2.0
  20. */
  21. class WP_Meta_Query {
  22. /**
  23. * Array of metadata queries.
  24. *
  25. * See WP_Meta_Query::__construct() for information on meta query arguments.
  26. *
  27. * @since 3.2.0
  28. * @var array
  29. */
  30. public $queries = array();
  31. /**
  32. * The relation between the queries. Can be one of 'AND' or 'OR'.
  33. *
  34. * @since 3.2.0
  35. * @var string
  36. */
  37. public $relation;
  38. /**
  39. * Database table to query for the metadata.
  40. *
  41. * @since 4.1.0
  42. * @var string
  43. */
  44. public $meta_table;
  45. /**
  46. * Column in meta_table that represents the ID of the object the metadata belongs to.
  47. *
  48. * @since 4.1.0
  49. * @var string
  50. */
  51. public $meta_id_column;
  52. /**
  53. * Database table that where the metadata's objects are stored (eg $wpdb->users).
  54. *
  55. * @since 4.1.0
  56. * @var string
  57. */
  58. public $primary_table;
  59. /**
  60. * Column in primary_table that represents the ID of the object.
  61. *
  62. * @since 4.1.0
  63. * @var string
  64. */
  65. public $primary_id_column;
  66. /**
  67. * A flat list of table aliases used in JOIN clauses.
  68. *
  69. * @since 4.1.0
  70. * @var array
  71. */
  72. protected $table_aliases = array();
  73. /**
  74. * A flat list of clauses, keyed by clause 'name'.
  75. *
  76. * @since 4.2.0
  77. * @var array
  78. */
  79. protected $clauses = array();
  80. /**
  81. * Whether the query contains any OR relations.
  82. *
  83. * @since 4.3.0
  84. * @var bool
  85. */
  86. protected $has_or_relation = false;
  87. /**
  88. * Constructor.
  89. *
  90. * @since 3.2.0
  91. * @since 4.2.0 Introduced support for naming query clauses by associative array keys.
  92. *
  93. *
  94. * @param array $meta_query {
  95. * Array of meta query clauses. When first-order clauses or sub-clauses use strings as
  96. * their array keys, they may be referenced in the 'orderby' parameter of the parent query.
  97. *
  98. * @type string $relation Optional. The MySQL keyword used to join
  99. * the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
  100. * @type array {
  101. * Optional. An array of first-order clause parameters, or another fully-formed meta query.
  102. *
  103. * @type string $key Meta key to filter by.
  104. * @type string $value Meta value to filter by.
  105. * @type string $compare MySQL operator used for comparing the $value. Accepts '=',
  106. * '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE',
  107. * 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'REGEXP',
  108. * 'NOT REGEXP', 'RLIKE', 'EXISTS' or 'NOT EXISTS'.
  109. * Default is 'IN' when `$value` is an array, '=' otherwise.
  110. * @type string $type MySQL data type that the meta_value column will be CAST to for
  111. * comparisons. Accepts 'NUMERIC', 'BINARY', 'CHAR', 'DATE',
  112. * 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', or 'UNSIGNED'.
  113. * Default is 'CHAR'.
  114. * }
  115. * }
  116. */
  117. public function __construct( $meta_query = false ) {
  118. if ( !$meta_query )
  119. return;
  120. if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
  121. $this->relation = 'OR';
  122. } else {
  123. $this->relation = 'AND';
  124. }
  125. $this->queries = $this->sanitize_query( $meta_query );
  126. }
  127. /**
  128. * Ensure the 'meta_query' argument passed to the class constructor is well-formed.
  129. *
  130. * Eliminates empty items and ensures that a 'relation' is set.
  131. *
  132. * @since 4.1.0
  133. *
  134. * @param array $queries Array of query clauses.
  135. * @return array Sanitized array of query clauses.
  136. */
  137. public function sanitize_query( $queries ) {
  138. $clean_queries = array();
  139. if ( ! is_array( $queries ) ) {
  140. return $clean_queries;
  141. }
  142. foreach ( $queries as $key => $query ) {
  143. if ( 'relation' === $key ) {
  144. $relation = $query;
  145. } elseif ( ! is_array( $query ) ) {
  146. continue;
  147. // First-order clause.
  148. } elseif ( $this->is_first_order_clause( $query ) ) {
  149. if ( isset( $query['value'] ) && array() === $query['value'] ) {
  150. unset( $query['value'] );
  151. }
  152. $clean_queries[ $key ] = $query;
  153. // Otherwise, it's a nested query, so we recurse.
  154. } else {
  155. $cleaned_query = $this->sanitize_query( $query );
  156. if ( ! empty( $cleaned_query ) ) {
  157. $clean_queries[ $key ] = $cleaned_query;
  158. }
  159. }
  160. }
  161. if ( empty( $clean_queries ) ) {
  162. return $clean_queries;
  163. }
  164. // Sanitize the 'relation' key provided in the query.
  165. if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) {
  166. $clean_queries['relation'] = 'OR';
  167. $this->has_or_relation = true;
  168. /*
  169. * If there is only a single clause, call the relation 'OR'.
  170. * This value will not actually be used to join clauses, but it
  171. * simplifies the logic around combining key-only queries.
  172. */
  173. } elseif ( 1 === count( $clean_queries ) ) {
  174. $clean_queries['relation'] = 'OR';
  175. // Default to AND.
  176. } else {
  177. $clean_queries['relation'] = 'AND';
  178. }
  179. return $clean_queries;
  180. }
  181. /**
  182. * Determine whether a query clause is first-order.
  183. *
  184. * A first-order meta query clause is one that has either a 'key' or
  185. * a 'value' array key.
  186. *
  187. * @since 4.1.0
  188. *
  189. * @param array $query Meta query arguments.
  190. * @return bool Whether the query clause is a first-order clause.
  191. */
  192. protected function is_first_order_clause( $query ) {
  193. return isset( $query['key'] ) || isset( $query['value'] );
  194. }
  195. /**
  196. * Constructs a meta query based on 'meta_*' query vars
  197. *
  198. * @since 3.2.0
  199. *
  200. * @param array $qv The query variables
  201. */
  202. public function parse_query_vars( $qv ) {
  203. $meta_query = array();
  204. /*
  205. * For orderby=meta_value to work correctly, simple query needs to be
  206. * first (so that its table join is against an unaliased meta table) and
  207. * needs to be its own clause (so it doesn't interfere with the logic of
  208. * the rest of the meta_query).
  209. */
  210. $primary_meta_query = array();
  211. foreach ( array( 'key', 'compare', 'type' ) as $key ) {
  212. if ( ! empty( $qv[ "meta_$key" ] ) ) {
  213. $primary_meta_query[ $key ] = $qv[ "meta_$key" ];
  214. }
  215. }
  216. // WP_Query sets 'meta_value' = '' by default.
  217. if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) {
  218. $primary_meta_query['value'] = $qv['meta_value'];
  219. }
  220. $existing_meta_query = isset( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ? $qv['meta_query'] : array();
  221. if ( ! empty( $primary_meta_query ) && ! empty( $existing_meta_query ) ) {
  222. $meta_query = array(
  223. 'relation' => 'AND',
  224. $primary_meta_query,
  225. $existing_meta_query,
  226. );
  227. } elseif ( ! empty( $primary_meta_query ) ) {
  228. $meta_query = array(
  229. $primary_meta_query,
  230. );
  231. } elseif ( ! empty( $existing_meta_query ) ) {
  232. $meta_query = $existing_meta_query;
  233. }
  234. $this->__construct( $meta_query );
  235. }
  236. /**
  237. * Return the appropriate alias for the given meta type if applicable.
  238. *
  239. * @since 3.7.0
  240. *
  241. * @param string $type MySQL type to cast meta_value.
  242. * @return string MySQL type.
  243. */
  244. public function get_cast_for_type( $type = '' ) {
  245. if ( empty( $type ) )
  246. return 'CHAR';
  247. $meta_type = strtoupper( $type );
  248. if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
  249. return 'CHAR';
  250. if ( 'NUMERIC' == $meta_type )
  251. $meta_type = 'SIGNED';
  252. return $meta_type;
  253. }
  254. /**
  255. * Generates SQL clauses to be appended to a main query.
  256. *
  257. * @since 3.2.0
  258. *
  259. * @param string $type Type of meta, eg 'user', 'post'.
  260. * @param string $primary_table Database table where the object being filtered is stored (eg wp_users).
  261. * @param string $primary_id_column ID column for the filtered object in $primary_table.
  262. * @param object $context Optional. The main query object.
  263. * @return false|array {
  264. * Array containing JOIN and WHERE SQL clauses to append to the main query.
  265. *
  266. * @type string $join SQL fragment to append to the main JOIN clause.
  267. * @type string $where SQL fragment to append to the main WHERE clause.
  268. * }
  269. */
  270. public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
  271. if ( ! $meta_table = _get_meta_table( $type ) ) {
  272. return false;
  273. }
  274. $this->table_aliases = array();
  275. $this->meta_table = $meta_table;
  276. $this->meta_id_column = sanitize_key( $type . '_id' );
  277. $this->primary_table = $primary_table;
  278. $this->primary_id_column = $primary_id_column;
  279. $sql = $this->get_sql_clauses();
  280. /*
  281. * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should
  282. * be LEFT. Otherwise posts with no metadata will be excluded from results.
  283. */
  284. if ( false !== strpos( $sql['join'], 'LEFT JOIN' ) ) {
  285. $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] );
  286. }
  287. /**
  288. * Filters the meta query's generated SQL.
  289. *
  290. * @since 3.1.0
  291. *
  292. * @param array $clauses Array containing the query's JOIN and WHERE clauses.
  293. * @param array $queries Array of meta queries.
  294. * @param string $type Type of meta.
  295. * @param string $primary_table Primary table.
  296. * @param string $primary_id_column Primary column ID.
  297. * @param object $context The main query object.
  298. */
  299. return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) );
  300. }
  301. /**
  302. * Generate SQL clauses to be appended to a main query.
  303. *
  304. * Called by the public WP_Meta_Query::get_sql(), this method is abstracted
  305. * out to maintain parity with the other Query classes.
  306. *
  307. * @since 4.1.0
  308. *
  309. * @return array {
  310. * Array containing JOIN and WHERE SQL clauses to append to the main query.
  311. *
  312. * @type string $join SQL fragment to append to the main JOIN clause.
  313. * @type string $where SQL fragment to append to the main WHERE clause.
  314. * }
  315. */
  316. protected function get_sql_clauses() {
  317. /*
  318. * $queries are passed by reference to get_sql_for_query() for recursion.
  319. * To keep $this->queries unaltered, pass a copy.
  320. */
  321. $queries = $this->queries;
  322. $sql = $this->get_sql_for_query( $queries );
  323. if ( ! empty( $sql['where'] ) ) {
  324. $sql['where'] = ' AND ' . $sql['where'];
  325. }
  326. return $sql;
  327. }
  328. /**
  329. * Generate SQL clauses for a single query array.
  330. *
  331. * If nested subqueries are found, this method recurses the tree to
  332. * produce the properly nested SQL.
  333. *
  334. * @since 4.1.0
  335. *
  336. * @param array $query Query to parse (passed by reference).
  337. * @param int $depth Optional. Number of tree levels deep we currently are.
  338. * Used to calculate indentation. Default 0.
  339. * @return array {
  340. * Array containing JOIN and WHERE SQL clauses to append to a single query array.
  341. *
  342. * @type string $join SQL fragment to append to the main JOIN clause.
  343. * @type string $where SQL fragment to append to the main WHERE clause.
  344. * }
  345. */
  346. protected function get_sql_for_query( &$query, $depth = 0 ) {
  347. $sql_chunks = array(
  348. 'join' => array(),
  349. 'where' => array(),
  350. );
  351. $sql = array(
  352. 'join' => '',
  353. 'where' => '',
  354. );
  355. $indent = '';
  356. for ( $i = 0; $i < $depth; $i++ ) {
  357. $indent .= " ";
  358. }
  359. foreach ( $query as $key => &$clause ) {
  360. if ( 'relation' === $key ) {
  361. $relation = $query['relation'];
  362. } elseif ( is_array( $clause ) ) {
  363. // This is a first-order clause.
  364. if ( $this->is_first_order_clause( $clause ) ) {
  365. $clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
  366. $where_count = count( $clause_sql['where'] );
  367. if ( ! $where_count ) {
  368. $sql_chunks['where'][] = '';
  369. } elseif ( 1 === $where_count ) {
  370. $sql_chunks['where'][] = $clause_sql['where'][0];
  371. } else {
  372. $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
  373. }
  374. $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
  375. // This is a subquery, so we recurse.
  376. } else {
  377. $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
  378. $sql_chunks['where'][] = $clause_sql['where'];
  379. $sql_chunks['join'][] = $clause_sql['join'];
  380. }
  381. }
  382. }
  383. // Filter to remove empties.
  384. $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
  385. $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
  386. if ( empty( $relation ) ) {
  387. $relation = 'AND';
  388. }
  389. // Filter duplicate JOIN clauses and combine into a single string.
  390. if ( ! empty( $sql_chunks['join'] ) ) {
  391. $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
  392. }
  393. // Generate a single WHERE clause with proper brackets and indentation.
  394. if ( ! empty( $sql_chunks['where'] ) ) {
  395. $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
  396. }
  397. return $sql;
  398. }
  399. /**
  400. * Generate SQL JOIN and WHERE clauses for a first-order query clause.
  401. *
  402. * "First-order" means that it's an array with a 'key' or 'value'.
  403. *
  404. * @since 4.1.0
  405. *
  406. * @global wpdb $wpdb WordPress database abstraction object.
  407. *
  408. * @param array $clause Query clause (passed by reference).
  409. * @param array $parent_query Parent query array.
  410. * @param string $clause_key Optional. The array key used to name the clause in the original `$meta_query`
  411. * parameters. If not provided, a key will be generated automatically.
  412. * @return array {
  413. * Array containing JOIN and WHERE SQL clauses to append to a first-order query.
  414. *
  415. * @type string $join SQL fragment to append to the main JOIN clause.
  416. * @type string $where SQL fragment to append to the main WHERE clause.
  417. * }
  418. */
  419. public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) {
  420. global $wpdb;
  421. $sql_chunks = array(
  422. 'where' => array(),
  423. 'join' => array(),
  424. );
  425. if ( isset( $clause['compare'] ) ) {
  426. $clause['compare'] = strtoupper( $clause['compare'] );
  427. } else {
  428. $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
  429. }
  430. if ( ! in_array( $clause['compare'], array(
  431. '=', '!=', '>', '>=', '<', '<=',
  432. 'LIKE', 'NOT LIKE',
  433. 'IN', 'NOT IN',
  434. 'BETWEEN', 'NOT BETWEEN',
  435. 'EXISTS', 'NOT EXISTS',
  436. 'REGEXP', 'NOT REGEXP', 'RLIKE'
  437. ) ) ) {
  438. $clause['compare'] = '=';
  439. }
  440. $meta_compare = $clause['compare'];
  441. // First build the JOIN clause, if one is required.
  442. $join = '';
  443. // We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
  444. $alias = $this->find_compatible_table_alias( $clause, $parent_query );
  445. if ( false === $alias ) {
  446. $i = count( $this->table_aliases );
  447. $alias = $i ? 'mt' . $i : $this->meta_table;
  448. // JOIN clauses for NOT EXISTS have their own syntax.
  449. if ( 'NOT EXISTS' === $meta_compare ) {
  450. $join .= " LEFT JOIN $this->meta_table";
  451. $join .= $i ? " AS $alias" : '';
  452. $join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
  453. // All other JOIN clauses.
  454. } else {
  455. $join .= " INNER JOIN $this->meta_table";
  456. $join .= $i ? " AS $alias" : '';
  457. $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
  458. }
  459. $this->table_aliases[] = $alias;
  460. $sql_chunks['join'][] = $join;
  461. }
  462. // Save the alias to this clause, for future siblings to find.
  463. $clause['alias'] = $alias;
  464. // Determine the data type.
  465. $_meta_type = isset( $clause['type'] ) ? $clause['type'] : '';
  466. $meta_type = $this->get_cast_for_type( $_meta_type );
  467. $clause['cast'] = $meta_type;
  468. // Fallback for clause keys is the table alias. Key must be a string.
  469. if ( is_int( $clause_key ) || ! $clause_key ) {
  470. $clause_key = $clause['alias'];
  471. }
  472. // Ensure unique clause keys, so none are overwritten.
  473. $iterator = 1;
  474. $clause_key_base = $clause_key;
  475. while ( isset( $this->clauses[ $clause_key ] ) ) {
  476. $clause_key = $clause_key_base . '-' . $iterator;
  477. $iterator++;
  478. }
  479. // Store the clause in our flat array.
  480. $this->clauses[ $clause_key ] =& $clause;
  481. // Next, build the WHERE clause.
  482. // meta_key.
  483. if ( array_key_exists( 'key', $clause ) ) {
  484. if ( 'NOT EXISTS' === $meta_compare ) {
  485. $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
  486. } else {
  487. $sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
  488. }
  489. }
  490. // meta_value.
  491. if ( array_key_exists( 'value', $clause ) ) {
  492. $meta_value = $clause['value'];
  493. if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
  494. if ( ! is_array( $meta_value ) ) {
  495. $meta_value = preg_split( '/[,\s]+/', $meta_value );
  496. }
  497. } else {
  498. $meta_value = trim( $meta_value );
  499. }
  500. switch ( $meta_compare ) {
  501. case 'IN' :
  502. case 'NOT IN' :
  503. $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
  504. $where = $wpdb->prepare( $meta_compare_string, $meta_value );
  505. break;
  506. case 'BETWEEN' :
  507. case 'NOT BETWEEN' :
  508. $meta_value = array_slice( $meta_value, 0, 2 );
  509. $where = $wpdb->prepare( '%s AND %s', $meta_value );
  510. break;
  511. case 'LIKE' :
  512. case 'NOT LIKE' :
  513. $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
  514. $where = $wpdb->prepare( '%s', $meta_value );
  515. break;
  516. // EXISTS with a value is interpreted as '='.
  517. case 'EXISTS' :
  518. $meta_compare = '=';
  519. $where = $wpdb->prepare( '%s', $meta_value );
  520. break;
  521. // 'value' is ignored for NOT EXISTS.
  522. case 'NOT EXISTS' :
  523. $where = '';
  524. break;
  525. default :
  526. $where = $wpdb->prepare( '%s', $meta_value );
  527. break;
  528. }
  529. if ( $where ) {
  530. if ( 'CHAR' === $meta_type ) {
  531. $sql_chunks['where'][] = "$alias.meta_value {$meta_compare} {$where}";
  532. } else {
  533. $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}";
  534. }
  535. }
  536. }
  537. /*
  538. * Multiple WHERE clauses (for meta_key and meta_value) should
  539. * be joined in parentheses.
  540. */
  541. if ( 1 < count( $sql_chunks['where'] ) ) {
  542. $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
  543. }
  544. return $sql_chunks;
  545. }
  546. /**
  547. * Get a flattened list of sanitized meta clauses.
  548. *
  549. * This array should be used for clause lookup, as when the table alias and CAST type must be determined for
  550. * a value of 'orderby' corresponding to a meta clause.
  551. *
  552. * @since 4.2.0
  553. *
  554. * @return array Meta clauses.
  555. */
  556. public function get_clauses() {
  557. return $this->clauses;
  558. }
  559. /**
  560. * Identify an existing table alias that is compatible with the current
  561. * query clause.
  562. *
  563. * We avoid unnecessary table joins by allowing each clause to look for
  564. * an existing table alias that is compatible with the query that it
  565. * needs to perform.
  566. *
  567. * An existing alias is compatible if (a) it is a sibling of `$clause`
  568. * (ie, it's under the scope of the same relation), and (b) the combination
  569. * of operator and relation between the clauses allows for a shared table join.
  570. * In the case of WP_Meta_Query, this only applies to 'IN' clauses that are
  571. * connected by the relation 'OR'.
  572. *
  573. * @since 4.1.0
  574. *
  575. * @param array $clause Query clause.
  576. * @param array $parent_query Parent query of $clause.
  577. * @return string|bool Table alias if found, otherwise false.
  578. */
  579. protected function find_compatible_table_alias( $clause, $parent_query ) {
  580. $alias = false;
  581. foreach ( $parent_query as $sibling ) {
  582. // If the sibling has no alias yet, there's nothing to check.
  583. if ( empty( $sibling['alias'] ) ) {
  584. continue;
  585. }
  586. // We're only interested in siblings that are first-order clauses.
  587. if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
  588. continue;
  589. }
  590. $compatible_compares = array();
  591. // Clauses connected by OR can share joins as long as they have "positive" operators.
  592. if ( 'OR' === $parent_query['relation'] ) {
  593. $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
  594. // Clauses joined by AND with "negative" operators share a join only if they also share a key.
  595. } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
  596. $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
  597. }
  598. $clause_compare = strtoupper( $clause['compare'] );
  599. $sibling_compare = strtoupper( $sibling['compare'] );
  600. if ( in_array( $clause_compare, $compatible_compares ) && in_array( $sibling_compare, $compatible_compares ) ) {
  601. $alias = $sibling['alias'];
  602. break;
  603. }
  604. }
  605. /**
  606. * Filters the table alias identified as compatible with the current clause.
  607. *
  608. * @since 4.1.0
  609. *
  610. * @param string|bool $alias Table alias, or false if none was found.
  611. * @param array $clause First-order query clause.
  612. * @param array $parent_query Parent of $clause.
  613. * @param object $this WP_Meta_Query object.
  614. */
  615. return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ) ;
  616. }
  617. /**
  618. * Checks whether the current query has any OR relations.
  619. *
  620. * In some cases, the presence of an OR relation somewhere in the query will require
  621. * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current
  622. * method can be used in these cases to determine whether such a clause is necessary.
  623. *
  624. * @since 4.3.0
  625. *
  626. * @return bool True if the query contains any `OR` relations, otherwise false.
  627. */
  628. public function has_or_relation() {
  629. return $this->has_or_relation;
  630. }
  631. }