|null */ private $submit; /** * Constructor. * * The default callback routes through InstantIndexingModule, the * single submission entry point, and never calls the client directly. * It only runs after the enable map gate, so a disabled module never * constructs a client. The outcome summary travels back so the * handler can report a storage failure the client recorded. * * @param IndexNowSettings|null $settings Settings store, fresh one when null. * @param ModuleEnableMap|null $enableMap Enable map, fresh one when null. * @param callable(string[]): array|null $submit Submission callback, null uses the module entry point. */ public function __construct( ?IndexNowSettings $settings = null, ?ModuleEnableMap $enableMap = null, ?callable $submit = null ) { $this->settings = $settings ?? new IndexNowSettings(); $this->enableMap = $enableMap ?? new ModuleEnableMap(); $this->submit = $submit ?? function ( array $urls ): array { return ( new InstantIndexingModule( $this->enableMap, $this->settings ) )->submitUrls( $urls, 'manual' ); }; } /** * Handle a posted form on the load hook, before any output is sent. * * Runs on load rankkernel page rankkernel instant indexing, so wp safe * redirect can still send headers. The marker field selects one of * six branches; the capability and the nonce mapped to that branch * are verified once, before dispatch, so no handler runs before the * gate and no handler repeats the check. * * @return void */ public function maybeHandleSave(): void { $action = $this->postedAction(); $nonce = $this->nonceActionFor( $action ); if ( '' === $nonce ) { return; } $this->requireAccess( $nonce ); switch ( $action ) { case 'save': $this->handleSave(); break; case 'regenerate': $this->handleRegenerate(); break; case 'submit': $this->handleSubmit(); break; case 'clear': $this->handleClear(); break; case 'verify': $this->handleVerify(); break; case 'retry': $this->handleRetry(); break; } } /** * Nonce action mapped to a posted action marker. * * Returning an empty string means the marker is not one of the known * actions, so nothing may be dispatched or verified. * * @param string $action Posted action marker. * @return string Nonce action, empty when unknown. */ private function nonceActionFor( string $action ): string { switch ( $action ) { case 'save': return self::NONCE_SAVE; case 'regenerate': return self::NONCE_REGENERATE; case 'submit': return self::NONCE_SUBMIT; case 'clear': return self::NONCE_CLEAR; case 'verify': return self::NONCE_VERIFY; case 'retry': return self::NONCE_RETRY; } return ''; } /** * Enqueue screen assets, and only on this screen. * * The stylesheet plus the validation script are registered, enqueued * and localized here. The site host, the site port, the log REST URL, * the REST nonce and the retry nonce reach the browser, the API key * never does, and the gate keeps the hook contract shared with the * other module pages. The nonce is the standard WordPress REST CSRF * token, action wp_rest, which core verifies itself for cookie * authenticated requests, so carrying it in the page is the documented * pattern, not a leak. The retry nonce lets an AJAX rebuilt row carry * the same retry form the server renders, so the control survives a * filter, a search or a page click instead of only a full page load. * * @param string $hookSuffix Current admin page hook suffix. * @return void */ public function enqueueAssets( string $hookSuffix ): void { if ( self::HOOK_SUFFIX !== $hookSuffix ) { return; } if ( ! function_exists( 'plugins_url' ) ) { return; } $version = Plugin::version(); if ( function_exists( 'wp_register_style' ) && function_exists( 'wp_enqueue_style' ) ) { AdminStyles::enqueueTokenLayer( (string) RANKKERNEL_FILE ); AdminStyles::enqueueUiLayer( (string) RANKKERNEL_FILE ); $css = plugins_url( 'assets/css/instant-indexing-admin.css', (string) RANKKERNEL_FILE ); wp_register_style( 'rankkernel-instant-indexing-admin', $css, [ AdminStyles::TOKEN_HANDLE, AdminStyles::UI_HANDLE ], $version ); wp_enqueue_style( 'rankkernel-instant-indexing-admin' ); } if ( ! function_exists( 'wp_register_script' ) || ! function_exists( 'wp_enqueue_script' ) ) { return; } $source = plugins_url( 'assets/js/instant-indexing-admin.js', (string) RANKKERNEL_FILE ); wp_register_script( 'rankkernel-instant-indexing-admin', $source, [ 'wp-a11y', 'wp-i18n' ], $version, true ); if ( function_exists( 'wp_set_script_translations' ) ) { wp_set_script_translations( 'rankkernel-instant-indexing-admin', 'rankkernel' ); } wp_enqueue_script( 'rankkernel-instant-indexing-admin' ); if ( ! function_exists( 'wp_localize_script' ) ) { return; } wp_localize_script( 'rankkernel-instant-indexing-admin', 'rankkernelInstantIndexing', [ 'siteHost' => $this->settings->siteHost(), 'sitePort' => $this->sitePort(), 'logUrl' => function_exists( 'rest_url' ) ? (string) rest_url( 'rankkernel/v1/instant-indexing/log' ) : '', 'restNonce' => function_exists( 'wp_create_nonce' ) ? (string) wp_create_nonce( 'wp_rest' ) : '', 'retryNonce' => function_exists( 'wp_create_nonce' ) ? (string) wp_create_nonce( self::NONCE_RETRY ) : '', ] ); } /** * Prepare the view state and load the Instant Indexing view. * * The key is reduced to a boolean plus its public file location here, * so the view never receives the key as a standalone value. The file * location contains the key because engines fetch it from that URL, * and this screen requires manage options, so access is the boundary. * The log filters are read only display values from the query string, * normalized by LogQuery::fromInput, and never stored or trusted for * a write. * * @return void */ public function render(): void { // Read only display flags, sanitized and compared strictly against literals. // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag, sanitized below. $settingsUpdated = isset( $_GET['settings-updated'] ) && is_string( $_GET['settings-updated'] ) && '1' === sanitize_key( wp_unslash( $_GET['settings-updated'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag, whitelisted by InstantIndexingLogView::noticeFor. $noticeCode = isset( $_GET['rk_indexnow_notice'] ) && is_string( $_GET['rk_indexnow_notice'] ) ? sanitize_key( wp_unslash( $_GET['rk_indexnow_notice'] ) ) : ''; $notice = InstantIndexingLogView::noticeFor( $noticeCode ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display value, numeric only. $verifyCode = isset( $_GET['rk_verify_code'] ) && is_numeric( $_GET['rk_verify_code'] ) ? max( 0, (int) sanitize_text_field( wp_unslash( (string) $_GET['rk_verify_code'] ) ) ) : 0; if ( 'verified' === $noticeCode ) { $notice = [ 'type' => 'success', 'message' => sprintf( /* translators: %d: HTTP status code from the key file check. */ __( 'Key file verified. The file returned %d and contained the expected key.', 'rankkernel' ), $verifyCode ), ]; } elseif ( 'verify_failed' === $noticeCode ) { $notice = [ 'type' => 'error', 'message' => sprintf( /* translators: %d: HTTP status code from the key file check. */ __( 'Key file check failed. The file returned %d. Opening the key file URL should show only the key as plain text.', 'rankkernel' ), $verifyCode ), ]; } $keyConfigured = '' !== $this->settings->getKey(); $keyFileUrl = $keyConfigured ? $this->settings->keyLocation() : ''; $autoSubmit = $this->settings->getAutoSubmit(); // The stats strip is unfiltered by design, so it describes the whole // table through one grouped count, never a bounded window. $statsCounts = LogQuery::fromInput( [], InstantIndexingLogView::PER_PAGE )->statusCounts(); $stats = InstantIndexingOutcomes::statsFromCounts( $statsCounts ); $screenUrl = function_exists( 'admin_url' ) ? admin_url( 'admin.php?page=' . self::SLUG ) : ''; $logInput = map_deep( // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display filters, sanitized and normalized by LogQuery::fromInput. wp_unslash( $_GET ), static function ( mixed $value ): mixed { return is_string( $value ) ? sanitize_text_field( $value ) : $value; } ); $logQuery = LogQuery::fromInput( is_array( $logInput ) ? $logInput : [], InstantIndexingLogView::PER_PAGE ); $logView = new InstantIndexingLogView( $logQuery, $screenUrl ); $statusTabs = $logView->tabs(); $pageRows = $logView->pageRows(); $pagination = $logView->pagination(); $showing = $logView->showing(); $hasFilter = $logView->hasFilter(); $listHasRows = $stats['total'] > 0; $nonceSave = self::NONCE_SAVE; $nonceRegenerate = self::NONCE_REGENERATE; $nonceSubmit = self::NONCE_SUBMIT; $nonceClear = self::NONCE_CLEAR; $nonceVerify = self::NONCE_VERIFY; $nonceRetry = self::NONCE_RETRY; $homeUrl = function_exists( 'home_url' ) ? (string) home_url() : ''; $base = '' !== $homeUrl ? rtrim( $homeUrl, '/' ) . '/' : 'https://example.com/'; $urlPlaceholder = $base . "\n" . $base . "sample-page/\n" . $base . 'hello-world/'; require __DIR__ . '/Views/instant-indexing.php'; } /** * Handle the auto submit toggle. * * Absent from POST means false, matching the purge_on_uninstall * pattern on the settings page. * * @return void */ private function handleSave(): void { // Verified before dispatch, checkbox presence is the value. // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified before dispatch, checkbox presence is the value. $this->settings->set( [ 'auto_submit' => isset( $_POST['rankkernel_indexnow_auto_submit'] ) ] ); $this->redirectTo(); } /** * Handle key regeneration, never echoing the replacement. * * @return void */ private function handleRegenerate(): void { $this->settings->resetKey(); $this->redirectTo(); } /** * Handle the clear log form, capability plus nonce first. * * A failed DELETE redirects with the storage failure notice instead * of telling the operator the log was cleared while rows remain. * * @return void */ private function handleClear(): void { $cleared = $this->settings->clearLog(); $this->redirectTo( false, $cleared ? 'cleared' : 'storage_failed' ); } /** * Handle the key file verification check, read only plus guarded. * * The check fetches only the plugin own key file location, never a * caller supplied URL, and never echoes the response body. Only the * verdict plus the status code travel on the redirect, both as * internal literals plus an integer, so nothing attacker controlled * reaches the screen. * * @return void */ private function handleVerify(): void { $result = ( new InstantIndexingKeyCheck() )->check( $this->settings ); $this->redirectTo( false, $result['ok'] ? 'verified' : 'verify_failed', (int) $result['code'] ); } /** * Handle a manual submission of one or many URLs. * * The module must be enabled, because a disabled module makes zero * outbound requests. Each line must pass wp_http_validate_url and * its host must equal the site host, so www and the apex are * different hosts. Every invalid line is logged with its own reason * and dropped, every valid line is submitted in one call, and no * request is ever made to a submitted URL. A submit with any invalid * line redirects with an outcome code, so the screen can render an * error notice that names the reason. When a rejection cannot be * written to the log, the code reports the storage failure instead * of implying the rejection was recorded. The same applies when the * client reports that an accepted batch could not be logged. * * @return void */ private function handleSubmit(): void { if ( ! $this->isModuleEnabled() ) { $recorded = $this->reject( '', __( 'Rejected: the Instant Indexing module is disabled.', 'rankkernel' ) ); $this->redirectTo( false, $recorded ? 'disabled' : 'storage_failed' ); return; } $urls = $this->postedUrls(); if ( [] === $urls ) { $recorded = $this->reject( '', __( 'Rejected: no URLs were provided.', 'rankkernel' ) ); $this->redirectTo( false, $recorded ? 'empty' : 'storage_failed' ); return; } $valid = []; $invalid = 0; $reasonsInvalid = false; $reasonsHost = false; $storageFailed = false; foreach ( $urls as $url ) { $validated = $this->validateUrl( $url ); if ( '' === $validated ) { if ( ! $this->reject( $url, __( 'Rejected: the URL could not be validated.', 'rankkernel' ) ) ) { $storageFailed = true; } ++$invalid; $reasonsInvalid = true; continue; } if ( ! $this->isSiteHost( $validated ) ) { if ( ! $this->reject( $url, __( 'Rejected: the URL host does not match this site.', 'rankkernel' ) ) ) { $storageFailed = true; } ++$invalid; $reasonsHost = true; continue; } $valid[] = $validated; } if ( [] !== $valid ) { $summary = ( $this->submit )( $valid ); if ( true === ( $summary['storage_failed'] ?? false ) ) { $storageFailed = true; } } if ( 0 === $invalid && ! $storageFailed ) { $this->redirectTo( true ); return; } // A rejected URL whose outcome could not be written is never reported as // recorded, so the operator is told the log failed instead of being sent // to a table that holds nothing. The same guard covers an accepted batch // that the client could not log. if ( $storageFailed ) { $this->redirectTo( false, 'storage_failed' ); return; } if ( $reasonsInvalid && $reasonsHost ) { $this->redirectTo( false, 'mixed' ); return; } $this->redirectTo( false, $reasonsHost ? 'host' : 'unvalidated' ); } /** * Handle a retry of one logged submission. * * The retry form posts the row id alone. The URL never travels through * the browser for this action, because it is attacker influenced: it * came from a submission, so a posted URL could be steered. The id is * cast to an int, read back through the shared query layer, which binds * it as a prepared placeholder, and the stored URL is then re-validated * through the same validator plus host check the manual submit uses * before it reaches the module. A refusal writes no submission and the * original row is never touched. A success appends a new row through * the module entry point with the manual source, so the host filter * inside the client still applies. The module must be enabled, because * a disabled module makes zero outbound requests. * * @return void */ private function handleRetry(): void { if ( ! $this->isModuleEnabled() ) { $this->redirectTo( false, 'disabled' ); return; } $id = $this->postedRowId(); if ( $id <= 0 ) { $this->redirectTo( false, 'retry_missing' ); return; } $row = LogQuery::fromInput( [] )->getRow( $id ); if ( null === $row ) { $this->redirectTo( false, 'retry_notfound' ); return; } $validated = $this->validateUrl( $row['url'] ); if ( '' === $validated ) { $this->redirectTo( false, 'retry_unvalidated' ); return; } if ( ! $this->isSiteHost( $validated ) ) { $this->redirectTo( false, 'retry_host' ); return; } ( $this->submit )( [ $validated ] ); $this->redirectTo( false, 'retried' ); } /** * Posted log row id from POST, zero when absent or not numeric. * * The value is only ever used as an int. It reaches SQL solely through * LogQuery::getRow(), which binds it as a prepared placeholder, so no * posted value is ever interpolated into a statement. * * @return int The result. */ private function postedRowId(): int { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified before dispatch, sanitized and cast below. $raw = isset( $_POST['rankkernel_indexnow_id'] ) && is_numeric( $_POST['rankkernel_indexnow_id'] ) ? sanitize_text_field( wp_unslash( $_POST['rankkernel_indexnow_id'] ) ) : '0'; return max( 0, (int) $raw ); } /** * Validate one URL through the WordPress URL validator. * * @param string $url Candidate URL. * @return string Validated URL, or an empty string when validation failed. */ private function validateUrl( string $url ): string { if ( ! function_exists( 'wp_http_validate_url' ) ) { return ''; } $validated = wp_http_validate_url( $url ); return is_string( $validated ) ? $validated : ''; } /** * Log a rejected manual submission, no request made. * * The caller redirects once after every rejection is logged, so a * paste with several invalid URLs records one entry per URL and the * screen still reloads a single time. * * @param string $url Submitted URL, logged for the operator. * @param string $reason Human readable rejection reason. * @return bool Whether the rejection was recorded. */ private function reject( string $url, string $reason ): bool { return $this->settings->logEntry( $url, 0, 'manual', $reason ); } /** * Action marker from POST, empty when absent or not a string. * * @return string The result. */ private function postedAction(): string { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified before dispatch, compared strictly against literals. return isset( $_POST['rankkernel_indexnow_action'] ) && is_string( $_POST['rankkernel_indexnow_action'] ) ? sanitize_key( wp_unslash( $_POST['rankkernel_indexnow_action'] ) ) : ''; } /** * Submitted URLs from POST, empty when absent or not a string. * * The textarea value is split on any newline style, each line * trimmed, empty lines dropped and duplicates removed with order * preserved. The values are never rewritten here, validation * happens next and must see the real value. * * @return string[] The result. */ private function postedUrls(): array { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified before dispatch, sanitized and validated line by line. $raw = isset( $_POST['rankkernel_indexnow_urls'] ) && is_string( $_POST['rankkernel_indexnow_urls'] ) ? sanitize_textarea_field( wp_unslash( $_POST['rankkernel_indexnow_urls'] ) ) : ''; if ( '' === $raw ) { return []; } $lines = preg_split( '/\r\n|\r|\n/', $raw ); if ( ! is_array( $lines ) ) { return []; } $urls = []; $seen = []; foreach ( $lines as $line ) { if ( count( $urls ) >= 100 ) { break; } $url = trim( (string) $line ); if ( '' === $url || isset( $seen[ $url ] ) ) { continue; } $seen[ $url ] = true; $urls[] = $url; } return $urls; } /** * Verify capability plus nonce, stopping with 403 otherwise. * * @param string $nonceAction Nonce action expected for this write. * @return void */ private function requireAccess( string $nonceAction ): void { if ( ! current_user_can( self::CAPABILITY ) ) { wp_die( esc_html__( 'Sorry, you are not allowed to manage Instant Indexing.', 'rankkernel' ), '', [ 'response' => 403 ] ); } check_admin_referer( $nonceAction ); } /** * Whether the Instant Indexing module is enabled in the enable map. * * @return bool The result. */ private function isModuleEnabled(): bool { return $this->enableMap->isEnabled( self::MODULE_ID ); } /** * Whether a validated URL host equals the site host, case folded. * * Both hosts are lower cased before the byte exact hash_equals * comparison, so a URL written with an uppercase host is accepted * while www and the apex stay different hosts. * * @param string $url Validated URL. * @return bool The result. */ private function isSiteHost( string $url ): bool { return hash_equals( strtolower( $this->settings->siteHost() ), strtolower( $this->urlHost( $url ) ) ); } /** * Port component of the home URL, empty for a default port. * * Derived from the same home_url the site host comes from, so the * browser can allow the site own port and refuse every other non * standard port exactly as the server does. * * @return string The result. */ private function sitePort(): string { $home = function_exists( 'home_url' ) ? (string) home_url() : ''; if ( '' === $home ) { return ''; } if ( function_exists( 'wp_parse_url' ) ) { $port = wp_parse_url( $home, PHP_URL_PORT ); } else { // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- wp_parse_url is unavailable outside WordPress, the fallback only parses the core built home URL. $port = parse_url( $home, PHP_URL_PORT ); } if ( ! is_int( $port ) || 80 === $port || 443 === $port ) { return ''; } return (string) $port; } /** * Host component of a URL, native parser fallback outside WordPress. * * @param string $url URL to parse. * @return string The result. */ private function urlHost( string $url ): string { if ( function_exists( 'wp_parse_url' ) ) { return (string) wp_parse_url( $url, PHP_URL_HOST ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- wp_parse_url is unavailable outside WordPress, the fallback only parses a URL already accepted by wp_http_validate_url. return (string) parse_url( $url, PHP_URL_HOST ); } /** * Redirect back to the screen, header safe on the load hook. * * The notice code is one of the internal outcome literals from the * submit and clear handlers, never user input, so it is safe to * carry on the query string for the view to map to a notice. * * @param bool $saved Whether the saved flag should render a notice. * @param string $notice Outcome code for the error or info notice, empty for none. * @param int $verifyCode Status code from the key file check, negative when absent. * @return void */ private function redirectTo( bool $saved = true, string $notice = '', int $verifyCode = -1 ): void { $url = admin_url( 'admin.php?page=' . self::SLUG ); if ( $saved ) { $url .= '&settings-updated=1'; } if ( '' !== $notice ) { $url .= '&rk_indexnow_notice=' . $notice; } if ( $verifyCode >= 0 ) { $url .= '&rk_verify_code=' . $verifyCode; } wp_safe_redirect( $url ); if ( ! defined( 'RANKKERNEL_TESTING' ) ) { exit; } } }