partial = $this->partialRequest();
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- delegates to handleSave which verifies capability plus nonce.
$requestMethod = isset( $_SERVER['REQUEST_METHOD'] ) && is_string( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- delegates to handleSave which verifies capability plus nonce.
if ( 'POST' === $requestMethod && ( isset( $_POST['rankkernel_save'] ) || isset( $_POST['rk_llms_save'] ) || isset( $_POST['rk_llms_write'] ) || isset( $_POST['rk_llms_reset'] ) || isset( $_POST['rk_robots_save'] ) || isset( $_POST['rk_robots_reset'] ) || isset( $_POST['rk_htaccess_save'] ) ) ) {
$this->handleSave();
}
// A partial must be rendered and finished here, on the load hook. The page
// callback runs after admin-header.php, so returning from it early would
// still ship the whole admin page, which is exactly what the section
// loader swaps into the panel. Rendering here keeps the reply to the one
// section plus its save button.
if ( null !== $this->partial ) {
$this->render();
$this->finishPartialRequest();
}
}
/**
* End the request after a partial render, before the admin chrome.
*
* Skipped under the test harness, which needs the call to return so it can
* assert on the captured output.
*/
private function finishPartialRequest(): void {
if ( ! defined( 'RANKKERNEL_TESTING' ) ) {
exit;
}
}
/**
* Prepare the view state and load the settings view.
*/
public function render(): void {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only flag, sanitized below.
$settingsUpdated = isset( $_GET['settings-updated'] ) && is_string( $_GET['settings-updated'] ) && '1' === sanitize_key( wp_unslash( $_GET['settings-updated'] ) );
// Read only failure flag, sanitized below. It rides the rk_notice
// query argument shared with the section notices.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only flag, sanitized below.
$saveNotice = isset( $_GET['rk_notice'] ) && is_string( $_GET['rk_notice'] ) ? sanitize_key( wp_unslash( $_GET['rk_notice'] ) ) : '';
$settingsSaveFailed = 'save_failed' === $saveNotice;
$allSettings = $this->store->all();
$titleTemplate = (string) ( $allSettings['title_template'] ?? '' );
$descriptionTemplate = (string) ( $allSettings['description_template'] ?? '' );
$titleSeparator = (string) ( $allSettings['separator'] ?? '' );
$socialDefaultImage = is_string( $allSettings['social_default_image'] ?? null ) ? $allSettings['social_default_image'] : '';
$socialDefaultImageId = is_numeric( $allSettings['social_default_image_id'] ?? null ) && (int) $allSettings['social_default_image_id'] > 0 ? (int) $allSettings['social_default_image_id'] : 0;
$twitterSite = MetaPayload::sanitizeTwitterHandle( $allSettings['twitter_site'] ?? '' );
$socialProfiles = array();
foreach ( array( 'facebook', 'twitter', 'instagram', 'linkedin', 'youtube', 'pinterest' ) as $socialNetwork ) {
$socialProfiles[ $socialNetwork ] = esc_url_raw( is_string( $allSettings[ 'social_' . $socialNetwork ] ?? null ) ? $allSettings[ 'social_' . $socialNetwork ] : '' );
}
$webmasterLabels = [
'webmaster_google' => __( 'Google', 'rankkernel' ),
'webmaster_bing' => __( 'Bing', 'rankkernel' ),
'webmaster_yandex' => __( 'Yandex', 'rankkernel' ),
'webmaster_pinterest' => __( 'Pinterest', 'rankkernel' ),
'webmaster_baidu' => __( 'Baidu', 'rankkernel' ),
];
$webmasters = [];
foreach ( $webmasterLabels as $webmasterKey => $webmasterLabel ) {
$webmasters[] = [
'fieldId' => 'rk-' . str_replace( '_', '-', $webmasterKey ),
'key' => $webmasterKey,
'label' => $webmasterLabel,
'value' => (string) ( $allSettings[ $webmasterKey ] ?? '' ),
];
}
$purgeChecked = ! empty( $allSettings['purge_on_uninstall'] );
$breadcrumbs = $this->breadcrumbsSettings()->all();
$breadcrumbSeparator = isset( $breadcrumbs['separator'] ) ? (string) $breadcrumbs['separator'] : '/';
$homeLabel = (string) ( $breadcrumbs['home_label'] ?? 'Home' );
$appearanceToggles = [
[
'name' => 'rk_breadcrumbs_show_home',
'title' => __( 'Show home link', 'rankkernel' ),
'checked' => ! empty( $breadcrumbs['show_home'] ),
'hint' => __( 'Start the trail with a link to the homepage.', 'rankkernel' ),
],
[
'name' => 'rk_breadcrumbs_show_current',
'title' => __( 'Show current page', 'rankkernel' ),
'checked' => ! empty( $breadcrumbs['show_current'] ),
'hint' => __( 'End the trail with the current page title.', 'rankkernel' ),
],
[
'name' => 'rk_breadcrumbs_hide_on_front_page',
'title' => __( 'Hide on front page', 'rankkernel' ),
'checked' => ! empty( $breadcrumbs['hide_on_front_page'] ),
'hint' => __( 'Show no trail on the static front page.', 'rankkernel' ),
],
];
$behaviorToggles = [
[
'name' => 'rk_breadcrumbs_show_blog_page',
'title' => __( 'Show blog page', 'rankkernel' ),
'checked' => ! empty( $breadcrumbs['show_blog_page'] ),
'hint' => __( 'Include the posts page in post trails when one exists.', 'rankkernel' ),
],
[
'name' => 'rk_breadcrumbs_show_ancestors',
'title' => __( 'Show term ancestors', 'rankkernel' ),
'checked' => ! empty( $breadcrumbs['show_ancestors'] ),
'hint' => __( 'Include parent terms above the current term.', 'rankkernel' ),
],
];
$isCustomSeparator = ! BreadcrumbsSettings::isSeparatorPreset( $breadcrumbSeparator );
$separatorChoices = [];
foreach ( BreadcrumbsSettings::separatorPresets() as $index => $preset ) {
$separatorChoices[] = [
'id' => 'rk-breadcrumbs-separator-choice-' . $index,
'value' => $preset,
'checked' => ! $isCustomSeparator && $breadcrumbSeparator === $preset,
];
}
/*
* The general separator picker reuses the breadcrumbs preset list, so
* the two pickers cannot drift apart. It saves into the same separator
* key it always has, which is a different option from the breadcrumbs
* separator. Any stored value outside the presets, including the en
* dash default, selects the Custom choice.
*/
$isCustomTitleSeparator = ! BreadcrumbsSettings::isSeparatorPreset( $titleSeparator );
$titleSeparatorChoices = [];
foreach ( BreadcrumbsSettings::separatorPresets() as $index => $preset ) {
$titleSeparatorChoices[] = [
'id' => 'rk-separator-choice-' . $index,
'value' => $preset,
'checked' => ! $isCustomTitleSeparator && $titleSeparator === $preset,
];
}
$taxonomyRows = [];
foreach ( $this->breadcrumbsPostTypes() as $slug => $label ) {
$taxes = $this->taxonomiesForType( $slug );
if ( [] === $taxes ) {
continue;
}
if ( 1 === count( $taxes ) ) {
$onlyLabel = (string) reset( $taxes );
$taxonomyRows[] = [
'rowType' => 'info',
/* translators: %s: post type label. */
'title' => sprintf( __( 'Primary taxonomy (%s)', 'rankkernel' ), $label ),
/* translators: %s: taxonomy label. */
'hint' => sprintf( __( 'Uses %s, the only public taxonomy available.', 'rankkernel' ), $onlyLabel ),
];
continue;
}
$key = 'primary_taxonomy_' . $slug;
$field = 'rk_breadcrumbs_primary_taxonomy_' . $slug;
$fieldId = 'rk-breadcrumbs-primary-taxonomy-' . $slug;
$current = isset( $breadcrumbs[ $key ] ) ? (string) $breadcrumbs[ $key ] : '';
$taxonomyOptions = [];
foreach ( $taxes as $taxSlug => $taxLabel ) {
$taxonomyOptions[] = [
'slug' => $taxSlug,
'label' => $taxLabel,
];
}
$taxonomyRows[] = [
'rowType' => 'select',
/* translators: %s: post type label. */
'title' => sprintf( __( 'Primary taxonomy (%s)', 'rankkernel' ), $label ),
'fieldId' => $fieldId,
'field' => $field,
'current' => $current,
'options' => $taxonomyOptions,
];
}
$robotsEnabled = $this->enableMap->isEnabled( 'robots' );
$settingsSections = [
[
'id' => 'general',
'label' => __( 'General', 'rankkernel' ),
],
[
'id' => 'breadcrumbs',
'label' => __( 'Breadcrumbs', 'rankkernel' ),
],
[
'id' => 'webmaster',
'label' => __( 'Webmaster Tools', 'rankkernel' ),
],
[
'id' => 'social',
'label' => __( 'Social', 'rankkernel' ),
],
];
if ( $robotsEnabled ) {
$settingsSections[] = [
'id' => 'robots',
'label' => __( 'Robots.txt', 'rankkernel' ),
];
$robotSettings = $this->robots ?? new RobotsSettings();
$robotPolicies = CrawlerPolicy::sanitizeMap( $robotSettings->get( 'crawlers', [] ) );
$robotOverride = (string) $robotSettings->get( 'override', '' );
$robotGroups = [];
foreach ( CrawlerPolicy::PURPOSES as $purposeKey => $purposeLabel ) {
$crawlers = [];
foreach ( CrawlerPolicy::all() as $crawlerSlug => $crawler ) {
if ( (string) $crawler['purpose'] !== (string) $purposeKey ) {
continue;
}
$crawlers[] = [
'slug' => (string) $crawlerSlug,
'label' => (string) $crawler['label'],
'note' => (string) $crawler['note'],
'policy' => $robotPolicies[ (string) $crawlerSlug ] ?? CrawlerPolicy::CUSTOM,
];
}
if ( [] !== $crawlers ) {
$robotGroups[] = [
'label' => (string) $purposeLabel,
'crawlers' => $crawlers,
];
}
}
$robotGenerated = ( new RobotsBuilder() )->build( $this->previewCoreBlock(), true, $robotPolicies, '' );
$robotEffective = ( '' !== trim( $robotOverride ) ) ? ( rtrim( trim( $robotOverride ) ) . "\n" ) : $robotGenerated;
$robotEditValue = ( '' !== trim( $robotOverride ) ) ? $robotOverride : $robotGenerated;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only tab flag, sanitized below.
$robotTab = 'edit' === ( isset( $_GET['robots_tab'] ) && is_string( $_GET['robots_tab'] ) ? sanitize_key( wp_unslash( $_GET['robots_tab'] ) ) : '' ) ? 'edit' : 'preview';
$robotValidation = RobotsDirectives::validate( $robotOverride );
$settingsSections[] = [
'id' => 'llms',
'label' => __( 'llms.txt', 'rankkernel' ),
];
$llmsSettings = $this->llms ?? new LlmsSettings();
$llmsEnabled = (bool) $llmsSettings->get( 'enabled', false );
$llmsSummary = (string) $llmsSettings->get( 'summary', '' );
$llmsContent = (string) $llmsSettings->get( 'content', '' );
$llmsPhysical = (bool) $llmsSettings->get( 'physical', false );
$llmsValidation = ( new LlmsGenerator() )->validate( $llmsContent );
$llmsPreview = ( new LlmsGenerator() )->render( (string) get_bloginfo( 'name' ), $llmsSummary, $llmsContent );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only flag, sanitized below.
$llmsNotice = isset( $_GET['rk_notice'] ) && is_string( $_GET['rk_notice'] ) ? sanitize_key( wp_unslash( $_GET['rk_notice'] ) ) : '';
// Derived from the settings already loaded above: no extra query and no write.
$consistencyWarnings = CrawlConsistency::warnings( $robotPolicies, $llmsEnabled, $robotEffective );
$settingsSections[] = [
'id' => 'htaccess',
'label' => __( '.htaccess', 'rankkernel' ),
];
}
$htaccessFile = new HtaccessFile();
$htaccessSupported = $htaccessFile->isSupported();
$htaccessWritable = $htaccessFile->isWritable();
$htaccessManaged = $htaccessSupported ? $htaccessFile->hasBlock() : false;
$htaccessSelected = $htaccessSupported ? $htaccessFile->blockSelection() : [];
$htaccessPath = $htaccessFile->path();
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only notice flag, sanitized below.
$htaccessNotice = isset( $_GET['rk_notice'] ) && is_string( $_GET['rk_notice'] ) ? sanitize_key( wp_unslash( $_GET['rk_notice'] ) ) : '';
$settingsSections[] = [
'id' => 'advanced',
'label' => __( 'Advanced', 'rankkernel' ),
];
$sectionIds = array_map(
static function ( array $section ): string {
return (string) $section['id'];
},
$settingsSections
);
// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- read-only panel flag, sanitized below.
$rawSection = isset( $_GET['section'] ) && is_string( $_GET['section'] ) ? sanitize_key( (string) wp_unslash( $_GET['section'] ) ) : '';
$currentSection = in_array( $rawSection, $sectionIds, true ) ? $rawSection : 'general';
$partial = ( null !== $this->partial && in_array( $this->partial, $sectionIds, true ) ) ? $this->partial : null;
if ( null !== $partial ) {
if ( $settingsSaveFailed ) {
?>
partial ) {
return;
}
wp_safe_redirect( $url );
if ( ! defined( 'RANKKERNEL_TESTING' ) ) {
exit;
}
}
/**
* Section requested as a partial, or null.
*
* @return string|null The result.
*/
private function partialRequest(): ?string {
$key = '';
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- read-only partial flag, sanitized below.
if ( isset( $_POST['rk_partial'] ) && is_string( $_POST['rk_partial'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- read-only partial flag, sanitized below.
$key = sanitize_key( wp_unslash( $_POST['rk_partial'] ) );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only partial flag, sanitized below.
} elseif ( isset( $_GET['rk_partial'] ) && is_string( $_GET['rk_partial'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only partial flag, sanitized below.
$key = sanitize_key( wp_unslash( $_GET['rk_partial'] ) );
}
return in_array( $key, [ 'general', 'breadcrumbs', 'webmaster', 'social', 'robots', 'llms', 'htaccess', 'advanced' ], true ) ? $key : null;
}
/**
* Save the robots.txt section through the module settings class.
*
* Field names carry an rk_robots_ prefix so they never collide with the
* other sections. The override is only written when the editor posted
* it, so saving from the preview tab keeps the stored override.
*
* @return bool Whether the robots settings were stored.
*/
private function saveRobots(): bool {
$settings = $this->robots ?? new RobotsSettings();
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave.
$rawPolicies = isset( $_POST['rk_robots_policy'] ) ? map_deep( wp_unslash( $_POST['rk_robots_policy'] ), 'sanitize_key' ) : [];
$partial = [
'crawlers' => is_array( $rawPolicies ) ? $rawPolicies : [],
];
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave.
if ( isset( $_POST['rk_robots_override'] ) && is_string( $_POST['rk_robots_override'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave.
$partial['override'] = sanitize_textarea_field( wp_unslash( $_POST['rk_robots_override'] ) );
}
return $settings->set( $partial );
}
/**
* Replace the managed .htaccess block, then redirect with a notice.
*
* The payload is an array of directive ids. saveBlock() ignores every
* id outside the whitelist, so the written content is always
* generated server side and no admin text reaches the file.
*/
private function saveHtaccess(): void {
$file = new HtaccessFile();
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave, request shape enforced below.
$requested = isset( $_POST['rk_htaccess_directives'] ) && is_array( $_POST['rk_htaccess_directives'] ) ? map_deep( wp_unslash( $_POST['rk_htaccess_directives'] ), 'sanitize_key' ) : [];
$selected = [];
if ( is_array( $requested ) ) {
foreach ( array_keys( $requested ) as $id ) {
if ( is_string( $id ) && array_key_exists( $id, HtaccessFile::DIRECTIVES ) ) {
$selected[] = $id;
}
}
}
$result = $file->saveBlock( $selected );
if ( $result['saved'] ) {
$notice = 'saved';
} elseif ( 'unsupported' === $result['reason'] ) {
$notice = 'unsupported';
} elseif ( 'backup_unavailable' === $result['reason'] || 'backup_failed' === $result['reason'] ) {
$notice = 'backup_failed';
} else {
$notice = 'failed';
}
$this->redirectTo( admin_url( 'admin.php?page=rankkernel-general§ion=htaccess&rk_notice=' . $notice ) );
}
/**
* Clear the robots.txt override, back to the generated document.
*/
private function resetRobots(): void {
$settings = $this->robots ?? new RobotsSettings();
$settings->set( [ 'override' => '' ] );
$this->redirectTo( admin_url( 'admin.php?page=rankkernel-general§ion=robots&robots_tab=preview&settings-updated=1' ) );
}
/**
* Save the llms.txt section through the module settings class.
*
* Field names carry an rk_llms_ prefix. Values sanitize through the
* llms settings store, then the cached document is invalidated.
*
* @return bool Whether the llms settings were stored.
*/
private function saveLlms(): bool {
$settings = $this->llms ?? new LlmsSettings();
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave.
$rawSummary = isset( $_POST['rk_llms_summary'] ) && is_string( $_POST['rk_llms_summary'] ) ? sanitize_textarea_field( wp_unslash( $_POST['rk_llms_summary'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave.
$rawContent = isset( $_POST['rk_llms_content'] ) && is_string( $_POST['rk_llms_content'] ) ? sanitize_textarea_field( wp_unslash( $_POST['rk_llms_content'] ) ) : '';
$saved = $settings->set(
[
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave.
'enabled' => isset( $_POST['rk_llms_enabled'] ),
'summary' => $rawSummary,
'content' => $rawContent,
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in handleSave.
'physical' => isset( $_POST['rk_llms_physical'] ),
]
);
LlmsRouter::invalidate();
// The route registers at boot, so a successful save must flush for it
// to go live (or disappear) at once instead of waiting for an
// unrelated flush. Without this the route 404s after a green save.
if ( $saved && function_exists( 'flush_rewrite_rules' ) ) {
flush_rewrite_rules( false );
}
// The physical file belongs to the enabled feature: once a save lands
// with it disabled, remove the managed file so a stale document stops
// shadowing the virtual route. delete() is a safe no-op when nothing
// managed exists, and it never touches a hand made file.
if ( $saved && ! (bool) $settings->get( 'enabled', false ) ) {
( new LlmsFileWriter() )->delete();
}
return $saved;
}
/**
* Write the physical llms.txt, then redirect with a status notice.
*/
private function writePhysicalLlms(): void {
$settings = $this->llms ?? new LlmsSettings();
$content = ( new LlmsGenerator() )->render(
(string) get_bloginfo( 'name' ),
(string) $settings->get( 'summary', '' ),
(string) $settings->get( 'content', '' )
);
$result = ( new LlmsFileWriter() )->write( $content );
if ( $result['written'] ) {
$notice = 'written';
} elseif ( 'exists' === $result['reason'] ) {
$notice = 'exists';
} else {
$notice = 'failed';
}
$this->redirectTo( admin_url( 'admin.php?page=rankkernel-general§ion=llms&rk_notice=' . $notice ) );
}
/**
* Reset the llms.txt settings to their defaults.
*/
private function resetLlms(): void {
$settings = $this->llms ?? new LlmsSettings();
$settings->set( LlmsSettings::defaults() );
LlmsRouter::invalidate();
( new LlmsFileWriter() )->delete();
$this->redirectTo( admin_url( 'admin.php?page=rankkernel-general§ion=llms&settings-updated=1' ) );
}
/**
* Section the save was posted from, read from the screen URL.
*
* The form carries only its own section, so each saver below runs solely
* for the section that posted. Unknown or missing values fall back to the
* general section, matching the render path.
*
* @return string Section id.
*/
private function postedSection(): string {
// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- the nonce action itself depends on this value; verified immediately after.
$raw = isset( $_GET['section'] ) && is_string( $_GET['section'] ) ? sanitize_key( (string) wp_unslash( $_GET['section'] ) ) : '';
$ids = [ 'general', 'breadcrumbs', 'webmaster', 'social', 'robots', 'llms', 'htaccess', 'advanced' ];
return in_array( $raw, $ids, true ) ? $raw : 'general';
}
/**
* Handle save, capability + nonce, then persist settings + modules.
*/
private function handleSave(): void {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die(
esc_html__( 'Sorry, you are not allowed to manage RankKernel settings.', 'rankkernel' ),
'',
[ 'response' => 403 ]
);
}
check_admin_referer( 'rankkernel_settings_' . $this->postedSection() );
// The .htaccess save is a distinct action on the same form, gated
// like the robots and llms actions: a disabled module writes nothing.
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
if ( $this->enableMap->isEnabled( 'robots' ) && isset( $_POST['rk_htaccess_save'] ) ) {
$this->saveHtaccess();
return;
}
// The robots reset is a distinct action on the same form.
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
if ( $this->enableMap->isEnabled( 'robots' ) && isset( $_POST['rk_robots_reset'] ) ) {
$this->resetRobots();
return;
}
// The llms.txt reset is a distinct action on the same form.
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
if ( $this->enableMap->isEnabled( 'robots' ) && isset( $_POST['rk_llms_reset'] ) ) {
$this->resetLlms();
return;
}
// The physical llms.txt write is a distinct action on the same form.
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
if ( $this->enableMap->isEnabled( 'robots' ) && isset( $_POST['rk_llms_write'] ) ) {
$this->saveLlms();
$this->writePhysicalLlms();
return;
}
// Collect settings partial from POST, sanitize each value.
$partial = [];
$textKeys = [
'title_template',
'description_template',
'separator',
'webmaster_google',
'webmaster_bing',
'webmaster_yandex',
'webmaster_pinterest',
'webmaster_baidu',
];
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
foreach ( $textKeys as $key ) {
if ( isset( $_POST[ $key ] ) && is_string( $_POST[ $key ] ) ) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized below.
$partial[ $key ] = sanitize_text_field( (string) wp_unslash( $_POST[ $key ] ) );
}
}
/*
* The general separator picker posts a radio choice plus a custom text
* field, the same shape the breadcrumbs chooser uses. Resolution runs
* after the plain text loop above, so the chooser wins when present and
* a request without it leaves the stored separator alone. Exactly one
* canonical value saves through the existing separator key.
*/
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
if ( isset( $_POST['rk_general_separator_choice'] ) && is_string( $_POST['rk_general_separator_choice'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, sanitized below.
$generalSeparatorChoice = sanitize_text_field( wp_unslash( $_POST['rk_general_separator_choice'] ) );
if ( 'custom' === $generalSeparatorChoice ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, sanitized below.
$generalSeparatorCustom = isset( $_POST['rk_general_separator_custom'] ) && is_string( $_POST['rk_general_separator_custom'] ) ? sanitize_text_field( wp_unslash( $_POST['rk_general_separator_custom'] ) ) : '';
$partial['separator'] = $generalSeparatorCustom;
} else {
$partial['separator'] = $generalSeparatorChoice;
}
}
// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce already verified above.
if ( isset( $_POST['social_default_image'] ) && is_string( $_POST['social_default_image'] ) ) {
$partial['social_default_image'] = esc_url_raw( wp_unslash( $_POST['social_default_image'] ) );
}
if ( isset( $_POST['social_default_image_id'] ) && is_string( $_POST['social_default_image_id'] ) ) {
$rawImageId = (int) sanitize_text_field( wp_unslash( $_POST['social_default_image_id'] ) );
$partial['social_default_image_id'] = $rawImageId > 0 ? $rawImageId : 0;
}
if ( isset( $_POST['twitter_site'] ) && is_string( $_POST['twitter_site'] ) ) {
$rawTwitter = sanitize_text_field( wp_unslash( $_POST['twitter_site'] ) );
$partial['twitter_site'] = MetaPayload::sanitizeTwitterHandle( $rawTwitter );
}
foreach ( array( 'facebook', 'twitter', 'instagram', 'linkedin', 'youtube', 'pinterest' ) as $socialNetwork ) {
$socialKey = 'social_' . $socialNetwork;
if ( isset( $_POST[ $socialKey ] ) && is_string( $_POST[ $socialKey ] ) ) {
$partial[ $socialKey ] = esc_url_raw( wp_unslash( $_POST[ $socialKey ] ) );
}
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
// Checkbox semantics: absent from POST = false. The checkbox lives on
// the Advanced tab only, so any other section leaves the stored value
// alone instead of deciding it.
if ( 'advanced' === $this->postedSection() ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
$partial['purge_on_uninstall'] = isset( $_POST['purge_on_uninstall'] );
}
$saved = [] === $partial ? true : $this->store->set( $partial );
if ( 'breadcrumbs' === $this->postedSection() ) {
$saved = $this->saveBreadcrumbs() && $saved;
}
if ( $this->enableMap->isEnabled( 'robots' ) && 'robots' === $this->postedSection() ) {
$saved = $this->saveRobots() && $saved;
}
if ( $this->enableMap->isEnabled( 'robots' ) && 'llms' === $this->postedSection() ) {
$saved = $this->saveLlms() && $saved;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- read-only section flag, sanitized below.
$section = isset( $_GET['section'] ) && is_string( $_GET['section'] ) ? sanitize_key( (string) wp_unslash( $_GET['section'] ) ) : '';
// A failed write is reported on the same rk_notice channel the section
// notices use, so the redirect never claims a write that did not happen.
$notice = $saved ? 'settings-updated=1' : 'rk_notice=save_failed';
$redirect = admin_url( 'admin.php?page=rankkernel-general' . ( '' !== $section ? '§ion=' . $section : '' ) . '&' . $notice );
$this->redirectTo( $redirect );
}
/**
* Breadcrumb settings store, injected or fresh.
*
* @return BreadcrumbsSettings The result.
*/
private function breadcrumbsSettings(): BreadcrumbsSettings {
return $this->breadcrumbs ?? new BreadcrumbsSettings();
}
/**
* Enqueue the settings assets on this screen only.
*
* @param string $hookSuffix Current admin page hook suffix.
*/
public function enqueueAssets( string $hookSuffix ): void {
// The admin hook suffix for this submenu differs from the documented
// form, so the page slug is matched as well.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- read-only screen check, sanitized below.
$page = isset( $_GET['page'] ) && is_string( $_GET['page'] ) ? sanitize_key( (string) wp_unslash( $_GET['page'] ) ) : '';
if ( 'rankkernel-general' !== $page && 'rankkernel_page_rankkernel-general' !== $hookSuffix && 'dashboard_page_rankkernel-general' !== $hookSuffix ) {
return;
}
if ( ! function_exists( 'plugins_url' ) ) {
return;
}
if ( function_exists( 'wp_enqueue_media' ) ) {
wp_enqueue_media();
}
$src = plugins_url( 'assets/js/breadcrumbs-admin.js', (string) RANKKERNEL_FILE );
$version = \RankKernel\Plugin::version();
wp_register_script( 'rankkernel-breadcrumbs-admin', $src, [], $version, true );
wp_enqueue_script( 'rankkernel-breadcrumbs-admin' );
wp_register_script(
'rankkernel-settings-admin',
plugins_url( 'assets/js/settings-admin.js', (string) RANKKERNEL_FILE ),
[ 'media-editor', 'wp-a11y', 'wp-i18n' ],
$version,
true
);
if ( function_exists( 'wp_set_script_translations' ) ) {
wp_set_script_translations( 'rankkernel-settings-admin', 'rankkernel' );
}
wp_enqueue_script( 'rankkernel-settings-admin' );
AdminStyles::enqueueTokenLayer( (string) RANKKERNEL_FILE );
if ( function_exists( 'wp_register_style' ) ) {
wp_register_style(
'rankkernel-settings-admin',
plugins_url( 'assets/css/settings-admin.css', (string) RANKKERNEL_FILE ),
[ AdminStyles::TOKEN_HANDLE, AdminStyles::UI_HANDLE ],
$version
);
}
if ( function_exists( 'wp_enqueue_style' ) ) {
wp_enqueue_style( 'rankkernel-settings-admin' );
}
}
/**
* Save the breadcrumbs section through the module settings class.
*
* Field names carry an rk_breadcrumbs_ prefix so they never collide
* with the title template separator key. Values sanitize through
* BreadcrumbsSettings::set, which whitelists keys and validates the
* per post type taxonomy mappings.
*
* Exactly one canonical separator setting is stored. The chooser
* posts a radio choice plus a custom text field; the save computes
* the separator from both and falls back to the legacy single text
* field when the chooser is absent. Taxonomy mappings save only for
* post types that render a select (two or more usable public
* taxonomies); hidden controls post nothing, so their stored values
* are preserved and never deleted.
*
* @return bool Whether the breadcrumbs settings were stored.
*/
private function saveBreadcrumbs(): bool {
$partial = [];
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
if ( isset( $_POST['rk_breadcrumbs_separator_choice'] ) && is_string( $_POST['rk_breadcrumbs_separator_choice'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
$choice = sanitize_text_field( wp_unslash( $_POST['rk_breadcrumbs_separator_choice'] ) );
if ( 'custom' === $choice ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
$custom = isset( $_POST['rk_breadcrumbs_separator_custom'] ) && is_string( $_POST['rk_breadcrumbs_separator_custom'] ) ? sanitize_text_field( wp_unslash( $_POST['rk_breadcrumbs_separator_custom'] ) ) : '';
$partial['separator'] = $custom;
} else {
$partial['separator'] = $choice;
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
} elseif ( isset( $_POST['rk_breadcrumbs_separator'] ) && is_string( $_POST['rk_breadcrumbs_separator'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
$partial['separator'] = sanitize_text_field( wp_unslash( $_POST['rk_breadcrumbs_separator'] ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
if ( isset( $_POST['rk_breadcrumbs_home_label'] ) && is_string( $_POST['rk_breadcrumbs_home_label'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
$partial['home_label'] = sanitize_text_field( wp_unslash( $_POST['rk_breadcrumbs_home_label'] ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, checkbox semantics: absent from POST means false.
$partial['show_home'] = isset( $_POST['rk_breadcrumbs_show_home'] );
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, checkbox semantics: absent from POST means false.
$partial['show_current'] = isset( $_POST['rk_breadcrumbs_show_current'] );
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, checkbox semantics: absent from POST means false.
$partial['hide_on_front_page'] = isset( $_POST['rk_breadcrumbs_hide_on_front_page'] );
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, checkbox semantics: absent from POST means false.
$partial['show_blog_page'] = isset( $_POST['rk_breadcrumbs_show_blog_page'] );
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, checkbox semantics: absent from POST means false.
$partial['show_ancestors'] = isset( $_POST['rk_breadcrumbs_show_ancestors'] );
foreach ( $this->breadcrumbsPostTypes() as $slug => $label ) {
if ( count( $this->taxonomiesForType( $slug ) ) < 2 ) {
continue;
}
$field = 'rk_breadcrumbs_primary_taxonomy_' . $slug;
$key = 'primary_taxonomy_' . $slug;
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified in handleSave.
if ( ! isset( $_POST[ $field ] ) ) {
continue;
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified, validated by the settings class against registered taxonomies.
$raw = isset( $_POST[ $field ] ) && is_string( $_POST[ $field ] ) ? sanitize_key( wp_unslash( $_POST[ $field ] ) ) : '';
$partial[ $key ] = $raw;
}
return $this->breadcrumbsSettings()->set( $partial );
}
/**
* Public post types as slug to label, without attachments.
*
* @return array
*/
private function breadcrumbsPostTypes(): array {
if ( ! function_exists( 'get_post_types' ) ) {
return [];
}
try {
$types = get_post_types( [ 'public' => true ], 'objects' );
} catch ( \Throwable $e ) {
// Test doubles can leak this name into later suites without a backend, so a failure here must never break the save. Production WP always provides it.
unset( $e );
return [];
}
if ( ! is_array( $types ) ) {
return [];
}
/**
* Core type map.
*
* @var array $map
*/
$map = $types;
return $this->slugsWithLabels( $map, [ 'attachment' ] );
}
/**
* Reduce an objects or names map to slug to label pairs.
*
* Slugs outside the settings key pattern are skipped, their keys
* could never be stored.
*
* @param array $map Type map from core.
* @param string[] $skip Slugs to drop.
* @return array
*/
private function slugsWithLabels( array $map, array $skip ): array {
$out = [];
foreach ( $map as $slug => $item ) {
if ( ! is_string( $slug ) || '' === $slug || in_array( $slug, $skip, true ) ) {
continue;
}
if ( 1 !== preg_match( '/^[a-z0-9_]+$/', $slug ) ) {
continue;
}
$label = $slug;
if ( is_object( $item ) && isset( $item->label ) && is_string( $item->label ) && '' !== $item->label ) {
$label = $item->label;
} elseif ( is_string( $item ) && '' !== $item ) {
$label = $item;
}
$out[ $slug ] = $label;
}
return $out;
}
/**
* Public taxonomy slugs registered for a post type.
*
* @param string $postType Post type slug.
* @return array Slug to label pairs.
*/
private function taxonomiesForType( string $postType ): array {
if ( ! function_exists( 'get_object_taxonomies' ) ) {
return [];
}
try {
$taxes = get_object_taxonomies( $postType, 'objects' );
} catch ( \Throwable $e ) {
// Test doubles can leak this name into later suites without a backend, so a failure here must never break the save. Production WP always provides it.
unset( $e );
return [];
}
if ( ! is_array( $taxes ) ) {
return [];
}
/**
* Core taxonomy map.
*
* @var array $map
*/
$map = $taxes;
$out = [];
foreach ( $map as $slug => $tax ) {
if ( ! is_string( $slug ) || '' === $slug ) {
continue;
}
$label = $slug;
$public = false;
if ( is_object( $tax ) ) {
if ( isset( $tax->label ) && is_string( $tax->label ) && '' !== $tax->label ) {
$label = $tax->label;
}
$public = ! empty( $tax->public );
} elseif ( is_string( $tax ) && '' !== $tax ) {
$label = $tax;
$public = true;
}
if ( $public ) {
$out[ $slug ] = $label;
}
}
return $out;
}
}