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