enableMap = $enableMap; $this->settings = $settings; $this->client = $client; } /** * Module id. * * @return string The result. */ public function getId(): string { return self::ID; } /** * Module name. * * @return string The result. */ public function getName(): string { return 'Instant Indexing (IndexNow)'; } /** * Boot priority. * * @return int The result. */ public function getPriority(): int { return 45; } /** * Module ids this module depends on. * * IndexNow signals deltas and needs no sitemap, so a sitemap * dependency would force this module off for no reason. * * @return string[] The result. */ public function dependsOn(): array { return []; } /** * Whether the module id is in the enable map. * * @return bool The result. */ public function isEnabled(): bool { return $this->enableMap()->isEnabled( self::ID ); } /** * Wire services, no hooks. * * Returns before anything is constructed while disabled, so a * disabled module registers zero hooks and constructs zero clients. * The register path runs on every request a module boots, not only * on activation, so the log table is also created for a site that * upgraded to this version with the module already enabled. * * @return void */ public function register(): void { if ( ! $this->isEnabled() ) { return; } LogTable::ensureTables(); $this->settings()->ensureKey(); } /** * Register the hooks, none of them while disabled. * * @return void */ public function boot(): void { if ( ! $this->isEnabled() ) { return; } $this->server()->register(); if ( ! function_exists( 'add_action' ) ) { return; } add_action( 'pre_post_update', [ $this, 'onPrePostUpdate' ], 10, 1 ); add_action( 'transition_post_status', [ $this, 'onTransitionPostStatus' ], 10, 3 ); add_action( self::SUBMIT_CRON_HOOK, [ $this, 'runDeferredSubmit' ] ); $this->registerTermHooks(); } /** * Register the created, edited and deleted term hooks. * * The hooks pass different argument shapes: created_term and * edited_term pass the term id, the term taxonomy id and the * taxonomy, while pre_delete_term passes the term id and the * taxonomy only. Each callback maps its own arguments, so the * taxonomy is never mistaken for the term taxonomy id. * * The pre_delete_term hook is used rather than delete_term because * the URL is only resolvable while the term row still exists, and * delete_term fires after the row is gone. * * @return void */ private function registerTermHooks(): void { add_action( 'created_term', function ( mixed $termId = null, mixed $ttId = null, mixed $taxonomy = null ): void { $this->onTermChange( (int) $termId, (int) $ttId, (string) $taxonomy, 'created' ); }, 10, 3 ); add_action( 'edited_term', function ( mixed $termId = null, mixed $ttId = null, mixed $taxonomy = null ): void { $this->onTermChange( (int) $termId, (int) $ttId, (string) $taxonomy, 'edited' ); }, 10, 3 ); add_action( 'pre_delete_term', function ( mixed $termId = null, mixed $taxonomy = null ): void { $this->onTermChange( (int) $termId, 0, (string) $taxonomy, 'deleted' ); }, 10, 2 ); } /** * Submit URLs through the client, never throwing. * * The debounce lives on the post signal path, which knows its post * id; this entry point is also the manual path, where no post id * exists and a human click is never suppressed. A thrown transport * failure is logged once per URL in the batch, so no URL disappears, * and returned as an empty summary. * * @param array $urls URLs to submit. * @param string $source Submitting surface, auto or manual. * @return array Outcome summary. */ public function submitUrls( array $urls, string $source ): array { $list = []; foreach ( $urls as $url ) { if ( is_string( $url ) && '' !== $url ) { $list[] = $url; } } if ( [] === $list ) { return self::emptyResult(); } try { return $this->client()->submit( $list, $source ); } catch ( \Throwable $error ) { foreach ( $list as $url ) { $this->settings()->logEntry( $url, 0, $source, $error->getMessage() ); } return self::emptyResult(); } } /** * Snapshot the permalink before an update lands. * * @param mixed $postId Post id passed by the pre_post_update action. * @return void */ public function onPrePostUpdate( mixed $postId = null ): void { if ( ! $this->isEnabled() || ! function_exists( 'get_permalink' ) ) { return; } $id = is_numeric( $postId ) ? (int) $postId : 0; if ( $id <= 0 ) { return; } $permalink = get_permalink( $id ); if ( is_string( $permalink ) && '' !== $permalink ) { $this->collector()->snapshotPermalink( $id, $permalink ); } } /** * Handle a post status transition. * * Guard order: revisions and autosaves first, then the post type * viewability, then the signal test. A signal is a transition into * publish, a publish to publish update, or a transition into trash * from a public status. Going from publish to draft is deliberately * not a signal, matching the sitemaps precedent. * * @param string $newStatus New post status. * @param string $oldStatus Previous post status. * @param mixed $post Post object passed by the action. * @return void */ public function onTransitionPostStatus( string $newStatus, string $oldStatus, mixed $post ): void { if ( ! $this->isEnabled() || ! $this->settings()->getAutoSubmit() ) { return; } $postId = $this->postId( $post ); if ( $postId <= 0 || $this->isRevisionOrAutosave( $postId ) ) { return; } $postType = $this->postType( $post ); if ( '' === $postType || 'attachment' === $postType || ! $this->isViewablePostType( $postType ) ) { return; } if ( '' !== $this->postPassword( $post ) ) { return; } if ( function_exists( 'get_post_meta' ) && NoindexFlag::isNoindex( get_post_meta( $postId, NoindexFlag::POST_PAYLOAD, true ) ) ) { return; } if ( ! $this->isSignal( $newStatus, $oldStatus ) ) { return; } $urls = $this->collector()->postUrls( $postId, $newStatus, $oldStatus ); if ( [] === $urls ) { return; } // The debounce compares against the newest URL, the state the post // is in now, because that is the URL a later signal carries. A // permalink change submits the previous URL first for deindexing, // so only the current URL can act as the throttle key. $current = $urls[ count( $urls ) - 1 ]; // The debounce applies to publish and update signals only. A trash // event is a distinct fact for the engine, so a URL that was just // signalled as updated is still signalled once as removed. if ( 'trash' !== $newStatus && $this->collector()->wasRecentlySubmitted( $postId, $current ) ) { return; } $contentHash = $this->postContentHash( $post ); // A publish-to-publish re-save with byte-identical content submits // nothing: same URL, same status, nothing new to discover. Any edit // changes the hash and still submits. if ( 'publish' === $newStatus && 'publish' === $oldStatus && $this->collector()->isUnchangedRepublish( $postId, $current, $contentHash ) ) { return; } // Never submit inline: a slow endpoint must not stall the save. // Queue one deferred event per payload; an identical pending event // is not duplicated. The cron worker marks the attempt on delivery. $this->queueDeferredSubmit( $postId, $urls, $current, $contentHash, $newStatus ); } /** * Queue deferred auto-submit delivery for collected URLs. * * @param int $postId Post id. * @param string[] $urls Collected URLs. * @param string $current Newest URL, the throttle key. * @param string $contentHash Content hash for the unchanged-republish dedupe. * @param string $signal Transition signal, part of the dedupe key. */ public function queueDeferredSubmit( int $postId, array $urls, string $current, string $contentHash = '', string $signal = '' ): void { if ( ! function_exists( 'wp_schedule_single_event' ) ) { return; } $payload = [ 'post_id' => $postId, 'urls' => array_values( $urls ), 'source' => 'auto', 'content_hash' => $contentHash, 'signal' => $signal, ]; if ( function_exists( 'wp_next_scheduled' ) && false !== wp_next_scheduled( self::SUBMIT_CRON_HOOK, [ $payload ] ) ) { return; } wp_schedule_single_event( time(), self::SUBMIT_CRON_HOOK, [ $payload ] ); } /** * Cron worker: deliver a deferred auto-submit payload. * * The payload crosses serialize/unserialize through the cron store, so * its shape is validated at runtime here rather than assumed. * * @param array $payload Queued payload with urls, post_id, content_hash. */ public function runDeferredSubmit( array $payload ): void { $rawUrls = isset( $payload['urls'] ) && is_array( $payload['urls'] ) ? array_values( $payload['urls'] ) : []; $urls = []; foreach ( $rawUrls as $url ) { if ( is_string( $url ) && '' !== $url ) { $urls[] = $url; } } if ( [] === $urls ) { return; } $postId = (int) ( $payload['post_id'] ?? 0 ); // Non-emptiness is established by the check above, so end() yields // a string here; the loop only ever collects non-empty strings. $current = end( $urls ); $result = $this->submitUrls( $urls, 'auto' ); // Mark the attempt, not just the acceptance: the spec debounces the // same URL for ten minutes, and an unmarked failure would let every // later save retry against the endpoint inside that window. if ( [] !== ( $result['results'] ?? [] ) ) { $rawHash = $payload['content_hash'] ?? ''; $contentHash = is_string( $rawHash ) ? $rawHash : ''; $this->collector()->markSubmitted( $postId, $current, $contentHash ); } } /** * Handle a term change. * * @param int $termId Term id. * @param int $ttId Term taxonomy id. * @param string $taxonomy Taxonomy slug. * @param string $action Hook action, created, edited or deleted. * @return void */ public function onTermChange( int $termId, int $ttId, string $taxonomy, string $action ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found -- term hook signature; the URL path never needs the term taxonomy id. if ( ! $this->isEnabled() || ! $this->settings()->getAutoSubmit() ) { return; } if ( ! in_array( $action, self::TERM_ACTIONS, true ) ) { return; } $url = $this->collector()->termUrl( $termId, $taxonomy ); if ( '' === $url ) { return; } if ( function_exists( 'get_term_meta' ) && NoindexFlag::isNoindex( get_term_meta( $termId, NoindexFlag::TERM_PAYLOAD, true ) ) ) { return; } $this->queueDeferredSubmit( 0, [ $url ], $url, '', 'term_' . $action ); } /** * Empty outcome summary matching the client result shape. * * @return array The result. */ private static function emptyResult(): array { return [ 'accepted' => 0, 'permanent' => 0, 'transient' => 0, 'results' => [], ]; } /** * Resolve the enable map, reading the option once when not injected. * * @return ModuleEnableMap The result. */ private function enableMap(): ModuleEnableMap { return $this->enableMap ??= new ModuleEnableMap(); } /** * Resolve the settings, constructing the default when not injected. * * @return IndexNowSettings The result. */ private function settings(): IndexNowSettings { return $this->settings ??= new IndexNowSettings(); } /** * Resolve the client, constructing the default when not injected. * * @return IndexNowClient The result. */ private function client(): IndexNowClient { return $this->client ??= new IndexNowClient( $this->settings() ); } /** * Resolve the URL collector. * * @return UrlCollector The result. */ private function collector(): UrlCollector { return $this->collector ??= new UrlCollector( $this->settings() ); } /** * Resolve the key file server. * * @return KeyFileServer The result. */ private function server(): KeyFileServer { return $this->server ??= new KeyFileServer( $this->settings() ); } /** * Post id from the mixed object a hook hands over. * * @param mixed $post Post object. * @return int The result. */ private function postId( mixed $post ): int { if ( ! is_object( $post ) || ! isset( $post->ID ) || ! is_numeric( $post->ID ) ) { return 0; } return (int) $post->ID; } /** * Post type from the mixed object a hook hands over. * * @param mixed $post Post object. * @return string The result. */ private function postType( mixed $post ): string { if ( ! is_object( $post ) || ! isset( $post->post_type ) || ! is_string( $post->post_type ) ) { return ''; } return $post->post_type; } /** * Content hash from the mixed object a hook hands over. * * Empty content hashes to the empty string, which never matches a * stored record, so the dedupe fails open toward submitting. * * @param mixed $post Post object. * @return string Hash of the post content, or empty string. */ private function postContentHash( mixed $post ): string { if ( ! is_object( $post ) || ! isset( $post->post_content ) || ! is_string( $post->post_content ) || '' === $post->post_content ) { return ''; } return md5( $post->post_content ); } /** * Post password from the mixed object a hook hands over. * * A non empty password keeps the post out of every submission, * matching the spec exclusion for password protected posts. * * @param mixed $post Post object. * @return string The result. */ private function postPassword( mixed $post ): string { if ( ! is_object( $post ) || ! isset( $post->post_password ) || ! is_string( $post->post_password ) ) { return ''; } return $post->post_password; } /** * Whether the post id is a revision or an autosave. * * @param int $postId Post id. * @return bool The result. */ private function isRevisionOrAutosave( int $postId ): bool { if ( function_exists( 'wp_is_post_revision' ) && wp_is_post_revision( $postId ) ) { return true; } return function_exists( 'wp_is_post_autosave' ) && (bool) wp_is_post_autosave( $postId ); } /** * Whether the post type is publicly viewable. * * @param string $postType Post type. * @return bool The result. */ private function isViewablePostType( string $postType ): bool { return function_exists( 'is_post_type_viewable' ) && (bool) is_post_type_viewable( $postType ); } /** * Whether the post status is publicly viewable. * * @param string $status Post status. * @return bool The result. */ private function isViewableStatus( string $status ): bool { return function_exists( 'is_post_status_viewable' ) && (bool) is_post_status_viewable( $status ); } /** * Whether a transition is a submit signal. * * @param string $newStatus New post status. * @param string $oldStatus Previous post status. * @return bool The result. */ private function isSignal( string $newStatus, string $oldStatus ): bool { if ( 'publish' === $newStatus ) { return true; } return 'trash' === $newStatus && $this->isViewableStatus( $oldStatus ); } }