PluginProbe
Code Snippets / 3.5.0
Code Snippets v3.5.0
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 3.0.1 All 64 releases
code-snippets / php / cloud / class-cloud-api.php

class-cloud-api.php in Code Snippets 3.5.0, at php/cloud/class-cloud-api.php

498 lines 12.9 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\Cloud;
4
5 use Code_Snippets\Snippet;
6 use WP_Error;
7 use function Code_Snippets\get_snippet_by_cloud_id;
8 use function Code_Snippets\get_snippets;
9 use function Code_Snippets\save_snippet;
10 use function Code_Snippets\update_snippet_fields;
11
12 /**
13 * Functions used to manage cloud synchronisation.
14 *
15 * @package Code_Snippets
16 */
17 class Cloud_API {
18
19 /**
20 * Base URL for cloud API.
21 *
22 * @var string
23 */
24 const CLOUD_API_URL = 'https://codesnippets.cloud/api/v1/';
25
26 /**
27 * Base URL for cloud API.
28 *
29 * @var string
30 */
31 const CLOUD_SEARCH_API_TOKEN = 'csc-1a2b3c4d5e6f7g8h9i0j';
32
33
34 /**
35 * Key used to access the local-to-cloud map transient data.
36 *
37 * @var string
38 */
39 const CLOUD_MAP_TRANSIENT_KEY = 'cs_local_to_cloud_map';
40
41
42 /**
43 * Days to cache data retrieved from API.
44 *
45 * @var integer
46 */
47 const DAYS_TO_STORE_CS = 1;
48
49 /**
50 * Local to Cloud Snippets Map Object
51 *
52 * @var Cloud_Link[]|null
53 */
54 private $local_to_cloud_map = null;
55
56 /**
57 * Create local-to-cloud map to keep track of local snippets that have been synced to the cloud.
58 *
59 * @return Cloud_Link[]
60 */
61 public function get_local_to_cloud_map() {
62 // Return the cached data if available.
63 if ( $this->local_to_cloud_map ) {
64 return $this->local_to_cloud_map;
65 }
66
67 // Fetch data from the stored transient, if available.
68 $stored_data = get_transient( self::CLOUD_MAP_TRANSIENT_KEY );
69 if ( $stored_data ) {
70 $this->local_to_cloud_map = $stored_data;
71 return $stored_data;
72 }
73
74 // Otherwise, regenerate the local-to-cloud-map.
75 $this->local_to_cloud_map = [];
76
77 // Fetch and iterate through all local snippets to create the map.
78 foreach ( get_snippets() as $local_snippet ) {
79 // Skip snippets that are only stored locally.
80 if ( ! $local_snippet->cloud_id ) {
81 continue;
82 }
83
84 // If the snippet is a token snippet skip it.
85 $has_valid_cloud_id = boolval( strpos( $local_snippet->cloud_id, '_' ) );
86 if ( ! $has_valid_cloud_id ) {
87 continue;
88 }
89
90 $link = new Cloud_Link();
91 $cloud_id = explode( '_', $local_snippet->cloud_id );
92 $cloud_id_int = (int) $cloud_id[0] ?? '';
93 $link->local_id = $local_snippet->id;
94 $link->cloud_id = $cloud_id_int;
95 $link->is_owner = false;
96 $link->in_codevault = false;
97
98 $this->local_to_cloud_map[] = $link;
99 }
100
101 set_transient(
102 self::CLOUD_MAP_TRANSIENT_KEY,
103 $this->local_to_cloud_map,
104 DAY_IN_SECONDS * self::DAYS_TO_STORE_CS
105 );
106
107 return $this->local_to_cloud_map;
108 }
109
110 /**
111 * Unpack JSON data from a request response.
112 *
113 * @param array|WP_Error $response Response from wp_request_*.
114 *
115 * @return array<string, mixed>|null Associative array of JSON data on success, null on failure.
116 */
117 private static function unpack_request_json( $response ) {
118 $body = wp_remote_retrieve_body( $response );
119 return $body ? json_decode( $body, true ) : null;
120 }
121
122 /**
123 * Search Code Snippets Cloud -> Static Function
124 *
125 * @param string $search_method Search by name of codevault or keyword(s).
126 * @param string $search Search query.
127 * @param integer $page Search result page to retrieve. Defaults to '0'.
128 *
129 * @return Cloud_Snippets Result of search query.
130 */
131 public static function fetch_search_results( string $search_method, string $search, int $page = 0 ): Cloud_Snippets {
132 $api_url = add_query_arg(
133 [
134 's_method' => $search_method,
135 's' => $search,
136 'page' => $page,
137 'site_token' => self::CLOUD_SEARCH_API_TOKEN,
138 'site_host' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
139 ],
140 self::CLOUD_API_URL . 'public/search'
141 );
142
143 $results = self::unpack_request_json( wp_remote_get( $api_url ) );
144
145 $results = new Cloud_Snippets( $results );
146 $results->page = $page;
147
148 return $results;
149 }
150
151 /**
152 * Refresh all stored data.
153 *
154 * @return void
155 */
156 public function refresh_synced_data() {
157 // Simply deleting the data is sufficient, as it will be recreated and stored the next time it is requested.
158 $this->local_to_cloud_map = null;
159 delete_transient( self::CLOUD_MAP_TRANSIENT_KEY );
160 }
161
162 /**
163 * Add a new link item to the local-to-cloud map.
164 *
165 * @param Cloud_Link $link Link to add.
166 *
167 * @return void
168 */
169 public function add_map_link( Cloud_Link $link ) {
170 $local_to_cloud_map = get_transient( self::CLOUD_MAP_TRANSIENT_KEY );
171 $local_to_cloud_map[] = $link;
172
173 set_transient(
174 self::CLOUD_MAP_TRANSIENT_KEY,
175 $local_to_cloud_map,
176 DAY_IN_SECONDS * self::DAYS_TO_STORE_CS
177 );
178 }
179
180
181 /**
182 * Delete a snippet from local-to-cloud map.
183 *
184 * @param integer $snippet_id Local snippet ID.
185 *
186 * @return Cloud_Link|null The deleted map link if one was found, null otherwise.
187 */
188 public function delete_snippet_from_transient_data( int $snippet_id ) {
189 $this->get_local_to_cloud_map();
190 $link_to_delete = null;
191
192 foreach ( $this->local_to_cloud_map as $link ) {
193 if ( $link->local_id === $snippet_id ) {
194 $link_to_delete = $link;
195 break;
196 }
197 }
198 if ( $link_to_delete ) {
199
200 $this->refresh_synced_data();
201 }
202
203 return $link_to_delete;
204 }
205
206 /**
207 * Get the current revision of a single cloud snippet.
208 *
209 * @param string $cloud_id Cloud snippet ID.
210 *
211 * @return string|null Revision number on success, null otherwise.
212 */
213 public static function get_cloud_snippet_revision( string $cloud_id ) {
214 $api_url = self::CLOUD_API_URL . sprintf( 'public/getsnippetrevision/%s', $cloud_id );
215 $body = wp_remote_retrieve_body( wp_remote_get( $api_url ) );
216
217 if ( ! $body ) {
218 return null;
219 }
220
221 $cloud_snippet_revision = json_decode( $body, true );
222 return $cloud_snippet_revision['snippet_revision'] ?? null;
223 }
224
225 /**
226 * Download a snippet from the cloud.
227 *
228 * @param int|string $cloud_id The cloud ID of the snippet as string from query args.
229 * @param string $source The source table of the snippet: 'codevault' or 'search'.
230 * @param string $action The action to be performed: 'download' or 'update'.
231 *
232 * @return array<string, string|bool> Result of operation: an array with `success` and `error_message` keys.
233 */
234 public function download_or_update_snippet( int $cloud_id, string $source, string $action ): array {
235 $cloud_id = intval( $cloud_id );
236 $snippet_to_store = $this->get_single_cloud_snippet( $cloud_id );
237
238 switch ( $action ) {
239 case 'download':
240 return $this->download_snippet_from_cloud( $snippet_to_store );
241 case 'update':
242 return $this->update_snippet_from_cloud( $snippet_to_store );
243 default:
244 return [
245 'success' => false,
246 'error' => __( 'Invalid action.', 'code-snippets' ),
247 ];
248 }
249 }
250
251 /**
252 * Retrieve a single cloud snippet from the API.
253 *
254 * @param int $cloud_id Remote cloud snippet ID.
255 *
256 * @return Cloud_Snippet Retrieved snippet.
257 */
258 public static function get_single_cloud_snippet( int $cloud_id ): Cloud_Snippet {
259 $url = self::CLOUD_API_URL . sprintf( 'public/getsnippet/%s', $cloud_id );
260 $response = wp_remote_get( $url );
261 $cloud_snippet = self::unpack_request_json( $response );
262
263 return new Cloud_Snippet( $cloud_snippet['snippet'] );
264 }
265
266 /**
267 * Download a snippet from the cloud.
268 *
269 * @param Cloud_Snippet|Cloud_Snippet[] $snippets_to_store The snippet to be downloaded.
270 *
271 * @return array The result of the download.
272 */
273 public function download_snippet_from_cloud( $snippets_to_store ): array {
274 $new_snippet = null;
275 $link = null;
276
277 if ( ! is_array( $snippets_to_store ) ) {
278 $snippets_to_store = [ $snippets_to_store ];
279 }
280
281 foreach ( $snippets_to_store as $snippet_to_store ) {
282 $snippet = new Snippet( $snippet_to_store );
283
284 // Set the snippet id to 0 to ensure that the snippet is saved as a new snippet.
285 $ownership = '0';
286 $snippet->id = 0;
287 $snippet->active = 0;
288 $snippet->cloud_id = $snippet_to_store->id . '_' . $ownership;
289 $snippet->desc = $snippet_to_store->description ? $snippet_to_store->description : '';
290
291 // Save the snippet to the database.
292 $new_snippet = save_snippet( $snippet );
293
294 $link = new Cloud_Link();
295 $link->local_id = $new_snippet->id;
296 $link->cloud_id = $snippet->cloud_id;
297 $link->is_owner = $snippet_to_store->is_owner;
298 $link->in_codevault = false;
299 $link->update_available = false;
300
301 $this->add_map_link( $link );
302 }
303
304 if ( 1 === count( $snippets_to_store ) && $new_snippet && $link ) {
305 return [
306 'success' => true,
307 'action' => __( 'Single Downloaded', 'code-snippets' ),
308 'snippet_id' => $new_snippet->id,
309 'link_id' => $link->cloud_id,
310 ];
311 }
312
313 if ( count( $snippets_to_store ) > 1 ) {
314 return [
315 'success' => true,
316 'action' => __( 'Downloaded', 'code-snippets' ),
317 ];
318 } else {
319 return [
320 'success' => false,
321 'error' => __( 'There was a problem saving or no snippets found to download.', 'code-snippets' ),
322 ];
323 }
324 }
325
326 /**
327 * Update a snippet from the cloud.
328 *
329 * @param Cloud_Snippet|Cloud_Snippet[] $snippet_to_store Array of snippets to be updated.
330 *
331 * @return array The result of the update.
332 */
333 public function update_snippet_from_cloud( $snippet_to_store ): array {
334 if ( is_array( $snippet_to_store ) ) {
335 $snippet_to_store = reset( $snippet_to_store );
336 }
337
338 $ownership = $snippet_to_store->is_owner ? '1' : '0';
339 $cloud_id = $snippet_to_store->id . '_' . $ownership;
340 $local_snippet = get_snippet_by_cloud_id( sanitize_key( $cloud_id ) );
341 // Only update the code, active and revision fields.
342 $fields = [
343 'code' => $snippet_to_store->code,
344 'active' => false,
345 'revision' => $snippet_to_store->revision,
346 ];
347
348 update_snippet_fields( $local_snippet->id, $fields );
349
350 $this->refresh_synced_data();
351
352 return [
353 'success' => true,
354 'action' => __( 'Updated', 'code-snippets' ),
355 ];
356 }
357
358 /**
359 * Check if a snippet has update available using cloud link.
360 *
361 * @param int $snippet_id The local ID of the snippet.
362 *
363 * @return bool Whether the snippet has update available or not.
364 */
365 public function is_update_available( int $snippet_id ): bool {
366 $cloud_link = $this->get_local_to_cloud_map();
367
368 // Find the snippet from the array of objects using snippet id.
369 $snippet = array_filter(
370 $cloud_link,
371 function ( $snippet ) use ( $snippet_id ) {
372 return $snippet->local_id === $snippet_id;
373 }
374 );
375
376 // Get the first element of the array.
377 $snippet = reset( $snippet );
378 // Return the update available value which is a boolean.
379 return $snippet->update_available;
380 }
381
382 /**
383 * Check if snippet is synced to cloud.
384 *
385 * @param int $snippet_id Snippet ID.
386 * @param string $local_or_cloud Whether the ID is a local ID or cloud ID.
387 *
388 * @return Cloud_Link|null
389 */
390 public function get_cloud_link( int $snippet_id, string $local_or_cloud ) {
391 $local_to_cloud_map = $this->get_local_to_cloud_map();
392
393 if ( 'local' === $local_or_cloud || 'cloud' === $local_or_cloud ) {
394 $column = 'cloud' === $local_or_cloud ? 'cloud_id' : 'local_id';
395 $local_id_array = array_map( 'intval', array_column( $local_to_cloud_map, $column ) );
396
397 if ( in_array( $snippet_id, $local_id_array, true ) ) {
398 $index = array_search( $snippet_id, $local_id_array, true );
399 return $local_to_cloud_map[ $index ];
400 }
401 }
402
403 return null;
404 }
405
406 /**
407 *
408 * Static Helper Methods
409 */
410
411 /**
412 * Translate a snippet scope to a type.
413 *
414 * @param string $scope The scope of the snippet.
415 *
416 * @return string The type of the snippet.
417 */
418 public static function get_type_from_scope( string $scope ): string {
419 switch ( $scope ) {
420 case 'global':
421 return 'php';
422 case 'site-css':
423 return 'css';
424 case 'site-footer-js':
425 return 'js';
426 case 'content':
427 return 'html';
428 default:
429 return '';
430 }
431 }
432
433 /**
434 * Translate a snippet status to a style class.
435 *
436 * @param int $status The scope of the snippet.
437 *
438 * @return string The style to be used for the stats badge.
439 */
440 public static function get_style_from_status( int $status ): string {
441 switch ( $status ) {
442 case 3: // Private.
443 return 'css';
444 case 4: // Public.
445 return 'js';
446 case 5: // Unverified.
447 return 'unverified';
448 case 6: // AI Verified.
449 case 8: // Pro Verified.
450 return 'html';
451 default:
452 return 'php';
453 }
454 }
455
456 /**
457 * Translate a snippet status to a status-name.
458 *
459 * @param int $status The scope of the snippet.
460 *
461 * @return string The style to be used for the stats badge.
462 */
463 public static function get_status_name_from_status( int $status ): string {
464 switch ( $status ) {
465 case 3:
466 return __( 'Private', 'code-snippets' );
467 case 4:
468 return __( 'Public', 'code-snippets' );
469 case 5:
470 return __( 'Unverified', 'code-snippets' );
471 case 6:
472 return __( 'AI Verified', 'code-snippets' );
473 case 8:
474 return __( 'Pro Verified', 'code-snippets' );
475 default:
476 return '';
477 }
478 }
479
480 /**
481 * Renders the html for the preview thickbox popup.
482 *
483 * @return void
484 */
485 public static function render_cloud_snippet_thickbox() {
486 add_thickbox();
487 ?>
488 <div id="show-code-preview" style="display: none;">
489 <h3 id="snippet-name-thickbox"></h3>
490 <h4><?php esc_html_e( 'Snippet Code:', 'code-snippets' ); ?></h4>
491 <pre class="thickbox-code-viewer">
492 <code id="snippet-code-thickbox"></code>
493 </pre>
494 </div>
495 <?php
496 }
497 }
498