true], 'names'); unset($post_types['attachment']); return array_values($post_types); } function ai_seo_cro_is_internal_link_href($href) { $href = trim((string) $href); if ($href === '' || $href[0] === '#') { return false; } if (preg_match('#^(mailto:|tel:|sms:|javascript:|data:)#i', $href)) { return false; } $absolute = ai_seo_cro_make_absolute(home_url('/'), $href); if ($absolute === '') { return false; } $home_host = strtolower((string) wp_parse_url(home_url('/'), PHP_URL_HOST)); $link_host = strtolower((string) wp_parse_url($absolute, PHP_URL_HOST)); return $home_host !== '' && $home_host === $link_host; } function ai_seo_cro_is_automatic_internal_link_repair_enabled() { return get_option('ai_seo_cro_enable_automatic_internal_link_repair', '0') === '1'; } function ai_seo_cro_get_canonical_internal_link_url($href) { $href = trim((string) $href); if ($href === '' || !preg_match('#^https?://#i', $href)) { return ''; } $home_url = home_url('/'); $home_host = strtolower((string) wp_parse_url($home_url, PHP_URL_HOST)); $link_host = strtolower((string) wp_parse_url($href, PHP_URL_HOST)); if ($home_host === '' || $link_host !== $home_host) { return ''; } $home_port = wp_parse_url($home_url, PHP_URL_PORT); $link_port = wp_parse_url($href, PHP_URL_PORT); if ((string) $home_port !== (string) $link_port) { return ''; } $link_path = '/' . ltrim((string) wp_parse_url($href, PHP_URL_PATH), '/'); $home_path = '/' . ltrim((string) wp_parse_url($home_url, PHP_URL_PATH), '/'); $canonical = ''; if (untrailingslashit($link_path) === untrailingslashit($home_path)) { $canonical = $home_url; } else { $candidate = set_url_scheme($href, wp_parse_url($home_url, PHP_URL_SCHEME)); $post_id = url_to_postid($candidate); if ($post_id > 0) { $canonical = get_permalink($post_id); } } if (!$canonical) { return ''; } $query = (string) wp_parse_url($href, PHP_URL_QUERY); $fragment = (string) wp_parse_url($href, PHP_URL_FRAGMENT); if ($query !== '') { $canonical .= '?' . $query; } if ($fragment !== '') { $canonical .= '#' . $fragment; } return $canonical !== $href ? $canonical : ''; } function ai_seo_cro_repair_internal_links_in_content($content) { $content = (string) $content; $changed_count = 0; if ($content === '' || stripos($content, 'href=') === false) { return [ 'content' => $content, 'changed' => false, 'count' => 0, ]; } $updated_content = (string) preg_replace_callback( '/(]*\shref\s*=\s*)(["\'])(.*?)\2/i', function ($matches) use (&$changed_count) { $decoded_href = html_entity_decode($matches[3], ENT_QUOTES, get_bloginfo('charset') ?: 'UTF-8'); $canonical = ai_seo_cro_get_canonical_internal_link_url($decoded_href); if ($canonical === '') { return $matches[0]; } $changed_count++; return $matches[1] . $matches[2] . esc_url($canonical) . $matches[2]; }, $content ); return [ 'content' => $updated_content, 'changed' => $changed_count > 0, 'count' => $changed_count, ]; } function ai_seo_cro_get_posts_with_repairable_internal_links($limit = 100) { global $wpdb; $post_types = ai_seo_cro_get_fixable_post_types(); if (empty($post_types)) { return []; } $rows = get_posts([ 'post_type' => $post_types, 'post_status' => 'publish', 'posts_per_page' => max(1, (int) $limit), 's' => 'href=', 'search_columns' => ['post_content'], 'sentence' => true, 'orderby' => 'ID', 'order' => 'DESC', ]); $items = []; foreach ($rows as $row) { $result = ai_seo_cro_repair_internal_links_in_content($row->post_content); if (empty($result['changed'])) { continue; } $items[] = [ 'id' => (int) $row->ID, 'title' => get_the_title($row->ID), 'type' => $row->post_type, 'url' => get_permalink($row->ID), 'edit_url' => get_edit_post_link($row->ID, 'raw'), 'count' => (int) $result['count'], ]; } return $items; } function ai_seo_cro_fix_repairable_internal_links() { $items = ai_seo_cro_get_posts_with_repairable_internal_links(); $fixed_posts = 0; $fixed_links = 0; foreach ($items as $item) { $post = get_post((int) $item['id']); if (!$post) { continue; } $result = ai_seo_cro_repair_internal_links_in_content($post->post_content); if (empty($result['changed'])) { continue; } $updated = wp_update_post([ 'ID' => $post->ID, 'post_content' => $result['content'], ], true); if (is_wp_error($updated)) { continue; } $fixed_posts++; $fixed_links += (int) $result['count']; } return [ 'fixed_posts' => $fixed_posts, 'fixed_links' => $fixed_links, ]; } function ai_seo_cro_get_automatic_internal_link_repair_status() { $items = ai_seo_cro_get_posts_with_repairable_internal_links(); $link_count = array_sum(array_map(function ($item) { return (int) $item['count']; }, $items)); $enabled = ai_seo_cro_is_automatic_internal_link_repair_enabled(); return [ 'success' => true, 'enabled' => $enabled, 'items' => $items, 'post_count' => count($items), 'link_count' => $link_count, 'home_url' => home_url('/'), 'message' => $enabled ? ($link_count > 0 ? 'Automatic repair is enabled; repairable stored links remain.' : 'Automatic internal-link repair is enabled for stored and rendered links.') : 'Automatic internal-link repair is disabled.', ]; } function ai_seo_cro_update_automatic_internal_link_repair($enabled = true) { update_option('ai_seo_cro_enable_automatic_internal_link_repair', $enabled ? '1' : '0'); $fixed = $enabled ? ai_seo_cro_fix_repairable_internal_links() : [ 'fixed_posts' => 0, 'fixed_links' => 0, ]; $status = ai_seo_cro_get_automatic_internal_link_repair_status(); $status = array_merge($status, $fixed); $status['message'] = $enabled ? sprintf( 'Automatic repair enabled for stored and rendered links. Normalized %d stored link(s) across %d post(s).', $fixed['fixed_links'], $fixed['fixed_posts'] ) : 'Automatic internal-link repair disabled. Existing content was left unchanged.'; return $status; } function ai_seo_cro_repair_internal_links_before_save($data, $postarr) { if ( !ai_seo_cro_is_automatic_internal_link_repair_enabled() || empty($data['post_content']) || wp_is_post_revision($postarr['ID'] ?? 0) ) { return $data; } $post_type = $data['post_type'] ?? ''; if (!in_array($post_type, ai_seo_cro_get_fixable_post_types(), true)) { return $data; } $result = ai_seo_cro_repair_internal_links_in_content($data['post_content']); if (!empty($result['changed'])) { $data['post_content'] = $result['content']; } return $data; } add_filter('wp_insert_post_data', 'ai_seo_cro_repair_internal_links_before_save', 20, 2); function ai_seo_cro_rel_without_nofollow($rel) { $tokens = preg_split('/\s+/', strtolower(trim((string) $rel))); $tokens = array_values(array_unique(array_filter($tokens, function ($token) { return $token !== '' && $token !== 'nofollow'; }))); return implode(' ', $tokens); } function ai_seo_cro_remove_internal_nofollow_from_content($content) { $content = (string) $content; $changed_count = 0; if ($content === '' || stripos($content, 'nofollow') === false) { return [ 'content' => $content, 'changed' => false, 'count' => 0, ]; } if (class_exists('WP_HTML_Tag_Processor') && method_exists('WP_HTML_Tag_Processor', 'remove_attribute')) { $processor = new WP_HTML_Tag_Processor($content); while ($processor->next_tag('A')) { $href = (string) $processor->get_attribute('href'); $rel = (string) $processor->get_attribute('rel'); if ($rel === '' || stripos($rel, 'nofollow') === false || !ai_seo_cro_is_internal_link_href($href)) { continue; } $updated_rel = ai_seo_cro_rel_without_nofollow($rel); if ($updated_rel === '') { $processor->remove_attribute('rel'); } else { $processor->set_attribute('rel', $updated_rel); } $changed_count++; } return [ 'content' => $processor->get_updated_html(), 'changed' => $changed_count > 0, 'count' => $changed_count, ]; } libxml_use_internal_errors(true); $dom = new DOMDocument(); $wrapped = '
' . $content . '
'; @$dom->loadHTML($wrapped, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NONET); foreach ($dom->childNodes as $node) { if ($node->nodeType === XML_PI_NODE) { $dom->removeChild($node); break; } } $xpath = new DOMXPath($dom); $links = $xpath->query('//a[@rel]'); if ($links) { foreach ($links as $link) { if (!$link instanceof DOMElement) { continue; } $href = $link->getAttribute('href'); $rel = $link->getAttribute('rel'); if ($rel === '' || stripos($rel, 'nofollow') === false || !ai_seo_cro_is_internal_link_href($href)) { continue; } $updated_rel = ai_seo_cro_rel_without_nofollow($rel); if ($updated_rel === '') { $link->removeAttribute('rel'); } else { $link->setAttribute('rel', $updated_rel); } $changed_count++; } } $wrapper = $dom->getElementById('360-seo-content-wrapper'); $updated_content = ''; if ($wrapper) { foreach ($wrapper->childNodes as $child) { $updated_content .= $dom->saveHTML($child); } } else { $updated_content = $dom->saveHTML(); } libxml_clear_errors(); return [ 'content' => $updated_content, 'changed' => $changed_count > 0, 'count' => $changed_count, ]; } function ai_seo_cro_get_posts_with_internal_nofollow($limit = 100) { global $wpdb; $post_types = ai_seo_cro_get_fixable_post_types(); if (empty($post_types)) { return []; } $rows = get_posts([ 'post_type' => $post_types, 'post_status' => 'publish', 'posts_per_page' => max(1, (int) $limit), 's' => 'nofollow', 'search_columns' => ['post_content'], 'sentence' => true, 'orderby' => 'ID', 'order' => 'DESC', ]); $items = []; foreach ((array) $rows as $row) { $result = ai_seo_cro_remove_internal_nofollow_from_content($row->post_content); if (empty($result['changed'])) { continue; } $items[] = [ 'id' => (int) $row->ID, 'title' => get_the_title($row->ID), 'type' => $row->post_type, 'url' => get_permalink($row->ID), 'edit_url' => get_edit_post_link($row->ID, 'raw'), 'count' => (int) $result['count'], ]; } return $items; } function ai_seo_cro_get_internal_nofollow_status() { $items = ai_seo_cro_get_posts_with_internal_nofollow(); $link_count = array_sum(array_map(function ($item) { return (int) $item['count']; }, $items)); return [ 'success' => true, 'items' => $items, 'post_count' => count($items), 'link_count' => $link_count, 'message' => count($items) > 0 ? 'Internal nofollow links found.' : 'No internal nofollow links found in published content.', ]; } function ai_seo_cro_fix_internal_nofollow_links() { $items = ai_seo_cro_get_posts_with_internal_nofollow(); $fixed_posts = 0; $fixed_links = 0; foreach ($items as $item) { $post = get_post((int) $item['id']); if (!$post) { continue; } $result = ai_seo_cro_remove_internal_nofollow_from_content($post->post_content); if (empty($result['changed'])) { continue; } $updated = wp_update_post([ 'ID' => $post->ID, 'post_content' => $result['content'], ], true); if (is_wp_error($updated)) { continue; } $fixed_posts++; $fixed_links += (int) $result['count']; } $status = ai_seo_cro_get_internal_nofollow_status(); $status['fixed_posts'] = $fixed_posts; $status['fixed_links'] = $fixed_links; $status['message'] = $fixed_links > 0 ? sprintf('Removed nofollow from %d internal link(s) across %d post(s).', $fixed_links, $fixed_posts) : 'No internal nofollow links needed changes.'; return $status; } function ai_seo_cro_get_sitemap_targets() { return [ai_seo_cro_get_virtual_sitemap_target()]; } function ai_seo_cro_get_virtual_sitemap_target() { return [ 'key' => 'virtual_sitemap_index', 'label' => 'Virtual sitemap index', 'path' => 'Served dynamically by this plugin; no physical file is created.', 'url' => home_url('/sitemap_index.xml'), 'virtual' => true, ]; } function ai_seo_cro_get_sitemap_target_status($target) { if (!empty($target['virtual'])) { return array_merge($target, [ 'exists' => true, 'size' => 0, 'modified' => '', 'modified_timestamp' => 0, 'timezone' => ai_seo_cro_get_wp_timezone_label(), 'writable' => true, 'source' => 'virtual', ]); } $exists = file_exists($target['path']); $size = $exists ? filesize($target['path']) : 0; $modified = $exists ? filemtime($target['path']) : false; return array_merge($target, [ 'exists' => $exists, 'size' => $size === false ? 0 : (int) $size, 'modified' => $modified ? ai_seo_cro_format_sitemap_modified_time($modified) : '', 'modified_timestamp' => $modified ? (int) $modified : 0, 'timezone' => ai_seo_cro_get_wp_timezone_label(), 'writable' => ($exists && ai_seo_cro_path_is_writable($target['path'])) || (!$exists && ai_seo_cro_path_is_writable(dirname($target['path']))), 'source' => 'file', ]); } function ai_seo_cro_get_sitemap_status_targets() { $targets = []; foreach (ai_seo_cro_get_sitemap_targets() as $target) { $targets[] = ai_seo_cro_get_sitemap_target_status($target); } return $targets; } function ai_seo_cro_get_existing_sitemap_target() { foreach (ai_seo_cro_get_sitemap_status_targets() as $target) { if (empty($target['exists'])) { continue; } if (!empty($target['virtual']) || (int) ($target['size'] ?? 0) > 0) { return $target; } } return null; } function ai_seo_cro_get_preferred_sitemap_urls() { $existing = ai_seo_cro_get_existing_sitemap_target(); if (!empty($existing['url'])) { return [(string) $existing['url']]; } return [home_url('/sitemap_index.xml')]; } function ai_seo_cro_get_sitemap_entries() { $entries = []; $latest_posts = get_posts([ 'post_type' => ai_seo_cro_get_fixable_post_types(), 'post_status' => 'publish', 'posts_per_page' => 1, 'orderby' => 'modified', 'order' => 'DESC', 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ]); $entries[] = [ 'loc' => home_url('/'), 'lastmod' => !empty($latest_posts[0]) ? get_post_modified_time('c', true, (int) $latest_posts[0]) : gmdate('c'), 'changefreq' => 'daily', 'priority' => '1.0', ]; $post_ids = get_posts([ 'post_type' => ai_seo_cro_get_fixable_post_types(), 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'modified', 'order' => 'DESC', 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ]); foreach ((array) $post_ids as $post_id) { $permalink = get_permalink($post_id); if (!$permalink) { continue; } $entries[] = [ 'loc' => $permalink, 'lastmod' => get_post_modified_time('c', true, $post_id), 'changefreq' => get_post_type($post_id) === 'page' ? 'monthly' : 'weekly', 'priority' => get_post_type($post_id) === 'page' ? '0.8' : '0.7', ]; } return $entries; } function ai_seo_cro_xml_escape($value) { return htmlspecialchars((string) $value, ENT_XML1 | ENT_COMPAT, 'UTF-8'); } function ai_seo_cro_generate_sitemap_xml() { $entries = ai_seo_cro_get_sitemap_entries(); $seen = []; $xml = "\n"; $xml .= "\n"; foreach ($entries as $entry) { $loc = (string) ($entry['loc'] ?? ''); if ($loc === '' || isset($seen[$loc])) { continue; } $seen[$loc] = true; $xml .= " \n"; $xml .= ' ' . ai_seo_cro_xml_escape($loc) . "\n"; $xml .= ' ' . ai_seo_cro_xml_escape($entry['lastmod'] ?? gmdate('c')) . "\n"; $xml .= ' ' . ai_seo_cro_xml_escape($entry['changefreq'] ?? 'weekly') . "\n"; $xml .= ' ' . ai_seo_cro_xml_escape($entry['priority'] ?? '0.7') . "\n"; $xml .= " \n"; } $xml .= "\n"; return $xml; } function ai_seo_cro_is_current_sitemap_request() { $request_uri = sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'] ?? '')); $request_path = '/' . ltrim((string) wp_parse_url($request_uri, PHP_URL_PATH), '/'); $targets = [ home_url('/sitemap.xml'), home_url('/wp-sitemap.xml'), home_url('/sitemap_index.xml'), ]; foreach ($targets as $target) { $target_path = '/' . ltrim((string) wp_parse_url($target, PHP_URL_PATH), '/'); if (untrailingslashit($request_path) === untrailingslashit($target_path)) { return true; } } return false; } function ai_seo_cro_render_virtual_sitemap() { if (is_admin() || !ai_seo_cro_is_current_sitemap_request()) { return; } status_header(200); nocache_headers(); header('Content-Type: application/xml; charset=UTF-8'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All dynamic XML values are escaped by ai_seo_cro_xml_escape in the generator. echo ai_seo_cro_generate_sitemap_xml(); exit; } add_action('template_redirect', 'ai_seo_cro_render_virtual_sitemap', 0); function ai_seo_cro_write_sitemap_file($path, $xml) { // Retained for compatibility; sitemaps are served dynamically. return [ 'success' => false, 'message' => 'Physical sitemap writes are disabled. Use the dynamic sitemap URL.', 'bytes' => 0, ]; } function ai_seo_cro_format_sitemap_modified_time($timestamp) { $timestamp = (int) $timestamp; if ($timestamp <= 0) { return ''; } return wp_date(get_option('date_format') . ' ' . get_option('time_format'), $timestamp); } function ai_seo_cro_get_wp_timezone_label() { $timezone = wp_timezone(); return $timezone instanceof DateTimeZone ? $timezone->getName() : 'UTC'; } function ai_seo_cro_get_sitemap_status() { $targets = ai_seo_cro_get_sitemap_status_targets(); $existing = ai_seo_cro_get_existing_sitemap_target(); return [ 'success' => true, 'targets' => $targets, 'has_sitemap' => !empty($existing), 'existing_sitemap' => $existing, 'url_count' => count(ai_seo_cro_get_sitemap_entries()), 'timezone' => ai_seo_cro_get_wp_timezone_label(), 'message' => !empty($existing) ? sprintf('Sitemap is already available at %s. No duplicate sitemap file is required.', $existing['url']) : 'No sitemap is available yet.', ]; } function ai_seo_cro_generate_sitemaps() { $status = ai_seo_cro_get_sitemap_status(); $status['results'] = []; $status['generated_count'] = 0; $status['skipped_count'] = 0; $status['failed_count'] = 0; $status['message'] = sprintf( 'Sitemap is served dynamically at %s and included in the WordPress virtual robots.txt. No physical files are created.', $status['existing_sitemap']['url'] ); return $status; } function ai_seo_cro_get_llms_txt_target() { $generated_at = (int) get_option('ai_seo_cro_llms_txt_generated_at', 0); return [ 'path' => 'Served dynamically by this plugin; no physical file is created.', 'url' => home_url('/llms.txt'), 'exists' => $generated_at > 0, 'writable' => true, 'virtual' => true, 'size' => $generated_at > 0 ? strlen(ai_seo_cro_generate_llms_txt_content()) : 0, 'modified' => ai_seo_cro_format_sitemap_modified_time($generated_at), ]; } function ai_seo_cro_get_llms_txt_entries() { $post_ids = get_posts([ 'post_type' => ai_seo_cro_get_fixable_post_types(), 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'menu_order date', 'order' => 'ASC', 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ]); $entries = []; foreach ((array) $post_ids as $post_id) { $url = get_permalink($post_id); if (!$url) { continue; } $title = trim(wp_strip_all_tags(get_the_title($post_id))); $summary = trim(wp_strip_all_tags(get_the_excerpt($post_id))); $entries[] = [ 'title' => $title !== '' ? $title : sprintf('Content #%d', $post_id), 'url' => $url, 'summary' => $summary, ]; } return $entries; } function ai_seo_cro_escape_llms_text($value) { return trim(str_replace(["\r", "\n", '[', ']'], [' ', ' ', '\[', '\]'], (string) $value)); } function ai_seo_cro_generate_llms_txt_content() { $site_name = ai_seo_cro_escape_llms_text(get_bloginfo('name')); $description = ai_seo_cro_escape_llms_text(get_bloginfo('description')); $entries = ai_seo_cro_get_llms_txt_entries(); $content = '# ' . ($site_name !== '' ? $site_name : (string) wp_parse_url(home_url('/'), PHP_URL_HOST)) . "\n\n"; if ($description !== '') { $content .= '> ' . $description . "\n\n"; } $content .= 'Canonical site: ' . home_url('/') . "\n\n"; $content .= "## Site content\n\n"; foreach ($entries as $entry) { $content .= '- [' . ai_seo_cro_escape_llms_text($entry['title']) . '](' . esc_url_raw($entry['url']) . ')'; if ($entry['summary'] !== '') { $content .= ': ' . ai_seo_cro_escape_llms_text($entry['summary']); } $content .= "\n"; } return $content; } function ai_seo_cro_get_llms_txt_status() { $target = ai_seo_cro_get_llms_txt_target(); $entry_count = count(ai_seo_cro_get_llms_txt_entries()); return [ 'success' => true, 'has_file' => $target['exists'], 'target' => $target, 'entry_count' => $entry_count, 'timezone' => ai_seo_cro_get_wp_timezone_label(), 'message' => $target['exists'] ? sprintf('llms.txt is available with %d public content link(s).', $entry_count) : 'llms.txt not found. Use Auto Generate to create it.', ]; } function ai_seo_cro_generate_llms_txt() { update_option('ai_seo_cro_llms_txt_generated_at', time(), false); $status = ai_seo_cro_get_llms_txt_status(); $status['generated'] = true; $status['bytes'] = $status['target']['size']; $status['message'] = sprintf('llms.txt is served dynamically with %d public content link(s).', $status['entry_count']); return $status; } function ai_seo_cro_render_virtual_llms_txt() { if (is_admin() || !(int) get_option('ai_seo_cro_llms_txt_generated_at', 0)) { return; } $request_uri = sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'] ?? '')); $request_path = wp_parse_url($request_uri, PHP_URL_PATH); $target_path = wp_parse_url(home_url('/llms.txt'), PHP_URL_PATH); if ($request_path !== $target_path) { return; } status_header(200); nocache_headers(); header('Content-Type: text/plain; charset=UTF-8'); header('X-Content-Type-Options: nosniff'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Plain text response; generator strips markup and escapes URLs. echo ai_seo_cro_generate_llms_txt_content(); exit; } add_action('template_redirect', 'ai_seo_cro_render_virtual_llms_txt', 0);