4096 ) { fseek( $fh, max( 0, $size - 4096 ) ); $tail = (string) fread( $fh, 4096 ); // phpcs:ignore WordPress.WP.AlternativeFunctions } fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions return self::has_marker( $head . $tail ); } /** * Hook in. */ public static function init() { add_action( 'aeoora_regenerate_llms', array( __CLASS__, 'regenerate' ) ); add_action( self::REFRESH_HOOK, array( __CLASS__, 'refresh' ) ); add_action( 'init', array( __CLASS__, 'ensure_refresh' ) ); add_action( 'transition_post_status', array( __CLASS__, 'on_transition' ), 10, 3 ); add_action( 'save_post', array( __CLASS__, 'on_save' ), 20, 2 ); add_action( 'aeoora_settings_updated', array( __CLASS__, 'on_settings' ) ); if ( ! Aeoora_Settings::get( 'llms', 'enabled', true ) ) { return; } add_filter( 'do_parse_request', array( __CLASS__, 'maybe_serve' ), 0 ); if ( Aeoora_Settings::get( 'llms', 'takeover', false ) ) { // Taken over: answer /llms.txt and /llms-full.txt before any other // plugin's handler gets the request (those run on init or later). add_action( 'init', array( __CLASS__, 'serve_early' ), PHP_INT_MIN ); } } /** * init, first of all, once the owner took over: serve the files now. */ public static function serve_early() { self::maybe_serve( true ); } /** * Serve the files before WordPress parses the request. * * @param bool $do_parse Whether to parse. * @return bool */ public static function maybe_serve( $do_parse ) { if ( Aeoora_Util::is_backend_request() ) { return $do_parse; } $path = strtolower( Aeoora_Util::relative_path() ); if ( 'llms.txt' === $path ) { self::send( 'llms' ); } elseif ( 'llms-full.txt' === $path && Aeoora_Settings::get( 'llms', 'full_enabled', true ) ) { self::send( 'full' ); } return $do_parse; } /** * Output a file and exit. * * @param string $type llms|full. */ private static function send( $type ) { Aeoora_Tracker::set_resource( 'full' === $type ? 'llms-full' : 'llms' ); if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Served from a file anyway; keeps every AI fetch logged. } header( 'Content-Type: text/plain; charset=utf-8' ); header( 'X-Content-Type-Options: nosniff' ); header( 'X-Aeoora: ' . ( 'full' === $type ? 'llms-full' : 'llms' ) ); // Lets the live check tell who answered. $file = self::file( $type ); if ( $file && is_readable( $file ) ) { status_header( 200 ); header( 'Cache-Control: public, max-age=3600' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', (int) filemtime( $file ) ) . ' GMT' ); readfile( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions exit; } $stored = get_option( 'aeoora_llms_store_' . $type ); if ( is_array( $stored ) && ! empty( $stored['body'] ) ) { // Uploads was not writable when the file was generated. status_header( 200 ); header( 'Cache-Control: public, max-age=3600' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', isset( $stored['at'] ) ? (int) $stored['at'] : time() ) . ' GMT' ); echo (string) $stored['body']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- plain text. exit; } // Not generated yet. Never build it inside a crawler's request: one // build renders hundreds of pages, and crawlers ask in parallel. // (Not again within ten minutes of a build that could not store it.) $stats = get_option( 'aeoora_llms_stats', array() ); if ( ! is_array( $stats ) || empty( $stats['generated_at'] ) || time() - (int) $stats['generated_at'] > 10 * MINUTE_IN_SECONDS ) { self::schedule( 30 ); } status_header( 503 ); nocache_headers(); header( 'Retry-After: 300' ); echo esc_html__( 'This file is being generated. Please try again in a few minutes.', 'aeoora' ) . "\n"; exit; } /** * Generated content of a file (for the admin preview), or ''. * * @param string $type llms|full. * @param int $bytes Maximum bytes. * @return string */ public static function content( $type, $bytes = 200000 ) { $file = self::file( $type ); if ( $file && is_readable( $file ) ) { return (string) file_get_contents( $file, false, null, 0, $bytes ); // phpcs:ignore WordPress.WP.AlternativeFunctions } $stored = get_option( 'aeoora_llms_store_' . $type ); return is_array( $stored ) && isset( $stored['body'] ) ? substr( (string) $stored['body'], 0, $bytes ) : ''; } /** * Storage path for a generated file. * * @param string $type llms|full. * @return string|null */ public static function file( $type ) { $dir = Aeoora_Util::upload_dir(); if ( ! $dir ) { return null; } return trailingslashit( $dir['dir'] ) . ( 'full' === $type ? 'llms-full.txt' : 'llms.txt' ); } /** * Regenerate both files now. * * @return array Stats. */ public static function regenerate() { if ( ! Aeoora_Settings::get( 'llms', 'enabled', true ) ) { return array( 'generated_at' => time(), 'llms_bytes' => 0, 'full_bytes' => 0, 'items' => 0, ); } // One build at a time (cron, the admin and WP-CLI may all ask at once). if ( ! Aeoora_Util::lock( 'llms', 15 * MINUTE_IN_SECONDS ) ) { $stats = (array) get_option( 'aeoora_llms_stats', array() ); $stats['busy'] = true; return $stats; } if ( function_exists( 'set_time_limit' ) && ( wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) ) { @set_time_limit( 300 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors, Squiz.PHP.DiscouragedFunctions.Discouraged -- background task. } try { // As a logged-out visitor (membership plugins answer for the public), // and without synchronous loopbacks (pages that need one are queued). $stats = Aeoora_Util::as_visitor( static function () { return Aeoora_Content::in_batch( static function () { return self::generate(); } ); } ); } finally { Aeoora_Util::unlock( 'llms' ); } return $stats; } /** * Build and store both files. * * @return array Stats. */ private static function generate() { $stats = array( 'generated_at' => time(), 'llms_bytes' => 0, 'full_bytes' => 0, 'items' => 0, ); $llms = self::build( false, $stats ); $stats['llms_bytes'] = strlen( $llms ); self::store( 'llms', $llms ); unset( $llms ); if ( Aeoora_Settings::get( 'llms', 'full_enabled', true ) ) { $cli = defined( 'WP_CLI' ) && WP_CLI; $budget = (int) apply_filters( 'aeoora_llms_full_time_budget', ( wp_doing_cron() || $cli ) ? 180 : 20 ); $full = array(); $stats['full_bytes'] = self::write_full( max( 5, $budget ), $full ); $stats['full_items'] = isset( $full['items'] ) ? (int) $full['items'] : 0; if ( ! empty( $full['partial'] ) ) { // Out of time (cold caches): the admin gets a partial file now, // and background runs complete it. Each run starts with more of // the pages' Markdown cached, so it gets further; after five // tries in a row the file stays as it is until the next refresh. $stats['partial'] = true; $tries = (int) get_option( 'aeoora_llms_partial_tries', 0 ) + 1; update_option( 'aeoora_llms_partial_tries', $tries, false ); if ( $tries <= 5 ) { self::schedule( 90 ); } } else { delete_option( 'aeoora_llms_partial_tries' ); } } self::write_static_files(); update_option( 'aeoora_llms_stats', $stats, false ); Aeoora_Compat::purge_urls( array( home_url( '/llms.txt' ), home_url( '/llms-full.txt' ) ) ); return $stats; } /** * Store generated text: a file in uploads (written atomically), or a * non-autoloaded option when uploads is not writable (up to 2 MB). * * @param string $type llms|full. * @param string $content Content. * @return bool */ private static function store( $type, $content ) { $file = self::file( $type ); if ( $file ) { $tmp = $file . '.tmp'; if ( false !== @file_put_contents( $tmp, $content, LOCK_EX ) && @rename( $tmp, $file ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors, WordPress.WP.AlternativeFunctions delete_option( 'aeoora_llms_store_' . $type ); return true; } if ( file_exists( $tmp ) ) { wp_delete_file( $tmp ); } } if ( strlen( $content ) <= 2 * MB_IN_BYTES ) { update_option( 'aeoora_llms_store_' . $type, array( 'at' => time(), 'body' => $content, ), false ); return true; } return false; } /** * Build llms-full.txt straight into its file (never the whole text in memory). * * @param int $budget Seconds. * @param array $stats Stats (by ref): items, partial. * @return int Bytes. */ private static function write_full( $budget, &$stats ) { $file = self::file( 'full' ); $tmp = $file ? $file . '.tmp' : ''; $fh = $tmp ? @fopen( $tmp, 'wb' ) : false; // phpcs:ignore WordPress.PHP.NoSilencedErrors, WordPress.WP.AlternativeFunctions if ( ! $fh ) { $fh = fopen( 'php://temp', 'w+b' ); // phpcs:ignore WordPress.WP.AlternativeFunctions self::build_full( $fh, $budget, $stats ); rewind( $fh ); $text = (string) apply_filters( 'aeoora_llms_output', (string) stream_get_contents( $fh ), true ); fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions self::store( 'full', $text ); return strlen( $text ); } $bytes = self::build_full( $fh, $budget, $stats ); if ( has_filter( 'aeoora_llms_output' ) ) { // Filters receive the whole text, as in 1.0.0. fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions $text = (string) apply_filters( 'aeoora_llms_output', (string) file_get_contents( $tmp ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions $bytes = strlen( $text ); file_put_contents( $tmp, $text, LOCK_EX ); // phpcs:ignore WordPress.WP.AlternativeFunctions } else { fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions } if ( @rename( $tmp, $file ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors, WordPress.WP.AlternativeFunctions delete_option( 'aeoora_llms_store_full' ); } else { wp_delete_file( $tmp ); } return $bytes; } /** * Settings changed: rebuild soon. */ public static function on_settings() { self::schedule( 120 ); } /** * Schedule a regeneration (debounced: a busy news site publishing every * few minutes rebuilds at most every ten minutes). * * @param int $delay Seconds. */ public static function schedule( $delay = 600 ) { if ( ! wp_next_scheduled( 'aeoora_regenerate_llms' ) ) { wp_schedule_single_event( time() + max( 1, (int) $delay ), 'aeoora_regenerate_llms' ); } } /** * Regenerate when content is published / unpublished. * * @param string $new New status. * @param string $old Old status. * @param WP_Post $post Post. */ public static function on_transition( $new, $old, $post ) { if ( ( 'publish' === $new || 'publish' === $old ) && in_array( $post->post_type, (array) Aeoora_Settings::get( 'llms', 'post_types', array() ), true ) ) { self::schedule(); } } /** * Regenerate when published content is edited. * * @param int $post_id Post ID. * @param WP_Post $post Post. */ public static function on_save( $post_id, $post ) { if ( wp_is_post_revision( $post_id ) || 'publish' !== $post->post_status ) { return; } if ( in_array( $post->post_type, (array) Aeoora_Settings::get( 'llms', 'post_types', array() ), true ) ) { self::schedule(); } } /** * IDs of the posts included, per post type. Loads posts in chunks, so a * site with thousands of items never holds them all in memory. * * @param bool $full For llms-full.txt. * @return array post_type => int[] */ public static function item_ids( $full = false ) { $s = Aeoora_Settings::get( 'llms' ); $limit = $full ? (int) $s['full_max_items'] : (int) $s['max_items']; $limit = $limit > 0 ? $limit : PHP_INT_MAX; // 0 = every page. $exclude = array_flip( array_map( 'absint', (array) $s['exclude_ids'] ) ); $out = array(); $total = 0; foreach ( (array) $s['post_types'] as $type ) { if ( ! post_type_exists( $type ) || $total >= $limit ) { continue; } $hier = is_post_type_hierarchical( $type ); $q = new WP_Query( array( 'post_type' => $type, 'post_status' => 'publish', 'has_password' => false, 'posts_per_page' => PHP_INT_MAX === $limit ? -1 : max( 1, $limit - $total + count( $exclude ) ), 'orderby' => $hier ? array( 'menu_order' => 'ASC', 'title' => 'ASC', ) : 'modified', 'order' => $hier ? 'ASC' : 'DESC', 'fields' => 'ids', 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'suppress_filters' => false, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ) ); foreach ( array_chunk( array_map( 'intval', $q->posts ), 200 ) as $chunk ) { _prime_post_caches( $chunk, false, true ); foreach ( $chunk as $id ) { if ( $total >= $limit ) { break 2; } if ( ! isset( $exclude[ $id ] ) && Aeoora_Content::is_public( $id, 'llms' ) ) { $out[ $type ][] = $id; $total++; } } self::release_memory(); } } return $out; } /** * Posts included, per post type (WP_Post objects; kept for the * `aeoora_llms_items` filter). * * @param bool $full For llms-full.txt. * @return array post_type => WP_Post[] */ public static function items( $full = false ) { $out = array(); foreach ( self::item_ids( $full ) as $type => $ids ) { foreach ( $ids as $id ) { $p = get_post( $id ); if ( $p ) { $out[ $type ][] = $p; } } } return apply_filters( 'aeoora_llms_items', $out, $full ); } /** * Post IDs to write, honouring the `aeoora_llms_items` filter when used. * * @param bool $full For llms-full.txt. * @return array post_type => int[] */ private static function groups( $full ) { if ( ! has_filter( 'aeoora_llms_items' ) ) { return self::item_ids( $full ); } $out = array(); foreach ( (array) self::items( $full ) as $type => $posts ) { foreach ( (array) $posts as $p ) { $p = get_post( $p ); if ( $p ) { $out[ $type ][] = (int) $p->ID; } } } return $out; } /** * Drop the in-request object cache between chunks once memory gets tight. */ private static function release_memory() { $limit = wp_convert_hr_to_bytes( (string) ini_get( 'memory_limit' ) ); if ( $limit > 0 && memory_get_usage() > $limit * 0.5 && function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) ) { wp_cache_flush_runtime(); } } /** * Common head of both files. * * @param bool $full llms-full.txt. * @return string */ private static function head( $full ) { $s = Aeoora_Settings::get( 'llms' ); $name = Aeoora_Util::one_line( get_bloginfo( 'name' ) ); $summary = trim( (string) $s['summary'] ); if ( '' === $summary ) { $summary = Aeoora_Util::one_line( get_bloginfo( 'description' ) ); } $out = '# ' . ( '' !== $name ? $name : home_url() ) . "\n\n"; if ( '' !== $summary ) { $out .= '> ' . Aeoora_Util::one_line( $summary ) . "\n\n"; } $details = trim( (string) $s['details'] ); if ( '' !== $details ) { $out .= $details . "\n\n"; } if ( $full ) { /* translators: 1: site URL, 2: llms.txt URL. */ $out .= sprintf( __( 'This file contains the full text of the main pages of %1$s, for language models. Index: %2$s', 'aeoora' ), home_url( '/' ), home_url( '/llms.txt' ) ) . "\n\n"; } return $out; } /** * Closing line with the marker that identifies files written by the plugin. * * @return string */ private static function foot() { return "\n\n"; } /** * Build llms.txt or llms-full.txt as a string. * * @param bool $full Full content version. * @param array $stats Stats (by ref). * @return string */ public static function build( $full = false, &$stats = array() ) { if ( $full ) { $fh = fopen( 'php://temp', 'w+b' ); // phpcs:ignore WordPress.WP.AlternativeFunctions self::build_full( $fh, 300, $stats ); rewind( $fh ); $out = (string) stream_get_contents( $fh ); fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions return (string) apply_filters( 'aeoora_llms_output', $out, true ); } $s = Aeoora_Settings::get( 'llms' ); $md_links = ! empty( $s['link_markdown'] ) && Aeoora_Settings::get( 'markdown', 'enabled', true ); $out = self::head( false ); $count = 0; foreach ( self::groups( false ) as $type => $ids ) { $obj = get_post_type_object( $type ); $out .= '## ' . ( $obj ? $obj->labels->name : $type ) . "\n\n"; foreach ( array_chunk( $ids, 200 ) as $chunk ) { _prime_post_caches( $chunk, true, true ); // Terms too: permalinks with %category% need them. foreach ( $chunk as $id ) { $p = get_post( $id ); if ( ! $p ) { continue; } $url = ( $md_links && Aeoora_Markdown::is_eligible( $p ) ) ? Aeoora_Markdown::url( $p ) : get_permalink( $p ); $desc = self::describe( $p ); $out .= '- [' . str_replace( array( '[', ']' ), '', Aeoora_Util::one_line( get_the_title( $p ) ) ) . '](' . $url . ')' . ( '' !== $desc ? ': ' . $desc : '' ) . "\n"; $count++; } self::release_memory(); } $out .= "\n"; } if ( ! empty( $s['taxonomies'] ) ) { $out .= self::taxonomy_section(); } $custom = trim( (string) $s['custom_sections'] ); if ( '' !== $custom ) { $out .= $custom . "\n\n"; } $out .= '## ' . __( 'Optional', 'aeoora' ) . "\n\n"; if ( Aeoora_Settings::get( 'llms', 'full_enabled', true ) ) { $out .= '- [' . __( 'Full content', 'aeoora' ) . '](' . home_url( '/llms-full.txt' ) . '): ' . __( 'The full text of the main pages in one Markdown file.', 'aeoora' ) . "\n"; } $sitemap = Aeoora_Compat::sitemap_url(); if ( $sitemap ) { $out .= '- [' . __( 'XML sitemap', 'aeoora' ) . '](' . $sitemap . '): ' . __( 'Every public URL.', 'aeoora' ) . "\n"; } $feed = get_bloginfo( 'rss2_url' ); if ( $feed ) { $out .= '- [' . __( 'RSS feed', 'aeoora' ) . '](' . $feed . '): ' . __( 'Latest posts.', 'aeoora' ) . "\n"; } $out .= self::foot(); $stats['items'] = $count; return (string) apply_filters( 'aeoora_llms_output', $out, false ); } /** * Write llms-full.txt to a stream, post by post, within a size and a time budget. * * @param resource $fh Stream. * @param int $budget Seconds. * @param array $stats Stats (by ref): items, partial. * @return int Bytes written. */ private static function build_full( $fh, $budget, &$stats ) { $start = microtime( true ); $max_bytes = (int) Aeoora_Settings::get( 'llms', 'full_max_kb', 0 ) * 1024; // 0 = no size limit. $bytes = (int) fwrite( $fh, self::head( true ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions $count = 0; foreach ( self::groups( true ) as $ids ) { foreach ( array_chunk( $ids, 50 ) as $chunk ) { _prime_post_caches( $chunk, true, true ); foreach ( $chunk as $id ) { if ( microtime( true ) - $start > $budget ) { $stats['partial'] = true; break 3; } $p = get_post( $id ); if ( ! $p ) { continue; } $body = trim( Aeoora_Markdown::body( $p ) ); if ( '' === $body ) { continue; } $title = Aeoora_Util::one_line( get_the_title( $p ) ); $body = preg_replace( '~^#\s+' . preg_quote( $title, '~' ) . '\s*\n~u', '', $body ); // Demote headings so each document keeps one H1. $body = preg_replace( '~^(#{1,5}) ~m', '#$1 ', (string) $body ); $doc = "---\n\n# " . $title . "\n\n" . 'URL: ' . get_permalink( $p ) . "\n" . __( 'Updated', 'aeoora' ) . ': ' . get_post_modified_time( 'Y-m-d', true, $p ) . "\n\n" . $body . "\n\n"; if ( $max_bytes > 0 && $bytes + strlen( $doc ) > $max_bytes ) { break 3; } $bytes += (int) fwrite( $fh, $doc ); // phpcs:ignore WordPress.WP.AlternativeFunctions $count++; } self::release_memory(); } } $bytes += (int) fwrite( $fh, self::foot() ); // phpcs:ignore WordPress.WP.AlternativeFunctions $stats['items'] = $count; return $bytes; } /** * One-line description of a post. * * @param WP_Post $p Post. * @return string */ private static function describe( WP_Post $p ) { $desc = Aeoora_Seo::get_description( $p->ID ); if ( '' === $desc ) { $tldr = (string) get_post_meta( $p->ID, '_aeoora_tldr', true ); $desc = '' !== $tldr ? $tldr : ( $p->post_excerpt ? $p->post_excerpt : wp_trim_words( wp_strip_all_tags( strip_shortcodes( $p->post_content ) ), 28, '…' ) ); } return Aeoora_Util::trim_chars( $desc, 180 ); } /** * Category / product category section. * * @return string */ private static function taxonomy_section() { $out = ''; foreach ( array( 'category', 'product_cat' ) as $tax ) { if ( ! taxonomy_exists( $tax ) ) { continue; } $terms = get_terms( array( 'taxonomy' => $tax, 'hide_empty' => true, 'number' => 50, 'orderby' => 'count', 'order' => 'DESC', ) ); if ( is_wp_error( $terms ) || ! $terms ) { continue; } $label = get_taxonomy( $tax )->labels->name; $lines = ''; foreach ( $terms as $t ) { if ( 'uncategorized' === $t->slug ) { continue; } $link = get_term_link( $t ); if ( is_wp_error( $link ) ) { continue; } $desc = Aeoora_Util::trim_chars( $t->description, 140 ); $lines .= '- [' . Aeoora_Util::one_line( $t->name ) . '](' . $link . ')' . ( '' !== $desc ? ': ' . $desc : '' ) . "\n"; } if ( '' === $lines ) { continue; } $out .= '## ' . $label . "\n\n" . $lines; $out .= "\n"; } return $out; } /** * Static copies at the site root (optional). */ private static function write_static_files() { if ( ! Aeoora_Settings::get( 'llms', 'static_files', false ) || is_multisite() ) { self::remove_static_files(); return; } foreach ( array( 'llms' => 'llms.txt', 'full' => 'llms-full.txt', ) as $type => $name ) { $src = self::file( $type ); $dest = Aeoora_Util::root_path() . $name; if ( ! $src || ! file_exists( $src ) ) { continue; } if ( file_exists( $dest ) && ! self::file_has_marker( $dest ) ) { continue; // Never overwrite a file we did not create. } if ( wp_is_writable( Aeoora_Util::root_path() ) ) { copy( $src, $dest ); } } } /** * Remove static copies we created. */ public static function remove_static_files() { foreach ( array( 'llms.txt', 'llms-full.txt' ) as $name ) { $dest = Aeoora_Util::root_path() . $name; if ( self::file_has_marker( $dest ) ) { wp_delete_file( $dest ); } } } /** * Other active plugins that also offer an llms.txt (so the owner knows who serves it). * * @return string[] Plugin names. */ public static function other_providers() { $out = array(); if ( defined( 'VIGIA_VERSION' ) ) { $out[] = 'VigIA'; } if ( defined( 'NATIVE_AEO_PACK_VERSION' ) ) { $out[] = 'Visibility'; } if ( class_exists( '\RankMath\Helper' ) && method_exists( '\RankMath\Helper', 'is_module_active' ) ) { try { if ( \RankMath\Helper::is_module_active( 'llms-txt' ) ) { $out[] = 'Rank Math'; } } catch ( Throwable $e ) { unset( $e ); } } if ( defined( 'WPSEO_VERSION' ) && class_exists( 'WPSEO_Options' ) && WPSEO_Options::get( 'enable_llms_txt', false ) ) { $out[] = 'Yoast SEO'; } // Plugins whose main job is llms.txt / llms-full.txt, by folder name. $known = array( 'website-llms-txt' => 'Website LLMs.txt', 'llms-full-txt-generator' => 'LLMs.txt and LLMs-Full.txt Generator', 'llms-txt-curator' => 'LLMs.txt Curator', 'auto-llms-generator' => 'Auto LLMS (.txt) Generator', 'odyssey-llms' => 'Odyssey LLMS', 'llm-markdown' => 'LLM Markdown', 'lovedbyai-seo-for-llms-and-ai-search' => 'LovedByAI', 'better-robots-txt' => 'Better Robots.txt', ); $active = (array) get_option( 'active_plugins', array() ); if ( is_multisite() ) { $active = array_merge( $active, array_keys( (array) get_site_option( 'active_sitewide_plugins', array() ) ) ); } foreach ( $active as $file ) { $slug = strtok( (string) $file, '/' ); if ( isset( $known[ $slug ] ) ) { $out[] = $known[ $slug ]; } } return array_values( array_unique( (array) apply_filters( 'aeoora_llms_other_providers', $out ) ) ); } /** * Is something aeoora can switch off serving llms.txt again (Yoast SEO's * or Rank Math's feature)? * * @return bool */ private static function switchable_provider_on() { return (bool) array_intersect( self::other_providers(), array( 'Yoast SEO', 'Rank Math' ) ); } /** * Is there a foreign llms.txt in the root that hides ours? * * @return bool */ public static function foreign_file() { return in_array( 'llms.txt', self::foreign_files(), true ); } /** * Files in the site root, written by something else, that the web server * serves instead of aeoora's llms.txt / llms-full.txt. * * @return string[] File names. */ public static function foreign_files() { $out = array(); foreach ( array( 'llms.txt', 'llms-full.txt' ) as $name ) { $path = Aeoora_Util::root_path() . $name; if ( file_exists( $path ) && ! self::file_has_marker( $path ) ) { $out[] = $name; } } return $out; } /* ------------------------------------------------------- scheduling */ /** * Keep the recurring rebuild scheduled at the chosen interval (cheap: one * look at the cron array, which WordPress has loaded already). */ public static function ensure_refresh() { // Taken over: every 10 minutes, look for a file or a plugin feature that // came back (another plugin may rewrite its llms.txt or llms-full.txt on // its own schedule) and take over again at once. if ( Aeoora_Settings::get( 'llms', 'takeover', false ) && false === get_transient( 'aeoora_llms_takeover_check' ) ) { set_transient( 'aeoora_llms_takeover_check', 1, 10 * MINUTE_IN_SECONDS ); if ( self::foreign_files() || self::switchable_provider_on() ) { self::takeover(); } } $want = Aeoora_Settings::get( 'llms', 'enabled', true ) ? (string) Aeoora_Settings::get( 'llms', 'refresh', 'twicedaily' ) : ''; $have = (string) wp_get_schedule( self::REFRESH_HOOK ); if ( $want === $have ) { return; } wp_clear_scheduled_hook( self::REFRESH_HOOK ); if ( '' !== $want ) { wp_schedule_event( time() + 15 * MINUTE_IN_SECONDS, $want, self::REFRESH_HOOK ); } } /** * Scheduled refresh: re-apply the takeover and robots.txt sync the owner * opted into (another plugin may have written its file again), then * rebuild both files from the current content. */ public static function refresh() { if ( Aeoora_Settings::get( 'llms', 'takeover', false ) ) { self::takeover(); } Aeoora_Robots::auto_sync(); delete_option( 'aeoora_llms_partial_tries' ); self::regenerate(); } /* --------------------------------------------------------- takeover */ /** * Make aeoora the one serving llms.txt and llms-full.txt: switch off the * llms.txt feature of other plugins that have one (Yoast SEO, Rank Math), * and move foreign files out of the site root into * wp-content/uploads/aeoora/backup/ (restorable). Only runs when the * owner asked for it (button or the llms.takeover setting). * * @return array What was done: files (name, backup), plugins, errors. */ public static function takeover() { $log = array( 'at' => time(), 'files' => array(), 'plugins' => array(), 'errors' => array(), ); // Other plugins' llms.txt features. try { if ( defined( 'WPSEO_VERSION' ) && class_exists( 'WPSEO_Options' ) && method_exists( 'WPSEO_Options', 'set' ) && WPSEO_Options::get( 'enable_llms_txt', false ) ) { WPSEO_Options::set( 'enable_llms_txt', false ); $log['plugins'][] = 'yoast'; } } catch ( Throwable $e ) { $log['errors'][] = 'Yoast SEO: ' . $e->getMessage(); } try { if ( class_exists( '\RankMath\Helper' ) && method_exists( '\RankMath\Helper', 'is_module_active' ) && method_exists( '\RankMath\Helper', 'update_modules' ) && \RankMath\Helper::is_module_active( 'llms-txt' ) ) { \RankMath\Helper::update_modules( array( 'llms-txt' => 'off' ) ); $log['plugins'][] = 'rankmath'; } } catch ( Throwable $e ) { $log['errors'][] = 'Rank Math: ' . $e->getMessage(); } // Foreign files in the root, moved to a backup (never deleted outright). $files = self::foreign_files(); $dir = $files ? Aeoora_Util::upload_dir( 'backup' ) : null; foreach ( $files as $name ) { $path = Aeoora_Util::root_path() . $name; if ( ! $dir || ! wp_is_writable( Aeoora_Util::root_path() ) ) { /* translators: %s: file name. */ $log['errors'][] = sprintf( __( '%s is in the site root, which is not writable. Delete or rename it there.', 'aeoora' ), $name ); continue; } $backup = trailingslashit( $dir['dir'] ) . $name . '-' . gmdate( 'Ymd-His' ) . '.bak'; if ( ! @copy( $path, $backup ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors /* translators: %s: file name. */ $log['errors'][] = sprintf( __( 'Could not back up %s, so it was left in place.', 'aeoora' ), $name ); continue; } wp_delete_file( $path ); if ( file_exists( $path ) ) { /* translators: %s: file name. */ $log['errors'][] = sprintf( __( 'Could not remove %s from the site root.', 'aeoora' ), $name ); continue; } $log['files'][] = array( 'name' => $name, 'backup' => $backup, ); } // Keep a record of everything ever taken over, for "Undo". $prev = get_option( self::TAKEOVER_OPTION, array() ); $prev = is_array( $prev ) ? $prev : array(); update_option( self::TAKEOVER_OPTION, array( 'at' => $log['at'], 'files' => array_merge( isset( $prev['files'] ) ? (array) $prev['files'] : array(), $log['files'] ), 'plugins' => array_values( array_unique( array_merge( isset( $prev['plugins'] ) ? (array) $prev['plugins'] : array(), $log['plugins'] ) ) ), 'errors' => $log['errors'], ), false ); if ( $log['files'] ) { self::write_static_files(); Aeoora_Compat::purge_urls( array( home_url( '/llms.txt' ), home_url( '/llms-full.txt' ) ) ); } return $log; } /** * Undo every takeover: put backed-up files back (when aeoora's copy or * nothing is there), switch the other plugins' llms.txt back on, and stop * taking over. * * @return array { files: restored names, plugins: re-enabled } */ public static function undo_takeover() { $rec = get_option( self::TAKEOVER_OPTION, array() ); $rec = is_array( $rec ) ? $rec : array(); $out = array( 'files' => array(), 'plugins' => array(), ); Aeoora_Settings::update( array( 'llms' => array( 'takeover' => false ) ), false ); $latest = array(); foreach ( isset( $rec['files'] ) ? (array) $rec['files'] : array() as $f ) { if ( ! empty( $f['name'] ) && ! empty( $f['backup'] ) ) { $latest[ $f['name'] ] = $f['backup']; // The newest backup of each file wins. } } foreach ( $latest as $name => $backup ) { $path = Aeoora_Util::root_path() . sanitize_file_name( $name ); if ( is_file( $backup ) && ( ! file_exists( $path ) || self::file_has_marker( $path ) ) && @copy( $backup, $path ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors $out['files'][] = $name; } } try { if ( in_array( 'yoast', (array) ( isset( $rec['plugins'] ) ? $rec['plugins'] : array() ), true ) && class_exists( 'WPSEO_Options' ) && method_exists( 'WPSEO_Options', 'set' ) ) { WPSEO_Options::set( 'enable_llms_txt', true ); $out['plugins'][] = 'yoast'; } if ( in_array( 'rankmath', (array) ( isset( $rec['plugins'] ) ? $rec['plugins'] : array() ), true ) && class_exists( '\RankMath\Helper' ) && method_exists( '\RankMath\Helper', 'update_modules' ) ) { \RankMath\Helper::update_modules( array( 'llms-txt' => 'on' ) ); $out['plugins'][] = 'rankmath'; } } catch ( Throwable $e ) { unset( $e ); } delete_option( self::TAKEOVER_OPTION ); Aeoora_Compat::purge_urls( array( home_url( '/llms.txt' ), home_url( '/llms-full.txt' ) ) ); return $out; } /** * Who really answers /llms.txt and /llms-full.txt (a request to the site * itself, as a crawler would make it): aeoora, something else, or nothing. * * @return array name => aeoora|other|missing|unreachable */ public static function live_check() { $out = array(); foreach ( array( 'llms.txt' => array( 'llms', home_url( '/llms.txt' ) ), 'llms-full.txt' => array( 'full', home_url( '/llms-full.txt' ) ), ) as $name => $what ) { // Ask for the last 8 KB: aeoora's marker is the file's last line, and // llms-full.txt can be megabytes. A static file (aeoora's root copy, // a CDN) answers 206 with the tail; WordPress answers 200 with the // whole file and the X-Aeoora header. $args = Aeoora_Util::loopback_args( array( 'timeout' => 15, 'limit_response_size' => 65536, ) ); $args['headers'] = array_merge( isset( $args['headers'] ) ? (array) $args['headers'] : array(), array( 'Range' => 'bytes=-8192' ) ); $res = wp_remote_get( $what[1], $args ); if ( is_wp_error( $res ) ) { $out[ $name ] = 'unreachable'; continue; } $code = (int) wp_remote_retrieve_response_code( $res ); $body = (string) wp_remote_retrieve_body( $res ); if ( 200 !== $code && 206 !== $code ) { $out[ $name ] = 'missing'; } elseif ( false !== stripos( (string) wp_remote_retrieve_header( $res, 'x-aeoora' ), 'llms' ) || self::has_marker( $body ) ) { $out[ $name ] = 'aeoora'; } elseif ( 200 === $code && self::same_start( $body, self::content( $what[0], 4096 ) ) ) { // A copy of aeoora's file without our header (cached, or a // server that ignores Range): its start matches ours. $out[ $name ] = 'aeoora'; } else { $out[ $name ] = 'other'; } } return $out; } /** * Do two texts start the same way (the first 2 KB, ignoring line endings)? * * @param string $a Text. * @param string $b Text. * @return bool */ private static function same_start( $a, $b ) { $norm = static function ( $s ) { return substr( str_replace( "\r\n", "\n", (string) $s ), 0, 2048 ); }; return '' !== $b && strlen( $norm( $a ) ) > 64 && $norm( $a ) === $norm( $b ); } /** * Everything the llms.txt screen shows about who serves the files. * * @param bool $live Also request the files from the site. * @return array */ public static function takeover_status( $live = false ) { $rec = get_option( self::TAKEOVER_OPTION, array() ); return array( 'plugins' => self::other_providers(), 'files' => self::foreign_files(), 'root_writable' => wp_is_writable( Aeoora_Util::root_path() ), 'takeover' => (bool) Aeoora_Settings::get( 'llms', 'takeover', false ), 'last' => is_array( $rec ) ? $rec : array(), 'live' => $live ? self::live_check() : null, 'next_refresh' => wp_next_scheduled( self::REFRESH_HOOK ) ? gmdate( 'c', (int) wp_next_scheduled( self::REFRESH_HOOK ) ) : null, ); } }