~canonical-sysadmins/wordpress/4.5.2

« back to all changes in this revision

Viewing changes to wp-includes/meta.php

  • Committer: Manuel Seelaus
  • Date: 2015-12-09 17:47:18 UTC
  • mfrom: (1.1.11 upstream)
  • Revision ID: manuel.seelaus@canonical.com-20151209174718-coxethm2swbeqksy
Merge WP4.4 from upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
<?php
2
2
/**
3
 
 * Metadata API
 
3
 * Core Metadata API
4
4
 *
5
5
 * Functions for retrieving and manipulating metadata of various WordPress object types. Metadata
6
6
 * for an object is a represented by a simple key-value pair. Objects may contain multiple
8
8
 *
9
9
 * @package WordPress
10
10
 * @subpackage Meta
11
 
 * @since 2.9.0
12
11
 */
13
12
 
14
13
/**
475
474
         *
476
475
         * @since 3.1.0
477
476
         *
478
 
         * @param null|array|string $value     The value get_metadata() should
479
 
         *                                     return - a single metadata value,
 
477
         * @param null|array|string $value     The value get_metadata() should return - a single metadata value,
480
478
         *                                     or an array of values.
481
479
         * @param int               $object_id Object ID.
482
480
         * @param string            $meta_key  Meta key.
483
 
         * @param string|array      $single    Meta value, or an array of values.
 
481
         * @param bool              $single    Whether to return only the first value of the specified $meta_key.
484
482
         */
485
483
        $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
486
484
        if ( null !== $check ) {
557
555
 *
558
556
 * @since 3.3.0
559
557
 *
560
 
 * @global wpdb $wpdb
 
558
 * @global wpdb $wpdb WordPress database abstraction object.
561
559
 *
562
 
 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
 
560
 * @param string $meta_type Type of object metadata is for (e.g., comment, post, term, or user).
563
561
 * @param int    $meta_id   ID for a specific meta row
564
562
 * @return object|false Meta object or false.
565
563
 */
598
596
 *
599
597
 * @since 3.3.0
600
598
 *
601
 
 * @global wpdb $wpdb
 
599
 * @global wpdb $wpdb WordPress database abstraction object.
602
600
 *
603
601
 * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
604
602
 * @param int    $meta_id    ID for a specific meta row
691
689
 *
692
690
 * @since 3.3.0
693
691
 *
694
 
 * @global wpdb $wpdb
 
692
 * @global wpdb $wpdb WordPress database abstraction object.
695
693
 *
696
 
 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
 
694
 * @param string $meta_type Type of object metadata is for (e.g., comment, post, term, or user).
697
695
 * @param int    $meta_id   ID for a specific meta row
698
696
 * @return bool True on successful delete, false on failure.
699
697
 */
870
868
}
871
869
 
872
870
/**
873
 
 * Class for generating SQL clauses that filter a primary query according to metadata keys and values.
874
 
 *
875
 
 * `WP_Meta_Query` is a helper that allows primary query classes, such as {@see WP_Query} and {@see WP_User_Query},
876
 
 * to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
877
 
 * to the primary SQL query string.
878
 
 *
879
 
 * @since 3.2.0
880
 
 */
881
 
class WP_Meta_Query {
882
 
        /**
883
 
         * Array of metadata queries.
884
 
         *
885
 
         * See {@see WP_Meta_Query::__construct()} for information on meta query arguments.
886
 
         *
887
 
         * @since 3.2.0
888
 
         * @access public
889
 
         * @var array
890
 
         */
891
 
        public $queries = array();
892
 
 
893
 
        /**
894
 
         * The relation between the queries. Can be one of 'AND' or 'OR'.
895
 
         *
896
 
         * @since 3.2.0
897
 
         * @access public
898
 
         * @var string
899
 
         */
900
 
        public $relation;
901
 
 
902
 
        /**
903
 
         * Database table to query for the metadata.
904
 
         *
905
 
         * @since 4.1.0
906
 
         * @access public
907
 
         * @var string
908
 
         */
909
 
        public $meta_table;
910
 
 
911
 
        /**
912
 
         * Column in meta_table that represents the ID of the object the metadata belongs to.
913
 
         *
914
 
         * @since 4.1.0
915
 
         * @access public
916
 
         * @var string
917
 
         */
918
 
