PluginProbe
Code Snippets / trunk
Code Snippets vtrunk
4.0.0-beta.2 3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 All 65 releases
code-snippets / php / Client / Feedback_Client.php

Feedback_Client.php in Code Snippets trunk, at php/Client/Feedback_Client.php

295 lines 8.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Code_Snippets\Client;
4
5 use Code_Snippets\Model\Feedback_Connection;
6 use Code_Snippets\Utils\System_Info;
7 use WP_Error;
8 use const Code_Snippets\PLUGIN_VERSION;
9
10 /**
11 * Sends feedback reports to Code Snippets Cloud.
12 *
13 * A site enrols once and signs everything it sends afterward. Two failures are worth
14 * recovering from rather than surfacing: a clock far enough out of step with the cloud that
15 * signatures arrive expired, and a credential the cloud no longer recognizes. Each is retried
16 * once, so a report is not lost to a problem the site can correct on its own.
17 *
18 * @package Code_Snippets
19 */
20 class Feedback_Client {
21
22 /**
23 * Transient recording that enrolment failed, so an unreachable endpoint is not
24 * contacted again on every request.
25 */
26 public const REGISTRATION_FAILURE_TRANSIENT = 'code_snippets_feedback_registration_failed';
27
28 /**
29 * How long to wait, in seconds, before attempting to enrol again.
30 */
31 private const REGISTRATION_FAILURE_TIMEOUT = 90;
32
33 /**
34 * Request timeout, in seconds, for enrolment.
35 */
36 private const REGISTRATION_REQUEST_TIMEOUT = 5;
37
38 /**
39 * Request timeout, in seconds, for sending a report.
40 */
41 private const REPORT_REQUEST_TIMEOUT = 15;
42
43 /**
44 * Request timeout, in seconds, for the duplicate search.
45 */
46 private const SEARCH_REQUEST_TIMEOUT = 10;
47
48 /**
49 * Maximum number of similar reports to offer.
50 */
51 private const MAX_SEARCH_RESULTS = 5;
52
53 /**
54 * Connection to the reporting API.
55 *
56 * @var Feedback_Connection
57 */
58 private Feedback_Connection $connection;
59
60 /**
61 * Class constructor.
62 *
63 * @param Feedback_Connection $connection Connection to the reporting API.
64 */
65 public function __construct( Feedback_Connection $connection ) {
66 $this->connection = $connection;
67 }
68
69 /**
70 * Enrol this site and store the credential it is issued.
71 *
72 * @param int $carry_offset Clock offset to preserve across a re-enrolment.
73 *
74 * @return array<string, mixed> Credential issued, or empty when enrolment failed.
75 */
76 public function register_site( int $carry_offset = 0 ): array {
77 $response = wp_remote_post(
78 $this->connection->get_endpoint_url( 'register' ),
79 [
80 'timeout' => self::REGISTRATION_REQUEST_TIMEOUT,
81 'headers' => $this->connection->get_request_headers(),
82 'body' => wp_json_encode(
83 [
84 'site_url' => site_url(),
85 'edition' => System_Info::get_edition(),
86 'plugin_version' => PLUGIN_VERSION,
87 ]
88 ),
89 ]
90 );
91
92 if ( is_wp_error( $response ) || 201 !== wp_remote_retrieve_response_code( $response ) ) {
93 return $this->fail_registration();
94 }
95
96 $body = json_decode( wp_remote_retrieve_body( $response ), true );
97 $body = is_array( $body ) ? $body : [];
98
99 if ( ! $this->connection->is_valid_credentials( $body ) ) {
100 return $this->fail_registration();
101 }
102
103 delete_transient( self::REGISTRATION_FAILURE_TRANSIENT );
104
105 $credentials = [
106 'public_id' => (string) $body['public_id'],
107 'secret' => (string) $body['secret'],
108 'offset' => $carry_offset,
109 ];
110
111 $this->connection->save_credentials( $credentials );
112
113 return $credentials;
114 }
115
116 /**
117 * Retrieve this site's credential, enrolling first when there is not one.
118 *
119 * @return array<string, mixed> Credential, or empty when enrolment is unavailable.
120 */
121 public function ensure_credentials(): array {
122 $credentials = $this->connection->get_credentials();
123
124 if ( $this->connection->is_valid_credentials( $credentials ) ) {
125 return $credentials;
126 }
127
128 if ( get_transient( self::REGISTRATION_FAILURE_TRANSIENT ) ) {
129 return [];
130 }
131
132 return $this->register_site();
133 }
134
135 /**
136 * Forward a report to the cloud.
137 *
138 * @param array<string, mixed> $payload Assembled report.
139 * @param string $idempotency_key Key identifying this submission.
140 *
141 * @return array{status: int, body: array<string, mixed>}|WP_Error
142 */
143 public function send_report( array $payload, string $idempotency_key ) {
144 $headers = $this->connection->get_request_headers();
145 $headers['Idempotency-Key'] = $idempotency_key;
146
147 $response = $this->send_signed(
148 $this->connection->get_endpoint_url(),
149 'POST',
150 $headers,
151 (string) wp_json_encode( $payload )
152 );
153
154 if ( is_wp_error( $response ) ) {
155 return $response;
156 }
157
158 $body = json_decode( wp_remote_retrieve_body( $response ), true );
159
160 return [
161 'status' => wp_remote_retrieve_response_code( $response ),
162 'body' => is_array( $body ) ? $body : [],
163 ];
164 }
165
166 /**
167 * Look for existing reports resembling a title being typed.
168 *
169 * @param string $query Title text entered so far.
170 *
171 * @return array<int, array<string, mixed>> Matching reports, empty when none or unavailable.
172 */
173 public function search_reports( string $query ): array {
174 // `add_query_arg()` builds the query through `build_query()`, which does not encode
175 // values, so the term is encoded here.
176 $url = add_query_arg( [ 'q' => rawurlencode( $query ) ], $this->connection->get_endpoint_url( 'search' ) );
177 $response = $this->send_signed( $url, 'GET', $this->connection->get_request_headers(), '' );
178
179 if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
180 return [];
181 }
182
183 $body = json_decode( wp_remote_retrieve_body( $response ), true );
184
185 return isset( $body['results'] ) && is_array( $body['results'] )
186 ? array_slice( $body['results'], 0, self::MAX_SEARCH_RESULTS )
187 : [];
188 }
189
190 /**
191 * Record that enrolment failed, and report it as unavailable.
192 *
193 * @return array<string, mixed> Always empty.
194 */
195 private function fail_registration(): array {
196 set_transient( self::REGISTRATION_FAILURE_TRANSIENT, 1, self::REGISTRATION_FAILURE_TIMEOUT );
197
198 return [];
199 }
200
201 /**
202 * Send a request signed with this site's credential, recovering once from a rejected
203 * signature.
204 *
205 * @param string $url Absolute endpoint URL.
206 * @param string $method HTTP method.
207 * @param array<string, string> $headers Request headers.
208 * @param string $body Raw request body, empty for a GET.
209 * @param bool $retrying Whether this is the second attempt.
210 *
211 * @return array<string, mixed>|WP_Error
212 */
213 private function send_signed( string $url, string $method, array $headers, string $body, bool $retrying = false ) {
214 $credentials = $this->ensure_credentials();
215
216 // Without a credential the cloud cannot tell who is reporting, so the request would
217 // be refused anyway. Stopping here keeps the report off the wire.
218 if ( ! $this->connection->is_valid_credentials( $credentials ) ) {
219 return new WP_Error(
220 'code_snippets_feedback_unregistered',
221 __( 'This site is not enrolled with the reporting service.', 'code-snippets' )
222 );
223 }
224
225 $uri = Feedback_Connection::get_request_uri( $url );
226
227 $headers = array_merge(
228 array_diff_key(
229 $headers,
230 array_flip( [ 'X-CS-Site-Id', 'X-CS-Timestamp', 'X-CS-Signature' ] )
231 ),
232 $this->connection->get_signature_headers( $credentials, $method, $uri, $body )
233 );
234
235 $args = [
236 'timeout' => 'GET' === $method ? self::SEARCH_REQUEST_TIMEOUT : self::REPORT_REQUEST_TIMEOUT,
237 'redirection' => 0,
238 'headers' => $headers,
239 ];
240
241 if ( 'GET' === $method ) {
242 $response = wp_remote_get( $url, $args );
243 } else {
244 $args['body'] = $body;
245 $response = wp_remote_post( $url, $args );
246 }
247
248 if ( is_wp_error( $response ) || $retrying ) {
249 return $response;
250 }
251
252 return $this->recover_from_rejected_signature( $response, $url, $method, $headers, $body );
253 }
254
255 /**
256 * Correct whatever the cloud objected to about a signature and try once more.
257 *
258 * @param array<string, mixed> $response Response received.
259 * @param string $url Absolute endpoint URL.
260 * @param string $method HTTP method.
261 * @param array<string, string> $headers Request headers.
262 * @param string $body Raw request body.
263 *
264 * @return array<string, mixed>|WP_Error
265 */
266 private function recover_from_rejected_signature( array $response, string $url, string $method, array $headers, string $body ) {
267 if ( 401 !== wp_remote_retrieve_response_code( $response ) ) {
268 return $response;
269 }
270
271 $parsed = json_decode( wp_remote_retrieve_body( $response ), true );
272 $error = $parsed['code'] ?? '';
273
274 if ( 'signature_expired' === $error && isset( $parsed['server_time'] ) ) {
275 $credentials = $this->connection->get_credentials();
276 $credentials['offset'] = (int) $parsed['server_time'] - time();
277 $this->connection->save_credentials( $credentials );
278
279 return $this->send_signed( $url, $method, $headers, $body, true );
280 }
281
282 if ( 'invalid_signature' === $error ) {
283 $credentials = $this->connection->get_credentials();
284 $offset = isset( $credentials['offset'] ) ? (int) $credentials['offset'] : 0;
285
286 $this->connection->delete_credentials();
287 $this->register_site( $offset );
288
289 return $this->send_signed( $url, $method, $headers, $body, true );
290 }
291
292 return $response;
293 }
294 }
295