Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.12% covered (warning)
88.12%
89 / 101
72.73% covered (warning)
72.73%
8 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Indexnow_Client
88.12% covered (warning)
88.12%
89 / 101
72.73% covered (warning)
72.73%
8 / 11
63.64
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 key
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 enabled
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
8
 site_is_public
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
5
 key_location
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 scope
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 matches_scope
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 in_scope
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
14
 maybe_serve_key
41.67% covered (danger)
41.67%
5 / 12
0.00% covered (danger)
0.00%
0 / 1
16.73
 batch_size
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 submit
92.73% covered (success)
92.73%
51 / 55
0.00% covered (danger)
0.00%
0 / 1
14.08
1<?php
2/**
3 * IndexNow ownership and bounded notifications.
4 *
5 * @package automattic/jetpack-seo
6 */
7
8namespace Automattic\Jetpack\SEO;
9
10use Automattic\Jetpack\Modules;
11use Automattic\Jetpack\Status;
12use Automattic\Jetpack\Status\Host;
13
14/**
15 * Supplies verification without requiring a physical file.
16 */
17class Indexnow_Client {
18    const KEY_OPTION     = 'jetpack_seo_indexnow_key';
19    const ENABLED_OPTION = 'jetpack_seo_indexnow_enabled';
20    const SCOPE_OPTION   = 'jetpack_seo_indexnow_enabled_scope';
21    const ENDPOINT       = 'https://api.indexnow.org/indexnow';
22    const BATCH_SIZE     = 100;
23
24    /** Register the ownership handler without enabling notifications. */
25    public static function init() {
26        add_action( 'template_redirect', array( __CLASS__, 'maybe_serve_key' ), 0 );
27    }
28
29    /**
30     * The persisted public verification key.
31     *
32     * @return string
33     */
34    public static function key() {
35        $key = get_option( self::KEY_OPTION, '' );
36        if ( ! is_string( $key ) || ! preg_match( '/^[a-f0-9]{32}$/', $key ) ) {
37            $key = bin2hex( random_bytes( 16 ) );
38            update_option( self::KEY_OPTION, $key, false );
39        }
40        return $key;
41    }
42
43    /**
44     * Whether notifications are enabled on a public site.
45     *
46     * @return bool
47     */
48    public static function enabled() {
49        /**
50         * Filters whether Jetpack may deliver IndexNow notifications on this host.
51         *
52         * @since 0.13.0
53         * @param bool $allowed Whether another host/provider permits Jetpack delivery.
54         */
55        $allowed = (bool) apply_filters( 'jetpack_seo_indexnow_can_notify', true );
56        return (bool) get_option( self::ENABLED_OPTION, false )
57            && $allowed
58            && self::matches_scope( get_option( self::SCOPE_OPTION, '' ) )
59            && Initializer::is_available() && ( new Modules() )->is_active( 'seo-tools' )
60            && ! ( new Host() )->is_vip_site() && self::site_is_public()
61            && ! Seo_Tools::is_disabled();
62    }
63
64    /**
65     * Whether anonymous discovery is permitted on this host.
66     *
67     * @return bool
68     */
69    public static function site_is_public() {
70        return 1 === (int) get_option( 'blog_public', 1 )
71            && 'production' === wp_get_environment_type() && ! ( new Status() )->in_safe_mode()
72            && ( ! ( new Host() )->is_wpcom_platform() || ! ( new Status() )->is_coming_soon() );
73    }
74
75    /**
76     * Verification location within this site's URL scope.
77     *
78     * @return string
79     */
80    public static function key_location() {
81        return self::scope() . self::key() . '.txt';
82    }
83
84    /**
85     * Current site's URL scope.
86     *
87     * @since 0.13.0
88     * @return string
89     */
90    public static function scope() {
91        return home_url( '/', wp_parse_url( get_option( 'home' ), PHP_URL_SCHEME ) );
92    }
93
94    /**
95     * Match the same address when HTTP and HTTPS resolve differently across requests.
96     *
97     * @since 0.13.0
98     * @param mixed $scope Saved consent or notification scope.
99     * @return bool
100     */
101    public static function matches_scope( $scope ) {
102        return is_string( $scope )
103            && preg_replace( '#^http://#', 'https://', $scope ) === preg_replace( '#^http://#', 'https://', self::scope() );
104    }
105
106    /**
107     * Restrict HTTP(S) notifications to this site's host and home path.
108     *
109     * @param string $url Candidate URL.
110     * @return bool
111     */
112    public static function in_scope( $url ) {
113        if ( ! is_string( $url ) || strlen( $url ) > 2048 || preg_match( '/[\x00-\x20\x7f]/', $url ) ) {
114            return false;
115        }
116        $home   = wp_parse_url( self::scope() );
117        $target = wp_parse_url( $url );
118        if ( ! is_array( $target ) || isset( $target['user'] ) || isset( $target['pass'] ) || isset( $target['fragment'] ) ) {
119            return false;
120        }
121        if ( ! in_array( $target['scheme'] ?? '', array( 'http', 'https' ), true ) || strtolower( $target['host'] ?? '' ) !== strtolower( $home['host'] ?? '' ) || ( $target['port'] ?? null ) !== ( $home['port'] ?? null ) ) {
122            return false;
123        }
124        $path = rawurldecode( $target['path'] ?? '/' );
125        if ( false !== strpos( $path, '\\' ) || preg_match( '~(?:^|/)\.{1,2}(?:/|$)~', $path ) || preg_match( '/%(?:2e|2f|5c)/i', $path ) ) {
126            return false;
127        }
128        return 0 === strpos( $path, trailingslashit( $home['path'] ?? '/' ) );
129    }
130
131    /** Serve the public key only while the feature can operate. */
132    public static function maybe_serve_key() {
133        $method = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? 'GET' ) );
134        if ( ! in_array( $method, array( 'GET', 'HEAD' ), true ) ) {
135            return;
136        }
137        $path = wp_parse_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) ), PHP_URL_PATH );
138        if ( ! is_string( $path ) || ! preg_match( '~/[a-f0-9]{32}\.txt$~', $path ) || ! self::enabled() || wp_parse_url( self::key_location(), PHP_URL_PATH ) !== $path ) {
139            return;
140        }
141        nocache_headers();
142        header( 'Content-Type: text/plain; charset=utf-8' );
143        status_header( 200 );
144        if ( 'HEAD' !== $method ) {
145            echo esc_html( self::key() );
146        }
147        exit;
148    }
149
150    /**
151     * Bound the configurable request size to the protocol maximum.
152     *
153     * @return int
154     */
155    public static function batch_size() {
156        /**
157         * Filters the maximum URLs in one IndexNow request.
158         *
159         * @since 0.13.0
160         * @param int $size Maximum URLs, between 1 and 10,000.
161         */
162        $size = apply_filters( 'jetpack_seo_indexnow_batch_size', self::BATCH_SIZE );
163        return is_int( $size ) ? max( 1, min( 10000, $size ) ) : self::BATCH_SIZE;
164    }
165
166    /**
167     * Send an already eligible batch to one participating endpoint.
168     *
169     * @param string[] $urls Public URLs.
170     * @return array
171     */
172    public static function submit( $urls ) {
173        if ( ! self::enabled() || ! is_array( $urls ) || ! $urls ) {
174            return array(
175                'state' => 'disabled_or_invalid',
176                'retry' => false,
177            );
178        }
179        if ( ! preg_match( '/^[a-f0-9]{32}$/', self::key() ) ) {
180            return array(
181                'state' => 'invalid_key',
182                'retry' => false,
183            );
184        }
185        foreach ( $urls as $url ) {
186            if ( ! self::in_scope( $url ) ) {
187                return array(
188                    'state' => 'invalid_scope',
189                    'retry' => false,
190                );
191            }
192        }
193        $urls = array_values( array_unique( $urls ) );
194        if ( count( $urls ) > self::batch_size() ) {
195            return array(
196                'state' => 'disabled_or_invalid',
197                'retry' => false,
198            );
199        }
200        $response = wp_safe_remote_post(
201            self::ENDPOINT,
202            array(
203                'timeout'     => 5,
204                'redirection' => 0,
205                'headers'     => array( 'Content-Type' => 'application/json; charset=utf-8' ),
206                'body'        => wp_json_encode(
207                    array(
208                        'host'        => wp_parse_url( self::scope(), PHP_URL_HOST ),
209                        'key'         => self::key(),
210                        'keyLocation' => self::key_location(),
211                        'urlList'     => $urls,
212                    ),
213                    JSON_UNESCAPED_SLASHES
214                ),
215            )
216        );
217        if ( is_wp_error( $response ) ) {
218            return array(
219                'state' => 'transport_failure',
220                'retry' => true,
221            );
222        }
223        $code        = wp_remote_retrieve_response_code( $response );
224        $retry       = 429 === $code || $code >= 500;
225        $retry_after = wp_remote_retrieve_header( $response, 'retry-after' );
226        $retry_after = is_string( $retry_after ) ? $retry_after : '';
227        $retry_after = ctype_digit( $retry_after ) ? (int) $retry_after : max( 0, (int) strtotime( $retry_after ) - time() );
228        return array(
229            'state'       => 200 === $code ? 'accepted' : ( 202 === $code ? 'verification_pending' : 'http_' . $code ),
230            'retry'       => $retry,
231            'code'        => $code,
232            'retry_after' => min( WEEK_IN_SECONDS, $retry_after ),
233        );
234    }
235}