        public $meta_id_column;
919
 
 
920
 
        /**
921
 
         * Database table that where the metadata's objects are stored (eg $wpdb->users).
922
 
         *
923
 
         * @since 4.1.0
924
 
         * @access public
925
 
         * @var string
926
 
         */
927
 
        public $primary_table;
928
 
 
929
 
        /**
930
 
         * Column in primary_table that represents the ID of the object.
931
 
         *
932
 
         * @since 4.1.0
933
 
         * @access public
934
 
         * @var string
935
 
         */
936
 
        public $primary_id_column;
937
 
 
938
 
        /**
939
 
         * A flat list of table aliases used in JOIN clauses.
940
 
         *
941
 
         * @since 4.1.0
942
 
         * @access protected
943
 
         * @var array
944
 
         */
945
 
        protected $table_aliases = array();
946
 
 
947
 
        /**
948
 
         * A flat list of clauses, keyed by clause 'name'.
949
 
         *
950
 
         * @since 4.2.0
951
 
         * @access protected
952
 
         * @var array
953
 
         */
954
 
        protected $clauses = array();
955
 
 
956
 
        /**
957
 
         * Whether the query contains any OR relations.
958
 
         *
959
 
         * @since 4.3.0
960
 
         * @access protected
961
 
         * @var bool
962
 
         */
963
 
        protected $has_or_relation = false;
964
 
 
965
 
        /**
966
 
         * Constructor.
967
 
         *
968
 
         * @since 3.2.0
969
 
         * @since 4.2.0 Introduced support for naming query clauses by associative array keys.
970
 
         *
971
 
         * @access public
972
 
         *
973
 
         * @param array $meta_query {
974
 
         *     Array of meta query clauses. When first-order clauses use strings as their array keys, they may be
975
 
         *     referenced in the 'orderby' parameter of the parent query.
976
 
         *
977
 
         *     @type string $relation Optional. The MySQL keyword used to join
978
 
         *                            the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
979
 
         *     @type array {
980
 
         *         Optional. An array of first-order clause parameters, or another fully-formed meta query.
981
 
         *
982
 
         *         @type string $key     Meta key to filter by.
983
 
         *         @type string $value   Meta value to filter by.
984
 
         *         @type string $compare MySQL operator used for comparing the $value. Accepts '=',
985
 
         *                               '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
986
 
         *                               'BETWEEN', 'NOT BETWEEN', 'REGEXP', 'NOT REGEXP', or 'RLIKE'.
987
 
         *                               Default is 'IN' when `$value` is an array, '=' otherwise.
988
 
         *         @type string $type    MySQL data type that the meta_value column will be CAST to for
989
 
         *                               comparisons. Accepts 'NUMERIC', 'BINARY', 'CHAR', 'DATE',
990
 
         *                               'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', or 'UNSIGNED'.
991
 
         *                               Default is 'CHAR'.
992
 
         *     }
993
 
         * }
994
 
         */
995
 
        public function __construct( $meta_query = false ) {
996
 
                if ( !$meta_query )
997
 
                        return;
998
 
 
999
 
                if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
1000
 
                        $this->relation = 'OR';
1001
 
                } else {
1002
 
                        $this->relation = 'AND';
1003
 
                }
1004
 
 
1005
 
                $this->queries = $this->sanitize_query( $meta_query );
1006
 
        }
1007
 
 
1008
 
        /**
1009
 
         * Ensure the 'meta_query' argument passed to the class constructor is well-formed.
1010
 
         *
1011
 
         * Eliminates empty items and ensures that a 'relation' is set.
1012
 
         *
1013
 
         * @since 4.1.0
1014
 
         * @access public
1015
 
         *
1016
 
         * @param array $queries Array of query clauses.
1017
 
         * @return array Sanitized array of query clauses.
1018
 
         */
