'utf-8' ] ); * * `is_utf8_charset` should be used outside of this file. * * @ignore * @since 6.6.1 * * @param string $charset_slug Slug representing a text character encoding, or "charset". * E.g. "UTF-8", "Windows-1252", "ISO-8859-1", "SJIS". * * @return bool Whether the slug represents the UTF-8 encoding. */ function _is_utf8_charset( $charset_slug ) { if ( ! is_string( $charset_slug ) ) { return false; } return ( 0 === strcasecmp( 'UTF-8', $charset_slug ) || 0 === strcasecmp( 'UTF8', $charset_slug ) ); } if ( ! function_exists( 'mb_substr' ) ) : /** * Compat function to mimic mb_substr(). * * @ignore * @since 3.2.0 * * @see _mb_substr() * * @param string $string The string to extract the substring from. * @param int $start Position to being extraction from in `$string`. * @param int|null $length Optional. Maximum number of characters to extract from `$string`. * Default null. * @param string|null $encoding Optional. Character encoding to use. Default null. * @return string Extracted substring. */ function mb_substr( $string, $start, $length = null, $encoding = null ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound return _mb_substr( $string, $start, $length, $encoding ); } endif; /** * Internal compat function to mimic mb_substr(). * * Only understands UTF-8 and 8bit. All other character sets will be treated as 8bit. * For `$encoding === UTF-8`, the `$str` input is expected to be a valid UTF-8 byte * sequence. The behavior of this function for invalid inputs is undefined. * * @ignore * @since 3.2.0 * * @param string $str The string to extract the substring from. * @param int $start Position to being extraction from in `$str`. * @param int|null $length Optional. Maximum number of characters to extract from `$str`. * Default null. * @param string|null $encoding Optional. Character encoding to use. Default null. * @return string Extracted substring. */ function _mb_substr( $str, $start, $length = null, $encoding = null ) { if ( null === $str ) { return ''; } if ( null === $encoding ) { $encoding = get_option( 'blog_charset' ); } /* * The solution below works only for UTF-8, so in case of a different * charset just use built-in substr(). */ if ( ! _is_utf8_charset( $encoding ) ) { return is_null( $length ) ? substr( $str, $start ) : substr( $str, $start, $length ); } if ( _wp_can_use_pcre_u() ) { // Use the regex unicode support to separate the UTF-8 characters into an array. preg_match_all( '/./us', $str, $match ); $chars = is_null( $length ) ? array_slice( $match[0], $start ) : array_slice( $match[0], $start, $length ); return implode( '', $chars ); } $regex = '/( [\x00-\x7F] # single-byte sequences 0xxxxxxx | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2 | [\xE1-\xEC][\x80-\xBF]{2} | \xED[\x80-\x9F][\x80-\xBF] | [\xEE-\xEF][\x80-\xBF]{2} | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3 | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2} )/x'; // Start with 1 element instead of 0 since the first thing we do is pop. $chars = array( '' ); do { // We had some string left over from the last round, but we counted it in that last round. array_pop( $chars ); /* * Split by UTF-8 character, limit to 1000 characters (last array element will contain * the rest of the string). */ $pieces = preg_split( $regex, $str, 1000, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); $chars = array_merge( $chars, $pieces ); // If there's anything left over, repeat the loop. } while ( count( $pieces ) > 1 && $str = array_pop( $pieces ) ); return implode( '', array_slice( $chars, $start, $length ) ); } if ( ! function_exists( 'mb_strlen' ) ) : /** * Compat function to mimic mb_strlen(). * * @ignore * @since 4.2.0 * * @see _mb_strlen() * * @param string $string The string to retrieve the character length from. * @param string|null $encoding Optional. Character encoding to use. Default null. * @return int String length of `$string`. */ function mb_strlen( $string, $encoding = null ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound return _mb_strlen( $string, $encoding ); } endif; /** * Internal compat function to mimic mb_strlen(). * * Only understands UTF-8 and 8bit. All other character sets will be treated as 8bit. * For `$encoding === UTF-8`, the `$str` input is expected to be a valid UTF-8 byte * sequence. The behavior of this function for invalid inputs is undefined. * * @ignore * @since 4.2.0 * * @param string $str The string to retrieve the character length from. * @param string|null $encoding Optional. Character encoding to use. Default null. * @return int String length of `$str`. */ function _mb_strlen( $str, $encoding = null ) { if ( null === $encoding ) { $encoding = get_option( 'blog_charset' ); } /* * The solution below works only for UTF-8, so in case of a different charset * just use built-in strlen(). */ if ( ! _is_utf8_charset( $encoding ) ) { return strlen( $str ); } if ( _wp_can_use_pcre_u() ) { // Use the regex unicode support to separate the UTF-8 characters into an array. preg_match_all( '/./us', $str, $match ); return count( $match[0] ); } $regex = '/(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2 | [\xE1-\xEC][\x80-\xBF]{2} | \xED[\x80-\x9F][\x80-\xBF] | [\xEE-\xEF][\x80-\xBF]{2} | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3 | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2} )/x'; // Start at 1 instead of 0 since the first thing we do is decrement. $count = 1; do { // We had some string left over from the last round, but we counted it in that last round. --$count; /* * Split by UTF-8 character, limit to 1000 characters (last array element will contain * the rest of the string). */ $pieces = preg_split( $regex, $str, 1000 ); // Increment. $count += count( $pieces ); // If there's anything left over, repeat the loop. } while ( $str = array_pop( $pieces ) ); // Fencepost: preg_split() always returns one extra item in the array. return --$count; } // sodium_crypto_box() was introduced in PHP 7.2. if ( ! function_exists( 'sodium_crypto_box' ) ) { require ABSPATH . WPINC . '/sodium_compat/autoload.php'; } if ( ! function_exists( 'is_countable' ) ) { /** * Polyfill for is_countable() function added in PHP 7.3. * * Verify that the content of a variable is an array or an object * implementing the Countable interface. * * @since 4.9.6 * * @param mixed $value The value to check. * @return bool True if `$value` is countable, false otherwise. */ function is_countable( $value ) { return ( is_array( $value ) || $value instanceof Countable || $value instanceof SimpleXMLElement || $value instanceof ResourceBundle ); } } if ( ! function_exists( 'array_key_first' ) ) { /** * Polyfill for array_key_first() function added in PHP 7.3. * * Get the first key of the given array without affecting * the internal array pointer. * * @since 5.9.0 * * @param array $array An array. * @return string|int|null The first key of array if the array * is not empty; `null` otherwise. */ function array_key_first( array $array ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound if ( empty( $array ) ) { return null; } foreach ( $array as $key => $value ) { return $key; } } } if ( ! function_exists( 'array_key_last' ) ) { /** * Polyfill for `array_key_last()` function added in PHP 7.3. * * Get the last key of the given array without affecting the * internal array pointer. * * @since 5.9.0 * * @param array $array An array. * @return string|int|null The last key of array if the array *. is not empty; `null` otherwise. */ function array_key_last( array $array ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound if ( empty( $array ) ) { return null; } end( $array ); return key( $array ); } } if ( ! function_exists( 'array_is_list' ) ) { /** * Polyfill for `array_is_list()` function added in PHP 8.1. * * Determines if the given array is a list. * * An array is considered a list if its keys consist of consecutive numbers from 0 to count($array)-1. * * @see https://github.com/symfony/polyfill-php81/tree/main * * @since 6.5.0 * * @param array $arr The array being evaluated. * @return bool True if array is a list, false otherwise. */ function array_is_list( $arr ) { if ( ( array() === $arr ) || ( array_values( $arr ) === $arr ) ) { return true; } $next_key = -1; foreach ( $arr as $k => $v ) { if ( ++$next_key !== $k ) { return false; } } return true; } } if ( ! function_exists( 'str_contains' ) ) { /** * Polyfill for `str_contains()` function added in PHP 8.0. * * Performs a case-sensitive check indicating if needle is * contained in haystack. * * @since 5.9.0 * * @param string $haystack The string to search in. * @param string $needle The substring to search for in the `$haystack`. * @return bool True if `$needle` is in `$haystack`, otherwise false. */ function str_contains( $haystack, $needle ) { if ( '' === $needle ) { return true; } return false !== strpos( $haystack, $needle ); } } if ( ! function_exists( 'str_starts_with' ) ) { /** * Polyfill for `str_starts_with()` function added in PHP 8.0. * * Performs a case-sensitive check indicating if * the haystack begins with needle. * * @since 5.9.0 * * @param string $haystack The string to search in. * @param string $needle The substring to search for in the `$haystack`. * @return bool True if `$haystack` starts with `$needle`, otherwise false. */ function str_starts_with( $haystack, $needle ) { if ( '' === $needle ) { return true; } return 0 === strpos( $haystack, $needle ); } } if ( ! function_exists( 'str_ends_with' ) ) { /** * Polyfill for `str_ends_with()` function added in PHP 8.0. * * Performs a case-sensitive check indicating if * the haystack ends with needle. * * @since 5.9.0 * * @param string $haystack The string to search in. * @param string $needle The substring to search for in the `$haystack`. * @return bool True if `$haystack` ends with `$needle`, otherwise false. */ function str_ends_with( $haystack, $needle ) { if ( '' === $haystack ) { return '' === $needle; } $len = strlen( $needle ); return substr( $haystack, -$len, $len ) === $needle; } } if ( ! function_exists( 'array_find' ) ) { /** * Polyfill for `array_find()` function added in PHP 8.4. * * Searches an array for the first element that passes a given callback. * * @since 6.8.0 * * @param array $array The array to search. * @param callable $callback The callback to run for each element. * @return mixed|null The first element in the array that passes the `$callback`, otherwise null. */ function array_find( array $array, callable $callback ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound foreach ( $array adynamicOptions->searchAppearance->postTypes->attachment->redirectAttachmentUrls ) ) { return []; } // Set defaults. $fields = '`p`.`ID`, `p`.`post_title`, `p`.`post_content`, `p`.`post_excerpt`, `p`.`post_type`, `p`.`post_password`, '; $fields .= '`p`.`post_parent`, `p`.`post_date_gmt`, `p`.`post_modified_gmt`, `ap`.`priority`, `ap`.`frequency`'; $maxAge = ''; if ( ! aioseo()->sitemap->helpers->excludeImages() ) { $fields .= ', `ap`.`images`'; } // Order by highest priority first (highest priority at the top), // then by post modified date (most recently updated at the top). $orderBy = '`ap`.`priority` DESC, `p`.`post_modified_gmt` DESC'; // Override defaults if passed as additional arg. foreach ( $additionalArgs as $name => $value ) { // Attachments need to be fetched with all their fields because we need to get their post parent further down the line. $$name = esc_sql( $value ); if ( 'root' === $name && $value && 'attachment' !== $includedPostTypes ) { $fields = '`p`.`ID`, `p`.`post_type`'; } if ( 'count' === $name && $value ) { $fields = 'count(`p`.`ID`) as total'; } } $query = aioseo()->core->db ->start( aioseo()->core->db->db->posts . ' as p', true ) ->select( $fields ) ->leftJoin( 'aioseo_posts as ap', '`ap`.`post_id` = `p`.`ID`' ) ->where( 'p.post_status', 'attachment' === $includedPostTypes ? 'inherit' : 'publish' ) ->whereRaw( "p.post_type IN ( '$includedPostTypes' )" ); $homePageId = (int) get_option( 'page_on_front' ); if ( ! is_array( $postTypes ) ) { if ( ! aioseo()->helpers->isPostTypeNoindexed( $includedPostTypes ) ) { $query->whereRaw( "( `ap`.`robots_noindex` IS NULL OR `ap`.`robots_default` = 1 OR `ap`.`robots_noindex` = 0 OR post_id = $homePageId )" ); } else { $query->whereRaw( "( `ap`.`robots_default` = 0 AND `ap`.`robots_noindex` = 0 OR post_id = $homePageId )" ); } } else { $robotsMetaSql = []; foreach ( $postTypes as $postType ) { if ( ! aioseo()->helpers->isPostTypeNoindexed( $postType ) ) { $robotsMetaSql[] = "( `p`.`post_type` = '$postType' AND ( `ap`.`robots_noindex` IS NULL OR `ap`.`robots_default` = 1 OR `ap`.`robots_noindex` = 0 OR post_id = $homePageId ) )"; } else { $robotsMetaSql[] = "( `p`.`post_type` = '$postType' AND ( `ap`.`robots_default` = 0 AND `ap`.`robots_noindex` = 0 OR post_id = $homePageId ) )"; } } $query->whereRaw( '( ' . implode( ' OR ', $robotsMetaSql ) . ' )' ); } $excludedPosts = aioseo()->sitemap->helpers->excludedPosts(); if ( $excludedPosts ) { $query->whereRaw( "( `p`.`ID` NOT IN ( $excludedPosts ) OR post_id = $homePageId )" ); } // Exclude posts assigned to excluded terms. $excludedTerms = aioseo()->sitemap->helpers->excludedTerms(); if ( $excludedTerms ) { $termRelationshipsTable = aioseo()->core->db->db->prefix . 'term_relationships'; $query->whereRaw(" ( `p`.`ID` NOT IN ( SELECT `tr`.`object_id` FROM `$termRelationshipsTable` as tr WHERE `tr`.`term_taxonomy_id` IN ( $excludedTerms ) ) )" ); } if ( $maxAge ) { $query->whereRaw( "( `p`.`post_date_gmt` >= '$maxAge' )" ); } if ( 'rss' === aioseo()->sitemap->type || ( aioseo()->sitemap->indexes && empty( $additionalArgs['root'] ) && empty( $additionalArgs['count'] ) ) ) { $query->limit( aioseo()->sitemap->linksPerIndex, aioseo()->sitemap->offset ); } $isStaticHomepage = 'page' === get_option( 'show_on_front' ); if ( $isStaticHomepage ) { $excludedPostIds = array_map( 'intval', explode( ',', $excludedPosts ) ); $blogPageId = (int) get_option( 'page_for_posts' ); if ( in_array( 'page', $postTypesArray, true ) ) { // Exclude the blog page from the pages post type. if ( $blogPageId ) { $query->whereRaw( "`p`.`ID` != $blogPageId" ); } // Custom order by statement to always move the home page to the top. if ( $homePageId ) { $orderBy = "case when `p`.`ID` = $homePageId then 0 else 1 end, $orderBy"; } } // Include the blog page in the posts post type unless manually excluded. if ( $blogPageId && ! in_array( $blogPageId, $excludedPostIds, true ) && in_array( 'post', $postTypesArray, true ) ) { // We are using a database class hack to get in an OR clause to // bypass all the other WHERE statements and just include the // blog page ID manually. $query->whereRaw( "1=1 OR `p`.`ID` = $blogPageId" ); // Custom order by statement to always move the blog posts page to the top. $orderBy = "case when `p`.`ID` = $blogPageId then 0 else 1 end, $orderBy"; } } $query->orderBy( $orderBy ); $query = $this->filterPostQuery( $query, $postTypes ); // Return the total if we are just counting the posts. if ( ! empty( $additionalArgs['count'] ) ) { return (int) $query->run( true, 'var' ) ->result(); } $posts = $query->run() ->result(); // Convert ID from string to int. foreach ( $posts as $post ) { $post->ID = (int) $post->ID; } return $this->filterPosts( $posts ); } /** * Filters the post query. * * @since 4.1.4 * * @param \AIOSEO\Plugin\Common\Utils\Database $query The query. * @param string $postType The post type. * @return \AIOSEO\Plugin\Common\Utils\Database The filtered query. */ private function filterPostQuery( $query, $postType ) { switch ( $postType ) { case 'product': return $this->excludeHiddenProducts( $query ); default: break; } return $query; } /** * Adds a condition to the query to exclude hidden WooCommerce products. * * @since 4.1.4 * * @param \AIOSEO\Plugin\Common\Utils\Database $query The query. * @return \AIOSEO\Plugin\Common\Utils\Database The filtered query. */ private function excludeHiddenProducts( $query ) { if ( ! aioseo()->helpers->isWooCommerceActive() || ! apply_filters( 'aioseo_sitemap_woocommerce_exclude_hidden_products', true ) ) { return $query; } static $hiddenProductIds = null; if ( null === $hiddenProductIds ) { $tempDb = new CommonUtils\Database(); $hiddenProducts = $tempDb->start( 'term_relationships as tr' ) ->select( 'tr.object_id' ) ->join( 'term_taxonomy as tt', 'tr.term_taxonomy_id = tt.term_taxonomy_id' ) ->join( 'terms as t', 'tt.term_id = t.term_id' ) ->where( 't.name', 'exclude-from-catalog' ) ->run() ->result(); if ( empty( $hiddenProducts ) ) { return $query; } $hiddenProductIds = []; foreach ( $hiddenProducts as $hiddenProduct ) { $hiddenProductIds[] = (int) $hiddenProduct->object_id; } $hiddenProductIds = esc_sql( implode( ', ', $hiddenProductIds ) ); } $query->whereRaw( "p.ID NOT IN ( $hiddenProductIds )" ); return $query; } /** * Filters the queried posts. * * @since 4.0.0 * * @param array $posts The posts. * @return array $remainingPosts The remaining posts. */ public function filterPosts( $posts ) { $remainingPosts = []; foreach ( $posts as $post ) { switch ( $post->post_type ) { case 'attachment': if ( ! $this->isInvalidAttachment( $post ) ) { $remainingPosts[] = $post; } break; default: $remainingPosts[] = $post; break; } } return $remainingPosts; } /** * Excludes attachments if their post parent isn't published or parent post type isn't registered anymore. * * @since 4.0.0 * * @param Object $post The post. * @return boolean Whether the attachment is invalid. */ private function isInvalidAttachment( $post ) { if ( empty( $post->post_parent ) ) { return false; } $parent = get_post( $post->post_parent ); if ( ! is_object( $parent ) ) { return false; } if ( 'publish' !== $parent->post_status || ! in_array( $parent->post_type, get_post_types(), true ) || $parent->post_password ) { return true; } return false; } /** * Returns all eligible sitemap entries for a given taxonomy. * * @since 4.0.0 * * @param string $taxonomy The taxonomy. * @param array $additionalArgs Any additional arguments for the term query. * @return array|int The term objects or the term count. */ public function terms( $taxonomy, $additionalArgs = [] ) { // Set defaults. $fields = 't.term_id'; $offset = aioseo()->sitemap->offset; // Override defaults if passed as additional arg. foreach ( $additionalArgs as $name => $value ) { $$name = esc_sql( $value ); if ( 'root' === $name && $value ) { $fields = 't.term_id, tt.count'; } if ( 'count' === $name && $value ) { $fields = 'count(t.term_id) as total'; } } $termRelationshipsTable = aioseo()->core->db->db->prefix . 'term_relationships'; $termTaxonomyTable = aioseo()->core->db->db->prefix . 'term_taxonomy'; // Include all terms that have assigned posts or whose children have assigned posts. $query = aioseo()->core->db ->start( aioseo()->core->db->db->terms . ' as t', true ) ->select( $fields ) ->leftJoin( 'term_taxonomy as tt', '`tt`.`term_id` = `t`.`term_id`' ) ->whereRaw( " ( `t`.`term_id` IN ( SELECT `tt`.`term_id` FROM `$termTaxonomyTable` as tt WHERE `tt`.`taxonomy` = '$taxonomy' AND ( `tt`.`count` > 0 OR EXISTS ( SELECT 1 FROM `$termTaxonomyTable` as tt2