share( Services\Generator::class, static fn( Container $c ) => new Services\Generator( $c->get( Options::class ) ) ); } public function boot( Container $container ): void { add_action( 'init', array( self::class, 'add_rewrite' ) ); add_filter( 'query_vars', static function ( array $vars ): array { $vars[] = self::QUERY_VAR; $vars[] = self::QUERY_VAR_FULL; return $vars; } ); Guard::action( 'template_redirect', array( $this, 'maybe_serve' ), 0 ); add_action( 'rest_api_init', static function () use ( $container ): void { ( new Rest\LlmsTxtController( $container->get( Services\Generator::class ) ) )->register_routes(); } ); // Invalidate caches when content changes (debounced by nature of transients). foreach ( array( 'save_post', 'deleted_post', 'edited_terms' ) as $hook ) { add_action( $hook, static function (): void { delete_transient( self::CACHE_KEY ); delete_transient( self::CACHE_KEY_FULL ); } ); } } /** * Register the /llms.txt + /llms-full.txt rewrites (also called from activation). */ public static function add_rewrite(): void { add_rewrite_rule( '^llms\.txt$', 'index.php?' . self::QUERY_VAR . '=1', 'top' ); add_rewrite_rule( '^llms-full\.txt$', 'index.php?' . self::QUERY_VAR_FULL . '=1', 'top' ); } /** * Serve /llms.txt or /llms-full.txt when requested. */ public function maybe_serve(): void { $full = '1' === get_query_var( self::QUERY_VAR_FULL ); if ( ! $full && '1' !== get_query_var( self::QUERY_VAR ) ) { return; } $container = \AiRankSuite\Kernel::instance()->container(); $settings = $container->get( Options::class )->get( 'llms_txt', Services\Generator::defaults() ); if ( empty( $settings['enabled'] ) || ( $full && empty( $settings['full_enabled'] ) ) ) { status_header( 404 ); exit; } $cache_key = $full ? self::CACHE_KEY_FULL : self::CACHE_KEY; $body = get_transient( $cache_key ); if ( ! is_string( $body ) || '' === $body ) { $generator = $container->get( Services\Generator::class ); $body = $full ? $generator->generate_full() : $generator->generate(); set_transient( $cache_key, $body, HOUR_IN_SECONDS ); } status_header( 200 ); header( 'Content-Type: text/plain; charset=utf-8' ); header( 'X-Robots-Tag: noindex' ); header( 'Cache-Control: public, max-age=3600' ); // A text/plain document. There is no esc_*() function for this context: // the body is built from sanitized fields and stripped of markup here, // and the checker's HTML rule does not apply to a file served as text. $body = wp_strip_all_tags( $body ); echo $body; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- text/plain, stripped of markup on the line above; HTML escaping would corrupt the file. exit; } }