1019
 
        public function sanitize_query( $queries ) {
1020
 
                $clean_queries = array();
1021
 
 
1022
 
                if ( ! is_array( $queries ) ) {
1023
 
                        return $clean_queries;
1024
 
                }
1025
 
 
1026
 
                foreach ( $queries as $key => $query ) {
1027
 
                        if ( 'relation' === $key ) {
1028
 
                                $relation = $query;
1029
 
 
1030
 
                        } elseif ( ! is_array( $query ) ) {
1031
 
                                continue;
1032
 
 
1033
 
                        // First-order clause.
1034
 
                        } elseif ( $this->is_first_order_clause( $query ) ) {
1035
 
                                if ( isset( $query['value'] ) && array() === $query['value'] ) {
1036
 
                                        unset( $query['value'] );
1037
 
                                }
1038
 
 
1039
 
                                $clean_queries[ $key ] = $query;
1040
 
 
1041
 
                        // Otherwise, it's a nested query, so we recurse.
1042
 
                        } else {
1043
 
                                $cleaned_query = $this->sanitize_query( $query );
1044
 
 
1045
 
                                if ( ! empty( $cleaned_query ) ) {
1046
 
                                        $clean_queries[ $key ] = $cleaned_query;
1047
 
                                }
1048
 
                        }
1049
 
                }
1050
 
 
1051
 
                if ( empty( $clean_queries ) ) {
1052
 
                        return $clean_queries;
1053
 
                }
1054
 
 
1055
 
                // Sanitize the 'relation' key provided in the query.
1056
 
                if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) {
1057
 
                        $clean_queries['relation'] = 'OR';
1058
 
                        $this->has_or_relation = true;
1059
 
 
1060
 
                /*
1061
 
                 * If there is only a single clause, call the relation 'OR'.
1062
 
                 * This value will not actually be used to join clauses, but it
1063
 
                 * simplifies the logic around combining key-only queries.
1064
 
                 */
1065
 
                } elseif ( 1 === count( $clean_queries ) ) {
1066
 
                        $clean_queries['relation'] = 'OR';
1067
 
 
1068
 
                // Default to AND.
1069
 
                } else {
1070
 
                        $clean_queries['relation'] = 'AND';
1071
 
                }
1072
 
 
1073
 
                return $clean_queries;
1074
 
        }
1075
 
 
1076
 
        /**
1077
 
         * Determine whether a query clause is first-order.
1078
 
         *
1079
 
         * A first-order meta query clause is one that has either a 'key' or
1080
 
         * a 'value' array key.
1081
 
         *
1082
 
         * @since 4.1.0
1083
 
         * @access protected
1084
 
         *
1085
 
         * @param array $query Meta query arguments.
1086
 
         * @return bool Whether the query clause is a first-order clause.
1087
 
         */
1088
 
        protected function is_first_order_clause( $query ) {
1089
 
                return isset( $query['key'] ) || isset( $query['value'] );
1090
 
        }
1091
 
 
1092
 
        /**
1093
 
         * Constructs a meta query based on 'meta_*' query vars
1094
 
         *
1095
 
         * @since 3.2.0
1096
 
         * @access public
1097
 
         *
1098
 
         * @param array $qv The query variables
1099
 
         */
1100
 
        public function parse_query_vars( $qv ) {
1101
 
                $meta_query = array();
1102
 
 
1103
 
                /*
1104
 
                 * For orderby=meta_value to work correctly, simple query needs to be
1105
 
                 * first (so that its table join is against an unaliased meta table) and
1106
 
                 * needs to be its own clause (so it doesn't interfere with the logic of
1107
 
                 * the rest of the meta_query).
1108
 
                 */
1109
 
                $primary_meta_query = array();
1110
 
                foreach ( array( 'key', 'compare', 'type' ) as $key ) {
1111
 
                        if ( ! empty( $qv[ "meta_$key" ] ) ) {
1112
 
                                $primary_meta_query[ $key ] = $qv[ "meta_$key" ];
1113
 
                        }
1114
 
                }
1115
 
 
1116
 
                // WP_Query sets 'meta_value' = '' by default.
1117
 
                if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) {
1118
 
                        $primary_meta_query['value'] = $qv['meta_value'];
1119
 
                }
