PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.1
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.1
1.1.10 1.1.9 1.1.8 1.1.7 1.1.6 1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.1 1.0.0 0.9.8 0.9.7 0.9.6 0.9.4 0.9.5 0.9.3 0.9.2 0.9.1 0.9.0 0.8.9 0.8.8 0.8.7 All 34 releases
desktop-mode / includes / os-settings.php

os-settings.php in OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin 1.1.1, at includes/os-settings.php

972 lines 39.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * OpenStation — OS Settings Persistence.
4 *
5 * Persists each user's OS Settings preferences (wallpaper, accent color,
6 * dock size, custom gradient/image, HD-only toggle, and AI integration
7 * settings) to user meta so they survive across browsers, devices, and
8 * private/incognito sessions. The JS layer writes to localStorage on
9 * every change for instant read-back, then asynchronously syncs to this
10 * endpoint so user meta is the durable source of truth.
11 *
12 * @package OpenStation
13 */
14
15 defined( 'ABSPATH' ) || exit;
16
17 /**
18 * User meta key for OS Settings.
19 *
20 * The VALUE keeps its pre-rebrand spelling on purpose: it is a
21 * persisted or externally-visible identifier, so renaming it would
22 * orphan data already written by live installs (or break a live
23 * URL). The mismatch between this constant's name and its value is
24 * deliberate — it is NOT a half-finished rename.
25 */
26 const OPENSTATION_OS_SETTINGS_META_KEY = 'desktop_mode_os_settings';
27
28 /** Valid dock-size IDs — mirrors the TS `DOCK_SIZES` constant. */
29 const OPENSTATION_OS_SETTINGS_DOCK_SIZES = array( 'compact', 'default', 'large' );
30
31 /** Valid window-radius IDs — mirrors the TS `WINDOW_RADII` constant. */
32 const OPENSTATION_OS_SETTINGS_WINDOW_RADII = array( 'sharp', 'default', 'round' );
33
34 /**
35 * Valid admin-bar mode IDs — mirrors the TS `ADMIN_BAR_MODES` constant.
36 *
37 * `static` keeps the WordPress admin bar pinned above the shell (the
38 * default), `dynamic` auto-hides it to a peek strip that reveals on
39 * hover or keyboard focus, and `hidden` removes it entirely.
40 */
41 const OPENSTATION_OS_SETTINGS_ADMIN_BAR_MODES = array( 'static', 'dynamic', 'hidden' );
42
43 /** Valid desktop-layout IDs — mirrors the TS `DESKTOP_LAYOUTS` constant. */
44 const OPENSTATION_OS_SETTINGS_DESKTOP_LAYOUTS = array( 'classic', 'unified' );
45
46 /**
47 * Valid dock-placement IDs — mirrors the TS `DOCK_PLACEMENTS` constant.
48 *
49 * Which edge the single dock sits on. Read by the layout dispatcher for
50 * `unified`; `classic` derives its two rails from the layout itself and
51 * ignores this.
52 */
53 const OPENSTATION_OS_SETTINGS_DOCK_PLACEMENTS = array( 'bottom', 'left', 'right' );
54
55 /**
56 * Playable range for the window-reveal duration override, in ms.
57 * Mirrors `MIN_REVEAL_DURATION_MS` / `MAX_REVEAL_DURATION_MS` in
58 * `src/reveals/registry.ts`.
59 *
60 * `0` sits OUTSIDE this range on purpose: it is the "no override"
61 * sentinel, not a duration, and is handled before the clamp.
62 */
63 const OPENSTATION_OS_SETTINGS_REVEAL_DURATION_MIN = 80;
64 const OPENSTATION_OS_SETTINGS_REVEAL_DURATION_MAX = 4000;
65
66 /**
67 * Returns a well-shaped default OS settings array.
68 *
69 * Mirrors the TypeScript `DEFAULTS` constant so a fresh user account
70 * gets the same starting state in both environments.
71 *
72 * @return array
73 */
74 function openstation_default_os_settings() {
75 return array(
76 'wallpaper' => 'galaxy',
77 'accent' => 'pulse',
78 // Only read when `accent` is `custom`. Seeded with Pulse so
79 // picking Custom before touching the wheel is a no-op rather
80 // than a jump to black. Mirrors `DEFAULTS` in
81 // `src/settings/constants.ts`.
82 'customAccent' => '#f252fc',
83 'dockSize' => 'default',
84 // `round` (16px), not the preset id literally named `default`.
85 // Preset ids are stored values and cannot be renamed, so the
86 // option labelled "Default" in the picker is no longer the
87 // shipped default. Must stay in step with `DEFAULTS` in
88 // `src/settings/constants.ts` — PHP seeds the first load and JS
89 // owns every paint after it, so a mismatch shows up as the
90 // corners changing shape a moment after the shell boots.
91 'windowRadius' => 'round',
92 // How the WordPress admin bar presents above the shell.
93 // `hidden` ships as the default so a fresh desktop has ONE
94 // navigation surface: everything the user can open lives on the
95 // dock, and the dock's "Exit OpenStation" tile is the way back
96 // to classic admin. `static` (vanilla behavior) and `dynamic`
97 // are one pick away in OpenStation Preferences → Appearance.
98 'adminBarMode' => 'hidden',
99 // One dock holding every menu, with the system tiles grouped
100 // behind a hairline. `classic` (side bar for core menus + bottom
101 // dock for plugins) is the other option; it is no longer what a
102 // first-run desktop looks like.
103 'desktopLayout' => 'unified',
104 // Which edge the single dock sits on. Ignored by `classic`,
105 // which derives both of its rails from the layout.
106 'dockPlacement' => 'bottom',
107 'dockRailRenderer' => 'default',
108 // Active desktop-theme slug, or `''` for the system default.
109 // Site-wide library (`includes/desktop-themes/`), per-user
110 // activation. Not validated against the installed list here —
111 // the enqueue path checks existence on every request, so a
112 // deleted theme degrades silently instead of needing a
113 // user-meta rewrite.
114 'desktopTheme' => '',
115 // Slugs of the desktop themes whose `recommendedOsSettings`
116 // block has already been applied for this user. A theme's
117 // recommendations are seeded ONCE — the first time the user
118 // activates it — and this list is the record of that. It is
119 // what makes "never overwrite a user's later choices" true:
120 // re-activating a theme they have worn before changes
121 // nothing. The Themes tab's "Apply recommended layout" action
122 // is the deliberate way back. Capped at 64 slugs.
123 'appliedThemeRecommendations' => array(),
124 'unfocusEffect' => 'darken',
125 // Window-reveal id — the clip-path transition that uncovers a
126 // window's content once it finishes loading. Off by default;
127 // `none` is the plain opacity fade the shell has always had.
128 'windowReveal' => 'none',
129 // Global reveal duration override in ms. 0 means "use each
130 // reveal's own tuned timing" — the shipped reveals have
131 // durations chosen per shape (Radar's full turn is slower
132 // than Sweep's straight line), and one flat number would
133 // lose that.
134 'windowRevealDuration' => 0,
135 // Window-link renderer id — how relation ties between windows
136 // are drawn (see includes/window-links.php). `svg-splines` is
137 // the shipped built-in; `none` disables the visuals.
138 'windowLinkRenderer' => 'svg-splines',
139 // When the ties are visible: 'always' (default), 'focus' (only
140 // while a group member is focused), or 'off'.
141 'windowLinkVisibility' => 'always',
142 // Master switch for the window-links feature (OS Settings →
143 // Features). Off unmounts the visuals AND the group behaviors
144 // below; the style knobs above keep their values for when it
145 // comes back on.
146 'windowLinksEnabled' => true,
147 // Focusing a relation-group member raises its related windows
148 // to just below it (silent restack, no focus theft).
149 'windowLinkRaiseOnFocus' => true,
150 // Related windows of the focused member get a subtle outline.
151 'windowLinkHighlight' => true,
152 'customGradient' => array(
153 'from' => '#2271b1',
154 'to' => '#7c3aed',
155 'angle' => 135,
156 ),
157 'customImage' => null,
158 // Per-wallpaper settings bags, keyed by wallpaper id — the
159 // values a wallpaper's `renderConfig` dialog writes (e.g. the
160 // Snow wallpaper's wind / particle count / flake size /
161 // background). Scalar values only; the wallpaper owns the keys'
162 // meaning. Missing ids mean "never configured" — the wallpaper
163 // falls back to its defaults. Capped at 64 wallpapers × 32 keys.
164 'wallpaperSettings' => array(),
165 'libraryHdOnly' => true,
166 'ai' => array(
167 'enabled' => false, // AI assistant is opt-in; enabled from OS Settings → Features once a provider is configured.
168 ),
169 // Per-user opt-IN for the native Posts window. When true,
170 // clicking the Posts dock tile opens the `<os-table>`-driven
171 // native window instead of the chromeless `edit.php` iframe.
172 // Default OFF — the native windows are opt-in
173 // Beta. Fresh installs land on the classic iframe; users turn
174 // this on in OS Settings → Features → Beta features to try it.
175 // Per-user override of the WordPress Heartbeat interval, in
176 // seconds. 60s matches Core's "idle" default; the allowed
177 // rates (15/30/45/60) all sit at or above Core's 15 s
178 // `minimalInterval` floor. See
179 // `openstation_apply_heartbeat_rate_setting` for the
180 // `heartbeat_settings` filter that applies this.
181 'heartbeatRate' => 60,
182 'nativePostsEnabled' => false,
183 // Per-user list of column keys hidden in the native Posts
184 // window (e.g. array( 'author', 'tags' )). Empty array means
185 // every column is visible. The sticky 'title' column is always
186 // shown — the UI prevents toggling it.
187 'nativePostsHiddenColumns' => array(),
188 // Per-user opt-IN for the native Pages window. Same posture as
189 // nativePostsEnabled — defaults OFF (Beta), users opt in to swap
190 // the classic `edit.php?post_type=page` iframe for the native UI.
191 'nativePagesEnabled' => false,
192 // Per-user opt-IN for the native Users window. Defaults OFF
193 // (Beta); the server-side cap gate (`list_users`) means the
194 // toggle only matters for users who could see the Users tile.
195 'nativeUsersEnabled' => false,
196 // Per-user opt-IN for the native Plugins window. Defaults OFF
197 // (Beta); the server-side cap gate (`activate_plugins`) means
198 // the toggle only matters for users who could see the Plugins
199 // tile anyway. When `false`, the dock click uses the classic
200 // `plugins.php` chromeless iframe path.
201 'nativePluginsEnabled' => false,
202 // Per-user opt-IN for the native Comments window. Defaults OFF
203 // (Beta); the server-side cap gate (`edit_posts`) means the
204 // toggle only matters for users who could see the Comments tile.
205 'nativeCommentsEnabled' => false,
206 // When true, left-clicking the empty wallpaper triggers the
207 // "Show desktop" toggle (macOS-style) and the matching entry is
208 // hidden from the wallpaper context menu. When false (default),
209 // the entry stays in the menu and left clicks on the wallpaper
210 // do nothing. Per-user.
211 'showDesktopOnWallpaperClick' => false,
212 // Mio — a soft-body companion that floats over
213 // the wallpaper, settles onto nearby windows, and watches the
214 // pointer. Off by default; toggled from the wallpaper context
215 // menu. Per-user. See `docs/mio.md`.
216 'mioEnabled' => false,
217 // The user's own Mio, as built in "Make it yours": partial
218 // appearance + silhouette overrides, both empty until they
219 // touch a control. Stored per user rather than per browser
220 // because it is a preference about the person — ten minutes
221 // spent building a companion should be waiting on their phone.
222 // Sanitized by `openstation_sanitize_mio_look()`; the ranges
223 // are enforced client-side in `sanitizeMioConfig()`.
224 'mioStyle' => array(
225 'appearance' => array(),
226 'physics' => array(),
227 ),
228 // Diagonal corner ribbon on My WordPress tiles whose post
229 // status isn't `publish` (draft / pending / private /
230 // scheduled). On by default — surfaces unpublished work at
231 // a glance. Per-user.
232 'showPostStatusRibbons' => true,
233 // Unlocks developer-facing surfaces meant for plugin
234 // authors: the Starter Widget appears in the add-widget
235 // picker, and the OS Settings → Components tab runs its
236 // intentional missing-import-warner demo. Off by default.
237 // Per-user.
238 'developerModeEnabled' => false,
239 // Per-user opt-OUT for the folder-sharing feature. Defaults
240 // ON. When false:
241 // - The Share button, share-settings modal, "Leave shared
242 // folder" entry, and pending-invite prompt are all
243 // suppressed in the user's shell.
244 // - The heartbeat skips the `shares.pending` payload for
245 // this user so they never see invites land.
246 // - REST share routes return 404 for this user — they
247 // can't list, invite, accept, deny, or leave.
248 // Sites that don't want the feature (solo admin, no
249 // collaborators) can flip the toggle and the surface
250 // disappears without any database changes. The site-wide
251 // "Delete folder sharing data" action in OS Settings →
252 // Features → Advanced is a separate destructive cleanup.
253 'foldersSharingEnabled' => true,
254 // Per-item placement preferences. Map of item id (dock-item
255 // slug or registered desktop-icon id) → one of:
256 // 'both' — show on both dock and desktop.
257 // 'dock' — show only on the dock; hide from desktop.
258 // 'desktop' — show only on the wallpaper; hide from dock.
259 // 'hidden' — hide from every shell surface.
260 // Missing keys mean "no override" — items use their native rail.
261 // Sanitized as map<sanitize_key, enum>. Capped at 256 entries.
262 'itemVisibility' => array(),
263 // Per-user dock ordering. Ordered list of item ids; ids not in
264 // the list keep their server-supplied position appended after
265 // the listed ones. Unknown ids are tolerated.
266 'dockOrder' => array(),
267 // Persisted desktop position for every dock item the user has
268 // promoted to the wallpaper via `itemVisibility[id]=desktop|both`.
269 // Keyed by item id, value is `{ x: int, y: int }`. The JS
270 // synthesizer reads this when building a synthetic placement so
271 // the icon lands where the user last dragged it instead of
272 // resetting to (0, 0) on every reload. Capped at 256 entries.
273 'dockPromotedPositions' => array(),
274 );
275 }
276
277 /**
278 * Retrieves the saved OS settings for a user.
279 *
280 * Always returns a fully-shaped array so the JS side doesn't need to
281 * defend against partial or missing keys.
282 *
283 * @param int $user_id The user ID.
284 * @return array
285 */
286 function openstation_get_os_settings( $user_id ) {
287 $user_id = (int) $user_id;
288 if ( $user_id <= 0 ) {
289 return openstation_default_os_settings();
290 }
291
292 $raw = get_user_meta( $user_id, OPENSTATION_OS_SETTINGS_META_KEY, true );
293 if ( ! is_array( $raw ) ) {
294 return openstation_default_os_settings();
295 }
296
297 return openstation_sanitize_os_settings( $raw );
298 }
299
300 /**
301 * Saves sanitized OS settings for a user.
302 *
303 * @param int $user_id The user ID.
304 * @param mixed $settings Raw settings payload from the client.
305 * @return bool True on success, false otherwise.
306 */
307 function openstation_save_os_settings( $user_id, $settings ) {
308 $user_id = (int) $user_id;
309 if ( $user_id <= 0 ) {
310 return false;
311 }
312
313 $clean = openstation_sanitize_os_settings( $settings );
314 return false !== update_user_meta( $user_id, OPENSTATION_OS_SETTINGS_META_KEY, $clean );
315 }
316
317 /**
318 * Sanitizes a raw OS settings payload.
319 *
320 * Unknown keys are ignored; known keys are coerced field-by-field so a
321 * partial save (e.g., only accent changed) merges cleanly with the
322 * defaults rather than wiping unset fields.
323 *
324 * @param mixed $raw Raw settings from the client or user meta.
325 * @return array Sanitized settings.
326 */
327 function openstation_sanitize_os_settings( $raw ) {
328 $defaults = openstation_default_os_settings();
329
330 if ( ! is_array( $raw ) ) {
331 return $defaults;
332 }
333
334 // Wallpaper — any non-empty string; registry membership is validated
335 // client-side at apply time.
336 $wallpaper = isset( $raw['wallpaper'] ) && is_string( $raw['wallpaper'] ) && '' !== $raw['wallpaper']
337 ? sanitize_key( $raw['wallpaper'] )
338 : $defaults['wallpaper'];
339
340 // Accent — non-empty string; swatch validity is enforced in the picker.
341 $accent = isset( $raw['accent'] ) && is_string( $raw['accent'] ) && '' !== $raw['accent']
342 ? sanitize_key( $raw['accent'] )
343 : $defaults['accent'];
344
345 // The colour behind the Custom swatch. A full `#rrggbb` triplet and
346 // nothing else: `sanitize_hex_color()` would also pass `#abc`, which
347 // the client-side parser rejects, and a value that survives the save
348 // only to be dropped on load is worse than one refused here.
349 $custom_accent = isset( $raw['customAccent'] )
350 && is_string( $raw['customAccent'] )
351 && preg_match( '/^#[0-9a-fA-F]{6}$/', $raw['customAccent'] )
352 ? strtolower( $raw['customAccent'] )
353 : $defaults['customAccent'];
354
355 // Dock size — must be one of the three known values.
356 $dock_size = isset( $raw['dockSize'] ) && in_array( $raw['dockSize'], OPENSTATION_OS_SETTINGS_DOCK_SIZES, true )
357 ? (string) $raw['dockSize']
358 : $defaults['dockSize'];
359
360 // Window radius — must be one of the three known values.
361 $window_radius = isset( $raw['windowRadius'] ) && in_array( $raw['windowRadius'], OPENSTATION_OS_SETTINGS_WINDOW_RADII, true )
362 ? (string) $raw['windowRadius']
363 : $defaults['windowRadius'];
364
365 // Admin-bar mode — must be one of the three known values.
366 $admin_bar_mode = isset( $raw['adminBarMode'] )
367 && in_array( $raw['adminBarMode'], OPENSTATION_OS_SETTINGS_ADMIN_BAR_MODES, true )
368 ? (string) $raw['adminBarMode']
369 : $defaults['adminBarMode'];
370
371 // Desktop layout — must be one of the known values (`classic`,
372 // `unified`). Default `unified`.
373 $desktop_layout = isset( $raw['desktopLayout'] )
374 && in_array( $raw['desktopLayout'], OPENSTATION_OS_SETTINGS_DESKTOP_LAYOUTS, true )
375 ? (string) $raw['desktopLayout']
376 : $defaults['desktopLayout'];
377
378 // Dock placement — which edge the single dock sits on. Must be one
379 // of the three known values (`bottom`, `left`, `right`).
380 $dock_placement = isset( $raw['dockPlacement'] )
381 && in_array( $raw['dockPlacement'], OPENSTATION_OS_SETTINGS_DOCK_PLACEMENTS, true )
382 ? (string) $raw['dockPlacement']
383 : $defaults['dockPlacement'];
384
385 // Dock rail renderer id — accept any sanitize_key()-clean
386 // string. JS-side registry resolves at use time and falls back
387 // to `'default'` when the picked renderer isn't registered.
388 $dock_rail_renderer = $defaults['dockRailRenderer'];
389 if ( isset( $raw['dockRailRenderer'] ) && is_string( $raw['dockRailRenderer'] ) ) {
390 $slug = sanitize_key( $raw['dockRailRenderer'] );
391 if ( '' !== $slug ) {
392 $dock_rail_renderer = $slug;
393 }
394 }
395
396 // Desktop theme slug — a pattern check, NOT an allow-list, the
397 // same idiom as `dockRailRenderer` above. Validating against the
398 // installed-theme option here would load (and unserialize) that
399 // option on every single settings write for a value the enqueue
400 // path re-checks anyway. `''` is the system default and is a
401 // legitimate value, so an empty/absent key keeps the default.
402 $desktop_theme = $defaults['desktopTheme'];
403 if ( isset( $raw['desktopTheme'] ) && is_string( $raw['desktopTheme'] ) ) {
404 $desktop_theme = sanitize_key( $raw['desktopTheme'] );
405 }
406
407 // appliedThemeRecommendations — list of desktop-theme slugs whose
408 // recommendations this user has already been seeded with. Unknown
409 // slugs are kept (a deleted-then-reinstalled theme must not
410 // re-seed and clobber the settings the user has since chosen).
411 $applied_theme_recommendations = $defaults['appliedThemeRecommendations'];
412 if ( isset( $raw['appliedThemeRecommendations'] ) && is_array( $raw['appliedThemeRecommendations'] ) ) {
413 $applied_theme_recommendations = array();
414 foreach ( $raw['appliedThemeRecommendations'] as $theme_slug ) {
415 if ( ! is_string( $theme_slug ) || '' === $theme_slug ) {
416 continue;
417 }
418 $theme_slug = sanitize_key( $theme_slug );
419 if ( '' === $theme_slug ) {
420 continue;
421 }
422 $applied_theme_recommendations[] = $theme_slug;
423 }
424 // Keep the MOST RECENT 64, not the first 64 — the client
425 // appends, so trimming from the front would silently discard
426 // the entry that was just written and let the theme re-seed on
427 // the next activation.
428 $applied_theme_recommendations = array_slice(
429 array_values( array_unique( $applied_theme_recommendations ) ),
430 -64
431 );
432 }
433
434 // Unfocus effect id — accept the `none` sentinel or any registry id.
435 // Effect ids mirror the JS registry pattern `^[a-z0-9_/-]+$` (slashes
436 // allowed for `vendor/sub-id` namespacing), so we lower-case and strip
437 // to that charset rather than using sanitize_key() (which would drop
438 // the slash and break a namespaced id on round-trip). No allow-list:
439 // the JS engine resolves at use time and treats an unknown id as "no
440 // effect".
441 $unfocus_effect = $defaults['unfocusEffect'];
442 if ( isset( $raw['unfocusEffect'] ) && is_string( $raw['unfocusEffect'] ) ) {
443 $slug = preg_replace( '/[^a-z0-9_\/-]/', '', strtolower( $raw['unfocusEffect'] ) );
444 if ( '' !== $slug ) {
445 $unfocus_effect = $slug;
446 }
447 }
448
449 // Window-reveal id — same id charset and same no-allow-list
450 // reasoning as the unfocus effect above. The JS surface resolves at
451 // play time and treats an unknown id as "no reveal", so a reveal
452 // belonging to a temporarily-deactivated plugin survives the
453 // round-trip and starts working again the moment it re-registers.
454 $window_reveal = $defaults['windowReveal'];
455 if ( isset( $raw['windowReveal'] ) && is_string( $raw['windowReveal'] ) ) {
456 $slug = preg_replace( '/[^a-z0-9_\/-]/', '', strtolower( $raw['windowReveal'] ) );
457 if ( '' !== $slug ) {
458 $window_reveal = $slug;
459 }
460 }
461
462 // Window-reveal duration override — 0 (the default) means "leave
463 // each reveal's own timing alone". Anything else is clamped into
464 // the playable range rather than rejected: a value past the end of
465 // the range still expresses a direction, and the nearest playable
466 // duration is the honest reading of it.
467 $window_reveal_duration = $defaults['windowRevealDuration'];
468 if ( isset( $raw['windowRevealDuration'] ) && is_numeric( $raw['windowRevealDuration'] ) ) {
469 $requested = (int) round( (float) $raw['windowRevealDuration'] );
470 if ( $requested > 0 ) {
471 $window_reveal_duration = max(
472 OPENSTATION_OS_SETTINGS_REVEAL_DURATION_MIN,
473 min( OPENSTATION_OS_SETTINGS_REVEAL_DURATION_MAX, $requested )
474 );
475 } else {
476 $window_reveal_duration = 0;
477 }
478 }
479
480 // Window-link renderer id — same id charset as unfocus effects
481 // (slashes allowed for `vendor/sub-id`). No allow-list: the JS
482 // render host resolves at use time and falls back to the built-in
483 // `svg-splines` when the picked renderer isn't registered.
484 $window_link_renderer = $defaults['windowLinkRenderer'];
485 if ( isset( $raw['windowLinkRenderer'] ) && is_string( $raw['windowLinkRenderer'] ) ) {
486 $slug = preg_replace( '/[^a-z0-9_\/-]/', '', strtolower( $raw['windowLinkRenderer'] ) );
487 if ( '' !== $slug ) {
488 $window_link_renderer = $slug;
489 }
490 }
491
492 // Window-link visibility — small closed set.
493 $window_link_visibility = $defaults['windowLinkVisibility'];
494 if (
495 isset( $raw['windowLinkVisibility'] )
496 && in_array( $raw['windowLinkVisibility'], array( 'focus', 'always', 'off' ), true )
497 ) {
498 $window_link_visibility = $raw['windowLinkVisibility'];
499 }
500
501 // Window-links feature switches — plain booleans.
502 $window_links_enabled = isset( $raw['windowLinksEnabled'] )
503 ? (bool) $raw['windowLinksEnabled']
504 : $defaults['windowLinksEnabled'];
505
506 $window_link_raise_on_focus = isset( $raw['windowLinkRaiseOnFocus'] )
507 ? (bool) $raw['windowLinkRaiseOnFocus']
508 : $defaults['windowLinkRaiseOnFocus'];
509
510 $window_link_highlight = isset( $raw['windowLinkHighlight'] )
511 ? (bool) $raw['windowLinkHighlight']
512 : $defaults['windowLinkHighlight'];
513
514 // Custom gradient — { from, to: valid hex; angle: int 0–360 }.
515 $custom_gradient = $defaults['customGradient'];
516 if ( isset( $raw['customGradient'] ) && is_array( $raw['customGradient'] ) ) {
517 $cg = $raw['customGradient'];
518 if ( isset( $cg['from'] ) && is_string( $cg['from'] ) && preg_match( '/^#[0-9a-f]{3,8}$/i', $cg['from'] ) ) {
519 $custom_gradient['from'] = strtolower( $cg['from'] );
520 }
521 if ( isset( $cg['to'] ) && is_string( $cg['to'] ) && preg_match( '/^#[0-9a-f]{3,8}$/i', $cg['to'] ) ) {
522 $custom_gradient['to'] = strtolower( $cg['to'] );
523 }
524 if ( isset( $cg['angle'] ) && is_numeric( $cg['angle'] ) ) {
525 $angle = (int) $cg['angle'];
526 if ( $angle >= 0 && $angle <= 360 ) {
527 $custom_gradient['angle'] = $angle;
528 }
529 }
530 }
531
532 // Custom image — { id: positive int, url: valid https? URL } or null.
533 $custom_image = null;
534 if ( isset( $raw['customImage'] ) && is_array( $raw['customImage'] ) ) {
535 $ci = $raw['customImage'];
536 $ci_id = isset( $ci['id'] ) && is_numeric( $ci['id'] ) ? (int) $ci['id'] : 0;
537 $ci_url = isset( $ci['url'] ) ? esc_url_raw( (string) $ci['url'] ) : '';
538 if ( $ci_id > 0 && '' !== $ci_url && preg_match( '/^https?:\/\//i', $ci_url ) ) {
539 $custom_image = array(
540 'id' => $ci_id,
541 'url' => $ci_url,
542 );
543 }
544 }
545
546 // wallpaperSettings — map<wallpaper id, map<key, scalar>>. Wallpaper
547 // ids follow the same charset as unfocus-effect ids (slashes allowed
548 // for `vendor/sub-id` namespacing); setting keys follow the JS
549 // identifier-ish charset wallpaper authors use (camelCase, hyphens,
550 // underscores). Values must be scalar — booleans and numbers pass
551 // through typed, strings are sanitized and length-capped. Unknown
552 // wallpaper ids are kept (a deactivated wallpaper plugin's settings
553 // should survive reactivation). Capped at 64 ids × 32 keys.
554 $wallpaper_settings = array();
555 if ( isset( $raw['wallpaperSettings'] ) && is_array( $raw['wallpaperSettings'] ) ) {
556 $id_count = 0;
557 foreach ( $raw['wallpaperSettings'] as $wp_id => $bag ) {
558 if ( $id_count >= 64 ) {
559 break;
560 }
561 if ( ! is_string( $wp_id ) || '' === $wp_id || ! is_array( $bag ) ) {
562 continue;
563 }
564 $wp_slug = preg_replace( '/[^a-z0-9_\/-]/', '', strtolower( $wp_id ) );
565 if ( '' === $wp_slug ) {
566 continue;
567 }
568 $clean_bag = array();
569 $key_count = 0;
570 foreach ( $bag as $key => $value ) {
571 if ( $key_count >= 32 ) {
572 break;
573 }
574 if ( ! is_string( $key ) || '' === $key || ! preg_match( '/^[a-zA-Z0-9_-]+$/', $key ) ) {
575 continue;
576 }
577 if ( is_bool( $value ) ) {
578 $clean_bag[ $key ] = $value;
579 } elseif ( is_int( $value ) || is_float( $value ) ) {
580 if ( ! is_finite( (float) $value ) ) {
581 continue;
582 }
583 $clean_bag[ $key ] = $value;
584 } elseif ( is_string( $value ) ) {
585 $clean_bag[ $key ] = mb_substr( sanitize_text_field( $value ), 0, 256 );
586 } else {
587 continue;
588 }
589 ++$key_count;
590 }
591 if ( empty( $clean_bag ) ) {
592 continue;
593 }
594 $wallpaper_settings[ $wp_slug ] = $clean_bag;
595 ++$id_count;
596 }
597 }
598
599 // Library HD only — boolean.
600 $library_hd_only = isset( $raw['libraryHdOnly'] ) ? (bool) $raw['libraryHdOnly'] : $defaults['libraryHdOnly'];
601
602 // AI settings — just the per-user on/off toggle. Provider + model selection
603 // is delegated to the Core AI Client, so there is no preference to persist.
604 $ai = $defaults['ai'];
605 if ( isset( $raw['ai'] ) && is_array( $raw['ai'] ) ) {
606 $raw_ai = $raw['ai'];
607
608 if ( isset( $raw_ai['enabled'] ) ) {
609 $ai['enabled'] = (bool) $raw_ai['enabled'];
610 }
611 }
612
613 // Heartbeat rate — one of the four allowed values. The PHP
614 // filter `openstation_apply_heartbeat_rate_setting` reads
615 // this and passes it through to `heartbeat_settings` so
616 // WordPress Core itself reduces the interval on the next page
617 // load. 5 s is intentionally excluded: Core's
618 // `minimalInterval` floor clamps anything below 15 back up to
619 // 15 unless every upstream filter cooperates, and the gain
620 // over 15 s is marginal.
621 $allowed_heartbeat_rates = array( 15, 30, 45, 60 );
622 $heartbeat_rate = $defaults['heartbeatRate'];
623 if ( isset( $raw['heartbeatRate'] ) && is_numeric( $raw['heartbeatRate'] ) ) {
624 $candidate = (int) $raw['heartbeatRate'];
625 if ( in_array( $candidate, $allowed_heartbeat_rates, true ) ) {
626 $heartbeat_rate = $candidate;
627 }
628 }
629
630 $native_posts_enabled = isset( $raw['nativePostsEnabled'] )
631 ? (bool) $raw['nativePostsEnabled']
632 : $defaults['nativePostsEnabled'];
633
634 $native_posts_hidden_columns = $defaults['nativePostsHiddenColumns'];
635 if ( isset( $raw['nativePostsHiddenColumns'] ) && is_array( $raw['nativePostsHiddenColumns'] ) ) {
636 $native_posts_hidden_columns = array();
637 foreach ( $raw['nativePostsHiddenColumns'] as $col ) {
638 if ( ! is_string( $col ) || '' === $col ) {
639 continue;
640 }
641 $slug = sanitize_key( $col );
642 if ( '' === $slug ) {
643 continue;
644 }
645 $native_posts_hidden_columns[] = $slug;
646 }
647 // Cap to a sane upper bound — far more than any plausible
648 // column count, but blocks a malicious payload from bloating
649 // user meta indefinitely.
650 $native_posts_hidden_columns = array_slice( array_values( array_unique( $native_posts_hidden_columns ) ), 0, 32 );
651 }
652
653 $native_pages_enabled = isset( $raw['nativePagesEnabled'] )
654 ? (bool) $raw['nativePagesEnabled']
655 : $defaults['nativePagesEnabled'];
656
657 $native_users_enabled = isset( $raw['nativeUsersEnabled'] )
658 ? (bool) $raw['nativeUsersEnabled']
659 : $defaults['nativeUsersEnabled'];
660
661 $native_plugins_enabled = isset( $raw['nativePluginsEnabled'] )
662 ? (bool) $raw['nativePluginsEnabled']
663 : $defaults['nativePluginsEnabled'];
664
665 $native_comments_enabled = isset( $raw['nativeCommentsEnabled'] )
666 ? (bool) $raw['nativeCommentsEnabled']
667 : $defaults['nativeCommentsEnabled'];
668
669 $show_desktop_on_wallpaper_click = isset( $raw['showDesktopOnWallpaperClick'] )
670 ? (bool) $raw['showDesktopOnWallpaperClick']
671 : $defaults['showDesktopOnWallpaperClick'];
672
673 $mio_enabled = isset( $raw['mioEnabled'] )
674 ? (bool) $raw['mioEnabled']
675 : $defaults['mioEnabled'];
676
677 // A missing key means "no look saved yet", which sanitizes to the
678 // same pair of empty arrays the defaults carry — so this needs no
679 // isset() branch of its own.
680 $mio_style = openstation_sanitize_mio_look(
681 isset( $raw['mioStyle'] ) ? $raw['mioStyle'] : null
682 );
683
684 $show_post_status_ribbons = isset( $raw['showPostStatusRibbons'] )
685 ? (bool) $raw['showPostStatusRibbons']
686 : $defaults['showPostStatusRibbons'];
687
688 $developer_mode_enabled = isset( $raw['developerModeEnabled'] )
689 ? (bool) $raw['developerModeEnabled']
690 : $defaults['developerModeEnabled'];
691
692 $folders_sharing_enabled = isset( $raw['foldersSharingEnabled'] )
693 ? (bool) $raw['foldersSharingEnabled']
694 : $defaults['foldersSharingEnabled'];
695
696 // itemVisibility — map<sanitize_key, enum>. Unknown ids are kept
697 // (a deactivated plugin's setting should survive reactivation);
698 // invalid placement values are dropped.
699 $item_visibility = array();
700 if ( isset( $raw['itemVisibility'] ) && is_array( $raw['itemVisibility'] ) ) {
701 $allowed_placements = array( 'both', 'dock', 'desktop', 'hidden' );
702 $count = 0;
703 foreach ( $raw['itemVisibility'] as $key => $val ) {
704 if ( $count >= 256 ) {
705 break;
706 }
707 if ( ! is_string( $key ) || '' === $key || ! is_string( $val ) ) {
708 continue;
709 }
710 $slug = sanitize_key( $key );
711 if ( '' === $slug ) {
712 continue;
713 }
714 if ( ! in_array( $val, $allowed_placements, true ) ) {
715 continue;
716 }
717 $item_visibility[ $slug ] = $val;
718 ++$count;
719 }
720 }
721
722 // dockOrder — ordered list of item ids. Most are sanitize_key()-
723 // clean dock slugs, but cross-rail tiles the user promoted carry a
724 // rail-synthesis prefix (`desktop:<id>` / `dock:<id>`, built by
725 // src/settings/item-placement.ts). sanitize_key() strips the colon,
726 // which silently breaks the JS order match on reload and can collide
727 // with an unrelated id — so allow the colon (and hyphen/underscore)
728 // while still rejecting anything outside the JS id charset.
729 $dock_order = array();
730 if ( isset( $raw['dockOrder'] ) && is_array( $raw['dockOrder'] ) ) {
731 $seen = array();
732 foreach ( $raw['dockOrder'] as $id ) {
733 if ( ! is_string( $id ) || '' === $id ) {
734 continue;
735 }
736 $slug = (string) preg_replace( '/[^a-z0-9_:-]+/', '', strtolower( $id ) );
737 if ( '' === $slug || isset( $seen[ $slug ] ) ) {
738 continue;
739 }
740 $seen[ $slug ] = true;
741 $dock_order[] = $slug;
742 if ( count( $dock_order ) >= 256 ) {
743 break;
744 }
745 }
746 }
747
748 // dockPromotedPositions — map<sanitize_key, {x: int, y: int}>.
749 // Persisted positions for synthetic dock-promoted placements, so
750 // the JS synthesizer can restore the user's manual placement on
751 // next reload. Capped at 256; absurd coordinates are dropped.
752 $dock_promoted_positions = array();
753 if ( isset( $raw['dockPromotedPositions'] ) && is_array( $raw['dockPromotedPositions'] ) ) {
754 $count = 0;
755 $max_coord = 100000; // generous; real screens stop in the thousands.
756 foreach ( $raw['dockPromotedPositions'] as $key => $val ) {
757 if ( $count >= 256 ) {
758 break;
759 }
760 if ( ! is_string( $key ) || '' === $key ) {
761 continue;
762 }
763 $slug = sanitize_key( $key );
764 if ( '' === $slug ) {
765 continue;
766 }
767 if ( ! is_array( $val ) ) {
768 continue;
769 }
770 if ( ! isset( $val['x'] ) || ! isset( $val['y'] ) ) {
771 continue;
772 }
773 $x = is_numeric( $val['x'] ) ? (int) $val['x'] : null;
774 $y = is_numeric( $val['y'] ) ? (int) $val['y'] : null;
775 if ( null === $x || null === $y ) {
776 continue;
777 }
778 if ( abs( $x ) > $max_coord || abs( $y ) > $max_coord ) {
779 continue;
780 }
781 $dock_promoted_positions[ $slug ] = array(
782 'x' => $x,
783 'y' => $y,
784 );
785 ++$count;
786 }
787 }
788
789 return array(
790 'wallpaper' => $wallpaper,
791 'accent' => $accent,
792 'customAccent' => $custom_accent,
793 'dockSize' => $dock_size,
794 'windowRadius' => $window_radius,
795 'adminBarMode' => $admin_bar_mode,
796 'desktopLayout' => $desktop_layout,
797 'dockPlacement' => $dock_placement,
798 'dockRailRenderer' => $dock_rail_renderer,
799 'desktopTheme' => $desktop_theme,
800 'appliedThemeRecommendations' => $applied_theme_recommendations,
801 'unfocusEffect' => $unfocus_effect,
802 'windowReveal' => $window_reveal,
803 'windowRevealDuration' => $window_reveal_duration,
804 'windowLinkRenderer' => $window_link_renderer,
805 'windowLinkVisibility' => $window_link_visibility,
806 'windowLinksEnabled' => $window_links_enabled,
807 'windowLinkRaiseOnFocus' => $window_link_raise_on_focus,
808 'windowLinkHighlight' => $window_link_highlight,
809 'customGradient' => $custom_gradient,
810 'customImage' => $custom_image,
811 'wallpaperSettings' => $wallpaper_settings,
812 'libraryHdOnly' => $library_hd_only,
813 'ai' => $ai,
814 'heartbeatRate' => $heartbeat_rate,
815 'nativePostsEnabled' => $native_posts_enabled,
816 'nativePostsHiddenColumns' => $native_posts_hidden_columns,
817 'nativePagesEnabled' => $native_pages_enabled,
818 'nativeUsersEnabled' => $native_users_enabled,
819 'nativePluginsEnabled' => $native_plugins_enabled,
820 'nativeCommentsEnabled' => $native_comments_enabled,
821 'showDesktopOnWallpaperClick' => $show_desktop_on_wallpaper_click,
822 'mioEnabled' => $mio_enabled,
823 'mioStyle' => $mio_style,
824 'showPostStatusRibbons' => $show_post_status_ribbons,
825 'developerModeEnabled' => $developer_mode_enabled,
826 'foldersSharingEnabled' => $folders_sharing_enabled,
827 'itemVisibility' => $item_visibility,
828 'dockOrder' => $dock_order,
829 'dockPromotedPositions' => $dock_promoted_positions,
830 );
831 }
832
833 /**
834 * Registers the REST routes for OS settings.
835 */
836 function openstation_register_os_settings_rest_routes() {
837 register_rest_route(
838 'desktop-mode/v1',
839 '/os-settings',
840 array(
841 array(
842 'methods' => WP_REST_Server::READABLE,
843 'callback' => 'openstation_rest_get_os_settings',
844 'permission_callback' => 'openstation_rest_os_settings_permission',
845 ),
846 array(
847 'methods' => WP_REST_Server::CREATABLE,
848 'callback' => 'openstation_rest_save_os_settings',
849 'permission_callback' => 'openstation_rest_os_settings_permission',
850 'args' => array(
851 'settings' => array(
852 'required' => true,
853 'type' => 'object',
854 ),
855 ),
856 ),
857 )
858 );
859 }
860 add_action( 'rest_api_init', 'openstation_register_os_settings_rest_routes' );
861
862 /**
863 * Permission gate for OS settings REST routes.
864 *
865 * Requires the caller to be logged in *and* have OpenStation enabled —
866 * see {@see openstation_rest_require_enabled()} for why `read` alone is
867 * insufficient.
868 *
869 * @return true|WP_Error
870 */
871 function openstation_rest_os_settings_permission() {
872 return openstation_rest_require_enabled();
873 }
874
875 /**
876 * GET /desktop-mode/v1/os-settings
877 *
878 * @return WP_REST_Response
879 */
880 function openstation_rest_get_os_settings() {
881 return rest_ensure_response( openstation_get_os_settings( get_current_user_id() ) );
882 }
883
884 /**
885 * POST /desktop-mode/v1/os-settings
886 *
887 * Accepts a PARTIAL payload: keys the request omits keep the value
888 * already stored for the user, rather than resetting to the shipped
889 * default. The client sends only the fields that changed since its
890 * last confirmed save, which is what stops two open sessions from
891 * overwriting each other — a session that never touched the
892 * wallpaper cannot express an opinion about it, so a stale snapshot
893 * can no longer undo another session's unrelated change.
894 *
895 * A full payload still behaves exactly as before: every key is
896 * present, so every key wins.
897 *
898 * The merge lives here rather than in {@see openstation_save_os_settings()}
899 * on purpose. That function's contract is REPLACE, and migrations
900 * depend on it: migration 1 in `includes/migrations.php` `unset()`s
901 * keys and re-saves precisely so the sanitizer backfills the new
902 * defaults. Give the saver merge semantics and that migration
903 * silently becomes a no-op.
904 *
905 * Merging is shallow, one level deep. For the map-shaped fields
906 * (`wallpaperSettings`, `itemVisibility`, `dockOrder`,
907 * `dockPromotedPositions`) a request that sends the key replaces the
908 * whole map — deep-merging them would leave no way to delete an
909 * entry.
910 *
911 * @param WP_REST_Request $request The REST request.
912 * @return WP_REST_Response The saved settings (after sanitization).
913 */
914 function openstation_rest_save_os_settings( WP_REST_Request $request ) {
915 $user_id = get_current_user_id();
916 $payload = $request->get_param( 'settings' );
917
918 // A payload that isn't an object says nothing about any field, so
919 // it changes nothing. The route declares `'settings' => object`
920 // and WP's schema validation rejects a scalar before the callback
921 // runs, so this is unreachable over real REST traffic — but the
922 // sanitizer resolves a non-array to the full defaults, which
923 // means the one way to reach this function with a bad payload
924 // used to be the one way to wipe a user's settings. Returning
925 // early costs nothing and keeps "don't destroy what wasn't sent"
926 // true of every path into this handler, not just the ones the
927 // schema happens to guard.
928 if ( ! is_array( $payload ) ) {
929 return rest_ensure_response( openstation_get_os_settings( $user_id ) );
930 }
931
932 openstation_save_os_settings(
933 $user_id,
934 array_merge( openstation_get_os_settings( $user_id ), $payload )
935 );
936 return rest_ensure_response( openstation_get_os_settings( $user_id ) );
937 }
938
939 /**
940 * Apply the per-user Heartbeat-rate preference to the
941 * `heartbeat_settings` Core filter. WordPress reads these settings
942 * once at page load. We set `interval` only; the allowed rates
943 * (15/30/45/60 s) all sit at or above Core's 15 s
944 * `minimalInterval` floor, so the floor never needs overriding.
945 *
946 * Only applies to users with OpenStation enabled — non-desktop
947 * sessions keep Core's defaults. Anonymous requests skip too.
948 *
949 * @param array $settings Filtered Heartbeat settings.
950 * @return array
951 */
952 function openstation_apply_heartbeat_rate_setting( $settings ) {
953 if ( ! is_array( $settings ) ) {
954 $settings = array();
955 }
956 $user_id = get_current_user_id();
957 if ( $user_id <= 0 ) {
958 return $settings;
959 }
960 if ( function_exists( 'openstation_is_enabled' ) && ! openstation_is_enabled( $user_id ) ) {
961 return $settings;
962 }
963 $os = openstation_get_os_settings( $user_id );
964 $rate = isset( $os['heartbeatRate'] ) ? (int) $os['heartbeatRate'] : 0;
965 if ( ! in_array( $rate, array( 15, 30, 45, 60 ), true ) ) {
966 return $settings;
967 }
968 $settings['interval'] = $rate;
969 return $settings;
970 }
971 add_filter( 'heartbeat_settings', 'openstation_apply_heartbeat_rate_setting' );
972