Redirects) ---\n" . $custom . "\n"; } return $body; } public static function robots_default_body() { $public = get_option( 'blog_public' ); $site_url = wp_parse_url( site_url() ); $path = ! empty( $site_url['path'] ) ? $site_url['path'] : ''; if ( '0' === (string) $public ) { $body = "User-agent: *\nDisallow: /\n"; } else { $body = "User-agent: *\n"; $body .= 'Disallow: ' . $path . "/wp-admin/\n"; $body .= 'Allow: ' . $path . "/wp-admin/admin-ajax.php\n"; } $filtered = apply_filters( 'robots_txt', $body, $public ); if ( is_string( $filtered ) && '' !== trim( $filtered ) ) { $body = $filtered; } return self::ROBOTS_MARKER . " — regenerated automatically; add your own rules in WP-Admin -> SEO -> Redirects.\n" . rtrim( $body ) . "\n"; } private static function write_robots() { $file = self::robots_file(); if ( is_file( $file ) ) { $head = (string) @file_get_contents( $file, false, null, 0, 256 ); if ( false === strpos( $head, self::ROBOTS_MARKER ) ) { return false; } } if ( self::site_discouraged() ) { if ( is_file( $file ) ) { @unlink( $file ); } return false; } return self::write_atomic( $file, self::robots_body() ); } public static function build() { if ( ! self::is_active() ) { self::remove(); return array( 'shards' => 0, 'urls' => 0, 'active' => false ); } $dir = self::dir(); if ( ! wp_mkdir_p( $dir ) ) { self::log_write_failure( $dir, 'could not create the sitemap directory' ); return array( 'shards' => 0, 'urls' => 0, 'active' => true, 'error' => 'mkdir', 'dir' => $dir ); } if ( ! is_writable( $dir ) ) { self::log_write_failure( $dir, 'sitemap directory is not writable by the web user' ); return array( 'shards' => 0, 'urls' => 0, 'active' => true, 'error' => 'not_writable', 'dir' => $dir ); } global $wpdb; $t = $wpdb->prefix . 'aieo_seo_posts'; $vt = $wpdb->prefix . 'aieo_core_product_vitals'; $home = trailingslashit( home_url() ); $last_id = 0; $shard = 0; $total = 0; $index = array(); $write_fail = 0; $listed = ( class_exists( 'AIEO_SEO_Sitemap_Rules' ) && AIEO_SEO_Sitemap_Rules::column_ok() ) ? ' AND sp.sitemap > 0' : ''; $ranked = class_exists( 'AIEO_SEO_Sitemap_Priority' ) && AIEO_SEO_Sitemap_Priority::columns_ok(); $listed .= $ranked ? ' AND (sp.sitemap_cut = 0 OR sp.sitemap = 2)' : ''; $score = ( $ranked && AIEO_SEO_Sitemap_Priority::active() ) ? ', sp.priority_score' : ''; $passes = array( '' ); $present = (array) $wpdb->get_col( "SELECT DISTINCT object_type FROM `{$t}` WHERE indexable = 1 AND canonical_url <> ''" ); $taxes = array_values( array_filter( $present, 'taxonomy_exists' ) ); if ( $taxes ) { $viewable = array_values( array_filter( $taxes, 'is_taxonomy_viewable' ) ); $in = array( __CLASS__, 'sql_list' ); $passes = array( ' AND sp.object_type NOT IN (' . $in( $taxes ) . ')' ); if ( $viewable ) { $passes[] = ' AND sp.object_type IN (' . $in( $viewable ) . ')'; } } $in = array( __CLASS__, 'sql_list' ); $post_list = $in( array_values( get_post_types() ) ); $tax_list = $in( array_values( get_taxonomies() ) ); $standing = " AND ( ( sp.object_type IN ({$post_list}) AND p.ID IS NOT NULL AND p.post_status = 'publish' )" . " OR ( sp.object_type IN ({$tax_list}) AND tm.term_id IS NOT NULL )" . " OR ( sp.object_type NOT IN ({$post_list}) AND sp.object_type NOT IN ({$tax_list}) ) )"; $joins = " LEFT JOIN `{$wpdb->posts}` p ON p.ID = sp.object_id LEFT JOIN `{$wpdb->terms}` tm ON tm.term_id = sp.object_id"; $fallback = self::fallback_keys(); $own = static function ( $row ) use ( $fallback ) { return self::has_own_address( (string) $row['canonical_url'], $fallback ); }; $home_row = null; if ( class_exists( 'AIEO_SEO_Sitemap_Rules' ) && ! empty( AIEO_SEO_Sitemap_Rules::settings()['home'] ) ) { if ( 0 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$t}` sp WHERE sp.canonical_url = '/'" ) ) { $home_row = array( 'canonical_url' => '/', 'updated' => (string) $wpdb->get_var( "SELECT MAX(sp.updated) FROM `{$t}` sp WHERE sp.indexable = 1{$listed}" ) ); } } foreach ( $passes as $pass ) { $last_id = $ranked ? PHP_INT_MAX : 0; $last_s = 65535 + 1; do { $after = $ranked ? '(sp.priority_score < %d OR (sp.priority_score = %d AND sp.id < %d))' : 'sp.id > %d'; $order = $ranked ? 'sp.priority_score DESC, sp.id DESC' : 'sp.id ASC'; $args = $ranked ? array( $last_s, $last_s, $last_id, self::SHARD_SIZE ) : array( $last_id, self::SHARD_SIZE ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT sp.id, sp.object_type, sp.object_id, sp.canonical_url, sp.sitemap_priority, sp.sitemap_frequency, sp.updated, sp.og_image_url{$score}" . ( $ranked ? ', sp.priority_score AS rank_score' : '' ) . ", v.image_url AS vitals_image FROM `{$t}` sp LEFT JOIN `{$vt}` v ON v.product_id = sp.object_id AND sp.object_type = 'product' AND v.product_id = v.parent_product_id{$joins} WHERE {$after} AND sp.canonical_url <> '' AND sp.indexable = 1{$listed}{$pass}{$standing} ORDER BY {$order} LIMIT %d", $args ), ARRAY_A ); $count = is_array( $rows ) ? count( $rows ) : 0; if ( 0 === $count ) { break; } $kept = array_values( array_filter( $rows, $own ) ); if ( $kept || ( 0 === $shard && $home_row ) ) { $shard++; $latest = ''; $listing = ( 1 === $shard && $home_row ) ? array_merge( array( $home_row ), $kept ) : $kept; if ( ! self::write_atomic( $dir . '/sitemap-' . $shard . '.xml', self::build_urlset( $listing, $home, $latest, self::collect_images( $kept ) ) ) ) { $write_fail++; } $index[] = array( 'n' => $shard, 'lastmod' => $latest ); $total += count( $kept ); } $last_id = (int) $rows[ $count - 1 ]['id']; $last_s = $ranked ? (int) $rows[ $count - 1 ]['rank_score'] : $last_s; } while ( $count === self::SHARD_SIZE ); } $loc_latest = ''; $loc_xml = self::build_locations_urlset( $loc_latest ); if ( '' !== $loc_xml ) { if ( ! self::write_atomic( $dir . '/sitemap-locations.xml', $loc_xml ) ) { $write_fail++; } $index[] = array( 'file' => 'sitemap-locations.xml', 'lastmod' => $loc_latest ); } elseif ( is_file( $dir . '/sitemap-locations.xml' ) ) { @unlink( $dir . '/sitemap-locations.xml' ); } if ( ! empty( $index ) ) { if ( ! self::write_atomic( $dir . '/sitemap.xml', self::build_index( $index ) ) ) { $write_fail++; } } else { $latest = ''; $ruled = class_exists( 'AIEO_SEO_Sitemap_Rules' ) && ( AIEO_SEO_Sitemap_Rules::settings()['rules'] || AIEO_SEO_Sitemap_Rules::settings()['only'] ); $alone = ( ! $ruled || ! empty( AIEO_SEO_Sitemap_Rules::settings()['home'] ) ) ? array( array( 'canonical_url' => '/', 'updated' => current_time( 'mysql', true ) ) ) : array(); if ( ! self::write_atomic( $dir . '/sitemap.xml', self::build_urlset( $alone, $home, $latest ) ) ) { $write_fail++; } } self::cleanup_stale_shards( $dir, $shard ); self::write_robots(); update_option( self::BUILT_OPT, time(), false ); if ( $write_fail > 0 ) { self::log_write_failure( $dir, $write_fail . ' sitemap file write(s) failed (permissions or disk?)' ); return array( 'shards' => $shard, 'urls' => $total, 'active' => true, 'error' => 'write', 'write_failed' => $write_fail, 'dir' => $dir ); } return array( 'shards' => $shard, 'urls' => $total, 'active' => true ); } public static function remove() { $dir = self::dir(); if ( is_dir( $dir ) ) { foreach ( (array) glob( $dir . '/sitemap*.xml' ) as $f ) { if ( is_file( $f ) ) { @unlink( $f ); } } } $rf = self::robots_file(); if ( is_file( $rf ) ) { $head = (string) @file_get_contents( $rf, false, null, 0, 256 ); if ( false !== strpos( $head, self::ROBOTS_MARKER ) ) { @unlink( $rf ); } } delete_option( self::BUILT_OPT ); } public static function fallback_keys() { $keys = array_fill_keys( array( 'p', 'page_id', 'attachment_id', 'post_type', 'cat', 'tag', 'taxonomy', 'term' ), true ); foreach ( array_merge( get_post_types( array(), 'objects' ), get_taxonomies( array(), 'objects' ) ) as $object ) { if ( isset( $object->query_var ) && is_string( $object->query_var ) && '' !== $object->query_var ) { $keys[ $object->query_var ] = true; } } return $keys; } public static function has_own_address( $url, $keys = null ) { $url = (string) $url; if ( false === strpos( $url, '?' ) || '' === (string) get_option( 'permalink_structure' ) ) { return true; } $query = (string) wp_parse_url( $url, PHP_URL_QUERY ); if ( '' === $query ) { return true; } parse_str( $query, $args ); $keys = is_array( $keys ) ? $keys : self::fallback_keys(); return ! array_intersect_key( (array) $args, $keys ); } public static function sql_list( array $names ) { return implode( ',', array_map( static fn( $x ) => "'" . esc_sql( (string) $x ) . "'", $names ) ); } public static function unlisted_types() { global $wpdb; $present = (array) $wpdb->get_col( "SELECT DISTINCT object_type FROM `{$wpdb->prefix}aieo_seo_posts` WHERE indexable = 1 AND canonical_url <> ''" ); return array_values( array_filter( $present, static fn( $x ) => taxonomy_exists( $x ) && ! is_taxonomy_viewable( $x ) ) ); } public static function is_active() { $competitor = defined( 'AIOSEO_VERSION' ) || class_exists( 'AIOSEO\\Plugin\\Common\\Main', false ) || defined( 'WPSEO_VERSION' ) || class_exists( 'WPSEO_Options', false ) || defined( 'RANK_MATH_VERSION' ) || class_exists( 'RankMath', false ); if ( $competitor ) { return false; } $opt = get_option( 'aieo_dmm_settings' ); return is_array( $opt ) && ! empty( $opt['seo']['enabled'] ); } private static function build_urlset( $rows, $home, &$latest, $images = array() ) { $out = '' . "\n"; $out .= '' . "\n"; $latest = ''; foreach ( (array) $rows as $r ) { $cu = (string) $r['canonical_url']; if ( '' === $cu ) { continue; } $loc = ( 0 === strpos( $cu, 'http://' ) || 0 === strpos( $cu, 'https://' ) ) ? $cu : $home . ltrim( $cu, '/' ); $out .= '' . esc_url( self::force_scheme( $loc ) ) . ''; if ( ! empty( $r['updated'] ) ) { $ts = strtotime( $r['updated'] . ' UTC' ); if ( $ts ) { $iso = gmdate( 'c', $ts ); $out .= '' . esc_html( $iso ) . ''; if ( $iso > $latest ) { $latest = $iso; } } } $freq = ! empty( $r['sitemap_frequency'] ) ? strtolower( (string) $r['sitemap_frequency'] ) : 'weekly'; if ( ! in_array( $freq, array( 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never' ), true ) ) { $freq = 'weekly'; } $out .= '' . esc_html( $freq ) . ''; if ( isset( $r['sitemap_priority'] ) && '' !== $r['sitemap_priority'] && null !== $r['sitemap_priority'] ) { $pri = number_format( min( 1.0, max( 0.0, (float) $r['sitemap_priority'] ) ), 1 ); } elseif ( ! empty( $r['priority_score'] ) ) { $pri = number_format( min( 1.0, max( 0.1, (int) $r['priority_score'] / 10000 ) ), 1 ); } else { $pri = '0.5'; } $out .= '' . esc_html( $pri ) . ''; $key = isset( $r['id'] ) ? (int) $r['id'] : 0; if ( $key && ! empty( $images[ $key ] ) ) { foreach ( $images[ $key ] as $src ) { $out .= '' . esc_url( self::force_scheme( self::absolute_url( $src, $home ) ) ) . ''; } $out .= '' . " "; continue; } $img_url = ''; if ( ! empty( $r['vitals_image'] ) ) { $img_url = (string) $r['vitals_image']; } elseif ( ! empty( $r['og_image_url'] ) ) { $img_url = (string) $r['og_image_url']; } $img_url = self::absolute_url( $img_url, $home ); if ( '' !== $img_url ) { $out .= '' . esc_url( self::force_scheme( $img_url ) ) . ''; } $out .= '' . "\n"; } $out .= ''; return $out; } const MAX_IMAGES_PER_URL = 50; private static function absolute_url( $url, $home ) { $url = preg_replace_callback( '/[^-]+/', static function ( $m ) { return rawurlencode( $m[0] ); }, (string) $url ); if ( '' === $url || 0 === strpos( $url, 'http://' ) || 0 === strpos( $url, 'https://' ) ) { return $url; } if ( 0 === strpos( $url, '//' ) ) { return 'https:' . $url; } return $home . ltrim( $url, '/' ); } private static function collect_images( $rows ) { global $wpdb; $by_post = array(); foreach ( (array) $rows as $r ) { if ( empty( $r['object_id'] ) || empty( $r['object_type'] ) || taxonomy_exists( (string) $r['object_type'] ) ) { continue; } $by_post[ (int) $r['object_id'] ] = (int) $r['id']; } if ( ! $by_post ) { return array(); } $ids = implode( ',', array_map( 'intval', array_keys( $by_post ) ) ); $att = array(); $meta = $wpdb->get_results( "SELECT post_id, meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id IN ({$ids}) AND meta_key IN ('_thumbnail_id','_product_image_gallery')", ARRAY_A ); foreach ( (array) $meta as $m ) { $pid = (int) $m['post_id']; if ( ! isset( $att[ $pid ] ) ) { $att[ $pid ] = array(); } foreach ( array_map( 'intval', explode( ',', (string) $m['meta_value'] ) ) as $a ) { if ( $a > 0 ) { if ( '_thumbnail_id' === $m['meta_key'] ) { array_unshift( $att[ $pid ], $a ); } else { $att[ $pid ][] = $a; } } } } $bodies = $wpdb->get_results( "SELECT ID, post_content FROM {$wpdb->posts} WHERE ID IN ({$ids}) AND post_type <> 'product' AND post_content LIKE '%wp-image-%'", ARRAY_A ); foreach ( (array) $bodies as $b ) { if ( preg_match_all( '/wp-image-(\d+)/', (string) $b['post_content'], $mm ) ) { foreach ( $mm[1] as $a ) { $att[ (int) $b['ID'] ][] = (int) $a; } } } $all = array(); foreach ( $att as $list ) { $all = array_merge( $all, $list ); } if ( $all ) { update_meta_cache( 'post', array_unique( $all ) ); } $out = array(); foreach ( $att as $pid => $list ) { $urls = array(); foreach ( array_unique( $list ) as $a ) { $u = wp_get_attachment_url( $a ); if ( $u && ! isset( $urls[ $u ] ) ) { $urls[ $u ] = $u; } if ( count( $urls ) >= self::MAX_IMAGES_PER_URL ) { break; } } if ( $urls && isset( $by_post[ $pid ] ) ) { $out[ $by_post[ $pid ] ] = array_values( $urls ); } } return $out; } private static function build_locations_urlset( &$latest ) { $latest = ''; if ( ! class_exists( 'AIEO_Google_Reviews_Locations' ) || ! class_exists( 'AIEO_SEO_Location_Page' ) ) { return ''; } $locs = AIEO_Google_Reviews_Locations::list_all( true ); if ( empty( $locs ) ) { return ''; } $rows = array(); foreach ( $locs as $loc ) { $url = (string) AIEO_SEO_Location_Page::url_for( $loc ); if ( '' === $url ) { continue; } $lastmod = ''; if ( ! empty( $loc['updated_at'] ) ) { $ts = strtotime( $loc['updated_at'] . ' UTC' ); if ( $ts ) { $lastmod = gmdate( 'c', $ts ); } } $rows[] = array( 'loc' => $url, 'lastmod' => $lastmod ); } if ( empty( $rows ) ) { return ''; } $out = '' . "\n"; $out .= '' . "\n"; foreach ( $rows as $r ) { $out .= '' . esc_url( self::force_scheme( $r['loc'] ) ) . ''; if ( '' !== $r['lastmod'] ) { $out .= '' . esc_html( $r['lastmod'] ) . ''; if ( $r['lastmod'] > $latest ) { $latest = $r['lastmod']; } } $out .= 'monthly0.6' . "\n"; } $out .= ''; return $out; } private static function build_index( $index ) { $base = trailingslashit( self::url() ); $out = '' . "\n"; $out .= '' . "\n"; foreach ( (array) $index as $m ) { $file = ! empty( $m['file'] ) ? (string) $m['file'] : 'sitemap-' . (int) $m['n'] . '.xml'; $out .= '' . esc_url( $base . $file ) . ''; if ( ! empty( $m['lastmod'] ) ) { $out .= '' . esc_html( (string) $m['lastmod'] ) . ''; } $out .= '' . "\n"; } $out .= ''; return $out; } private static function log_write_failure( $dir, $what ) { error_log( sprintf( 'AIEO sitemap: %s — %s. The static sitemap could not be (re)generated; ensure the directory and its files are owned/writable by the web user (a prior `wp … --allow-root` run can leave root-owned files that block regeneration).', $what, $dir ) ); } private static function write_atomic( $path, $contents ) { $tmp = $path . '.' . wp_generate_password( 6, false ) . '.tmp'; if ( false === file_put_contents( $tmp, $contents ) ) { return false; } if ( ! @rename( $tmp, $path ) ) { @unlink( $tmp ); return false; } return true; } private static function cleanup_stale_shards( $dir, $current_max ) { foreach ( (array) glob( $dir . '/sitemap-*.xml' ) as $f ) { if ( preg_match( '/sitemap-(\d+)\.xml$/', (string) $f, $mm ) && (int) $mm[1] > $current_max ) { @unlink( $f ); } } } } }