user_agent = 'px320siteaudit/' . $plugin_version; } public function get( string $url, int $max_body_bytes, string $resource_class ): HttpTransportResponse { if ( $max_body_bytes < 1 || $max_body_bytes > self::MAX_BODY_BYTES ) { throw new InvalidArgumentException( 'invalid_http_body_budget' ); } $accept = $this->accept_header( $resource_class ); $response = wp_safe_remote_get( $url, array( 'timeout' => 5, 'redirection' => 0, 'httpversion' => '1.1', 'user-agent' => $this->user_agent, 'headers' => array( 'Accept' => $accept ), 'cookies' => array(), 'blocking' => true, 'decompress' => true, 'sslverify' => true, 'limit_response_size' => $max_body_bytes + 1, ) ); if ( is_wp_error( $response ) ) { return HttpTransportResponse::network_error(); } $status = wp_remote_retrieve_response_code( $response ); if ( $status < 100 || $status > 599 ) { return HttpTransportResponse::network_error(); } $body = wp_remote_retrieve_body( $response ); $truncated = strlen( $body ) > $max_body_bytes; if ( $truncated ) { $body = substr( $body, 0, $max_body_bytes ); } $location = $this->safe_header( wp_remote_retrieve_header( $response, 'location' ), 2048 ); $content_type = $this->safe_header( wp_remote_retrieve_header( $response, 'content-type' ), 128 ); $x_robots = $this->safe_header( wp_remote_retrieve_header( $response, 'x-robots-tag' ), 1024 ); return HttpTransportResponse::received( $status, $body, $location, $content_type ?? '', $x_robots ?? '', $truncated ); } private function accept_header( string $resource_class ): string { $headers = array( 'html' => 'text/html,application/xhtml+xml;q=0.9', 'robots' => 'text/plain,*/*;q=0.1', 'sitemap' => 'application/xml,text/xml;q=0.9', 'publisher' => 'text/plain,text/markdown;q=0.9,*/*;q=0.1', ); if ( ! isset( $headers[ $resource_class ] ) ) { throw new InvalidArgumentException( 'invalid_http_resource_class' ); } return $headers[ $resource_class ]; } /** * @param mixed $value Header projection from WordPress. */ private function safe_header( $value, int $max_bytes ): ?string { if ( ! is_string( $value ) || '' === trim( $value ) || strlen( $value ) > $max_bytes ) { return null; } $value = trim( $value ); return 1 === preg_match( '/[\x00-\x1F\x7F]/', $value ) ? null : $value; } }