*/ public static function defaults(): array { return array( 'strategy' => 'mobile' ); } public function register( Container $container ): void {} public function boot( Container $container ): void { add_action( 'rest_api_init', array( $this, 'routes' ) ); } /** * Fetch scores for one URL. The API works without a key at low volume; * a key raises the quota. * * @return array|WP_Error */ public function measure( string $url, string $strategy = 'mobile' ): array|WP_Error { $host = wp_parse_url( $url, PHP_URL_HOST ); if ( $host !== wp_parse_url( home_url(), PHP_URL_HOST ) ) { return new WP_Error( 'airanksuite_psi_foreign_url', __( 'Only URLs on this site can be measured.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $args = array( 'url' => $url, 'strategy' => 'desktop' === $strategy ? 'desktop' : 'mobile', 'category' => 'performance', ); $key = $this->key(); if ( null !== $key ) { $args['key'] = $key; } $response = wp_remote_get( 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?' . http_build_query( $args ), array( 'timeout' => 60 ) ); if ( $response instanceof WP_Error ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( $code >= 400 || ! is_array( $body ) ) { $msg = is_array( $body ) ? (string) ( $body['error']['message'] ?? '' ) : ''; return new WP_Error( 'airanksuite_psi_failed', '' !== $msg ? $msg : sprintf( 'PageSpeed Insights error (HTTP %d).', $code ), array( 'status' => 502 ) ); } $audits = (array) ( $body['lighthouseResult']['audits'] ?? array() ); $score = $body['lighthouseResult']['categories']['performance']['score'] ?? null; return array( 'score' => null === $score ? null : (int) round( 100 * (float) $score ), 'strategy' => $args['strategy'], 'lcp' => (string) ( $audits['largest-contentful-paint']['displayValue'] ?? '' ), 'cls' => (string) ( $audits['cumulative-layout-shift']['displayValue'] ?? '' ), 'tbt' => (string) ( $audits['total-blocking-time']['displayValue'] ?? '' ), 'fcp' => (string) ( $audits['first-contentful-paint']['displayValue'] ?? '' ), 'si' => (string) ( $audits['speed-index']['displayValue'] ?? '' ), 'measured' => time(), ); } private function key(): ?string { $stored = get_option( self::OPT_KEY ); if ( ! is_string( $stored ) || '' === $stored ) { return null; } $key = Secret::decrypt( $stored ); return is_string( $key ) && '' !== $key ? $key : null; } public function routes(): void { // The post is in the URL, so each method also asks WordPress about that // post: reading the stored result is a read, and a fresh measurement is // written onto the post as meta, which makes it an edit. register_rest_route( self::NAMESPACE, '/pagespeed/(?P\d+)', array( array( 'methods' => 'GET', 'callback' => array( $this, 'get_stored' ), 'permission_callback' => static fn( $request ): bool => current_user_can( 'manage_options' ) && self::post_allowed( (int) ( $request['id'] ?? 0 ), 'read_post' ), ), array( 'methods' => 'POST', 'callback' => array( $this, 'run' ), 'permission_callback' => static function ( $request ) { if ( ! current_user_can( 'manage_options' ) || ! self::post_allowed( (int) ( $request['id'] ?? 0 ), 'edit_post' ) ) { return self::forbidden(); } return self::spend( 'psi', 40 ); }, ), ) ); /* * Measure the site's front page, here, now. * * The screen called "PageSpeed Insights" could only store an API key. * Everything it configured happened somewhere else — inside a single * page's analysis panel — so a customer set it up, pressed Save, and * the screen never showed a number. A settings form named after a * measurement has to be able to take one. */ register_rest_route( self::NAMESPACE, '/pagespeed/home', array( 'methods' => 'POST', 'callback' => array( $this, 'run_home' ), 'permission_callback' => static function () { if ( ! current_user_can( 'manage_options' ) ) { return self::forbidden(); } return self::spend( 'psi', 40 ); }, ) ); register_rest_route( self::NAMESPACE, '/settings/pagespeed', array( array( 'methods' => 'GET', 'callback' => array( $this, 'get_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'strategy' => array( 'type' => 'string', 'enum' => array( 'mobile', 'desktop' ), ), 'api_key' => array( 'type' => 'string' ), ), ), ) ); } /** * Measure the front page and keep the answer for the screen to show. * * Stored in an option rather than post meta: this is a reading about the * site, not about a post, and the front page may not be a post at all. */ public function run_home(): WP_REST_Response|WP_Error { $result = $this->measure( home_url( '/' ), (string) $this->settings()['strategy'] ); if ( $result instanceof WP_Error ) { return $result; } $result['url'] = home_url( '/' ); update_option( 'airanksuite_pagespeed_home', $result, false ); return new WP_REST_Response( array( 'result' => $result ) ); } public function get_stored( WP_REST_Request $request ): WP_REST_Response|WP_Error { $post = $this->find( $request ); if ( $post instanceof WP_Error ) { return $post; } $stored = get_post_meta( $post->ID, '_airanksuite_pagespeed', true ); return new WP_REST_Response( array( 'result' => is_array( $stored ) ? $stored : null ) ); } public function run( WP_REST_Request $request ): WP_REST_Response|WP_Error { $post = $this->find( $request ); if ( $post instanceof WP_Error ) { return $post; } $result = $this->measure( (string) get_permalink( $post ), (string) $this->settings()['strategy'] ); if ( $result instanceof WP_Error ) { return $result; } update_post_meta( $post->ID, '_airanksuite_pagespeed', $result ); return new WP_REST_Response( array( 'result' => $result ) ); } public function get_settings(): WP_REST_Response { $home = get_option( 'airanksuite_pagespeed_home' ); return new WP_REST_Response( array( 'settings' => $this->settings(), 'has_key' => null !== $this->key(), // The last front-page reading, so the screen opens with a // number instead of an empty form. 'home' => is_array( $home ) ? $home : null, 'home_url' => home_url( '/' ), ) ); } public function update_settings( WP_REST_Request $request ): WP_REST_Response { $defaults = self::defaults(); if ( $request->has_param( 'strategy' ) ) { \AiRankSuite\Kernel::service( Options::class ) ->set( 'pagespeed', array( 'strategy' => (string) $request->get_param( 'strategy' ) ), $defaults ); } if ( $request->has_param( 'api_key' ) ) { $key = trim( (string) $request->get_param( 'api_key' ) ); if ( '' === $key ) { delete_option( self::OPT_KEY ); } else { update_option( self::OPT_KEY, Secret::encrypt( $key ), false ); } } return $this->get_settings(); } private function find( WP_REST_Request $request ): WP_Post|WP_Error { $post = get_post( (int) $request['id'] ); if ( ! $post instanceof WP_Post || 'publish' !== $post->post_status ) { return new WP_Error( 'airanksuite_content_not_found', __( 'Post not found.', 'ai-rank-suite' ), array( 'status' => 404 ) ); } return $post; } /** @return array */ private function settings(): array { return \AiRankSuite\Kernel::service( Options::class )->get( 'pagespeed', self::defaults() ); } }