1120
 
 
1121
 
                $existing_meta_query = isset( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ? $qv['meta_query'] : array();
1122
 
 
1123
 
                if ( ! empty( $primary_meta_query ) && ! empty( $existing_meta_query ) ) {
1124
 
                        $meta_query = array(
1125
 
                                'relation' => 'AND',
1126
 
                                $primary_meta_query,
1127
 
                                $existing_meta_query,
1128
 
                        );
1129
 
                } elseif ( ! empty( $primary_meta_query ) ) {
1130
 
                        $meta_query = array(
1131
 
                                $primary_meta_query,
1132
 
                        );
1133
 
                } elseif ( ! empty( $existing_meta_query ) ) {
1134
 
                        $meta_query = $existing_meta_query;
1135
 
                }
1136
 
 
1137
 
                $this->__construct( $meta_query );
1138
 
        }
1139
 
 
1140
 
        /**
1141
 
         * Return the appropriate alias for the given meta type if applicable.
1142
 
         *
1143
 
         * @since 3.7.0
1144
 
         * @access public
1145
 
         *
1146
 
         * @param string $type MySQL type to cast meta_value.
1147
 
         * @return string MySQL type.
1148
 
         */
1149
 
        public function get_cast_for_type( $type = '' ) {
1150
 
                if ( empty( $type ) )
1151
 
                        return 'CHAR';
1152
 
 
1153
 
                $meta_type = strtoupper( $type );
1154
 
 
1155
 
                if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
1156
 
                        return 'CHAR';
1157
 
 
1158
 
                if ( 'NUMERIC' == $meta_type )
1159
 
                        $meta_type = 'SIGNED';
1160
 
 
1161
 
                return $meta_type;
1162
 
        }
1163
 
 
1164
 
        /**
1165
 
         * Generates SQL clauses to be appended to a main query.
1166
 
         *
1167
 
         * @since 3.2.0
1168
 
         * @access public
1169
 
         *
1170
 
         * @param string $type              Type of meta, eg 'user', 'post'.
1171
 
         * @param string $primary_table     Database table where the object being filtered is stored (eg wp_users).
1172
 
         * @param string $primary_id_column ID column for the filtered object in $primary_table.
1173
 
         * @param object $context           Optional. The main query object.
1174
 
         * @return false|array {
1175
 
         *     Array containing JOIN and WHERE SQL clauses to append to the main query.
1176
 
         *
1177
 
         *     @type string $join  SQL fragment to append to the main JOIN clause.
1178
 
         *     @type string $where SQL fragment to append to the main WHERE clause.
1179
 
         * }
1180
 
         */
1181
 
        public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
1182
 
                if ( ! $meta_table = _get_meta_table( $type ) ) {
1183
 
                        return false;
1184
 
                }
1185
 
 
1186
 
                $this->meta_table     = $meta_table;
1187
 
                $this->meta_id_column = sanitize_key( $type . '_id' );
1188
 
 
1189
 
                $this->primary_table     = $primary_table;
1190
 
                $this->primary_id_column = $primary_id_column;
1191
 
 
1192
 
                $sql = $this->get_sql_clauses();
1193
 
 
1194
 
                /*
1195
 
                 * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should
1196
 
                 * be LEFT. Otherwise posts with no metadata will be excluded from results.
1197
 
                 */
1198
 
                if ( false !== strpos( $sql['join'], 'LEFT JOIN' ) ) {
1199
 
                        $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] );
1200
 
                }
1201
 
 
1202
 
                /**
1203
 
                 * Filter the meta query's generated SQL.
1204
 
                 *
1205
 
                 * @since 3.1.0
1206
 
                 *
1207
 
                 * @param array $args {
1208
 
                 *     An array of meta query SQL arguments.
1209
 
                 *
1210
 
                 *     @type array  $clauses           Array containing the query's JOIN and WHERE clauses.
1211
 
                 *     @type array  $queries           Array of meta queries.
1212
 
                 *     @type string $type              Type of meta.
1213
 
                 *     @type string $primary_table     Primary table.
1214
 
                 *     @type string $primary_id_column Primary column ID.
1215
 
                 *     @type object $context           The main query object.
1216
 
                 * }
1217
 
                 */
1218
 
                return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) );
1219
 
        }
