PluginProbe
EasyFonts – Host Google Fonts Locally, Fast & Auto-Optimize, GDPR Compliant / 2.0.2
EasyFonts – Host Google Fonts Locally, Fast & Auto-Optimize, GDPR Compliant v2.0.2
2.0.4 2.0.3 2.0.2 2.0.1 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.2 1.3 2.0.0
easyfonts / src / Admin / RestApi.php

RestApi.php in EasyFonts – Host Google Fonts Locally, Fast & Auto-Optimize, GDPR Compliant 2.0.2, at src/Admin/RestApi.php

735 lines 22.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * REST API.
4 *
5 * @package EasyFonts
6 */
7
8 namespace EasyFonts\Admin;
9
10 use EasyFonts\Database\Migrator;
11 use EasyFonts\Fonts\Registry;
12 use EasyFonts\Fonts\Storage;
13 use EasyFonts\Fonts\UsageTracker;
14 use EasyFonts\Settings;
15 use WP_REST_Request;
16 use WP_REST_Response;
17
18 defined( 'ABSPATH' ) || exit;
19
20 /**
21 * Registers and handles all REST routes.
22 */
23 class RestApi {
24
25 const NS = 'easyfonts/v1';
26
27 /**
28 * Register hooks.
29 */
30 public function boot(): void {
31 add_action( 'rest_api_init', array( $this, 'register' ) );
32 }
33
34 /**
35 * Register routes.
36 */
37 public function register(): void {
38 $admin = array( $this, 'can_manage' );
39
40 register_rest_route(
41 self::NS,
42 '/settings',
43 array(
44 array(
45 'methods' => 'GET',
46 'callback' => array( $this, 'get_settings' ),
47 'permission_callback' => $admin,
48 ),
49 array(
50 'methods' => 'POST',
51 'callback' => array( $this, 'save_settings' ),
52 'permission_callback' => $admin,
53 ),
54 )
55 );
56
57 register_rest_route( self::NS, '/fonts', array(
58 'methods' => 'GET',
59 'callback' => array( $this, 'get_fonts' ),
60 'permission_callback' => $admin,
61 ) );
62
63 register_rest_route( self::NS, '/font/toggle', array(
64 'methods' => 'POST',
65 'callback' => array( $this, 'toggle_font' ),
66 'permission_callback' => $admin,
67 ) );
68
69 register_rest_route( self::NS, '/fonts/bulk', array(
70 'methods' => 'POST',
71 'callback' => array( $this, 'bulk_toggle' ),
72 'permission_callback' => $admin,
73 ) );
74
75 register_rest_route( self::NS, '/optimize', array(
76 'methods' => 'POST',
77 'callback' => array( $this, 'optimize' ),
78 'permission_callback' => $admin,
79 ) );
80
81 register_rest_route( self::NS, '/usage', array(
82 'methods' => 'GET',
83 'callback' => array( $this, 'get_usage' ),
84 'permission_callback' => $admin,
85 ) );
86
87 register_rest_route( self::NS, '/stats', array(
88 'methods' => 'GET',
89 'callback' => array( $this, 'get_stats' ),
90 'permission_callback' => $admin,
91 ) );
92
93 register_rest_route( self::NS, '/purge', array(
94 'methods' => 'POST',
95 'callback' => array( $this, 'purge' ),
96 'permission_callback' => $admin,
97 ) );
98
99 register_rest_route( self::NS, '/repair', array(
100 'methods' => 'POST',
101 'callback' => array( $this, 'repair' ),
102 'permission_callback' => $admin,
103 ) );
104
105 register_rest_route( self::NS, '/diagnostics', array(
106 'methods' => 'GET',
107 'callback' => array( $this, 'diagnostics' ),
108 'permission_callback' => $admin,
109 ) );
110
111 // Public beacon ingest (nonce-checked in handler).
112 register_rest_route( self::NS, '/beacon', array(
113 'methods' => 'POST',
114 'callback' => array( $this, 'beacon' ),
115 'permission_callback' => '__return_true',
116 ) );
117
118 // Public async-font ingest: records Google/Bunny CSS URLs injected by JS
119 // at runtime so the next render can self-host them (nonce-checked).
120 register_rest_route( self::NS, '/async-fonts', array(
121 'methods' => 'POST',
122 'callback' => array( $this, 'async_fonts' ),
123 'permission_callback' => '__return_true',
124 ) );
125
126 // Settings export / import (admin only).
127 register_rest_route( self::NS, '/export', array(
128 'methods' => 'GET',
129 'callback' => array( $this, 'export_settings' ),
130 'permission_callback' => $admin,
131 ) );
132
133 register_rest_route( self::NS, '/import', array(
134 'methods' => 'POST',
135 'callback' => array( $this, 'import_settings' ),
136 'permission_callback' => $admin,
137 ) );
138 }
139
140 /**
141 * Capability gate.
142 *
143 * @return bool
144 */
145 public function can_manage(): bool {
146 return current_user_can( 'manage_options' );
147 }
148
149 /**
150 * GET /settings
151 *
152 * @return WP_REST_Response
153 */
154 public function get_settings(): WP_REST_Response {
155 return new WP_REST_Response( Settings::all(), 200 );
156 }
157
158 /**
159 * POST /settings
160 *
161 * @param WP_REST_Request $request Request.
162 * @return WP_REST_Response
163 */
164 public function save_settings( WP_REST_Request $request ): WP_REST_Response {
165 $input = (array) $request->get_json_params();
166 $current = Settings::all();
167
168 $bools = array( 'enabled', 'auto_config', 'strip_hints', 'smart_preload', 'metric_fallbacks', 'beacon', 'inline_css', 'async_blocker', 'remove_data_on_uninstall' );
169
170 foreach ( $bools as $key ) {
171 if ( array_key_exists( $key, $input ) ) {
172 $current[ $key ] = $input[ $key ] ? 1 : 0;
173 }
174 }
175
176 if ( isset( $input['font_display'] ) ) {
177 $allowed = array( 'swap', 'fallback', 'optional', 'block', 'auto', 'none' );
178 $val = sanitize_text_field( $input['font_display'] );
179 $current['font_display'] = in_array( $val, $allowed, true ) ? $val : 'swap';
180 }
181
182 if ( array_key_exists( 'cdn_url', $input ) ) {
183 $cdn = trim( (string) $input['cdn_url'] );
184
185 // Accept protocol-relative; require http(s); store without trailing slash.
186 if ( '' === $cdn ) {
187 $current['cdn_url'] = '';
188 } else {
189 if ( 0 === strpos( $cdn, '//' ) ) {
190 $cdn = ( is_ssl() ? 'https:' : 'http:' ) . $cdn;
191 }
192
193 $current['cdn_url'] = preg_match( '#^https?://#i', $cdn )
194 ? untrailingslashit( esc_url_raw( $cdn ) )
195 : '';
196 }
197 }
198
199 if ( isset( $input['subsets'] ) && is_array( $input['subsets'] ) ) {
200 $current['subsets'] = array_values( array_map( 'sanitize_text_field', $input['subsets'] ) );
201 }
202
203 if ( isset( $input['excluded_urls'] ) && is_array( $input['excluded_urls'] ) ) {
204 $current['excluded_urls'] = array_values( array_filter( array_map( 'sanitize_text_field', $input['excluded_urls'] ) ) );
205 }
206
207 Settings::save( $current );
208 Settings::bump_buster();
209
210 return new WP_REST_Response( Settings::all(), 200 );
211 }
212
213 /**
214 * GET /fonts
215 *
216 * @return WP_REST_Response
217 */
218 public function get_fonts(): WP_REST_Response {
219 $rendered = ( new UsageTracker() )->rendered_set();
220
221 $grouped = ( new Registry() )->grouped_with_usage(
222 $rendered['variants'],
223 $rendered['families']
224 );
225
226 return new WP_REST_Response( $grouped, 200 );
227 }
228
229 /**
230 * POST /font/toggle — enable/disable or set preload on a variant or family.
231 *
232 * Body: { field: 'enabled'|'preloaded', value: bool, family: string,
233 * weight?: string, style?: string }
234 * Omitting weight/style targets the whole family.
235 *
236 * @param WP_REST_Request $request Request.
237 * @return WP_REST_Response
238 */
239 public function toggle_font( WP_REST_Request $request ): WP_REST_Response {
240 $params = (array) $request->get_json_params();
241
242 $field = sanitize_text_field( $params['field'] ?? '' );
243 $family = sanitize_text_field( $params['family'] ?? '' );
244 $weight = isset( $params['weight'] ) ? sanitize_text_field( (string) $params['weight'] ) : '';
245 $style = isset( $params['style'] ) ? sanitize_text_field( (string) $params['style'] ) : '';
246 $value = ! empty( $params['value'] );
247
248 $column = 'enabled' === $field ? 'is_enabled' : ( 'preloaded' === $field ? 'is_preloaded' : '' );
249
250 if ( '' === $column || '' === $family ) {
251 return new WP_REST_Response( array( 'ok' => false, 'error' => 'bad_request' ), 400 );
252 }
253
254 ( new Registry() )->set_flag( $column, $value, $family, $weight, $style );
255
256 // Enabling/disabling changes which fonts the stylesheet contains, so the
257 // next render must rebuild it; bump the buster to invalidate caches.
258 if ( 'is_enabled' === $column ) {
259 Settings::bump_buster();
260 }
261
262 return new WP_REST_Response( array( 'ok' => true ), 200 );
263 }
264
265 /**
266 * POST /fonts/bulk — enable/disable (or preload) every font in a scope at
267 * once. Body: { field:'enabled'|'preloaded', value:bool, scope:'used'|'unused'|'all' }
268 *
269 * @param WP_REST_Request $request Request.
270 * @return WP_REST_Response
271 */
272 public function bulk_toggle( WP_REST_Request $request ): WP_REST_Response {
273 $params = (array) $request->get_json_params();
274
275 $field = 'preloaded' === ( $params['field'] ?? '' ) ? 'is_preloaded' : 'is_enabled';
276 $value = ! empty( $params['value'] );
277 $scope = in_array( $params['scope'] ?? 'all', array( 'used', 'unused', 'all' ), true ) ? $params['scope'] : 'all';
278
279 $registry = new Registry();
280
281 if ( 'all' === $scope ) {
282 $registry->set_flag_all( $field, $value );
283 } else {
284 $rendered = ( new UsageTracker() )->rendered_set();
285 $grouped = $registry->grouped_with_usage( $rendered['variants'], $rendered['families'] );
286
287 foreach ( $grouped as $family ) {
288 $is_used = ! empty( $family['used'] );
289
290 if ( ( 'used' === $scope && $is_used ) || ( 'unused' === $scope && ! $is_used ) ) {
291 $registry->set_flag( $field, $value, $family['family'] );
292 }
293 }
294 }
295
296 if ( 'is_enabled' === $field ) {
297 Settings::bump_buster();
298 }
299
300 return new WP_REST_Response( array( 'ok' => true ), 200 );
301 }
302
303 /**
304 * POST /optimize — prime optimisation now via a cache-busting loopback to
305 * the front page, so the user doesn't have to visit it manually.
306 *
307 * @return WP_REST_Response
308 */
309 public function optimize(): WP_REST_Response {
310 $targets = apply_filters(
311 'easyfonts_optimize_urls',
312 array( home_url( '/' ) )
313 );
314
315 // Clear any throttled decision for the target routes so the X-ray beacon
316 // that runs right after this is accepted immediately (a fresh, on-demand
317 // measurement rather than waiting out the throttle window).
318 $tracker = new UsageTracker();
319
320 foreach ( (array) $targets as $t ) {
321 $tracker->forget_decision( UsageTracker::route_for( (string) $t ) );
322 }
323
324 $ok = 0;
325
326 foreach ( (array) $targets as $target ) {
327 // Cache-busting param forces a fresh PHP render (bypasses page cache).
328 // The warm key authorises this unauthenticated self-request to download.
329 $url = add_query_arg(
330 array(
331 'easyfonts_probe' => Settings::warm_key(),
332 'efbust' => (string) time(),
333 ),
334 $target
335 );
336
337 $response = wp_remote_get(
338 $url,
339 array(
340 'timeout' => 30,
341 /**
342 * Verify SSL on the loopback self-request. True by default;
343 * filter to false only for self-signed/staging certs.
344 *
345 * @param bool $verify
346 */
347 'sslverify' => (bool) apply_filters( 'easyfonts_loopback_sslverify', true ),
348 )
349 );
350
351 if ( ! is_wp_error( $response ) && (int) wp_remote_retrieve_response_code( $response ) < 400 ) {
352 $ok++;
353 }
354 }
355
356 $stats = ( new Registry() )->stats();
357
358 return new WP_REST_Response(
359 array(
360 'ok' => $ok > 0,
361 'probed' => $ok,
362 'families' => $stats['families'],
363 'variants' => $stats['variants'],
364 // The admin loads this in a hidden iframe to run the real-browser
365 // X-ray (beacon), which measures rendered fonts + subsets.
366 'probe_url' => add_query_arg( 'easyfonts_probe', (string) time(), home_url( '/' ) ),
367 // Snapshot of the last-beacon time BEFORE the X-ray; the client
368 // polls /stats and watches for this to advance, which confirms the
369 // iframe actually rendered (and wasn't blocked by X-Frame-Options).
370 'beacon_before' => (int) get_option( 'easyfonts_last_beacon', 0 ),
371 ),
372 200
373 );
374 }
375
376 /**
377 * GET /usage
378 *
379 * @return WP_REST_Response
380 */
381 public function get_usage(): WP_REST_Response {
382 return new WP_REST_Response( ( new UsageTracker() )->summary(), 200 );
383 }
384
385 /**
386 * GET /stats
387 *
388 * @return WP_REST_Response
389 */
390 public function get_stats(): WP_REST_Response {
391 $registry = new Registry();
392 $storage = new Storage();
393 $stats = $registry->stats();
394
395 return new WP_REST_Response(
396 array(
397 'families' => $stats['families'],
398 'variants' => $stats['variants'],
399 'hosted_kb' => (int) round( $stats['bytes'] / 1024 ),
400 'cache_kb' => (int) round( $storage->total_size() / 1024 ),
401 'detectors' => (array) Settings::get( 'detectors', array() ),
402 'last_buster' => Settings::buster(),
403 'last_beacon' => (int) get_option( 'easyfonts_last_beacon', 0 ),
404 ),
405 200
406 );
407 }
408
409 /**
410 * POST /purge — clear cache + tables, keep settings.
411 *
412 * @return WP_REST_Response
413 */
414 public function purge(): WP_REST_Response {
415 ( new Storage() )->purge();
416 ( new Registry() )->truncate();
417 ( new UsageTracker() )->truncate();
418
419 delete_option( 'easyfonts_processed_local' );
420 delete_option( 'easyfonts_processed_external' );
421
422 $settings = Settings::all();
423 $settings['detectors'] = array();
424 Settings::save( $settings );
425 Settings::bump_buster();
426
427 return new WP_REST_Response( array( 'ok' => true ), 200 );
428 }
429
430 /**
431 * POST /repair — drop + recreate the tables (fixes stale/legacy schema),
432 * then clear cache + learned state so the next page view rebuilds cleanly.
433 *
434 * @return WP_REST_Response
435 */
436 public function repair(): WP_REST_Response {
437 ( new Migrator() )->repair();
438 ( new Storage() )->purge();
439
440 delete_option( 'easyfonts_processed_local' );
441 delete_option( 'easyfonts_processed_external' );
442 delete_transient( 'easyfonts_schema_checked' );
443
444 $settings = Settings::all();
445 $settings['detectors'] = array();
446 Settings::save( $settings );
447 Settings::bump_buster();
448
449 return new WP_REST_Response(
450 array(
451 'ok' => true,
452 'tables' => ( new Migrator() )->status(),
453 ),
454 200
455 );
456 }
457
458 /**
459 * GET /diagnostics
460 *
461 * @return WP_REST_Response
462 */
463 public function diagnostics(): WP_REST_Response {
464 return new WP_REST_Response( Diagnostics::collect(), 200 );
465 }
466
467 /**
468 * POST /beacon — ingest real-render decisions.
469 *
470 * @param WP_REST_Request $request Request.
471 * @return WP_REST_Response
472 */
473 public function beacon( WP_REST_Request $request ): WP_REST_Response {
474 $nonce = $request->get_header( 'X-WP-Nonce' );
475
476 if ( ! $nonce ) {
477 $nonce = $request->get_param( '_wpnonce' );
478 }
479
480 if ( ! wp_verify_nonce( (string) $nonce, 'wp_rest' ) ) {
481 return new WP_REST_Response( array( 'ok' => false ), 403 );
482 }
483
484 $params = (array) $request->get_json_params();
485 $route = sanitize_text_field( $params['route'] ?? '/' );
486 $device = in_array( $params['device'] ?? '', array( 'mobile', 'desktop' ), true ) ? $params['device'] : 'any';
487
488 // Cap the route length to keep the indexed column sane.
489 $route = '' === $route ? '/' : substr( $route, 0, 480 );
490
491 $usage = new UsageTracker();
492
493 // Per-route/device throttle: once we record a beacon for a route we
494 // ignore further beacons for it for a short window. This bounds writes
495 // on an anonymous endpoint and neutralises repeated-request abuse, while
496 // still letting used/unused classification and page scoping self-correct
497 // quickly (hourly by default) as pages change — the old week-long
498 // write-once meant a font that started or stopped being used wasn't
499 // reflected for days.
500 $throttle = (int) apply_filters( 'easyfonts_beacon_throttle_hours', 1 );
501
502 if ( $throttle > 0 && $usage->has_fresh_decision( $route, (string) $device, $throttle ) ) {
503 return new WP_REST_Response( array( 'ok' => true, 'cached' => true ), 200 );
504 }
505
506 // Hard caps on payload size (defence against oversized public payloads).
507 $cap = 200;
508 $rendered = is_array( $params['rendered'] ?? null ) ? array_slice( $params['rendered'], 0, $cap ) : array();
509 $preload = is_array( $params['preload'] ?? null ) ? array_slice( $params['preload'], 0, $cap ) : array();
510 $unload = is_array( $params['unload'] ?? null ) ? array_slice( $params['unload'], 0, $cap ) : array();
511
512 // Mark that a real-browser beacon just reported in. The admin polls this
513 // after opening the optimize iframe to confirm the X-ray actually ran
514 // (vs. being blocked by X-Frame-Options / CSP).
515 update_option( 'easyfonts_last_beacon', time(), false );
516
517 // Record observed usage.
518 $records = array();
519
520 foreach ( $rendered as $r ) {
521 if ( empty( $r['family'] ) ) {
522 continue;
523 }
524
525 $records[] = array(
526 'family' => $r['family'],
527 'weight' => $r['weight'] ?? '400',
528 'style' => $r['style'] ?? 'normal',
529 'origin' => 'beacon',
530 'rendered' => 1,
531 'above_fold' => ! empty( $r['above_fold'] ) ? 1 : 0,
532 );
533 }
534
535 // Also record what loaded but never rendered, as beacon-origin rows with
536 // rendered = 0. This is what lets page scoping tell a CONFIRMED-unused
537 // font (drop it from this page) apart from a font that simply hasn't been
538 // measured yet (keep it) — so a newly added/replaced font is never
539 // wrongly scoped out before the beacon has judged it.
540 foreach ( $unload as $u ) {
541 if ( empty( $u['family'] ) ) {
542 continue;
543 }
544
545 $records[] = array(
546 'family' => $u['family'],
547 'weight' => $u['weight'] ?? '400',
548 'style' => $u['style'] ?? 'normal',
549 'origin' => 'beacon',
550 'rendered' => 0,
551 'above_fold' => 0,
552 );
553 }
554
555 if ( ! empty( $records ) ) {
556 $usage->record( $route, url_to_postid( home_url( $route ) ), $records );
557
558 // Refresh the uniformly-above-the-fold family cache from the updated
559 // usage data. Runs only when a beacon is accepted (throttled), so the
560 // cost is a single grouped scan of the capped usage table.
561 $usage->recompute_global_preload();
562 }
563
564 // Persist the raw beacon measurement for this route/device. Page scoping
565 // and preload are driven from the recorded usage above (family-level,
566 // self-correcting); this row anchors the per-route throttle (updated_at)
567 // and keeps the raw above-the-fold/unrendered snapshot for diagnostics.
568 $usage->store_decision( $route, (string) $device, $this->clean_variants( $preload ), $this->clean_variants( $unload ) );
569
570 return new WP_REST_Response( array( 'ok' => true ), 200 );
571 }
572
573 /**
574 * Sanitise a list of {family,weight,style} entries.
575 *
576 * @param array<int,mixed> $list List.
577 * @return array<int,array{family:string,weight:string,style:string}>
578 */
579 private function clean_variants( array $list ): array {
580 $out = array();
581
582 foreach ( $list as $item ) {
583 if ( empty( $item['family'] ) ) {
584 continue;
585 }
586
587 $out[] = array(
588 'family' => sanitize_text_field( $item['family'] ),
589 'weight' => sanitize_text_field( (string) ( $item['weight'] ?? '400' ) ),
590 'style' => sanitize_text_field( (string) ( $item['style'] ?? 'normal' ) ),
591 );
592 }
593
594 return $out;
595 }
596
597 /**
598 * POST /async-fonts — record Google/Bunny CSS URLs that were injected by
599 * JavaScript at runtime (caught client-side by async-blocker.js) so the next
600 * server render can self-host them. Nonce-checked, provider-validated, and
601 * capped. Public input only ever queues *provider* CSS URLs for hosting; it
602 * cannot write arbitrary data or flip any persistent setting.
603 *
604 * @param WP_REST_Request $request Request.
605 * @return WP_REST_Response
606 */
607 public function async_fonts( WP_REST_Request $request ): WP_REST_Response {
608 $nonce = $request->get_header( 'X-WP-Nonce' );
609
610 if ( ! $nonce ) {
611 $nonce = $request->get_param( '_wpnonce' );
612 }
613
614 if ( ! wp_verify_nonce( (string) $nonce, 'wp_rest' ) ) {
615 return new WP_REST_Response( array( 'ok' => false ), 403 );
616 }
617
618 if ( ! Settings::get( 'enabled', 1 ) || ! Settings::get( 'async_blocker', 0 ) ) {
619 return new WP_REST_Response( array( 'ok' => false ), 403 );
620 }
621
622 $params = (array) $request->get_json_params();
623 $urls = is_array( $params['urls'] ?? null ) ? array_slice( $params['urls'], 0, 25 ) : array();
624
625 $stored = (array) get_option( 'easyfonts_async_urls', array() );
626 $before = count( $stored );
627
628 foreach ( $urls as $raw ) {
629 $url = \EasyFonts\Detect\Providers::normalize_url( (string) $raw );
630
631 // Only accept genuine provider stylesheet URLs.
632 if ( ! \EasyFonts\Detect\Providers::is_css_url( $url ) ) {
633 continue;
634 }
635
636 $url = esc_url_raw( $url );
637
638 if ( '' !== $url && ! in_array( $url, $stored, true ) ) {
639 $stored[] = $url;
640 }
641 }
642
643 // Keep the queue bounded.
644 if ( count( $stored ) > 50 ) {
645 $stored = array_slice( $stored, -50 );
646 }
647
648 if ( count( $stored ) !== $before ) {
649 update_option( 'easyfonts_async_urls', array_values( $stored ), false );
650 // New runtime fonts discovered → invalidate so the next render hosts them.
651 Settings::bump_buster();
652 }
653
654 return new WP_REST_Response( array( 'ok' => true, 'queued' => count( $stored ) ), 200 );
655 }
656
657 /**
658 * GET /export — return the current settings as a portable JSON payload.
659 *
660 * @return WP_REST_Response
661 */
662 public function export_settings(): WP_REST_Response {
663 return new WP_REST_Response(
664 array(
665 '_type' => 'easyfonts-settings',
666 '_version' => EASYFONTS_VERSION,
667 'settings' => Settings::all(),
668 ),
669 200
670 );
671 }
672
673 /**
674 * POST /import — replace settings from an exported payload. Values are run
675 * through the same validation as the normal save path (no raw write).
676 *
677 * @param WP_REST_Request $request Request.
678 * @return WP_REST_Response
679 */
680 public function import_settings( WP_REST_Request $request ): WP_REST_Response {
681 $body = (array) $request->get_json_params();
682
683 // Accept either the wrapped export ({settings:{…}}) or a bare object.
684 $incoming = isset( $body['settings'] ) && is_array( $body['settings'] ) ? $body['settings'] : $body;
685
686 if ( empty( $incoming ) ) {
687 return new WP_REST_Response( array( 'ok' => false, 'error' => 'empty' ), 400 );
688 }
689
690 $defaults = Migrator::default_settings();
691 $current = Settings::all();
692
693 // Booleans.
694 foreach ( array( 'enabled', 'auto_config', 'strip_hints', 'smart_preload', 'metric_fallbacks', 'beacon', 'inline_css', 'async_blocker', 'remove_data_on_uninstall' ) as $key ) {
695 if ( array_key_exists( $key, $incoming ) ) {
696 $current[ $key ] = $incoming[ $key ] ? 1 : 0;
697 }
698 }
699
700 // font-display.
701 if ( isset( $incoming['font_display'] ) ) {
702 $allowed = array( 'swap', 'fallback', 'optional', 'block', 'auto', 'none' );
703 $val = sanitize_text_field( (string) $incoming['font_display'] );
704 $current['font_display'] = in_array( $val, $allowed, true ) ? $val : 'swap';
705 }
706
707 // Subsets / excluded URLs (arrays of strings).
708 foreach ( array( 'subsets', 'excluded_urls' ) as $key ) {
709 if ( isset( $incoming[ $key ] ) && is_array( $incoming[ $key ] ) ) {
710 $current[ $key ] = array_values( array_filter( array_map( 'sanitize_text_field', $incoming[ $key ] ) ) );
711 }
712 }
713
714 // CDN URL.
715 if ( array_key_exists( 'cdn_url', $incoming ) ) {
716 $cdn = trim( (string) $incoming['cdn_url'] );
717
718 if ( '' !== $cdn && 0 === strpos( $cdn, '//' ) ) {
719 $cdn = ( is_ssl() ? 'https:' : 'http:' ) . $cdn;
720 }
721
722 $current['cdn_url'] = ( '' !== $cdn && preg_match( '#^https?://#i', $cdn ) )
723 ? untrailingslashit( esc_url_raw( $cdn ) )
724 : '';
725 }
726
727 // Never import a foreign detector set; keep what this site learned.
728 $current['detectors'] = (array) ( $current['detectors'] ?? $defaults['detectors'] );
729
730 Settings::save( $current );
731 Settings::bump_buster();
732
733 return new WP_REST_Response( array( 'ok' => true, 'settings' => Settings::all() ), 200 );
734 }
735 }