JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | Feedback_Client.php
  • File: Feedback_Client.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/wp-content/plugins/code-snippets/php/Client/Feedback_Client.php
  • File size: 8.8 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php

namespace Code_Snippets\Client;

use Code_Snippets\Model\Feedback_Connection;
use Code_Snippets\Utils\System_Info;
use WP_Error;
use const Code_Snippets\PLUGIN_VERSION;

/**
 * Sends feedback reports to Code Snippets Cloud.
 *
 * A site enrols once and signs everything it sends afterward. Two failures are worth
 * recovering from rather than surfacing: a clock far enough out of step with the cloud that
 * signatures arrive expired, and a credential the cloud no longer recognizes. Each is retried
 * once, so a report is not lost to a problem the site can correct on its own.
 *
 * @package Code_Snippets
 */
class Feedback_Client {

	/**
	 * Transient recording that enrolment failed, so an unreachable endpoint is not
	 * contacted again on every request.
	 */
	public const REGISTRATION_FAILURE_TRANSIENT = 'code_snippets_feedback_registration_failed';

	/**
	 * How long to wait, in seconds, before attempting to enrol again.
	 */
	private const REGISTRATION_FAILURE_TIMEOUT = 90;

	/**
	 * Request timeout, in seconds, for enrolment.
	 */
	private const REGISTRATION_REQUEST_TIMEOUT = 5;

	/**
	 * Request timeout, in seconds, for sending a report.
	 */
	private const REPORT_REQUEST_TIMEOUT = 15;

	/**
	 * Request timeout, in seconds, for the duplicate search.
	 */
	private const SEARCH_REQUEST_TIMEOUT = 10;

	/**
	 * Maximum number of similar reports to offer.
	 */
	private const MAX_SEARCH_RESULTS = 5;

	/**
	 * Connection to the reporting API.
	 *
	 * @var Feedback_Connection
	 */
	private Feedback_Connection $connection;

	/**
	 * Class constructor.
	 *
	 * @param Feedback_Connection $connection Connection to the reporting API.
	 */
	public function __construct( Feedback_Connection $connection ) {
		$this->connection = $connection;
	}