1220
 
 
1221
 
        /**
1222
 
         * Generate SQL clauses to be appended to a main query.
1223
 
         *
1224
 
         * Called by the public {@see WP_Meta_Query::get_sql()}, this method
1225
 
         * is abstracted out to maintain parity with the other Query classes.
1226
 
         *
1227
 
         * @since 4.1.0
1228
 
         * @access protected
1229
 
         *
1230
 
         * @return array {
1231
 
         *     Array containing JOIN and WHERE SQL clauses to append to the main query.
1232
 
         *
1233
 
         *     @type string $join  SQL fragment to append to the main JOIN clause.
1234
 
         *     @type string $where SQL fragment to append to the main WHERE clause.
1235
 
         * }
1236
 
         */
1237
 
        protected function get_sql_clauses() {
1238
 
                /*
1239
 
                 * $queries are passed by reference to get_sql_for_query() for recursion.
1240
 
                 * To keep $this->queries unaltered, pass a copy.
1241
 
                 */
1242
 
                $queries = $this->queries;
1243
 
                $sql = $this->get_sql_for_query( $queries );
1244
 
 
1245
 
                if ( ! empty( $sql['where'] ) ) {
1246
 
                        $sql['where'] = ' AND ' . $sql['where'];
1247
 
                }
1248
 
 
1249
 
                return $sql;
1250
 
        }
1251
 
 
1252
 
        /**
1253
 
         * Generate SQL clauses for a single query array.
1254
 
         *
1255
 
         * If nested subqueries are found, this method recurses the tree to
1256
 
         * produce the properly nested SQL.
1257
 
         *
1258
 
         * @since 4.1.0
1259
 
         * @access protected
1260
 
         *
1261
 
         * @param array $query Query to parse, passed by reference.
1262
 
         * @param int   $depth Optional. Number of tree levels deep we currently are.
1263
 
         *                     Used to calculate indentation. Default 0.
1264
 
         * @return array {
1265
 
         *     Array containing JOIN and WHERE SQL clauses to append to a single query array.
1266
 
         *
1267
 
         *     @type string $join  SQL fragment to append to the main JOIN clause.
1268
 
         *     @type string $where SQL fragment to append to the main WHERE clause.
1269
 
         * }
1270
 
         */
