array( 'key' => $key ) ), false ); } return $key; } /** * Serve /{key}.txt. * * @param bool $do_parse Whether to parse. * @return bool */ public static function serve_key( $do_parse ) { $key = self::key( false ); if ( '' !== $key && strtolower( Aeoora_Util::relative_path() ) === strtolower( $key . '.txt' ) ) { status_header( 200 ); header( 'Content-Type: text/plain; charset=utf-8' ); echo esc_html( $key ); exit; } return $do_parse; } /** * Ping on publish / update. * * @param string $new New status. * @param string $old Old status. * @param WP_Post $post Post. */ public static function on_transition( $new, $old, $post ) { if ( 'publish' !== $new || wp_is_post_revision( $post ) || ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) ) { return; } if ( ! is_post_type_viewable( $post->post_type ) || ! Aeoora_Content::is_public( $post ) ) { return; } // One ping per URL per 10 minutes. $flag = 'aeoora_in_' . $post->ID; if ( get_transient( $flag ) ) { return; } set_transient( $flag, 1, 10 * MINUTE_IN_SECONDS ); self::submit( array( get_permalink( $post ) ) ); } /** * Submit URLs. * * @param string[] $urls URLs. * @param bool $blocking Wait for the answer (manual submits) and report errors. * @return array|WP_Error */ public static function submit( array $urls, $blocking = false ) { $host = (string) wp_parse_url( home_url(), PHP_URL_HOST ); $urls = array_values( array_filter( $urls, static function ( $u ) use ( $host ) { return wp_parse_url( $u, PHP_URL_HOST ) === $host; } ) ); if ( ! $urls || in_array( wp_get_environment_type(), array( 'local', 'development' ), true ) ) { return new WP_Error( 'aeoora_indexnow_skip', __( 'Nothing to submit (or this is a local/development site).', 'aeoora' ) ); } $key = self::key(); $res = wp_remote_post( 'https://api.indexnow.org/indexnow', array( 'timeout' => 10, 'blocking' => (bool) $blocking, 'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ), 'body' => wp_json_encode( array( 'host' => $host, 'key' => $key, 'keyLocation' => home_url( '/' . $key . '.txt' ), 'urlList' => array_slice( $urls, 0, 10000 ), ) ), ) ); $log = (array) get_option( 'aeoora_indexnow_log', array() ); $log[] = array( 'time' => time(), 'urls' => count( $urls ), 'url' => $urls[0], ); update_option( 'aeoora_indexnow_log', array_slice( $log, -20 ), false ); if ( $blocking && ! is_wp_error( $res ) ) { $code = (int) wp_remote_retrieve_response_code( $res ); if ( $code < 200 || $code >= 300 ) { return new WP_Error( 'aeoora_indexnow_http', /* translators: %d: HTTP status code. */ sprintf( __( 'IndexNow answered with HTTP %d. Check that your key file is reachable, then try again.', 'aeoora' ), $code ), array( 'status' => 502 ) ); } } return $res; } }