localize foreach ( (array) $data as $key => $value ) { if ( is_string($value) ) { $data[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8'); } } if ( $safe_mode ) { // If the inline script was merged or moved by a minify, the object may already exist, so keep the properties $script = "window.$object_name = typeof window.$object_name !== 'undefined' ? window.$object_name : {};"; foreach ( (array) $data as $key => $value ) { if ( is_int($value) || is_float($value) || self::isPlainDecimal($value) ) { $script .= " window.$object_name.$key = $value;"; } elseif ( is_bool($value) ) { if ( $value ) { $script .= " window.$object_name.$key = true;"; } else { $script .= " window.$object_name.$key = false;"; } } else { $script .= " window.$object_name.$key = " . wp_json_encode($value) . ';'; } } } else { $script = "var $object_name = " . wp_json_encode( $data ) . ';'; } wp_add_inline_script($handle, $script, $position); } /** * A string that may print without quotes in safe mode: a plain decimal ("1", "-2", "0.25"), which * JavaScript reads as the number PHP sees. Any other string is_numeric() accepts stays a string: * "0123e45678" (a nonce can look like that) is a legacy octal literal followed by "e" in JavaScript, * a syntax error that loses the whole inline script, and "1e5", "0123" or " 5" become another * number or none (#177; php-utils 1.0.8 Script::objectToInlineScript() does the same). * * @param mixed $value */ private static function isPlainDecimal( $value ): bool { return is_string($value) && preg_match('/^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/D', $value) === 1; } /** * Prepares the headers for the ajax request * * @param string $content_type */ public static function prepareAjaxHeaders( $content_type = 'text/plain' ) { if ( !headers_sent() ) { header('Content-Type: ' . $content_type); } } /** * The home URL the front-end search redirects and live loader requests build on * * @return string */ public static function getHomeUrl(): string { if ( is_admin() || !function_exists('PLL') ) { return home_url('/'); } return PLL()->links->get_home_url('', true); } /** * Removes gutenberg blocks from the given string by block names array * * @param string $content * @param string[] $block_names * @return string */ public static function removeGutenbergBlocks( string $content, array $block_names = array( 'core-embed/*' ) ) { foreach ( $block_names as &$block_name ) { $block_name = str_replace('*', 'AAAAAAAAAAAAAAA', $block_name); $block_name = preg_quote($block_name, ''); $block_name = str_replace('AAAAAAAAAAAAAAA', '.*?', $block_name); } $block_names = implode('|', $block_names); // preg_quote does not escape '/' by default - use the '~' or '#' as the regex delimiter return preg_replace( "~(.*?)~s", '', $content ); } /** * Generates a string reverse, support multibyte strings, plus fallback if mbstring if not avail * * @param string $str * @return string */ public static function reverseString( string $str ) { if ( function_exists('mb_detect_encoding') && function_exists('mb_strlen') && function_exists('mb_substr') ) { // Using mbstring $encoding = mb_detect_encoding($str); $length = mb_strlen($str, $encoding); $reversed = ''; while ( $length-- > 0 ) { $reversed .= mb_substr($str, $length, 1, $encoding); } return $reversed; } else { // Good old regex method, still supporting fully UFT8 preg_match_all('/./us', $str, $ar); return implode(array_reverse($ar[0])); } } /** * Clears and trims a search phrase from extra slashes and extra space characters * * @param string $s * @return mixed */ public static function clear_phrase( string $s ) { return preg_replace( '/\s+/', ' ', trim(stripcslashes($s)) ); } /** * Helper method to be used before printing the font styles. Converts font families to apostrophed versions. * * @param string $font * @return mixed */ public static function font( $font ) { preg_match('/family:(.*?);/', $font, $fonts); if ( isset($fonts[1]) ) { $f = explode(',', str_replace(array( '"', "'" ), '', $fonts[1])); foreach ( $f as &$_f ) { if ( trim($_f) !== 'inherit' ) { $_f = '"' . trim($_f) . '"'; } else { $_f = trim($_f); } } $f = implode(',', $f); return preg_replace('/family:(.*?);/', 'family:' . $f . ';', $font); } else { return $font; } } /** * Translates search data and options to query arguments to use with ASL_Query * * @param int $search_id * @param array $o * @param array $args * @return mixed */ public static function toQueryArgs( int $search_id, array $o = array(), array $args = array() ): array { // Always return an emtpy array if something goes wrong if ( !wd_asl()->instances->exists($search_id) ) { return array(); } // The options the search reads, nothing else: the results cache keys the response on exactly these $o = array_intersect_key($o, array_flip(RequestOptions::KEYS)); $search = wd_asl()->instances->get(0); $sd = $search['data']; $orm = CompatibilityOptions::instance(); $exclude_post_ids = array_unique(explode(',', str_replace(' ', '', $sd['excludeposts']))); foreach ( $exclude_post_ids as $k =>$v ) { if ( $v === '' ) { unset($exclude_post_ids[ $k ]); } else { $exclude_post_ids[ $k ] = intval($v); } } // ---------------------------------------------------------------- // 1. CPT // ---------------------------------------------------------------- $args = array_merge( $args, array( '_sd' => $sd, // Search Data 'keyword_logic' => $sd['keyword_logic'], 'secondary_logic' => 'none', 'post_not_in' => $exclude_post_ids, 'post_in' => array(), 'post_primary_order' => $sd['orderby_primary'], 'post_secondary_order' => $sd['orderby_secondary'], '_db_force_case' => $orm->db_force_case->value, '_db_force_utf8_like' => $orm->db_force_utf8_like->value, '_db_force_unicode' => $orm->db_force_unicode->value, // LIMITS 'posts_limit' => intval($sd['maxresults']), ) ); $args['posts_limit'] = $args['posts_limit'] <= 0 ? 10 : $args['posts_limit']; // A request language only counts when its plugin is active and it is one of its languages $args['_qtranslate_lang'] = RequestLanguage::qtranslate($o['qtranslate_lang'] ?? ''); if ( $sd['polylang_compatibility'] ) { $polylang_lang = RequestLanguage::polylang($o['polylang_lang'] ?? ''); $args['_polylang_lang'] = $polylang_lang !== '' ? $polylang_lang : ( function_exists('pll_current_language') ? (string) pll_current_language() : '' ); } $args['_exact_matches'] = isset($o['asl_gen']) && is_array($o['asl_gen']) && in_array('exact', $o['asl_gen'], true); $args['_exact_match_location'] = $sd['exact_match_location']; /*----------------------- Meta key order ------------------------*/ if ( strpos($sd['orderby_primary'], 'customfp') !== false ) { if ( !empty($sd['orderby_primary_cf']) ) { $args['_post_primary_order_metakey'] = $sd['orderby_primary_cf']; $args['post_primary_order_metatype'] = $sd['orderby_primary_cf_type']; } } if ( strpos($sd['orderby_secondary'], 'customfs') !== false ) { if ( !empty($sd['orderby_secondary_cf']) ) { $args['_post_secondary_order_metakey'] = $sd['orderby_secondary_cf']; $args['post_secondary_order_metatype'] = $sd['orderby_secondary_cf_type']; } } /*------------------------- Statuses ----------------------------*/ $args['post_status'] = explode(',', str_replace(' ', '', $sd['post_status'])); /*--------------------- Password protected ----------------------*/ $args['has_password'] = (bool) $sd['show_password_protected_posts']; /*----------------------- Gather Types --------------------------*/ // The front-end can only pick from the configured types and the front-end selector types $allowed_types = isset( $sd['customtypes'] ) && is_array($sd['customtypes']) ? $sd['customtypes'] : array(); if ( isset( $sd['selected-showcustomtypes'] ) && is_array($sd['selected-showcustomtypes']) ) { $allowed_types = array_merge($allowed_types, array_column($sd['selected-showcustomtypes'], 0)); } $customset = array(); if ( isset( $o['customset'] ) && is_array($o['customset']) ) { $customset = array_values(array_intersect(array_filter($o['customset'], 'is_string'), $allowed_types)); } $args['post_type'] = array(); if ( count( $customset ) > 0 ) { $args['post_type'] = $customset; } elseif ( isset( $sd['customtypes'] ) && is_array($sd['customtypes']) && count( $sd['customtypes'] ) > 0 ) { $args['post_type'] = array_merge( $args['post_type'], $sd['customtypes'] ); } /*--------------------- OTHER FILTER RELATED --------------------*/ $args['filters_changed'] = isset($o['filters_changed']) && is_scalar($o['filters_changed']) ? $o['filters_changed'] : ( $args['filters_changed'] ?? false ); $args['filters_initial'] = isset($o['filters_initial']) && is_scalar($o['filters_initial']) ? $o['filters_initial'] : ( $args['filters_initial'] ?? true ); /*--------------------- GENERAL FIELDS --------------------------*/ $args['search_type'] = array(); $args['post_fields'] = array(); if ( $sd['searchinterms'] ) { $args['post_fields'][] = 'terms'; } if ( isset($o['asl_gen']) && is_array($o['asl_gen']) ) { foreach ( array( 'title', 'content', 'excerpt' ) as $field ) { // Only a field the admin enabled, or the visitor sees the checkbox of, can be searched. The excerpt // checkbox is never shown (its wrapper is always hidden), so only the admin can enable the field $tickable = $sd[ 'searchin' . $field ] || ( $field !== 'excerpt' && $sd['show_frontend_search_settings'] && $sd[ 'showsearchin' . $field ] ); if ( $tickable && in_array($field, $o['asl_gen'], true) ) { $args['post_fields'][] = $field; } } } else { if ( $sd['searchintitle'] ) { $args['post_fields'][] = 'title'; } if ( $sd['searchincontent'] ) { $args['post_fields'][] = 'content'; } if ( $sd['searchinexcerpt'] ) { $args['post_fields'][] = 'excerpt'; } } if ( $sd['search_in_ids'] ) { $args['post_fields'][] = 'ids'; } if ( $sd['search_in_permalinks'] ) { $args['post_fields'][] = 'permalink'; } /*--------------------- CUSTOM FIELDS ---------------------------*/ $args['post_custom_fields_all'] = $sd['search_all_cf']; $args['post_custom_fields'] = $sd['selected-customfields'] ?? array(); if ( count($args['post_fields']) > 0 || $args['post_custom_fields_all'] || count($args['post_custom_fields']) > 0 || count($args['post_type']) > 0 ) { $args['search_type'][] = 'cpt'; } /*-------------------------- WPML -------------------------------*/ if ( $sd['wpml_compatibility'] ) { $wpml_lang = RequestLanguage::wpml($o['wpml_lang'] ?? ''); if ( $wpml_lang !== '' && $args['_ajax_search'] ) { $args['_wpml_lang'] = $wpml_lang; } elseif ( defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE !== '' && defined('ICL_SITEPRESS_VERSION') ) { $args['_wpml_lang'] = ICL_LANGUAGE_CODE; } /** * Switching the language will resolve issues with get_terms(..) and other functions * Otherwise wrong taxonomy terms would be returned etc.. */ global $sitepress; if ( is_object($sitepress) && method_exists($sitepress, 'switch_lang') ) { $sitepress->switch_lang($args['_wpml_lang']); } $args['wpml_display_missing_translations'] = $sd['wpml_display_missing_translations']; } /*-------------------- Content, Excerpt -------------------------*/ $args['_post_get_content'] = (bool) $sd['showdescription']; $args['_post_get_excerpt'] = ( $sd['primary_titlefield'] || $sd['secondary_titlefield'] || $sd['primary_descriptionfield'] || $sd['secondary_descriptionfield'] ); // WooCommerce - Exclude out of stock if ( $sd['woo_exclude_outofstock'] ) { $args['post_meta_filter'][] = array( 'key' => '_stock_status', 'value' => 'instock', 'operator' => 'ELIKE', 'allow_missing' => true, ); } /*---------------------- Taxonomy Terms -------------------------*/ $args['post_tax_filter'] = self::toQueryArgs_Taxonomies($sd, $o); // ---------------------------------------------------------------- // X. MISC FIXES // ---------------------------------------------------------------- $args['woo_currency'] = isset($o['woo_currency']) && is_string($o['woo_currency']) ? $o['woo_currency'] : ( function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '' ); $args['_page_id'] = isset($o['current_page_id']) && is_scalar($o['current_page_id']) ? intval($o['current_page_id']) : intval($args['_page_id'] ?? 0); // Reset search type and post types for the WooCommerce search results page. The page URL is not part of // the form data an ajax request posts: the ajax search ignores it, or anyone could add it to the ajax URL // and have a different response cached under the key the form's own requests compute if ( !( $args['_ajax_search'] ?? false ) && isset($_GET['post_type']) && $_GET['post_type'] === 'product' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $old_ptype = $args['post_type']; $args['post_type'] = array(); if ( in_array('product', $old_ptype, true) ) { $args['post_type'][] = 'product'; } if ( in_array('product_variation', $old_ptype, true) ) { $args['post_type'][] = 'product_variation'; } } // Restrict to parent posts from SHORTCODE arguments if ( isset($o['post_parent']) && is_array($o['post_parent']) ) { $args['post_parent'] = array_map( 'intval', array_filter( $o['post_parent'], 'is_numeric' ) ); } // ---------------------------------------------------------------- return $args; } /** * Converts search data and options to Taxonomy Term query argument arrays to use with ASL_Query * * @param mixed $sd * @param mixed $o * @return array */ private static function toQueryArgs_Taxonomies( $sd, array $o = array() ) { $ret = array(); $term_logic = 'and'; $exclude_categories = array(); $categoryset = isset($o['categoryset']) && is_array($o['categoryset']) ? array_map('intval', array_filter($o['categoryset'], 'is_scalar')) : array(); $sd['selected-exsearchincategories'] = w_isset_def( $sd['selected-exsearchincategories'], array() ); $sd['selected-excludecategories'] = w_isset_def( $sd['selected-excludecategories'], array() ); if ( count( $sd['selected-exsearchincategories'] ) > 0 || count( $sd['selected-excludecategories'] ) > 0 || count( $categoryset ) > 0 || $sd['showsearchincategories'] ) { // If the category settings are invisible, ignore the excluded frontend categories, reset to empty array if ( !$sd['showsearchincategories'] ) { $sd['selected-exsearchincategories'] = array(); } $_all_cat = get_terms( array( 'taxonomy' => 'category', 'fields' => 'ids', ) ); if ( is_wp_error($_all_cat) ) { $_all_cat = array(); } $_needed_cat = array_diff( $_all_cat, $sd['selected-exsearchincategories'] ); $_needed_cat = ! is_array( $_needed_cat ) ? array() : $_needed_cat; if ( $sd['showsearchincategories'] && isset($o['categoryset']) ) { // Only the categories the front-end filter shows can be ticked, a hidden category stays as the admin set it $categoryset = array_intersect($categoryset, $_needed_cat); $exclude_categories = array_diff( array_merge( $_needed_cat, $sd['selected-excludecategories'] ), $categoryset ); } else // ..if the settings is not visible, then only the excluded categories count { $exclude_categories = $sd['selected-excludecategories']; } } $exclude_terms = array(); $exclude_terms = array_unique( array_merge( $exclude_categories, $exclude_terms ) ); if ( count($exclude_terms) > 0 ) { $ret[] = array( 'taxonomy' => 'category', 'include' => array(), // phpcs:ignore 'exclude' => array_map('intval', $exclude_terms), 'logic' => $term_logic, '_termset' => $categoryset, '_is_checkbox' => true, 'allow_empty' => true, ); } // Woocommerce - Exclude hidden and catalog if ( class_exists('WooCommerce') && ( $sd['exclude_woo_hidden'] || $sd['exclude_woo_catalog'] ) ) { // Check if this is version > 3.0 if ( asl_woo_version_check('3.0') ) { $exclude = array(); if ( $sd['exclude_woo_hidden'] ) { $exclude[] = 'exclude-from-search'; } if ( $sd['exclude_woo_catalog'] ) { $exclude[] = 'exclude-from-catalog'; } if ( !empty($exclude) ) { $_t = get_terms( array( 'taxonomy' => 'product_visibility', 'slug' => $exclude, 'hide_empty' => 0, 'fields' => 'ids', ) ); if ( !is_wp_error($_t) && count($_t) > 0 ) { $ret[] = array( 'taxonomy' => 'product_visibility', 'exclude' => $_t, // phpcs:ignore 'allow_empty' => true, ); } } } } return $ret; } } }