1271
 
        protected function get_sql_for_query( &$query, $depth = 0 ) {
1272
 
                $sql_chunks = array(
1273
 
                        'join'  => array(),
1274
 
                        'where' => array(),
1275
 
                );
1276
 
 
1277
 
                $sql = array(
1278
 
                        'join'  => '',
1279
 
                        'where' => '',
1280
 
                );
1281
 
 
1282
 
                $indent = '';
1283
 
                for ( $i = 0; $i < $depth; $i++ ) {
1284
 
                        $indent .= "  ";
1285
 
                }
1286
 
 
1287
 
                foreach ( $query as $key => &$clause ) {
1288
 
                        if ( 'relation' === $key ) {
1289
 
                                $relation = $query['relation'];
1290
 
                        } elseif ( is_array( $clause ) ) {
1291
 
 
1292
 
                                // This is a first-order clause.
1293
 
                                if ( $this->is_first_order_clause( $clause ) ) {
1294
 
                                        $clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
1295
 
 
1296
 
                                        $where_count = count( $clause_sql['where'] );
1297
 
                                        if ( ! $where_count ) {
1298
 
                                                $sql_chunks['where'][] = '';
1299
 
                                        } elseif ( 1 === $where_count ) {
1300
 
                                                $sql_chunks['where'][] = $clause_sql['where'][0];
1301
 
                                        } else {
1302
 
                                                $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
1303
 
                                        }
1304
 
 
1305
 
                                        $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
1306
 
                                // This is a subquery, so we recurse.
1307
 
                                } else {
1308
 
                                        $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
1309
 
 
1310
 
                                        $sql_chunks['where'][] = $clause_sql['where'];
1311
 
                                        $sql_chunks['join'][]  = $clause_sql['join'];
1312
 
                                }
1313
 
                        }
1314
 
                }
1315
 
 
1316
 
                // Filter to remove empties.
1317
 
                $sql_chunks['join']  = array_filter( $sql_chunks['join'] );
1318
 
                $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
1319
 
 
1320
 
                if ( empty( $relation ) ) {
1321
 
                        $relation = 'AND';
1322
 
                }
1323
 
 
1324
 
                // Filter duplicate JOIN clauses and combine into a single string.
1325
 
                if ( ! empty( $sql_chunks['join'] ) ) {
1326
 
                        $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
1327
 
                }
1328
 
 
1329
 
                // Generate a single WHERE clause with proper brackets and indentation.
1330
 
                if ( ! empty( $sql_chunks['where'] ) ) {
1331
 
                        $sql['where'] = '( ' . "\n  " . $indent . implode( ' ' . "\n  " . $indent . $relation . ' ' . "\n  " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
1332
 
                }
1333
 
 
1334
 
                return $sql;
1335
 
        }
1336
 
 
1337
 
        /**
1338
 
         * Generate SQL JOIN and WHERE clauses for a first-order query clause.
1339
 
         *
1340
 
         * "First-order" means that it's an array with a 'key' or 'value'.
1341
 
         *
1342
 
         * @since 4.1.0
1343
 
         * @access public
1344
 
         *
1345
 
         * @global wpdb $wpdb
1346
 
         *
1347
 
         * @param array  $clause       Query clause, passed by reference.
1348
 
         * @param array  $parent_query Parent query array.
1349
 
         * @param string $clause_key   Optional. The array key used to name the clause in the original `$meta_query`
1350
 
         *                             parameters. If not provided, a key will be generated automatically.
1351
 
         * @return array {
1352
 
         *     Array containing JOIN and WHERE SQL clauses to append to a first-order query.
1353
 
         *
1354
 
         *     @type string $join  SQL fragment to append to the main JOIN clause.
1355
 
         *     @type string $where SQL fragment to append to the main WHERE clause.
1356
 
         * }
1357
 
         */
1358
 
        public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) {
1359
 
                global $wpdb;
1360
 
 
1361
 
                $sql_chunks = array(
1362
 
                        'where' => array(),
1363
 
                        'join' => array(),
1364
 
                );
1365
 
 
1366
 
                if ( isset( $clause['compare'] ) ) {
1367
 
                        $clause['compare'] = strtoupper( $clause['compare'] );
1368
 
                } else {
1369
 
                        $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
1370
 
                }
1371
 
 
1372
 
                if ( ! in_array( $clause['compare'], array(
1373
 
                        '=', '!=', '>', '>=', '<', '<=',
1374
 
                        'LIKE', 'NOT LIKE',
1375
 
                        'IN', 'NOT IN',
1376
 
                        'BETWEEN', 'NOT BETWEEN',
1377
 
                        'EXISTS', 'NOT EXISTS',
1378
 
                        'REGEXP', 'NOT REGEXP', 'RLIKE'
1379
 
                ) ) ) {
1380
 
                        $clause['compare'] = '=';
1381
 
                }
1382
 
 
1383
 
                $meta_compare = $clause['compare'];
1384
 
 
1385
 
                // First build the JOIN clause, if one is required.
1386
 
                $join = '';
1387
 
 
1388
 
                // We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
1389
 
                $alias = $this->find_compatible_table_alias( $clause, $parent_query );
1390
 
                if ( false === $alias ) {
1391
 
                        $i = count( $this->table_aliases );
1392
 
                        $alias = $i ? 'mt' . $i : $this->meta_table;
1393
 
 
1394
 
                        // JOIN clauses for NOT EXISTS have their own syntax.
1395
 
                        if ( 'NOT EXISTS' === $meta_compare ) {
1396
 
                                $join .= " LEFT JOIN $this->meta_table";
1397
 
                                $join .= $i ? " AS $alias" : '';
1398
 
                                $join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
1399
 
 
1400
 
                        // All other JOIN clauses.
1401
 
                        } else {
1402
 
                                $join .= " INNER JOIN $this->meta_table";
1403
 
                                $join .= $i ? " AS $alias" : '';
1404
 
                                $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
1405
 
                        }
1406
 
 
1407
 
                        $this->table_aliases[] = $alias;
1408
 
                        $sql_chunks['join'][] = $join;
1409
 
                }
1410
 
 
1411
 
                // Save the alias to this clause, for future siblings to find.
1412
 
                $clause['alias'] = $alias;
1413
 
 
1414
 
                // Determine the data type.
1415
 
                $_meta_type = isset( $clause['type'] ) ? $clause['type'] : '';
1416
 
                $meta_type  = $this->get_cast_for_type( $_meta_type );
1417
 
                $clause['cast'] = $meta_type;
1418
 
 
1419
 
                // Fallback for clause keys is the table alias.
1420
 
                if ( ! $clause_key ) {
1421
 
                        $clause_key = $clause['alias'];
1422
 
                }
1423
 
 
1424
 
                // Ensure unique clause keys, so none are overwritten.
1425
 
                $iterator = 1;
1426
 
                $clause_key_base = $clause_key;
1427
 
                while ( isset( $this->clauses[ $clause_key ] ) ) {
1428
 
                        $clause_key = $clause_key_base . '-' . $iterator;
1429
 
                        $iterator++;
1430
 
                }
1431
 
 
1432
 
                // Store the clause in our flat array.
1433
 
                $this->clauses[ $clause_key ] =& $clause;
1434
 
 
1435
 
                // Next, build the WHERE clause.
1436
 
 
1437
 
                // meta_key.
1438
 
                if ( array_key_exists( 'key', $clause ) ) {
1439
 
                        if ( 'NOT EXISTS' === $meta_compare ) {
1440
 
                                $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
1441
 
                        } else {
1442
 
                                $sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
1443
 
                        }
1444
 
                }
1445
 
 
1446
 
                // meta_value.
1447
 
                if ( array_key_exists( 'value', $clause ) ) {
1448
 
                        $meta_value = $clause['value'];
1449
 
 
1450
 
                        if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
1451
 
                                if ( ! is_array( $meta_value ) ) {
1452
 
                                        $meta_value = preg_split( '/[,\s]+/', $meta_value );
1453
 
                                }
1454
 
                        } else {
1455
 
                                $meta_value = trim( $meta_value );
1456
 
                        }
1457
 
 
1458
 
                        switch ( $meta_compare ) {
1459
 
                                case 'IN' :
1460
 
                                case 'NOT IN' :
1461
 
                                        $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
1462
 
                                        $where = $wpdb->prepare( $meta_compare_string, $meta_value );
1463
 
                                        break;
1464
 
 
1465
 
                                case 'BETWEEN' :
1466
 
                                case 'NOT BETWEEN' :
1467
 
                                        $meta_value = array_slice( $meta_value, 0, 2 );
1468
 
                                        $where = $wpdb->prepare( '%s AND %s', $meta_value );
1469
 
                                        break;
1470
 
 
1471
 
                                case 'LIKE' :
1472
 
                                case 'NOT LIKE' :
1473
 
                                        $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
1474
 
                                        $where = $wpdb->prepare( '%s', $meta_value );
1475
 
                                        break;
1476
 
 
1477
 
                                // EXISTS with a value is interpreted as '='.
1478
 
                                case 'EXISTS' :
1479
 
                                        $meta_compare = '=';
1480
 
                                        $where = $wpdb->prepare( '%s', $meta_value );
1481
 
                                        break;
1482
 
 
1483
 
                                // 'value' is ignored for NOT EXISTS.
1484
 
                                case 'NOT EXISTS' :
1485
 
                                        $where = '';
1486
 
                                        break;
1487
 
 
1488
 
                                default :
1489
 
                                        $where = $wpdb->prepare( '%s', $meta_value );
1490
 
                                        break;
1491
 
 
1492
 
                        }
1493
 
 
1494
 
                        if ( $where ) {
1495
 
                                $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}";
1496
 
                        }
