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 / migrations.php

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

603 lines 21.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * OpenStation — one-time data migrations.
4 *
5 * A tiny, option-versioned migration runner modeled on the lazy schema
6 * installer in `includes/desktop-files/schema.php`: a stored option holds
7 * the highest migration version that has run; on every admin load we
8 * compare it against {@see OPENSTATION_MIGRATION_VERSION} and run any
9 * pending migrations exactly once. Guarded so it is a cheap no-op after
10 * the first successful pass.
11 *
12 * On a site with no history the runner fires at activation instead, so
13 * nothing here ever has to infer the past of a site from evidence that
14 * site wrote after it was installed. See
15 * {@see openstation_run_migrations_on_activation}.
16 *
17 * @package OpenStation
18 */
19
20 defined( 'ABSPATH' ) || exit;
21
22 /**
23 * Highest migration version shipped by the plugin.
24 *
25 * Bump this (and add a matching branch in
26 * {@see openstation_run_pending_migrations}) whenever a new one-time
27 * migration is needed.
28 *
29 * A new migration runs on every install, including brand-new ones: on a
30 * site with no history the runner fires at activation
31 * ({@see openstation_run_migrations_on_activation}) rather than on the
32 * first `admin_init`.
33 *
34 * - 1: native list windows flipped from opt-out (default ON) to opt-in
35 * Beta (default OFF). Clears the five `native*Enabled` flags from every
36 * user who had them persisted so the whole install reverts to opt-in.
37 * - 2: post & taxonomy-term AI analysis was removed (the copilot now only
38 * analyzes comments for spam, and the assistant finds content via native
39 * WordPress search). Unschedules any queued `desktop_mode_ai_analyze_post`
40 * / `desktop_mode_ai_analyze_term` cron events left over from prior versions.
41 * - 3: the copilot dropped its self-managed AI credentials in favour of
42 * WordPress 7.0 Connectors. Deletes the platform key option and strips the
43 * per-user `apiKey` / `apiKeys` / `provider` / `transport` fields from the
44 * stored OS settings so no provider secret lingers in the database.
45 * - 4: the OpenStation brand. Moves anyone still sitting on the PRE-brand
46 * defaults — accent `wp-blue`, wallpaper `dark` — onto the new ones,
47 * Pulse and Galaxy. Without it the rebrand only reaches fresh accounts:
48 * the stored snapshot is authoritative over the shipped default, so an
49 * existing desk keeps a blue accent on every focus ring, tab underline
50 * and sort arrow.
51 * - 5: flags the users who were using Desktop Mode before the rename, so
52 * the shell can explain the new name once to the people it happened
53 * to and to nobody else. Sets user meta and nothing else — see
54 * {@see openstation_migrate_flag_rebrand_notice} for why that is a
55 * separate migration from 4.
56 * - 6: the Trash stopped registering a desktop icon. Removes the
57 * placement the shell had auto-placed for it and closes the hole that
58 * leaves in the icon column.
59 */
60 const OPENSTATION_MIGRATION_VERSION = 6;
61
62 /**
63 * Option storing the highest migration version that has run. autoload=no.
64 *
65 * The VALUE keeps its pre-rebrand spelling on purpose: it is a
66 * persisted or externally-visible identifier, so renaming it would
67 * orphan data already written by live installs (or break a live
68 * URL). The mismatch between this constant's name and its value is
69 * deliberate — it is NOT a half-finished rename.
70 */
71 const OPENSTATION_MIGRATION_OPTION = 'desktop_mode_migration_version';
72
73 /**
74 * Runs any pending migrations, then records the new high-water mark.
75 *
76 * Idempotent: bails immediately when the stored version is already at
77 * or above the shipped version, so it is safe to fire on every request.
78 *
79 * @return void
80 */
81 function openstation_maybe_run_migrations() {
82 $installed = (int) get_option( OPENSTATION_MIGRATION_OPTION, 0 );
83 if ( $installed >= OPENSTATION_MIGRATION_VERSION ) {
84 return;
85 }
86
87 openstation_run_pending_migrations( $installed );
88
89 update_option( OPENSTATION_MIGRATION_OPTION, OPENSTATION_MIGRATION_VERSION, false );
90 }
91 add_action( 'admin_init', 'openstation_maybe_run_migrations' );
92
93 /**
94 * Runs the pending migrations at activation, on a site with no history.
95 *
96 * Migration 5 infers who used the shell before the rename from user meta
97 * that a site can write to itself between activation and the first
98 * `admin_init` (the portal auto-enable). Running at activation is the
99 * one moment that window is still shut, so the same runner reaches the
100 * same conclusion about the same site and cannot be fooled by evidence
101 * that arrives later.
102 *
103 * The whole runner, not a subset: migrations 2 and 3 clear leftover AI
104 * cron events and a stored provider credential, neither of which any
105 * user meta predicts.
106 *
107 * @return void
108 */
109 function openstation_run_migrations_on_activation() {
110 // Migrations have already run here; their high-water mark is the
111 // truth and the runner would be a no-op anyway.
112 if ( false !== get_option( OPENSTATION_MIGRATION_OPTION, false ) ) {
113 return;
114 }
115
116 // The site has history, so this is a reactivation and not a new
117 // install. Leave it to `admin_init`, where migration 5 reads meta
118 // that is genuinely older than this request.
119 $prior_users = openstation_users_with_prior_desktop_use();
120 if ( ! empty( $prior_users ) ) {
121 return;
122 }
123
124 openstation_maybe_run_migrations();
125 }
126 register_activation_hook( OPENSTATION_FILE, 'openstation_run_migrations_on_activation' );
127
128 /**
129 * Dispatches each migration whose version is newer than what has run.
130 *
131 * @param int $from The highest migration version already applied.
132 * @return void
133 */
134 function openstation_run_pending_migrations( $from ) {
135 $from = (int) $from;
136
137 if ( $from < 1 ) {
138 openstation_migrate_os_settings_optin();
139 }
140
141 if ( $from < 2 ) {
142 openstation_migrate_unschedule_post_term_ai();
143 }
144
145 if ( $from < 3 ) {
146 openstation_migrate_delete_ai_keys();
147 }
148
149 if ( $from < 4 ) {
150 openstation_migrate_brand_defaults();
151 }
152
153 if ( $from < 5 ) {
154 openstation_migrate_flag_rebrand_notice( $from );
155 }
156
157 if ( $from < 6 ) {
158 openstation_migrate_close_recycle_bin_icon_gap();
159 }
160 }
161
162 /**
163 * Grid the desktop auto-placer lays icons out on: 16px of padding, a
164 * 96px column, a 110px row. Mirrored from `src/desktop-files/grid.ts`
165 * via {@see openstation_files_auto_place_orphans}, which is what wrote
166 * the coordinates this migration edits.
167 */
168 const OPENSTATION_DESKTOP_GRID_ROW_H = 110;
169
170 /**
171 * Migration 6 — take back the Trash's desktop icon, and close the hole.
172 *
173 * The bin used to register a desktop icon, and every viewer's first
174 * hydrate auto-placed it into the icon column. Now that the
175 * registration is gone the placement is dead weight: it is no longer
176 * served (`OpenStation_Shortcut_File::can_read()` is false without a
177 * registry entry), so the tile has already vanished on its own. What it
178 * leaves behind is an empty cell with the icons that were under it
179 * still sitting where they were.
180 *
181 * So: delete the row, and pull everything below it in the same column
182 * up by one. Same column only, because the auto-placer fills
183 * column-major, so a column is the run the bin was part of. This does
184 * move tiles a user may have arranged, which is the point — the shell
185 * put that icon there and the shell is taking it away, so the shell
186 * tidies up after itself rather than leaving a gap nobody chose.
187 *
188 * A user who wants the bin back on the wallpaper picks "On the desktop"
189 * in Apps & Plugins, which promotes the dock tile and never touches
190 * these rows.
191 *
192 * @return void
193 */
194 function openstation_migrate_close_recycle_bin_icon_gap() {
195 global $wpdb;
196
197 if ( ! function_exists( 'openstation_files_table_names' ) ) {
198 return;
199 }
200 $tables = openstation_files_table_names();
201 $tbl = $tables['placements'];
202
203 // The files schema installs lazily, so a site that never opened
204 // the desktop has no table to migrate.
205 $table_exists = (int) $wpdb->get_var(
206 $wpdb->prepare(
207 'SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
208 WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s',
209 $tbl
210 )
211 );
212 if ( 0 === $table_exists ) {
213 return;
214 }
215
216 // Shift first, delete second: the derived table has to still find
217 // the bin's own row to know which cell is being vacated. It is
218 // materialized before the update runs, so reading and writing the
219 // same table in one statement is fine here.
220 //
221 // The UNIQUE index on (owner_id, parent_id, file_type, file_ref)
222 // guarantees at most one bin row per owner, so no row can be
223 // shifted twice.
224 $wpdb->query(
225 $wpdb->prepare(
226 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name, not user input.
227 "UPDATE `{$tbl}` AS p
228 INNER JOIN (
229 SELECT owner_id, x, y FROM `{$tbl}`
230 WHERE parent_id = 0
231 AND file_type = 'shortcut'
232 AND file_ref = %s
233 ) AS bin
234 ON p.owner_id = bin.owner_id
235 AND p.x = bin.x
236 AND p.y > bin.y
237 SET p.y = p.y - %d
238 WHERE p.parent_id = 0
239 AND p.trashed_at_ms IS NULL",
240 'desktop-mode-recycle-bin',
241 OPENSTATION_DESKTOP_GRID_ROW_H
242 )
243 );
244
245 $wpdb->delete(
246 $tbl,
247 array(
248 'parent_id' => 0,
249 'file_type' => 'shortcut',
250 'file_ref' => 'desktop-mode-recycle-bin',
251 ),
252 array( '%d', '%s', '%s' )
253 );
254 }
255
256 /**
257 * User meta marking someone as a Desktop Mode user from before the rebrand.
258 *
259 * Present and truthy => the shell offers this user the one-off rebrand
260 * announcement, once. Absent => they never used the plugin under its old
261 * name, so there is no rename to explain to them. Written only by
262 * migration 5, and only for users who were actually using Desktop Mode
263 * at the moment it ran.
264 *
265 * The VALUE keeps the pre-rebrand spelling for the reason every other
266 * stored key does — see {@see OPENSTATION_MIGRATION_OPTION}.
267 */
268 const OPENSTATION_REBRAND_NOTICE_META_KEY = 'desktop_mode_rebrand_notice';
269
270 /**
271 * Slug the rebrand announcement records in `desktop_mode_seen_intros`.
272 *
273 * A slug in the shared registry rather than a bespoke meta key, so the
274 * announcement is dismissed, reset and reasoned about exactly like the
275 * native-window intros beside it.
276 */
277 const OPENSTATION_REBRAND_INTRO_SLUG = 'openstation-rebrand';
278
279 /**
280 * Every user who carries proof of having used the shell on this site:
281 * `desktop_mode_mode` (the per-user opt-in, tested for EXISTENCE rather
282 * than for being `'1'`, since switching back to classic empties the
283 * value but leaves the row) or a saved `desktop_mode_os_settings`.
284 *
285 * @return int[] User IDs, unsorted and deduplicated.
286 */
287 function openstation_users_with_prior_desktop_use() {
288 return array_map(
289 'intval',
290 array_unique(
291 array_merge(
292 get_users(
293 array(
294 'fields' => 'ID',
295 'meta_key' => 'desktop_mode_mode', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- runs once per install; the key is indexed in usermeta and both callers are guarded to a single pass.
296 'meta_compare' => 'EXISTS',
297 )
298 ),
299 get_users(
300 array(
301 'fields' => 'ID',
302 'meta_key' => OPENSTATION_OS_SETTINGS_META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- see above.
303 'meta_compare' => 'EXISTS',
304 )
305 )
306 )
307 )
308 );
309 }
310
311 /**
312 * Migration 5 — remember who was using Desktop Mode before the rebrand.
313 *
314 * Migration 4 moved the pre-brand *defaults* onto the brand ones. This
315 * one answers a different question: not "what should this desk look
316 * like" but "does this person need to be told why it changed". Someone
317 * who has been running Desktop Mode for months opens wp-admin one
318 * morning to a differently-named, differently-coloured shell; without a
319 * word of explanation that reads as a compromised site, not a release.
320 *
321 * Two gates. The install gate is a bare "has the rebrand already
322 * happened here", and the user gate does the actual work.
323 *
324 * **The install** must not already be past the rebrand: `$from < 4`. A
325 * `4` means migration 4 has run, which today means a checkout tracking
326 * trunk between the two release tags. Not a surprised user.
327 *
328 * Note what is deliberately NOT tested: whether `$from` is zero. It is
329 * tempting to read `0` as "fresh install, nothing to explain", and that
330 * reading is wrong in the one direction that matters. The migration
331 * runner itself only shipped in 0.9.1, so an install still on 0.9.0 or
332 * earlier that updates straight to the rebrand release has no stored
333 * version at all and arrives here with `$from === 0`, indistinguishable
334 * from a brand new site. Those are the installs that update rarely,
335 * which makes them the ones most likely to be blindsided by a rename,
336 * and gating on `$from > 0` would have silenced precisely them.
337 *
338 * **The user** has to have actually used it — see
339 * {@see openstation_users_with_prior_desktop_use} for what counts as
340 * proof. That separates a long-dormant install from a genuinely new one
341 * without needing to date the install at all, and it keeps the
342 * announcement away from an editor who joined an old site last week and
343 * enabled OpenStation this morning.
344 *
345 * What that gate does NOT do on its own is prove the evidence is old.
346 * On a new install it can be written between activation and the first
347 * `admin_init`, and then read back here as history. That window is
348 * closed by {@see openstation_run_migrations_on_activation}, which runs
349 * this migration before anything can write it.
350 *
351 * Deliberately NOT folded into migration 4, even though the two ship
352 * together: 4 has already run on trunk checkouts, and a migration that
353 * has run does not run again. Extending it would have silently skipped
354 * the flag exactly where it was easiest to believe it had been set.
355 *
356 * Flags are never cleared. Dismissal lives in the seen-intros registry,
357 * so one admin dismissing the announcement does not silence it for
358 * their editors, and "Reset what's-new dialogs" in OpenStation Preferences
359 * → Features brings it back with every other intro.
360 *
361 * @param int $from The highest migration version already applied.
362 * @return void
363 */
364 function openstation_migrate_flag_rebrand_notice( $from ) {
365 if ( (int) $from >= 4 ) {
366 return;
367 }
368
369 foreach ( openstation_users_with_prior_desktop_use() as $user_id ) {
370 update_user_meta( $user_id, OPENSTATION_REBRAND_NOTICE_META_KEY, 1 );
371 }
372 }
373
374 /**
375 * Whether the current user should be offered the rebrand announcement.
376 *
377 * Two gates: migration 5 flagged this user as one who was using Desktop
378 * Mode before the rename, and they have not already dismissed it. The
379 * seen-intros registry owns the second one, which is what makes the
380 * announcement behave like every other one-time dialog — including
381 * being brought back by "Reset what's-new dialogs".
382 *
383 * Only ever consulted while building the shell config, which is itself
384 * behind the `openstation_is_enabled()` / not-classic guard in
385 * `includes/render/assets.php`. So the announcement cannot reach the
386 * classic admin or a chromeless iframe: the bundle that would show it
387 * is not loaded there.
388 *
389 * @return bool
390 */
391 function openstation_should_show_rebrand_notice() {
392 $user_id = get_current_user_id();
393 if ( ! $user_id ) {
394 return false;
395 }
396
397 if ( ! get_user_meta( $user_id, OPENSTATION_REBRAND_NOTICE_META_KEY, true ) ) {
398 return false;
399 }
400
401 return ! openstation_has_seen_intro( $user_id, OPENSTATION_REBRAND_INTRO_SLUG );
402 }
403
404 /**
405 * Migration 4 — move the pre-brand defaults onto the OpenStation ones.
406 *
407 * The stored OS-settings snapshot outranks the shipped default, so
408 * changing `openstation_default_os_settings()` reaches new accounts and
409 * nobody else. Every existing desk would keep `wp-blue` on its focus
410 * rings, tab underlines, sort arrows and selection washes, and keep the
411 * graphite `dark` desk under the station's chrome — a half-applied
412 * rebrand, which reads as a bug rather than as a choice.
413 *
414 * **Only values still equal to the OLD default are touched.** A user who
415 * picked Indigo, or the Snow wallpaper, expressed a preference and keeps
416 * it. The one unavoidable cost is the user who deliberately chose
417 * WordPress Blue — indistinguishable from never having chosen at all,
418 * because it WAS the default — and for them it is one click in
419 * OS Settings → Appearance to set it back.
420 *
421 * Users with no stored settings are skipped entirely: they read the new
422 * defaults already.
423 *
424 * @return void
425 */
426 function openstation_migrate_brand_defaults() {
427 // The pre-brand => brand value map, keyed by OS-settings field.
428 // Deliberately not filterable: this runs once, against one release's
429 // stored defaults, and a third party rewriting which values get
430 // migrated would leave desks in a state no later migration accounts
431 // for.
432 $map = array(
433 'accent' => array(
434 'from' => 'wp-blue',
435 'to' => 'pulse',
436 ),
437 'wallpaper' => array(
438 'from' => 'dark',
439 'to' => 'galaxy',
440 ),
441 );
442
443 $user_ids = get_users(
444 array(
445 'fields' => 'ID',
446 'meta_key' => OPENSTATION_OS_SETTINGS_META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- one-time migration; the key is indexed in usermeta and the scan is guarded to run once.
447 'meta_compare' => 'EXISTS',
448 )
449 );
450
451 foreach ( $user_ids as $user_id ) {
452 $raw = get_user_meta( (int) $user_id, OPENSTATION_OS_SETTINGS_META_KEY, true );
453 if ( ! is_array( $raw ) ) {
454 continue;
455 }
456
457 $changed = false;
458 foreach ( $map as $key => $move ) {
459 if ( ! isset( $move['from'], $move['to'] ) ) {
460 continue;
461 }
462 // An absent key already resolves to the new default.
463 if ( isset( $raw[ $key ] ) && $move['from'] === $raw[ $key ] ) {
464 $raw[ $key ] = $move['to'];
465 $changed = true;
466 }
467 }
468
469 if ( $changed ) {
470 openstation_save_os_settings( (int) $user_id, $raw );
471 }
472 }
473 }
474
475 /**
476 * Migration 1 — reset the native list windows to opt-in.
477 *
478 * The native Posts/Pages/Users/Plugins/Comments windows used to default
479 * ON (opt-out). The shell persists the whole OS-settings object on every
480 * change, so most active users already have these flags stored as `true`
481 * and would keep the native UI even after the default flips. This clears
482 * the five flags from every user who has the meta, leaving the rest of
483 * their settings (wallpaper, accent, dock order, …) untouched. On the
484 * next read the cleared keys fall back to the new `false` default, so the
485 * whole install lands on opt-in and users re-enable each window from
486 * OS Settings → Features → Beta features.
487 *
488 * Only users who actually have the meta are queried — fresh accounts and
489 * users who never touched OS Settings are skipped entirely.
490 *
491 * @return void
492 */
493 function openstation_migrate_os_settings_optin() {
494 $flags = array(
495 'nativePostsEnabled',
496 'nativePagesEnabled',
497 'nativeUsersEnabled',
498 'nativePluginsEnabled',
499 'nativeCommentsEnabled',
500 );
501
502 $user_ids = get_users(
503 array(
504 'fields' => 'ID',
505 'meta_key' => OPENSTATION_OS_SETTINGS_META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- one-time migration; the key is indexed in usermeta and the scan is guarded to run once.
506 'meta_compare' => 'EXISTS',
507 )
508 );
509
510 foreach ( $user_ids as $user_id ) {
511 $raw = get_user_meta( (int) $user_id, OPENSTATION_OS_SETTINGS_META_KEY, true );
512 if ( ! is_array( $raw ) ) {
513 continue;
514 }
515
516 $changed = false;
517 foreach ( $flags as $flag ) {
518 if ( array_key_exists( $flag, $raw ) ) {
519 unset( $raw[ $flag ] );
520 $changed = true;
521 }
522 }
523
524 if ( ! $changed ) {
525 continue;
526 }
527
528 // Re-save through the canonical sanitizer so the cleared flags are
529 // backfilled with the new `false` default and the rest of the
530 // settings array is normalized exactly as a client write would be.
531 openstation_save_os_settings( (int) $user_id, $raw );
532 }
533 }
534
535 /**
536 * Migration 2 — unschedule leftover post/term AI analysis jobs.
537 *
538 * Post and taxonomy-term analysis was removed: the copilot now only
539 * analyzes comments (for the spam score), and the AI assistant finds
540 * content with native WordPress keyword search. Their cron callbacks no
541 * longer exist, so any single-events still queued from a prior version
542 * would simply no-op — but we clear them so the cron array stays tidy and
543 * `wp cron event list` doesn't show orphaned hooks.
544 *
545 * Existing `_desktop_mode_ai_analysis` meta on posts/terms is left in place
546 * (hidden, harmless, and cheap to ignore).
547 *
548 * @return void
549 */
550 function openstation_migrate_unschedule_post_term_ai() {
551 wp_unschedule_hook( 'desktop_mode_ai_analyze_post' );
552 wp_unschedule_hook( 'desktop_mode_ai_analyze_term' );
553 }
554
555 /**
556 * Migration 3 — delete self-managed AI credentials.
557 *
558 * WordPress 7.0 owns provider credentials (Settings → Connectors), so the
559 * copilot no longer stores keys of its own. Remove the platform key option and
560 * strip the now-unused key / provider / model / transport fields from every
561 * user's stored OS settings so no secret is left behind. The only `ai` field
562 * that remains is `enabled` (the per-user assistant toggle), backfilled from
563 * defaults on next read.
564 *
565 * @return void
566 */
567 function openstation_migrate_delete_ai_keys() {
568 // Platform-wide key option (formerly `desktop_mode_ai_platform`).
569 delete_option( 'desktop_mode_ai_platform' );
570
571 $user_ids = get_users(
572 array(
573 'fields' => 'ID',
574 'meta_key' => OPENSTATION_OS_SETTINGS_META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- one-time migration; guarded to run once.
575 'meta_compare' => 'EXISTS',
576 )
577 );
578
579 foreach ( $user_ids as $user_id ) {
580 $raw = get_user_meta( (int) $user_id, OPENSTATION_OS_SETTINGS_META_KEY, true );
581 if ( ! is_array( $raw ) || ! isset( $raw['ai'] ) || ! is_array( $raw['ai'] ) ) {
582 continue;
583 }
584
585 // Strip every legacy AI field: the self-managed credentials/transport,
586 // plus the `provider` / `model` preferences — provider + model selection
587 // is now delegated entirely to the Core AI Client.
588 $changed = false;
589 foreach ( array( 'apiKey', 'apiKeys', 'transport', 'provider', 'model' ) as $stale ) {
590 if ( array_key_exists( $stale, $raw['ai'] ) ) {
591 unset( $raw['ai'][ $stale ] );
592 $changed = true;
593 }
594 }
595
596 if ( ! $changed ) {
597 continue;
598 }
599
600 openstation_save_os_settings( (int) $user_id, $raw );
601 }
602 }
603