if ( ! empty( $sql_chunks['join'] ) ) { $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) ); } // Generate a single WHERE clause with proper brackets and indentation. if ( ! empty( $sql_chunks['where'] ) ) { $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')'; } return $sql; } /** * Generates SQL JOIN and WHERE clauses for a first-order query clause. * * "First-order" means that it's an array with a 'key' or 'value'. * * @since 4.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param array $clause Query clause (passed by reference). * @param array $parent_query Parent query array. * @param string $clause_key Optional. The array key used to name the clause in the original `$meta_query` * parameters. If not provided, a key will be generated automatically. * Default empty string. * @return array { * Array containing JOIN and WHERE SQL clauses to append to a first-order query. * * @type string[] $join Array of SQL fragments to append to the main JOIN clause. * @type string[] $where Array of SQL fragments to append to the main WHERE clause. * } */ public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) { global $wpdb; $sql_chunks = array( 'where' => array(), 'join' => array(), ); if ( isset( $clause['compare'] ) ) { $clause['compare'] = strtoupper( $clause['compare'] ); } else { $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '='; } $non_numeric_operators = array( '=', '!=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'EXISTS', 'NOT EXISTS', 'RLIKE', 'REGEXP', 'NOT REGEXP', ); $numeric_operators = array( '>', '>=', '<', '<=', 'BETWEEN', 'NOT BETWEEN', ); if ( ! in_array( $clause['compare'], $non_numeric_operators, true ) && ! in_array( $clause['compare'], $numeric_operators, true ) ) { $clause['compare'] = '='; } if ( isset( $clause['compare_key'] ) ) { $clause['compare_key'] = strtoupper( $clause['compare_key'] ); } else { $clause['compare_key'] = isset( $clause['key'] ) && is_array( $clause['key'] ) ? 'IN' : '='; } if ( ! in_array( $clause['compare_key'], $non_numeric_operators, true ) ) { $clause['compare_key'] = '='; } $meta_compare = $clause['compare']; $meta_compare_key = $clause['compare_key']; // First build the JOIN clause, if one is required. $join = ''; // We prefer to avoid joins if possible. Look for an existing join compatible with this clause. $alias = $this->find_compatible_table_alias( $clause, $parent_query ); if ( false === $alias ) { $i = count( $this->table_aliases ); $alias = $i ? 'mt' . $i : $this->meta_table; // JOIN clauses for NOT EXISTS have their own syntax. if ( 'NOT EXISTS' === $meta_compare ) { $join .= " LEFT JOIN $this->meta_table"; $join .= $i ? " AS $alias" : ''; if ( 'LIKE' === $meta_compare_key ) { $join .= $wpdb->prepare( " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key LIKE %s )", '%' . $wpdb->esc_like( $clause['key'] ) . '%' ); } else { $join .= $wpdb->prepare( " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] ); } // All other JOIN clauses. } else { $join .= " INNER JOIN $this->meta_table"; $join .= $i ? " AS $alias" : ''; $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )"; } $this->table_aliases[] = $alias; $sql_chunks['join'][] = $join; } // Save the alias to this clause, for future siblings to find. $clause['alias'] = $alias; // Determine the data type. $_meta_type = isset( $clause['type'] ) ? $clause['type'] : ''; $meta_type = $this->get_cast_for_type( $_meta_type ); $clause['cast'] = $meta_type; // Fallback for clause keys is the table alias. Key must be a string. if ( is_int( $clause_key ) || ! $clause_key ) { $clause_key = $clause['alias']; } // Ensure unique clause keys, so none are overwritten. $iterator = 1; $clause_key_base = $clause_key; while ( isset( $this->clauses[ $clause_key ] ) ) { $clause_key = $clause_key_base . '-' . $iterator; $iterator++; } // Store the clause in our flat array. $this->clauses[ $clause_key ] =& $clause; // Next, build the WHERE clause. // meta_key. if ( array_key_exists( 'key', $clause ) ) { if ( 'NOT EXISTS' === $meta_compare ) { $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL'; } else { /** * In joined clauses negative operators have to be nested into a * NOT EXISTS clause and flipped, to avoid returning records with * matching post IDs but different meta keys. Here we prepare the * nested clause. */ if ( in_array( $meta_compare_key, array( '!=', 'NOT IN', 'NOT LIKE', 'NOT EXISTS', 'NOT REGEXP' ), true ) ) { // Negative clauses may be reused. $i = count( $this->table_aliases ); $subquery_alias = $i ? 'mt' . $i : $this->meta_table; $this->table_aliases[] = $subquery_alias; $meta_compare_string_start = 'NOT EXISTS ('; $meta_compare_string_start .= "SELECT 1 FROM $wpdb->postmeta $subquery_alias "; $meta_compare_string_start .= "WHERE $subquery_alias.post_ID = $alias.post_ID "; $meta_compare_string_end = 'LIMIT 1'; $meta_compare_string_end .= ')'; } switch ( $meta_compare_key ) { case '=': case 'EXISTS': $where = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'LIKE': $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%'; $where = $wpdb->prepare( "$alias.meta_key LIKE %s", $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'IN': $meta_compare_string = "$alias.meta_key IN (" . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ')'; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'RLIKE': case 'REGEXP': $operator = $meta_compare_key; if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) { $cast = 'BINARY'; $meta_key = "CAST($alias.meta_key AS BINARY)"; } else { $cast = ''; $meta_key = "$alias.meta_key"; } $where = $wpdb->prepare( "$meta_key $operator $cast %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case '!=': case 'NOT EXISTS': $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key = %s " . $meta_compare_string_end; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'NOT LIKE': $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key LIKE %s " . $meta_compare_string_end; $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%'; $where = $wpdb->prepare( $meta_compare_string, $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'NOT IN': $array_subclause = '(' . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ') '; $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key IN " . $array_subclause . $meta_compare_string_end; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'NOT REGEXP': $operator = $meta_compare_key; if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) { $cast = 'BINARY'; $meta_key = "CAST($subquery_alias.meta_key AS BINARY)"; } else { $cast = ''; $meta_key = "$subquery_alias.meta_key"; } $meta_compare_string = $meta_compare_string_start . "AND $meta_key REGEXP $cast %s " . $meta_compare_string_end; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; } $sql_chunks['where'][] = $where; } } // meta_value. if ( array_key_exists( 'value', $clause ) ) { $meta_value = $clause['value']; if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) { if ( ! is_array( $meta_value ) ) { $meta_value = preg_split( '/[,\s]+/', $meta_value ); } } elseif ( is_string( $meta_value ) ) { $meta_value = trim( $meta_value ); } switch ( $meta_compare ) { case 'IN': case 'NOT IN': $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')'; $where = $wpdb->prepare( $meta_compare_string, $meta_value ); break; case 'BETWEEN': case 'NOT BETWEEN': $where = $wpdb->prepare( '%s AND %s', $meta_value[0], $meta_value[1] ); break; case 'LIKE': case 'NOT LIKE': $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%'; $where = $wpdb->prepare( '%s', $meta_value ); break; // EXISTS with a value is interpreted as '='. case 'EXISTS': $meta_compare = '='; $where = $wpdb->prepare( '%s', $meta_value ); break; // 'value' is ignored for NOT EXISTS. case 'NOT EXISTS': $where = ''; break; default: $where = $wpdb->prepare( '%s', $meta_value ); break; } if ( $where ) { if ( 'CHAR' === $meta_type ) { $sql_chunks['where'][] = "$alias.meta_value {$meta_compare} {$where}"; } else { $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}"; } } } /* * Multiple WHERE clauses (for meta_key and meta_value) should * be joined in parentheses. */ if ( 1 < count( $sql_chunks['where'] ) ) { $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' ); } return $sql_chunks; } /** * Gets a flattened list of sanitized meta clauses. * * This array should be used for clause lookup, as when the table alias and CAST type must be determined for * a value of 'orderby' corresponding to a meta clause. * * @since 4.2.0 * * @return array Meta clauses. */ public function get_clauses() { return $this->clauses; } /** * Identifies an existing table alias that is compatible with the current * query clause. * * We avoid unnecessary table joins by allowing each clause to look for * an existing table alias that is compatible with the query that it * needs to perform. * * An existing alias is compatible if (a) it is a sibling of `$clause` * (ie, it's under the scope of the same relation), and (b) the combination * of operator and relation between the clauses allows for a shared table join. * In the case of WP_Meta_Query, this only applies to 'IN' clauses that are * connected by the relation 'OR'. * * @since 4.1.0 * * @param array $clause Query clause. * @param array $parent_query Parent query of $clause. * @return string|false Table alias if found, otherwise false. */ protected function find_compatible_table_alias( $clause, $parent_query ) { $alias = false; foreach ( $parent_query as $sibling ) { // If the sibling has no alias yet, there's nothing to check. if ( empty( $sibling['alias'] ) ) { continue; } // We're only interested in siblings that are first-order clauses. if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) { continue; } $compatible_compares = array(); // Clauses connected by OR can share joins as long as they have "positive" operators. if ( 'OR' === $parent_query['relation'] ) { $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' ); // Clauses joined by AND with "negative" operators share a join only if they also share a key. } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) { $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' ); } $clause_compare = strtoupper( $clause['compare'] ); $sibling_compare = strtoupper( $sibling['compare'] ); if ( in_array( $clause_compare, $compatible_compares, true ) && in_array( $sibling_compare, $compatible_compares, true ) ) { $alias = preg_replace( '/\W/', '_', $sibling['alias'] ); break; } } /** * Filters the table alias identified as compatible with the current clause. * * @since 4.1.0 * * @param string|false $alias Table alias, or false if none was found. * @param array $clause First-order query clause. * @param array $parent_query Parent of $clause. * @param WP_Meta_Query $query WP_Meta_Query object. */ return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ); } /** * Checks whether the current query has any OR relations. * * In some cases, the presence of an OR relation somewhere in the query will require * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current * method can be used in these cases to determine whether such a clause is necessary. * * @since 4.3.0 * * @return bool True if the query contains any `OR` relations, otherwise false. */ public function has_or_relation() { return $this->has_or_relation; } } ); if ( false === $open || false === $close ) { continue; // Go to next attribute. Square braces will be escaped at end of loop. } $double = strpos( $attr, '"' ); $single = strpos( $attr, "'" ); if ( ( false === $single || $open < $single ) && ( false === $double || $open < $double ) ) { /* * $attr like '[shortcode]' or 'name = [shortcode]' implies unfiltered_html. * In this specific situation we assume KSES did not run because the input * was written by an administrator, so we should avoid changing the output * and we do not need to run KSES here. */ $attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr ); } else { /* * $attr like 'name = "[shortcode]"' or "name = '[shortcode]'". * We do not know if $content was unfiltered. Assume KSES ran before shortcodes. */ $count = 0; $new_attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr, -1, $count ); if ( $count > 0 ) { // Sanitize the shortcode output using KSES. $new_attr = wp_kses_one_attr( $new_attr, $elname ); if ( '' !== trim( $new_attr ) ) { // The shortcode is safe to use now. $attr = $new_attr; } } } } $element = $front . implode( '', $attributes ) . $back; // Now encode any remaining '[' or ']' chars. $element = strtr( $element, $trans ); } $content = implode( '', $textarr ); return $content; } /** * Removes placeholders added by do_shortcodes_in_html_tags(). * * @since 4.2.3 * * @param string $content Content to search for placeholders. * @return string Content with placeholders removed. */ function unescape_invalid_shortcodes( $content ) { // Clean up entire string, avoids re-parsing HTML. $trans = array( '[' => '[', ']' => ']', ); $content = strtr( $content, $trans ); return $content; } /** * Retrieves the shortcode attributes regex. * * @since 4.4.0 * * @return string The shortcode attribute regular expression. */ function get_shortcode_atts_regex() { return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|\'([^\']*)\'(?:\s|$)|(\S+)(?:\s|$)/'; } /** * Retrieves all attributes from the shortcodes tag. * * The attributes list has the attribute name as the key and the value of the * attribute as the value in the key/value pair. This allows for easier * retrieval of the attributes, since all attributes have to be known. * * @since 2.5.0 * * @param string $text Shortcode arguments list. * @return array|string Array of attribute values keyed by attribute name. * Returns empty array if there are no attributes. * Returns the original arguments string if it cannot be parsed. */ function shortcode_parse_atts( $text ) { $atts = array(); $pattern = get_shortcode_atts_regex(); $text = preg_replace( "/[\x{00a0}\x{200b}]+/u", ' ', $text ); if ( preg_match_all( $pattern, $text, $match, PREG_SET_ORDER ) ) { foreach ( $match as $m ) { if ( ! empty( $m[1] ) ) { $atts[ strtolower( $m[1] ) ] = stripcslashes( $m[2] ); } elseif ( ! empty( $m[3] ) ) { $atts[ strtolower( $m[3] ) ] = stripcslashes( $m[4] ); } elseif ( ! empty( $m[5] ) ) { $atts[ strtolower( $m[5] ) ] = stripcslashes( $m[6] ); } elseif ( isset( $m[7] ) && strlen( $m[7] ) ) { $atts[] = stripcslashes( $m[7] ); } elseif ( isset( $m[8] ) && strlen( $m[8] ) ) { $atts[] = stripcslashes( $m[8] ); } elseif ( isset( $m[9] ) ) { $atts[] = stripcslashes( $m[9] ); } } // Reject any unclosed HTML elements. foreach ( $atts as &$value ) { if ( str_contains( $value, '<' ) ) { if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) { $value = ''; } } } } else { $atts = ltrim( $text ); } return $atts; } /** * Combines user attributes with known attributes and fill in defaults when needed. * * The pairs should be considered to be all of the attributes which are * supported by the caller and given as a list. The returned attributes will * only contain the attributes in the $pairs list. * * If the $atts list has unsupported attributes, then they will be ignored and * removed from the final returned list. * * @since 2.5.0 * * @param array $pairs Entire list of supported attributes and their defaults. * @param array $atts User defined attributes in shortcode tag. * @param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering * @return array Combined and filtered attribute list. */ function shortcode_atts( $pairs, $atts, $shortcode = '' ) { $atts = (array) $atts; $out = array(); foreach ( $pairs as $name => $default ) { if ( array_key_exists( $name, $atts ) ) { $out[ $name ] = $atts[ $name ]; } else { $out[ $name ] = $default; } } if ( $shortcode ) { /** * Filters shortcode attributes. * * If the third parameter of the shortcode_atts() function is present then this filter is available. * The third parameter, $shortcode, is the name of the shortcode. * * @since 3.6.0 * @since 4.4.0 Added the `$shortcode` parameter. * * @param array $out The output array of shortcode attributes. * @param array $pairs The supported attributes and their defaults. * @param array $atts The user defined shortcode attributes. * @param string $shortcode The shortcode name. */ $out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts, $shortcode ); } return $out; } /** * Removes all shortcode tags from the given content. * * @since 2.5.0 * * @global array $shortcode_tags * * @param string $content Content to remove shortcode tags. * @return string Content without shortcode tags. */ function strip_shortcodes( $content ) { global $shortcode_tags; if ( ! str_contains( $content, '[' ) ) { return $content; } if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) { return $content; } // Find all registered tag names in $content. preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches ); $tags_to_remove = array_keys( $shortcode_tags ); /** * Filters the list of shortcode tags to remove from the content. * * @since 4.7.0 * * @param array $tags_to_remove Array of shortcode tags to remove. * @param string $content Content shortcodes are being removed from. */ $tags_to_remove = apply_filters( 'strip_shortcodes_tagnames', $tags_to_remove, $content ); $tagnames = array_intersect( $tags_to_remove, $matches[1] ); if ( empty( $tagnames ) ) { return $content; } $content = do_shortcodes_in_html_tags( $content, true, $tagnames ); $pattern = get_shortcode_regex( $tagnames ); $content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content ); // Always restore square braces so we don't break things like