1497
 
                }
1498
 
 
1499
 
                /*
1500
 
                 * Multiple WHERE clauses (for meta_key and meta_value) should
1501
 
                 * be joined in parentheses.
1502
 
                 */
1503
 
                if ( 1 < count( $sql_chunks['where'] ) ) {
1504
 
                        $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
1505
 
                }
1506
 
 
1507
 
                return $sql_chunks;
1508
 
        }
1509
 
 
1510
 
        /**
1511
 
         * Get a flattened list of sanitized meta clauses.
1512
 
         *
1513
 
         * This array should be used for clause lookup, as when the table alias and CAST type must be determined for
1514
 
         * a value of 'orderby' corresponding to a meta clause.
1515
 
         *
1516
 
         * @since 4.2.0
1517
 
         * @access public
1518
 
         *
1519
 
         * @return array Meta clauses.
1520
 
         */
1521
 
        public function get_clauses() {
1522
 
                return $this->clauses;
1523
 
        }
1524
 
 
1525
 
        /**
1526
 
         * Identify an existing table alias that is compatible with the current
1527
 
         * query clause.
1528
 
         *
1529
 
         * We avoid unnecessary table joins by allowing each clause to look for
1530
 
         * an existing table alias that is compatible with the query that it
1531
 
         * needs to perform.
1532
 
         *
1533
 
         * An existing alias is compatible if (a) it is a sibling of `$clause`
1534
 
         * (ie, it's under the scope of the same relation), and (b) the combination
1535
 
         * of operator and relation between the clauses allows for a shared table join.
1536
 
         * In the case of {@see WP_Meta_Query}, this only applies to 'IN' clauses that
1537
 
         * are connected by the relation 'OR'.
1538
 
         *
1539
 
         * @since 4.1.0
1540
 
         * @access protected
1541
 
         *
1542
 
         * @param  array       $clause       Query clause.
1543
 
         * @param  array       $parent_query Parent query of $clause.
1544
 
         * @return string|bool Table alias if found, otherwise false.
1545
 
         */
