This commit is contained in:
Javier Casares 2026-11-26 15:53:50 +00:00
commit ba2c697d36

View file

@ -3,7 +3,7 @@
* Plugin Name: noindex SEO
* Plugin URI: https://www.robotstxt.software/plugins/noindex-seo/
* Description: Control search engine indexing with robots directives (noindex, nofollow, noarchive, nosnippet, noimageindex) for specific parts of your WordPress site.
* Version: 3.7.0
* Version: 3.7.1
* Requires at least: 7.0
* Requires PHP: 8.3
* Author: ROBOTSTXT
@ -81,8 +81,13 @@ defined( 'ABSPATH' ) || die( 'Bye bye!' );
* other SEO plugins (Yoast, Rank Math, SEOPress, AIOSEO) and
* virtual robots.txt management (bot rules appended to the
* WordPress-generated robots.txt, inactive by default).
* @since 3.7.1 Maintenance release: certified on WordPress 7.2 and PHP 8.6,
* PHPStan level 10 (no baseline), search-results follow/nofollow
* conflict and the missing notranslate fallback icon fixed,
* legacy settings sanitized, direct SQL reduced to the uninstall
* wildcard cleanup.
*/
define( 'NOINDEX_SEO_VERSION', '3.7.0' );
define( 'NOINDEX_SEO_VERSION', '3.7.1' );
/**
* Option key holding the consolidated plugin settings array.
@ -183,14 +188,35 @@ function noindex_seo_normalize_directive_value( $directive, $raw ) {
return '';
}
/**
* Converts a stored `unavailable_after` value to an ISO 8601 datetime.
*
* The stored value is 'Y-m-d H:i' in the site timezone; the output carries
* the numeric UTC offset (e.g. `2025-06-25T15:00:00+02:00`), so crawlers read
* the right instant whatever the site timezone, and it contains no comma
* (the robots directive separator).
*
* @since 3.7.1
*
* @param string $value Normalized stored value.
* @return string ISO 8601 datetime, or '' when the value is not a valid datetime.
*/
function noindex_seo_format_unavailable_after( $value ) {
$dt = date_create_from_format( 'Y-m-d H:i', $value, wp_timezone() );
return ( false !== $dt ) ? $dt->format( 'c' ) : '';
}
/**
* Formats a stored value directive for robots output.
*
* Value directives render as `name:value`; `unavailable_after` additionally
* converts its stored 'Y-m-d H:i' site-time value to the RFC-style datetime
* search engines expect (e.g. `unavailable_after: Wed, 25 Jun 2025 15:00:00 +0200`).
* converts its stored 'Y-m-d H:i' site-time value to an ISO 8601 datetime
* with a UTC offset (e.g. `unavailable_after: 2025-06-25T15:00:00+02:00`).
*
* @since 3.6.0
* @since 3.7.1 `unavailable_after` renders as ISO 8601 instead of the RFC
* 1123 form, whose comma ("Wed, 25 Jun …") collided with the
* directive separator.
*
* @param string $directive Directive slug.
* @param string $value Normalized stored value (non-empty).
@ -198,13 +224,8 @@ function noindex_seo_normalize_directive_value( $directive, $raw ) {
*/
function noindex_seo_format_value_directive( $directive, $value ) {
if ( 'unavailable_after' === $directive ) {
$dt = date_create_from_format( 'Y-m-d H:i', $value, wp_timezone() );
if ( false !== $dt ) {
// RFC 1123-style with a numeric UTC offset ('O'): stable across
// PHP versions, unlike the 'T' abbreviation.
return $directive . ': ' . $dt->format( 'D, d M Y H:i:s O' );
}
return '';
$datetime = noindex_seo_format_unavailable_after( $value );
return ( '' !== $datetime ) ? $directive . ': ' . $datetime : '';
}
return $directive . ':' . $value;
@ -279,6 +300,17 @@ function noindex_seo_format_directives( array $directives ) {
* }
*/
function noindex_seo_get_settings( $force_refresh = false ) {
/**
* Per-request cache of the merged settings (same shape as the return value).
*
* @var array{
* version: int,
* contexts: array<string, array<string, int|string>>,
* rules: array<int, array{field: string, value: string}>,
* robots_txt: array{enabled: int, rules: array<int, array{user_agent: string, policy: string}>},
* config: array{method: string, granular: int, taxonomies_granular: int, seoplugins: int, delete_on_uninstall: int}
* }|null $cached
*/
static $cached = null;
if ( null !== $cached && ! $force_refresh ) {
@ -748,9 +780,100 @@ function noindex_seo_get_import_sources() {
*
* @since 3.7.0
*
* @since 3.7.1 Malformed entries returned by the filter are dropped
* (they used to raise PHP warnings in the counter and runner).
*
* @param array $sources Source registry (see noindex_seo_get_import_sources()).
*/
return apply_filters( 'noindex_seo_import_sources', $sources );
return noindex_seo_validate_import_sources( apply_filters( 'noindex_seo_import_sources', $sources ) );
}
/**
* Validates the filtered import source registry.
*
* Drops every entry that does not match the shape documented on
* noindex_seo_get_import_sources(); a non-array filter result yields no
* sources.
*
* @since 3.7.1
*
* @param mixed $filtered Untrusted result of the noindex_seo_import_sources filter.
* @return array<string, array{
* label: string,
* posts: array{noindex: array{key: string, is?: string, has?: string}, nofollow: array{key: string, is?: string, has?: string}},
* terms?: array{noindex: array{key: string, is?: string, has?: string}, nofollow: array{key: string, is?: string, has?: string}}
* }> Valid sources.
*/
function noindex_seo_validate_import_sources( $filtered ) {
if ( ! is_array( $filtered ) ) {
return array();
}
$valid = array();
foreach ( $filtered as $slug => $source ) {
if ( ! is_string( $slug ) || sanitize_key( $slug ) !== $slug || ! is_array( $source ) || ! isset( $source['label'] ) || ! is_string( $source['label'] ) ) {
continue;
}
$posts = noindex_seo_validate_import_flags( isset( $source['posts'] ) ? $source['posts'] : null );
if ( null === $posts ) {
continue;
}
$entry = array(
'label' => $source['label'],
'posts' => $posts,
);
$terms = noindex_seo_validate_import_flags( isset( $source['terms'] ) ? $source['terms'] : null );
if ( null !== $terms ) {
$entry['terms'] = $terms;
}
$valid[ $slug ] = $entry;
}
return $valid;
}
/**
* Validates the noindex / nofollow flag specs of one import source.
*
* Both flags are required; each needs a non-empty meta `key` plus either an
* exact `is` value or a non-empty `has` substring (see
* noindex_seo_get_import_sources()).
*
* @since 3.7.1
*
* @param mixed $flags Untrusted flag specs (from the noindex_seo_import_sources filter).
* @return array{noindex: array{key: string, is?: string, has?: string}, nofollow: array{key: string, is?: string, has?: string}}|null
* The validated specs, or null when the set is malformed.
*/
function noindex_seo_validate_import_flags( $flags ) {
if ( ! is_array( $flags ) ) {
return null;
}
$valid = array();
foreach ( array( 'noindex', 'nofollow' ) as $directive ) {
$spec = isset( $flags[ $directive ] ) ? $flags[ $directive ] : null;
if ( ! is_array( $spec ) || ! isset( $spec['key'] ) || ! is_string( $spec['key'] ) || '' === $spec['key'] ) {
return null;
}
if ( isset( $spec['is'] ) && is_string( $spec['is'] ) ) {
$valid[ $directive ] = array(
'key' => $spec['key'],
'is' => $spec['is'],
);
} elseif ( isset( $spec['has'] ) && is_string( $spec['has'] ) && '' !== $spec['has'] ) {
$valid[ $directive ] = array(
'key' => $spec['key'],
'has' => $spec['has'],
);
} else {
return null;
}
}
return array(
'noindex' => $valid['noindex'],
'nofollow' => $valid['nofollow'],
);
}
/**
@ -819,11 +942,11 @@ function noindex_seo_count_import_sources() {
// Transients can hold stale or foreign shapes: validate per row.
$valid = array();
foreach ( $cached as $slug => $row ) {
if ( is_string( $slug ) && is_array( $row ) && isset( $row['label'], $row['posts'], $row['terms'] ) ) {
if ( is_string( $slug ) && is_array( $row ) && isset( $row['label'], $row['posts'], $row['terms'] ) && is_string( $row['label'] ) && is_int( $row['posts'] ) && is_int( $row['terms'] ) ) {
$valid[ $slug ] = array(
'label' => (string) $row['label'],
'posts' => (int) $row['posts'],
'terms' => (int) $row['terms'],
'label' => $row['label'],
'posts' => $row['posts'],
'terms' => $row['terms'],
);
}
}
@ -838,13 +961,12 @@ function noindex_seo_count_import_sources() {
foreach ( noindex_seo_get_import_sources() as $slug => $source ) {
$found = get_posts(
array(
'post_type' => $coverage['post_types'],
'post_status' => $coverage['post_statuses'],
'fields' => 'ids',
'posts_per_page' => -1,
'no_found_rows' => true,
'suppress_filters' => true,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'post_type' => $coverage['post_types'],
'post_status' => $coverage['post_statuses'],
'fields' => 'ids',
'posts_per_page' => -1,
'no_found_rows' => true,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
array_merge( array( 'relation' => 'OR' ), noindex_seo_import_flags_meta_query( $source['posts'] ) ),
),
)
@ -940,13 +1062,12 @@ function noindex_seo_run_import( array $slugs ) {
$coverage = noindex_seo_import_posts_coverage();
$post_ids = get_posts(
array(
'post_type' => $coverage['post_types'],
'post_status' => $coverage['post_statuses'],
'fields' => 'ids',
'posts_per_page' => -1,
'no_found_rows' => true,
'suppress_filters' => true,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'post_type' => $coverage['post_types'],
'post_status' => $coverage['post_statuses'],
'fields' => 'ids',
'posts_per_page' => -1,
'no_found_rows' => true,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
array_merge( array( 'relation' => 'OR' ), noindex_seo_import_flags_meta_query( $source['posts'] ) ),
),
)
@ -1134,6 +1255,13 @@ function noindex_seo_update_settings( array $settings ) {
* (value directive), so value-carrying directives such as
* `max-snippet` render as `max-snippet:-1`. Flat lists of
* boolean names passed by third-party code still work.
* @since 3.7.1 `nofollow` / `noindex` remove a `follow` / `index` already in
* the wp_robots array (core's search-results `follow` produced
* contradictory "follow, nofollow" output). The header-only
* method applies the same clean-up to the meta tag other
* sources print, without adding the plugin's own directives.
* `unavailable_after` reaches wp_robots as ISO 8601 with the
* UTC offset instead of the raw site-time value.
*
* @see https://developer.wordpress.org/reference/hooks/wp_robots/
* @see https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag
@ -1196,21 +1324,18 @@ function noindex_seo_metarobots( $method = 'meta', array $directives = array( 'n
// Add HTML meta tag if requested, or as fallback if headers already sent.
$use_meta = in_array( $method, array( 'meta', 'both' ), true );
$fallback_needed = in_array( $method, array( 'header', 'both' ), true ) && ! $header_sent;
if ( ! ( $use_meta || $fallback_needed ) ) {
return;
}
$add_own = $use_meta || $fallback_needed;
if ( function_exists( 'wp_robots' ) ) {
// WordPress 5.7+: inject the directives into the core robots API.
// On WordPress older than 5.7 the wp_robots filter does not exist and the classic wp_head output below is used instead.
// With the header-only method the plugin adds nothing to the meta
// tag, but still keeps other sources' tag from contradicting the
// header (core's search-results 'follow' next to a header 'nofollow').
add_filter(
'wp_robots',
function ( array $robots ) use ( $directives ) {
foreach ( $directives as $name => $value ) {
$robots[ $name ] = ( true === $value ) ? true : $value;
}
return $robots;
function ( array $robots ) use ( $directives, $add_own ) {
return noindex_seo_merge_robots( $robots, $directives, $add_own );
},
99 // High priority to ensure our directives take precedence over other plugins.
);
@ -1218,6 +1343,10 @@ function noindex_seo_metarobots( $method = 'meta', array $directives = array( 'n
return;
}
if ( ! $add_own ) {
return;
}
// WordPress 4.0 - 5.6: classic <meta name="robots"> tag on wp_head.
add_action(
'wp_head',
@ -1228,6 +1357,44 @@ function noindex_seo_metarobots( $method = 'meta', array $directives = array( 'n
);
}
/**
* Merge the plugin's directives into a wp_robots array without contradictions.
*
* A plugin `nofollow` / `noindex` removes a `follow` / `index` set by core
* (search results), the theme or another plugin. With `$add_own` false
* (header-only method) nothing is added or changed; only those positive
* counterparts are removed, so the meta tag other sources print does not
* contradict the X-Robots-Tag header. `unavailable_after` is converted to
* ISO 8601 with the UTC offset (core prints the value as given).
*
* @since 3.7.1
*
* @param array<mixed> $robots The wp_robots array (filter input, untyped).
* @param array<string, int|string|true> $directives Normalized directive map (name => true or value).
* @param bool $add_own Whether to add the plugin's directives to the array.
* @return array<mixed> The merged array.
*/
function noindex_seo_merge_robots( array $robots, array $directives, $add_own ) {
if ( $add_own ) {
foreach ( $directives as $name => $value ) {
if ( 'unavailable_after' === $name ) {
$value = noindex_seo_format_unavailable_after( (string) $value );
if ( '' === $value ) {
continue;
}
}
$robots[ $name ] = $value;
}
}
if ( isset( $directives['nofollow'] ) ) {
unset( $robots['follow'] );
}
if ( isset( $directives['noindex'] ) ) {
unset( $robots['index'] );
}
return $robots;
}
/**
* Clear all robots directive meta values for a post.
*
@ -1668,38 +1835,20 @@ function noindex_seo_migrate_to_v3() {
update_option( NOINDEX_SEO_SETTINGS_KEY, $consolidated );
// Mark each legacy option as non-autoloaded. update_option() short-circuits
// when the value is unchanged (which is the case here — we are only flipping
// the autoload flag), so we use a direct SQL UPDATE on the options table.
// The options themselves remain readable for a safe rollback to 2.x; they
// will be deleted entirely in 4.0.
global $wpdb;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
// Migration is a one-shot operation. Direct update is necessary because
// update_option() does not change autoload when the value is unchanged.
// This is a UPDATE (no result set), so caching is not applicable.
// when the value is unchanged (we are only flipping the autoload flag), so
// the dedicated core API is used instead (WP 6.4+; it also keeps the
// alloptions cache consistent). The options themselves remain readable for
// a safe rollback to 2.x; they will be deleted entirely in 4.0.
$legacy_keys = array();
foreach ( $contexts as $context ) {
foreach ( $directives as $directive ) {
$option_key = $directive . '_seo_' . $context;
$wpdb->query(
$wpdb->prepare(
"UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name = %s",
$option_key
)
);
$legacy_keys[ $directive . '_seo_' . $context ] = false;
}
}
foreach ( array( 'method', 'granular', 'seoplugins', 'delete_on_uninstall' ) as $config_key ) {
$option_key = 'noindex_seo_config_' . $config_key;
$wpdb->query(
$wpdb->prepare(
"UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name = %s",
$option_key
)
);
$legacy_keys[ 'noindex_seo_config_' . $config_key ] = false;
}
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
wp_set_option_autoload_values( $legacy_keys );
// Mark migration complete and clear cache.
update_option( 'noindex_seo_config_version', 3 );
@ -2355,8 +2504,10 @@ add_action( 'init', 'noindex_seo_register_icons' );
* the legacy emoji glyph, escaped and hidden from assistive technology.
*
* @since 3.5.0
* @since 3.7.1 Added the missing notranslate fallback glyph (WP 7.0 - 7.1
* rendered no icon for it since 3.6.0).
*
* @param string $directive Directive slug (noindex|nofollow|noarchive|nosnippet|noimageindex).
* @param string $directive Directive slug (noindex|nofollow|noarchive|nosnippet|noimageindex|notranslate).
* @return string Safe-to-embed icon markup (SVG from the plugin's own registry, or the escaped emoji fallback).
*/
function noindex_seo_get_directive_icon_html( $directive ) {
@ -2380,6 +2531,7 @@ function noindex_seo_get_directive_icon_html( $directive ) {
'noarchive' => '💾',
'nosnippet' => '📄',
'noimageindex' => '🖼️',
'notranslate' => '🌐',
);
// The emoji is decorative (the directive name is always rendered next to
@ -2696,12 +2848,13 @@ function noindex_seo_get_contexts() {
* @return string The label to display.
*/
function noindex_seo_get_cpt_label( $cpt ) {
if ( isset( $cpt->labels->name ) && '' !== (string) $cpt->labels->name ) {
return (string) $cpt->labels->name;
$labels = isset( $cpt->labels ) && is_object( $cpt->labels ) ? $cpt->labels : null;
if ( null !== $labels && isset( $labels->name ) && is_string( $labels->name ) && '' !== $labels->name ) {
return $labels->name;
}
if ( isset( $cpt->name ) ) {
return (string) $cpt->name;
if ( isset( $cpt->name ) && is_string( $cpt->name ) ) {
return $cpt->name;
}
return '';
@ -2729,6 +2882,9 @@ function noindex_seo_get_cpt_label( $cpt ) {
* @since 3.1.3 Uses the two-argument register_setting() form: the third
* $args array is only supported since WordPress 4.7, and all
* sanitization already happens in the admin-post form handler.
* @since 3.7.1 Back to the $args form (the WordPress floor is 7.0) with a
* sanitize_callback on every legacy option, so a direct
* options.php write can no longer store unsanitized values.
*
* @return void
*/
@ -2737,23 +2893,54 @@ function noindex_seo_register() {
$directives = noindex_seo_get_directives();
// Register each directive for each context.
// Legacy 2.x flags are 0|1 integers; the method is a short slug.
$int_args = array(
'type' => 'integer',
'sanitize_callback' => 'absint',
);
// Register each legacy directive for each context. Only the five 2.x
// directives ever had individual options (the 3.6.0 directives live in
// the consolidated option only).
foreach ( $contexts as $context ) {
foreach ( $directives as $directive ) {
register_setting( 'noindexseo', $directive . '_seo_' . $context );
foreach ( array_intersect( $directives, array( 'noindex', 'nofollow', 'noarchive', 'nosnippet', 'noimageindex' ) ) as $directive ) {
register_setting( 'noindexseo', $directive . '_seo_' . $context, $int_args );
}
}
register_setting( 'noindexseo', 'noindex_seo_config_seoplugins' );
register_setting( 'noindexseo', 'noindex_seo_config_method' );
register_setting( 'noindexseo', 'noindex_seo_config_granular' );
register_setting( 'noindexseo', 'noindex_seo_config_delete_on_uninstall' );
register_setting( 'noindexseo', 'noindex_seo_config_seoplugins', $int_args );
register_setting(
'noindexseo',
'noindex_seo_config_method',
array(
'type' => 'string',
'sanitize_callback' => 'noindex_seo_sanitize_legacy_method',
)
);
register_setting( 'noindexseo', 'noindex_seo_config_granular', $int_args );
register_setting( 'noindexseo', 'noindex_seo_config_delete_on_uninstall', $int_args );
// NOTE: 'noindexseo' is the Settings API *group* name, not an option name.
// update_option_noindexseo would never fire; the transient is cleared explicitly
// inside noindex_seo_process_form() after every successful form save.
}
/**
* Sanitize the legacy 2.x `noindex_seo_config_method` option.
*
* Whitelists the three output methods; anything else becomes 'meta', the
* same fallback noindex_seo_metarobots() applies.
*
* @since 3.7.1
*
* @param mixed $value Raw option value.
* @return string 'meta', 'header' or 'both'.
*/
function noindex_seo_sanitize_legacy_method( $value ) {
$value = is_string( $value ) ? sanitize_key( $value ) : '';
return in_array( $value, array( 'meta', 'header', 'both' ), true ) ? $value : 'meta';
}
/**
* Deprecated: clears the cached plugin settings stored in the transient.
*
@ -2824,7 +3011,10 @@ function noindex_seo_detect_conflicts() {
// Iterate through the conflicting plugins to check if any are active.
$found_conflict = false;
foreach ( $conflicting_plugins as $plugin_path => $plugin_name ) {
foreach ( is_array( $conflicting_plugins ) ? $conflicting_plugins : array() as $plugin_path => $plugin_name ) {
if ( ! is_string( $plugin_path ) || ! is_string( $plugin_name ) ) {
continue;
}
if ( is_plugin_active( $plugin_path ) ) {
// Add an admin notice if a conflicting plugin is active..
add_action(