	/**
	 * Enrol this site and store the credential it is issued.
	 *
	 * @param int $carry_offset Clock offset to preserve across a re-enrolment.
	 *
	 * @return array<string, mixed> Credential issued, or empty when enrolment failed.
	 */
	public function register_site( int $carry_offset = 0 ): array {
		$response = wp_remote_post(
			$this->connection->get_endpoint_url( 'register' ),
			[
				'timeout' => self::REGISTRATION_REQUEST_TIMEOUT,
				'headers' => $this->connection->get_request_headers(),
				'body'    => wp_json_encode(
					[
						'site_url'       => site_url(),
						'edition'        => System_Info::get_edition(),
						'plugin_version' => PLUGIN_VERSION,
					]
				),
			]
		);

		if ( is_wp_error( $response ) || 201 !== wp_remote_retrieve_response_code( $response ) ) {
			return $this->fail_registration();
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		$body = is_array( $body ) ? $body : [];

		if ( ! $this->connection->is_valid_credentials( $body ) ) {
			return $this->fail_registration();
		}

		delete_transient( self::REGISTRATION_FAILURE_TRANSIENT );

		$credentials = [
			'public_id' => (string) $body['public_id'],
			'secret'    => (string) $body['secret'],
			'offset'    => $carry_offset,
		];

		$this->connection->save_credentials( $credentials );

		return $credentials;
	}

	/**
	 * Retrieve this site's credential, enrolling first when there is not one.
	 *
	 * @return array<string, mixed> Credential, or empty when enrolment is unavailable.
	 */
	public function ensure_credentials(): array {
		$credentials = $this->connection->get_credentials();

		if ( $this->connection->is_valid_credentials( $credentials ) ) {
			return $credentials;
		}

		if ( get_transient( self::REGISTRATION_FAILURE_TRANSIENT ) ) {
			return [];
		}

		return $this->register_site();
	}

	/**
	 * Forward a report to the cloud.
	 *
	 * @param array<string, mixed> $payload         Assembled report.
	 * @param string               $idempotency_key Key identifying this submission.
	 *
	 * @return array{status: int, body: array<string, mixed>}|WP_Error
	 */
	public function send_report( array $payload, string $idempotency_key ) {
		$headers = $this->connection->get_request_headers();
		$headers['Idempotency-Key'] = $idempotency_key;

		$response = $this->send_signed(
			$this->connection->get_endpoint_url(),
			'POST',
			$headers,
			(string) wp_json_encode( $payload )
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		return [
			'status' => wp_remote_retrieve_response_code( $response ),
			'body'   => is_array( $body ) ? $body : [],
		];
	}

	/**
	 * Look for existing reports resembling a title being typed.
	 *
	 * @param string $query Title text entered so far.
	 *
	 * @return array<int, array<string, mixed>> Matching reports, empty when none or unavailable.
	 */
	public function search_reports( string $query ): array {
		// `add_query_arg()` builds the query through `build_query()`, which does not encode
		// values, so the term is encoded here.
		$url = add_query_arg( [ 'q' => rawurlencode( $query ) ], $this->connection->get_endpoint_url( 'search' ) );
		$response = $this->send_signed( $url, 'GET', $this->connection->get_request_headers(), '' );

		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
			return [];
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		return isset( $body['results'] ) && is_array( $body['results'] )
			? array_slice( $body['results'], 0, self::MAX_SEARCH_RESULTS )
			: [];
	}

	/**
	 * Record that enrolment failed, and report it as unavailable.
	 *
	 * @return array<string, mixed> Always empty.
	 */
	private function fail_registration(): array {
		set_transient( self::REGISTRATION_FAILURE_TRANSIENT, 1, self::REGISTRATION_FAILURE_TIMEOUT );

		return [];
	}

	/**
	 * Send a request signed with this site's credential, recovering once from a rejected
	 * signature.
	 *
	 * @param string                $url      Absolute endpoint URL.
	 * @param string                $method   HTTP method.
	 * @param array<string, string> $headers  Request headers.
	 * @param string                $body     Raw request body, empty for a GET.
	 * @param bool                  $retrying Whether this is the second attempt.
	 *
	 * @return array<string, mixed>|WP_Error
	 */
	private function send_signed( string $url, string $method, array $headers, string $body, bool $retrying = false ) {
		$credentials = $this->ensure_credentials();

		// Without a credential the cloud cannot tell who is reporting, so the request would
		// be refused anyway. Stopping here keeps the report off the wire.
		if ( ! $this->connection->is_valid_credentials( $credentials ) ) {
			return new WP_Error(
				'code_snippets_feedback_unregistered',
				__( 'This site is not enrolled with the reporting service.', 'code-snippets' )
			);
		}

		$uri = Feedback_Connection::get_request_uri( $url );

		$headers = array_merge(
			array_diff_key(
				$headers,
				array_flip( [ 'X-CS-Site-Id', 'X-CS-Timestamp', 'X-CS-Signature' ] )
			),
			$this->connection->get_signature_headers( $credentials, $method, $uri, $body )
		);

		$args = [
			'timeout'     => 'GET' === $method ? self::SEARCH_REQUEST_TIMEOUT : self::REPORT_REQUEST_TIMEOUT,
			'redirection' => 0,
			'headers'     => $headers,
		];

		if ( 'GET' === $method ) {
			$response = wp_remote_get( $url, $args );
		} else {
			$args['body'] = $body;
			$response = wp_remote_post( $url, $args );
		}

		if ( is_wp_error( $response ) || $retrying ) {
			return $response;
		}

		return $this->recover_from_rejected_signature( $response, $url, $method, $headers, $body );
	}

	/**
	 * Correct whatever the cloud objected to about a signature and try once more.
	 *
	 * @param array<string, mixed>  $response Response received.
	 * @param string                $url      Absolute endpoint URL.
	 * @param string                $method   HTTP method.
	 * @param array<string, string> $headers  Request headers.
	 * @param string                $body     Raw request body.
	 *
	 * @return array<string, mixed>|WP_Error
	 */
	private function recover_from_rejected_signature( array $response, string $url, string $method, array $headers, string $body ) {
		if ( 401 !== wp_remote_retrieve_response_code( $response ) ) {
			return $response;
		}

		$parsed = json_decode( wp_remote_retrieve_body( $response ), true );
		$error = $parsed['code'] ?? '';

		if ( 'signature_expired' === $error && isset( $parsed['server_time'] ) ) {
			$credentials = $this->connection->get_credentials();
			$credentials['offset'] = (int) $parsed['server_time'] - time();
			$this->connection->save_credentials( $credentials );

			return $this->send_signed( $url, $method, $headers, $body, true );
		}

		if ( 'invalid_signature' === $error ) {
			$credentials = $this->connection->get_credentials();
			$offset = isset( $credentials['offset'] ) ? (int) $credentials['offset'] : 0;

			$this->connection->delete_credentials();
			$this->register_site( $offset );

			return $this->send_signed( $url, $method, $headers, $body, true );
		}

		return $response;
	}
}