1546
 
        protected function find_compatible_table_alias( $clause, $parent_query ) {
1547
 
                $alias = false;
1548
 
 
1549
 
                foreach ( $parent_query as $sibling ) {
1550
 
                        // If the sibling has no alias yet, there's nothing to check.
1551
 
                        if ( empty( $sibling['alias'] ) ) {
1552
 
                                continue;
1553
 
                        }
1554
 
 
1555
 
                        // We're only interested in siblings that are first-order clauses.
1556
 
                        if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
1557
 
                                continue;
1558
 
                        }
1559
 
 
1560
 
                        $compatible_compares = array();
1561
 
 
1562
 
                        // Clauses connected by OR can share joins as long as they have "positive" operators.
1563
 
                        if ( 'OR' === $parent_query['relation'] ) {
1564
 
                                $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
1565
 
 
1566
 
                        // Clauses joined by AND with "negative" operators share a join only if they also share a key.
1567
 
                        } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
1568
 
                                $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
1569
 
                        }
1570
 
 
1571
 
                        $clause_compare  = strtoupper( $clause['compare'] );
1572
 
                        $sibling_compare = strtoupper( $sibling['compare'] );
1573
 
                        if ( in_array( $clause_compare, $compatible_compares ) && in_array( $sibling_compare, $compatible_compares ) ) {
1574
 
                                $alias = $sibling['alias'];
1575
 
                                break;
1576
 
                        }
1577
 
                }
1578
 
 
1579
 
                /**
1580
 
                 * Filter the table alias identified as compatible with the current clause.
1581
 
                 *
1582
 
                 * @since 4.1.0
1583
 
                 *
1584
 
                 * @param string|bool $alias        Table alias, or false if none was found.
1585
 
                 * @param array       $clause       First-order query clause.
1586
 
                 * @param array       $parent_query Parent of $clause.
1587
 
                 * @param object      $this         WP_Meta_Query object.
1588
 
                 */
1589
 
                return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ) ;
1590
 
        }
1591
 
 
1592
 
        /**
1593
 
         * Checks whether the current query has any OR relations.
1594
 
         *
1595
 
         * In some cases, the presence of an OR relation somewhere in the query will require
1596
 
         * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current
1597
 
         * method can be used in these cases to determine whether such a clause is necessary.
1598
 
         *
1599
 
         * @since 4.3.0
1600
 
         *
1601
 
         * @return bool True if the query contains any `OR` relations, otherwise false.
1602
 
         */
1603
 
        public function has_or_relation() {
1604
 
                return $this->has_or_relation;
1605
 
        }
1606
 
}
1607
 
 
1608
 
/**
1609
871
 * Retrieve the name of the metadata table for the specified object type.
1610
872
 *
1611
873
 * @since 2.9.0