-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystemdeck.php
More file actions
1374 lines (1227 loc) · 61.4 KB
/
Copy pathsystemdeck.php
File metadata and controls
1374 lines (1227 loc) · 61.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: SystemDeck
* Plugin URI: https://systemdeck.dev
* Description: WordPress Creative Operations Layer.
* Version: 3.3.1
* Author: SystemDeck
* Text Domain: systemdeck
* Domain Path: /languages
* License: GPL-2.0-or-later
* Requires PHP: 8.0
*/
defined('ABSPATH') || exit;
// Constants
define('SYSTEMDECK_VERSION', '3.3.1');
define('SYSTEMDECK_MIN_WP', '6.7');
define('SYSTEMDECK_MIN_PHP', '8.0');
define('SYSTEMDECK_PATH', plugin_dir_path(__FILE__));
define('SYSTEMDECK_URL', plugin_dir_url(__FILE__));
if (!defined('SYSTEMDECK_HYDRATION_DIAGNOSTICS_ENABLED')) {
define('SYSTEMDECK_HYDRATION_DIAGNOSTICS_ENABLED', false);
}
if (file_exists(SYSTEMDECK_PATH . 'core/Autoloader.php')) {
require_once SYSTEMDECK_PATH . 'core/Autoloader.php';
\SystemDeck\Core\Autoloader::register();
}
if (defined('WP_CLI') && WP_CLI && file_exists(SYSTEMDECK_PATH . 'devtools/cli-registry.php')) {
require_once SYSTEMDECK_PATH . 'devtools/cli-registry.php';
}
// Core Component Bootstrapping (Universal CPTs & Hooks)
if (class_exists('\\SystemDeck\\Core\\Services\\ModuleBootstrap')) {
\SystemDeck\Core\Services\ModuleBootstrap::run();
}
// SAFETY CHECKS
if (version_compare(PHP_VERSION, SYSTEMDECK_MIN_PHP, '<')) {
add_action('admin_notices', function () {
echo '<div class="notice notice-error"><p>';
echo esc_html__('SystemDeck requires PHP 8.0 or higher.', 'systemdeck');
echo '</p></div>';
});
return;
}
if (version_compare(get_bloginfo('version'), SYSTEMDECK_MIN_WP, '<')) {
add_action('admin_notices', function () {
echo '<div class="notice notice-error"><p>';
echo esc_html__('SystemDeck requires WordPress 6.7 or higher.', 'systemdeck');
echo '</p></div>';
});
return;
}
add_action('admin_head', function () {
if (!class_exists('\SystemDeck\Core\Schema')) {
return;
}
echo \SystemDeck\Core\Schema::to_style_tag('fresh');
});
/**
* PHASE 1: INFRASTRUCTURE (Universal / Always On)
* Hooked early to 'init' to ensure routes are registered before permission gates.
* This fixes the "too early" translation error while keeping registration un-gated.
*/
add_action('init', 'systemdeck_register_infrastructure', 0);
function systemdeck_load_app_provider_modules(): void
{
$widgets_dir = SYSTEMDECK_PATH . 'widgets/';
if (is_dir($widgets_dir)) {
$provider_files = glob($widgets_dir . '*/widget.php');
if (is_array($provider_files)) {
foreach ($provider_files as $provider_file) {
if (is_string($provider_file) && file_exists($provider_file)) {
require_once $provider_file;
}
}
}
}
/**
* Allow external providers to load their app modules before AJAX/actions init.
*/
do_action('systemdeck_load_app_providers');
}
function systemdeck_register_infrastructure(): void
{
// Ensure app/widget modules with external AJAX hooks are loaded before AjaxHandler::init().
systemdeck_load_app_provider_modules();
// Canvas Repository (V3 Alpha Step 1: CPT registration)
if (class_exists('\\SystemDeck\\Core\\Services\\CanvasRepository')) {
\SystemDeck\Core\Services\CanvasRepository::init();
}
// Block Contract (V3 Alpha)
if (class_exists('\\SystemDeck\\Core\\Blocks\\WidgetPlaceholderBlock')) {
\SystemDeck\Core\Blocks\WidgetPlaceholderBlock::init();
}
if (class_exists('\\SystemDeck\\Core\\Blocks\\CanvasGridBlock')) {
\SystemDeck\Core\Blocks\CanvasGridBlock::init();
}
// AJAX Handler (Core Gateway)
if (class_exists('\\SystemDeck\\Core\\AjaxHandler')) {
\SystemDeck\Core\AjaxHandler::init();
}
if (class_exists('\\SystemDeck\\Core\\Rest\\WidgetPreviewRoute')) {
\SystemDeck\Core\Rest\WidgetPreviewRoute::init();
}
// Dashboard Tunnel (Widget iframes)
if (class_exists('\\SystemDeck\\Modules\\DashboardTunnel')) {
\SystemDeck\Modules\DashboardTunnel::init();
}
// System Screen (Command Center)
if (class_exists('\\SystemDeck\\Modules\\SystemScreen')) {
\SystemDeck\Modules\SystemScreen::init();
}
// HUD Atlas Admin Page
if (class_exists('\\SystemDeck\\Modules\\HudAtlasPage')) {
\SystemDeck\Modules\HudAtlasPage::init();
}
// Assets Engine (Color Tokens)
if (class_exists('\\SystemDeck\\Core\\Assets')) {
\SystemDeck\Core\Assets::init();
}
// Register sd-common at the earliest admin hook so the handle is always
// present before any admin_enqueue_scripts or admin_print_styles callback
// resolves the sd-pins dependency chain (WP 6.9.1 strict dep validation).
add_action('admin_init', static function () {
if (!wp_style_is('sd-common', 'registered')) {
wp_register_style('sd-common', SYSTEMDECK_URL . 'assets/css/common.css', [], SYSTEMDECK_VERSION);
}
}, 0);
// Re-register sd-common immediately before WP resolves the style dep chain
// (admin_print_styles priority 10). The diagnostic confirmed something between
// priority 1 and 10 deregisters the handle (likely a third-party security plugin).
add_action('admin_print_styles', static function () {
if (!wp_style_is('sd-common', 'registered')) {
wp_register_style('sd-common', SYSTEMDECK_URL . 'assets/css/common.css', [], SYSTEMDECK_VERSION);
}
}, 1);
// Re-assert dashicons late in admin style lifecycle when advanced modal
// audio is enabled. Some stacks deregister/dequeue it after enqueue hooks.
add_action('admin_print_styles', static function () {
$user_id = get_current_user_id();
if ($user_id <= 0) {
return;
}
$advanced_media_modal = get_user_meta($user_id, 'sd_advanced_audio_media_modal', true) === '1';
$advanced_vault_modal = get_user_meta($user_id, 'sd_advanced_audio_vault_modal', true) === '1';
if (!$advanced_media_modal && !$advanced_vault_modal) {
return;
}
if (!wp_style_is('dashicons', 'registered')) {
wp_register_style(
'dashicons',
includes_url('css/dashicons.min.css'),
[],
get_bloginfo('version')
);
}
wp_enqueue_style('dashicons');
}, 1000);
if (class_exists('\\SystemDeck\\Core\\Logo')) {
\SystemDeck\Core\Logo::init();
}
if (class_exists('\\SystemDeck\\Core\\StorageEngine')) {
\SystemDeck\Core\StorageEngine::init();
}
if (class_exists('\\SystemDeck\\Core\\Rest\\AudioMemoryRoute')) {
\SystemDeck\Core\Rest\AudioMemoryRoute::init();
}
// RC Directive Phase 2: Check if Registry Snapshot needs refresh
do_action('system_deck_init');
// Note: RegistryService::get_snapshot() handles refresh internally on read
if (class_exists('\\SystemDeck\\Core\\Services\\RegistryService')) {
\SystemDeck\Core\Services\RegistryService::get_snapshot();
} elseif (class_exists('\\SystemDeck\\Core\\Registry')) {
\SystemDeck\Core\Registry::get_snapshot();
}
// Deterministic widget preloading from snapshot
if (class_exists('\\SystemDeck\\Core\\CanvasEngine')) {
\SystemDeck\Core\CanvasEngine::init();
}
}
function systemdeck_rebuild_snapshot_now(): void
{
if (class_exists('\\SystemDeck\\Core\\Services\\RegistryService')) {
\SystemDeck\Core\Services\RegistryService::build_snapshot();
if (method_exists('\\SystemDeck\\Core\\Services\\RegistryService', 'refresh_discovered_widget_cache')) {
\SystemDeck\Core\Services\RegistryService::refresh_discovered_widget_cache();
}
}
}
function systemdeck_schedule_snapshot_rebuild(): void
{
update_option('sd_registry_rebuild_needed', 1, false);
}
function systemdeck_maybe_run_scheduled_snapshot_rebuild(): void
{
$needs = (int) get_option('sd_registry_rebuild_needed', 0);
if ($needs !== 1) {
return;
}
delete_option('sd_registry_rebuild_needed');
systemdeck_rebuild_snapshot_now();
}
function systemdeck_rebuild_snapshot_on_change($plugin = '', $network_wide = false): void
{
systemdeck_schedule_snapshot_rebuild();
}
function systemdeck_rebuild_snapshot_on_theme_switch($new_name = '', $new_theme = null, $old_theme = null): void
{
systemdeck_schedule_snapshot_rebuild();
}
function systemdeck_rebuild_snapshot_on_upgrade($upgrader_object = null, $options = []): void
{
if (!is_array($options)) {
return;
}
$type = $options['type'] ?? '';
if ($type === 'plugin' || $type === 'theme') {
systemdeck_schedule_snapshot_rebuild();
}
}
add_action('activated_plugin', 'systemdeck_rebuild_snapshot_on_change', 10, 2);
add_action('deactivated_plugin', 'systemdeck_rebuild_snapshot_on_change', 10, 2);
add_action('switch_theme', 'systemdeck_rebuild_snapshot_on_theme_switch', 10, 3);
add_action('upgrader_process_complete', 'systemdeck_rebuild_snapshot_on_upgrade', 10, 2);
add_action('admin_init', 'systemdeck_maybe_run_scheduled_snapshot_rebuild', 1);
/**
* Plugin Activation Hook
* Build the Registry Snapshot on activation
*/
register_activation_hook(__FILE__, 'systemdeck_on_activation');
function systemdeck_on_activation(): void
{
// Create database tables
if (class_exists('\\SystemDeck\\Core\\StorageEngine')) {
\SystemDeck\Core\StorageEngine::create_tables();
}
// Build the Registry Snapshot (The Mailbox)
// Run after table creation to avoid activation-time SQL warnings.
if (class_exists('\\SystemDeck\\Core\\Services\\RegistryService')) {
\SystemDeck\Core\Services\RegistryService::build_snapshot();
}
update_option('sd_registry_rebuild_needed', 0, false);
}
// Permissions (Keep this for the safety check)
function systemdeck_user_can_boot(): bool
{
if (!is_user_logged_in()) {
return false;
}
$user = wp_get_current_user();
if (!$user || !$user->exists()) {
return false;
}
$can_boot = systemdeck_user_can('shell_access');
$can_boot = (bool) apply_filters('systemdeck_user_can_boot', $can_boot, $user->ID);
return $can_boot;
}
function systemdeck_get_access_policy_defaults(): array
{
return [
'shell_roles' => ['administrator'],
'workspace_view_roles' => ['administrator'],
'workspace_manage_roles' => ['administrator'],
];
}
function systemdeck_sanitize_access_policy(array $policy): array
{
$defaults = systemdeck_get_access_policy_defaults();
$allowed_roles = ['administrator', 'editor', 'author', 'contributor', 'subscriber'];
$clean = $defaults;
foreach ($defaults as $key => $default_value) {
$incoming = $policy[$key] ?? $default_value;
if (!is_array($incoming)) {
$incoming = $default_value;
}
$roles = array_values(array_unique(array_filter(array_map('sanitize_key', $incoming), static function ($role) use ($allowed_roles) {
return in_array($role, $allowed_roles, true);
})));
$clean[$key] = !empty($roles) ? $roles : $default_value;
}
return $clean;
}
function systemdeck_get_access_policy(): array
{
$stored = get_option('sd_access_policy', []);
if (!is_array($stored)) {
$stored = [];
}
return systemdeck_sanitize_access_policy($stored);
}
function systemdeck_role_rank(string $role): int
{
$rank = [
'subscriber' => 1,
'contributor' => 2,
'author' => 3,
'editor' => 4,
'administrator' => 5,
];
return $rank[$role] ?? 0;
}
function systemdeck_user_rank(int $user_id): int
{
$user = get_userdata($user_id);
if (!$user) {
return 0;
}
$max = 0;
foreach ((array) $user->roles as $role) {
$max = max($max, systemdeck_role_rank((string) $role));
}
return $max;
}
function systemdeck_user_matches_roles(int $user_id, array $roles): bool
{
$user = get_userdata($user_id);
if (!$user) {
return false;
}
$user_roles = (array) $user->roles;
foreach ($roles as $role) {
if (in_array($role, $user_roles, true)) {
return true;
}
}
return false;
}
function systemdeck_user_meets_workspace_access(int $user_id, string $workspace_id, string $permission = 'workspace_view'): bool
{
if ($workspace_id === '' || $workspace_id === 'default') {
return true;
}
if (!class_exists('\\SystemDeck\\Core\\Services\\CanvasRepository')) {
return true;
}
$canvas_post = systemdeck_get_canvas_post_by_workspace($workspace_id);
if (!$canvas_post) {
return true;
}
$canvas_id = (int) $canvas_post->ID;
$owner_id = (int) $canvas_post->post_author;
$is_owner = ($owner_id > 0 && $owner_id === $user_id);
if ($is_owner) {
return true;
}
// Private always means owner-only (+ admin handled by caller).
$is_public = (bool) get_post_meta($canvas_id, \SystemDeck\Core\Services\CanvasRepository::META_PUBLIC, true);
if (!$is_public) {
return false;
}
$audience_scope = \SystemDeck\Core\Services\CanvasRepository::normalize_audience_scope(
(string) get_post_meta($canvas_id, \SystemDeck\Core\Services\CanvasRepository::META_AUDIENCE_SCOPE, true)
);
if ($audience_scope === 'targeted_users') {
$target_user_ids = \SystemDeck\Core\Services\CanvasRepository::get_workspace_target_user_ids($workspace_id, $owner_id > 0 ? $owner_id : $user_id);
if (!in_array($user_id, $target_user_ids, true)) {
return false;
}
}
// Public + locked means view-only for non-owner.
$is_locked = (bool) get_post_meta($canvas_id, \SystemDeck\Core\Services\CanvasRepository::META_LOCKED, true);
if ($is_locked && in_array($permission, ['workspace_manage', 'workspace_delete', 'workspace_edit'], true)) {
return false;
}
$required = (string) get_post_meta($canvas_id, \SystemDeck\Core\Services\CanvasRepository::META_ACCESS_ROLE, true);
if ($required === '' || $required === 'all')
$required = 'administrator';
return systemdeck_user_rank($user_id) >= systemdeck_role_rank($required);
}
function systemdeck_get_canvas_post_by_workspace(string $workspace_id): ?WP_Post
{
$workspace_id = sanitize_key($workspace_id);
if ($workspace_id === '' || $workspace_id === 'default') {
return null;
}
if (!class_exists('\\SystemDeck\\Core\\Services\\CanvasRepository')) {
return null;
}
$posts = get_posts([
'post_type' => \SystemDeck\Core\Services\CanvasRepository::CPT,
'post_status' => ['publish', 'private', 'draft', 'pending'],
'posts_per_page' => 1,
'meta_query' => [
[
'key' => \SystemDeck\Core\Services\CanvasRepository::META_WORKSPACE,
'value' => $workspace_id,
'compare' => '=',
]
],
'orderby' => 'ID',
'order' => 'DESC',
'no_found_rows' => true,
]);
return (!empty($posts) && $posts[0] instanceof \WP_Post) ? $posts[0] : null;
}
function systemdeck_get_shared_workspaces_for_user(int $user_id): array
{
if ($user_id <= 0 || !class_exists('\\SystemDeck\\Core\\Services\\CanvasRepository')) {
return [];
}
$posts = get_posts([
'post_type' => \SystemDeck\Core\Services\CanvasRepository::CPT,
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => \SystemDeck\Core\Services\CanvasRepository::META_PUBLIC,
'value' => '1',
'compare' => '=',
]
],
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => true,
]);
if (empty($posts)) {
return [];
}
$shared = [];
foreach ($posts as $post) {
if (!$post instanceof \WP_Post) {
continue;
}
if ((int) $post->post_author === $user_id) {
continue;
}
$workspace_id = sanitize_key((string) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_WORKSPACE, true));
if ($workspace_id === '' || $workspace_id === 'default') {
continue;
}
if (!systemdeck_user_meets_workspace_access($user_id, $workspace_id, 'workspace_view')) {
continue;
}
$author = get_userdata((int) $post->post_author);
$is_locked = (bool) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_LOCKED, true);
$runtime_items = \SystemDeck\Core\Services\CanvasRepository::extract_runtime_blocks_from_content((string) $post->post_content);
$workspace_widgets = [];
foreach ($runtime_items as $runtime_item) {
if (($runtime_item['type'] ?? '') !== 'block_widget_placeholder') {
continue;
}
$candidate = \SystemDeck\Core\Services\WidgetRuntimeBridge::sanitize_widget_id((string) (($runtime_item['settings']['widgetId'] ?? '')));
if ($candidate !== '') {
$workspace_widgets[] = $candidate;
}
}
$workspace_widgets = array_values(array_unique($workspace_widgets));
$shared[$workspace_id] = [
'id' => $workspace_id,
'name' => (string) ($post->post_title ?: __('Untitled Workspace', 'systemdeck')),
'title' => (string) ($post->post_title ?: __('Untitled Workspace', 'systemdeck')),
'created' => (string) $post->post_date,
'widgets' => $workspace_widgets,
'available' => $workspace_widgets,
'shared' => true,
'shared_incoming' => true,
'shared_menu_only' => $is_locked,
'canvas_id' => (int) $post->ID,
'cpt_post_id' => (int) $post->ID,
'cpt_author_id' => (int) $post->post_author,
'cpt_author_name' => $author ? (string) $author->display_name : '',
'cpt_created' => (string) $post->post_date,
'cpt_modified' => (string) $post->post_modified,
'cpt_post_status' => (string) $post->post_status,
'is_public' => true,
'is_locked' => $is_locked,
'collaboration_mode' => \SystemDeck\Core\Services\CanvasRepository::normalize_collaboration_mode(
(string) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_COLLABORATION_MODE, true)
),
'audience_scope' => \SystemDeck\Core\Services\CanvasRepository::normalize_audience_scope(
(string) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_AUDIENCE_SCOPE, true)
),
'target_user_ids' => \SystemDeck\Core\Services\CanvasRepository::get_workspace_target_user_ids($workspace_id, (int) $post->post_author),
'target_user_logins' => \SystemDeck\Core\Services\CanvasRepository::get_workspace_target_user_logins($workspace_id, (int) $post->post_author),
'access_role' => (string) (get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_ACCESS_ROLE, true) ?: 'administrator'),
'show_top_level_menu' => (bool) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_SHOW_TOP_LEVEL_MENU, true),
'menu_icon' => (string) (sanitize_html_class((string) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_MENU_ICON, true)) ?: 'dashicons-screenoptions'),
'is_app_workspace' => (bool) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_IS_APP_WORKSPACE, true),
'app_id' => \SystemDeck\Core\Services\PinRuntimeBridge::sanitize_pin_id((string) get_post_meta($post->ID, \SystemDeck\Core\Services\CanvasRepository::META_APP_ID, true)),
'archived' => false,
];
}
return $shared;
}
function systemdeck_user_can(string $permission, string $workspace_id = ''): bool
{
if (!is_user_logged_in()) {
return false;
}
$user_id = (int) get_current_user_id();
if ($user_id <= 0) {
return false;
}
if (user_can($user_id, 'manage_options')) {
return true;
}
$map = [
'shell_access' => 'shell_roles',
'workspace_view' => 'workspace_view_roles',
'workspace_manage' => 'workspace_manage_roles',
'workspace_create' => 'workspace_manage_roles',
'workspace_delete' => 'workspace_manage_roles',
'workspace_edit' => 'workspace_manage_roles',
];
$key = $map[$permission] ?? 'shell_roles';
$policy = systemdeck_get_access_policy();
$allowed = systemdeck_user_matches_roles($user_id, (array) ($policy[$key] ?? []));
if ($workspace_id !== '' && in_array($permission, ['workspace_view', 'workspace_manage', 'workspace_delete', 'workspace_edit'], true)) {
$workspace_allowed = systemdeck_user_meets_workspace_access($user_id, sanitize_key($workspace_id), $permission);
$allowed = $allowed && $workspace_allowed;
}
return (bool) apply_filters('systemdeck_user_can', $allowed, $permission, $workspace_id, $user_id);
}
class SystemDeck_Assets
{
private static function should_enqueue_advanced_audio_assets_for_admin(): bool
{
if (!is_admin()) {
return false;
}
static $cached = null;
if ($cached !== null) {
return $cached;
}
$user_id = get_current_user_id();
if ($user_id <= 0) {
$cached = false;
return $cached;
}
$advanced_media_modal = get_user_meta($user_id, 'sd_advanced_audio_media_modal', true) === '1';
$advanced_vault_modal = get_user_meta($user_id, 'sd_advanced_audio_vault_modal', true) === '1';
if (!$advanced_media_modal && !$advanced_vault_modal) {
$cached = false;
return $cached;
}
// Toggle-controlled authority: when either advanced-audio toggle is ON,
// modal-capable admin surfaces must have the core player stack available
// regardless of workspace layout or widget activation.
$cached = true;
return $cached;
}
/**
* Boot the System.
* Hooked into 'init' to wait for User Session.
*/
public static function run(): void
{
// Infrastructure is already registered at the top level (Phase 1).
// 7. Text Domain
load_plugin_textdomain('systemdeck', false, dirname(plugin_basename(__DIR__)) . '/languages');
// ---------------------------------------------------------
// PHASE 2: UI SHELL GATE (Permission & Context Checks)
// ---------------------------------------------------------
// Prevent recursive boot in scanner iframe (The Inception Guard)
if (
(isset($_GET['sd_block_boot']) && $_GET['sd_block_boot'] === '1') ||
(isset($_GET['sd_inspect']) && $_GET['sd_inspect'] === '1')
) {
return;
}
if (function_exists('systemdeck_user_can_boot')) {
$can_boot = systemdeck_user_can_boot();
if (!$can_boot) {
return;
}
}
// ---------------------------------------------------------
// PHASE 3: SHELL BOOT (Assets, Context, Canvas Engine)
// ---------------------------------------------------------
// Initialize Context
if (class_exists('\\SystemDeck\\Core\\Context')) {
// Context initialization if needed
}
// Register Shell Assets (Rebirth)
add_action('enqueue_block_editor_assets', [self::class, 'register_assets']);
add_action('wp_enqueue_scripts', [self::class, 'register_assets']);
add_action('admin_enqueue_scripts', [self::class, 'register_assets']);
// Canvas Engine (Runtime)
if (class_exists('SystemDeck\Core\CanvasEngine')) {
$canvas = new \SystemDeck\Core\CanvasEngine();
$canvas->run();
}
// User Preferences
if (class_exists('\\SystemDeck\\Core\\UserPreferences')) {
\SystemDeck\Core\UserPreferences::init();
}
// Editor Controller (Gutenberg)
if (class_exists('\\SystemDeck\\Core\\EditorController')) {
\SystemDeck\Core\EditorController::init();
}
// Retail Controller is initialized independently at the bottom of
// systemdeck.php (priority 5) so it runs even when the Inception Guard
// fires — do NOT re-initialize here to avoid double hook registration.
}
public static function register_assets(): void
{
if (isset($_GET['sd_embed']))
return;
$is_block_editor_context = false;
if (is_admin() && function_exists('get_current_screen')) {
$screen = get_current_screen();
$is_block_editor_context = (bool) ($screen && method_exists($screen, 'is_block_editor') && $screen->is_block_editor());
}
// 1. Register Shell Assets (Updated Paths)
$tone_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/vendor/tone.min.js') ?: SYSTEMDECK_VERSION);
$tonejs_midi_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/vendor/tonejs-midi.min.js') ?: SYSTEMDECK_VERSION);
$audio_engine_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/js/sd-audio-engine.js') ?: SYSTEMDECK_VERSION);
$playback_adapter_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/js/sd-playback-adapter.js') ?: SYSTEMDECK_VERSION);
$audio_identity_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/js/sd-audio-identity.js') ?: SYSTEMDECK_VERSION);
$audio_memory_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/js/sd-audio-memory.js') ?: SYSTEMDECK_VERSION);
$player_style_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/css/systemdeck-player.css') ?: SYSTEMDECK_VERSION);
$player_app_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'assets/js/sd-player-app.js') ?: SYSTEMDECK_VERSION);
$modal_shell_js_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'modals/modal-shell.js') ?: SYSTEMDECK_VERSION);
$modal_shell_css_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'modals/modal-shell.css') ?: SYSTEMDECK_VERSION);
$modal_comments_js_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'modals/comments-modal.js') ?: SYSTEMDECK_VERSION);
$modal_comments_css_ver = (string) (@filemtime(SYSTEMDECK_PATH . 'modals/comments-modal.css') ?: SYSTEMDECK_VERSION);
wp_register_script('tone', SYSTEMDECK_URL . 'assets/vendor/tone.min.js', [], $tone_ver, true);
wp_register_script('sd-tonejs-midi', SYSTEMDECK_URL . 'assets/vendor/tonejs-midi.min.js', [], $tonejs_midi_ver, true);
wp_register_script('sd-audio-engine', SYSTEMDECK_URL . 'assets/js/sd-audio-engine.js', ['tone'], $audio_engine_ver, true);
wp_register_script('sd-playback-adapter', SYSTEMDECK_URL . 'assets/js/sd-playback-adapter.js', ['jquery', 'sd-audio-engine'], $playback_adapter_ver, true);
wp_register_script('sd-audio-identity', SYSTEMDECK_URL . 'assets/js/sd-audio-identity.js', [], $audio_identity_ver, true);
wp_register_script('sd-audio-memory', SYSTEMDECK_URL . 'assets/js/sd-audio-memory.js', ['wp-api-fetch', 'sd-audio-identity'], $audio_memory_ver, true);
if (class_exists('\\SystemDeck\\Core\\Assets')) {
\SystemDeck\Core\Assets::register_all();
}
wp_register_style('sd-player-style', SYSTEMDECK_URL . 'assets/css/systemdeck-player.css', ['sd-common', 'dashicons'], $player_style_ver);
wp_register_script('sd-player-app', SYSTEMDECK_URL . 'assets/js/sd-player-app.js', ['jquery', 'sd-audio-engine', 'sd-playback-adapter'], $player_app_ver, true);
wp_register_style('sd-modal-shell-style', SYSTEMDECK_URL . 'modals/modal-shell.css', [], $modal_shell_css_ver);
wp_register_script('sd-modal-shell', SYSTEMDECK_URL . 'modals/modal-shell.js', ['wp-element'], $modal_shell_js_ver, true);
wp_register_style('sd-modal-comments-style', SYSTEMDECK_URL . 'modals/comments-modal.css', ['sd-modal-shell-style'], $modal_comments_css_ver);
wp_register_script('sd-modal-comments', SYSTEMDECK_URL . 'modals/comments-modal.js', ['wp-element', 'sd-modal-shell'], $modal_comments_js_ver, true);
wp_add_inline_script(
'sd-audio-engine',
'window.SYSTEMDECK_AUDIO_ASSETS = Object.assign({}, window.SYSTEMDECK_AUDIO_ASSETS || {}, ' . wp_json_encode([
'toneUrl' => SYSTEMDECK_URL . 'assets/vendor/tone.min.js',
'midiUrl' => SYSTEMDECK_URL . 'assets/vendor/tonejs-midi.min.js',
'toneVersion' => $tone_ver,
'midiVersion' => $tonejs_midi_ver,
]) . ');',
'before'
);
wp_register_style('systemdeck-shell', SYSTEMDECK_URL . 'assets/css/systemdeck-shell.css', ['dashicons'], SYSTEMDECK_VERSION);
wp_register_script('systemdeck-shell', SYSTEMDECK_URL . 'assets/js/systemdeck-shell.js', ['jquery'], SYSTEMDECK_VERSION, true);
if (self::should_enqueue_advanced_audio_assets_for_admin()) {
if (!wp_style_is('dashicons', 'registered')) {
wp_register_style(
'dashicons',
includes_url('css/dashicons.min.css'),
[],
get_bloginfo('version')
);
}
wp_enqueue_style('dashicons');
wp_enqueue_style('sd-player-style');
wp_enqueue_script('tone');
wp_enqueue_script('sd-audio-engine');
wp_enqueue_script('sd-playback-adapter');
wp_enqueue_script('sd-player-app');
}
if (is_user_logged_in()) {
wp_enqueue_style('sd-modal-shell-style');
wp_enqueue_style('sd-modal-comments-style');
wp_enqueue_script('sd-modal-shell');
wp_enqueue_script('sd-modal-comments');
wp_add_inline_script(
'sd-modal-shell',
'window.SystemDeckModalEnv = Object.assign({}, window.SystemDeckModalEnv || {}, ' . wp_json_encode([
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('systemdeck_runtime'),
]) . ');',
'before'
);
}
// Build Payload
$user_id = get_current_user_id();
$workspaces = get_user_meta($user_id, 'sd_workspaces', true) ?: [];
// Cleanup: ensure every workspace is valid and has an ID
$cleaned_workspaces = [];
foreach ($workspaces as $id => $ws) {
if (!is_array($ws)) {
// Handle legacy string-only workspaces if they exist
$ws = ['id' => sanitize_title($ws), 'name' => $ws];
}
$ws_id = $ws['id'] ?? (is_string($id) ? $id : 'ws_' . uniqid());
$ws['id'] = $ws_id;
if (empty($ws['name']) && empty($ws['title'])) {
$ws['name'] = ($ws_id === 'default') ? 'Main Workspace' : 'Untitled Workspace';
}
if (empty($ws['created'])) {
$ws['created'] = current_time('mysql');
}
if (!isset($ws['widgets']) || !is_array($ws['widgets'])) {
$ws['widgets'] = [];
}
if (!isset($ws['shared'])) {
$ws['shared'] = false;
}
if (!isset($ws['pinned'])) {
$ws['pinned'] = false;
}
if (!isset($ws['source_workspace_id'])) {
$ws['source_workspace_id'] = '';
}
if (!isset($ws['source_version_at_clone'])) {
$ws['source_version_at_clone'] = 0;
}
// Map 'widgets' (PHP side) to 'available' (JS side)
$ws['available'] = $ws['widgets'] ?? [];
$cleaned_workspaces[$ws_id] = $ws;
}
$workspaces = $cleaned_workspaces;
update_user_meta($user_id, 'sd_workspaces', $workspaces);
if (class_exists('\\SystemDeck\\Core\\Services\\CanvasRepository')) {
$workspaces = \SystemDeck\Core\Services\CanvasRepository::enrich_workspaces_with_canvas_data($workspaces, (int) $user_id);
update_user_meta($user_id, 'sd_workspaces', $workspaces);
}
// Include shared (public) workspaces from other owners in runtime state.
$shared_workspaces = systemdeck_get_shared_workspaces_for_user((int) $user_id);
if (!empty($shared_workspaces)) {
foreach ($shared_workspaces as $shared_id => $shared_ws) {
if (!isset($workspaces[$shared_id])) {
$workspaces[$shared_id] = $shared_ws;
}
}
}
$visible_workspaces = array_filter($workspaces, static function ($ws) use ($user_id) {
if (!is_array($ws)) {
return false;
}
$workspace_id = sanitize_key((string) ($ws['id'] ?? ''));
$owner_id = (int) ($ws['cpt_author_id'] ?? 0);
if (
$workspace_id !== '' &&
$workspace_id !== 'default' &&
$owner_id > 0 &&
$owner_id !== (int) $user_id &&
!systemdeck_user_meets_workspace_access((int) $user_id, $workspace_id, 'workspace_view')
) {
return false;
}
// CPT status is the source of truth when available.
if (isset($ws['cpt_post_status']) && $ws['cpt_post_status'] !== '') {
$status = (string) $ws['cpt_post_status'];
if ($owner_id > 0 && $owner_id === (int) $user_id) {
return $status !== 'trash';
}
return $status === 'publish';
}
// Legacy fallback for workspaces without a mapped canvas.
return empty($ws['archived']);
});
// Sort by saved order field so drag-and-drop arrangement persists on reload.
uasort($visible_workspaces, static function ($a, $b) {
$orderA = (int) ($a['order'] ?? PHP_INT_MAX);
$orderB = (int) ($b['order'] ?? PHP_INT_MAX);
return $orderA <=> $orderB;
});
// Hydrate Initial Layout for visible workspaces
$initial_layouts = [];
if (class_exists('SystemDeck\Core\StorageEngine') && class_exists('SystemDeck\Core\Context')) {
try {
foreach ($visible_workspaces as $ws_id => $ws_data) {
$context = new \SystemDeck\Core\Context(get_current_user_id(), $ws_id);
$items = \SystemDeck\Core\StorageEngine::get('layout', $context);
$hidden_lookup = [];
$is_shared_overlay = !empty($ws_data['shared_incoming']) && (($ws_data['collaboration_mode'] ?? 'owner_only') !== 'collaborative');
if ($is_shared_overlay && class_exists('\\SystemDeck\\Core\\AjaxHandler')) {
$hidden_widget_ids = \SystemDeck\Core\AjaxHandler::get_hidden_base_widget_ids((int) get_current_user_id(), (string) $ws_id);
$hidden_lookup = array_fill_keys($hidden_widget_ids, true);
}
$layout_data = [];
if ($items && is_array($items)) {
foreach ($items as $item) {
if (empty($item['id']) || $item['id'] === 'undefined')
continue;
$item_id = (string) $item['id'];
$settings = (array) ($item['settings'] ?? []);
$slot_widget_id = \SystemDeck\Core\Services\WidgetRuntimeBridge::sanitize_widget_id((string) ($settings['widgetId'] ?? ''));
$candidate = \SystemDeck\Core\Services\WidgetRuntimeBridge::sanitize_widget_id((string) ($settings['widgetId'] ?? ''));
if ($candidate !== '' && isset($hidden_lookup[$candidate])) {
continue;
}
if (!isset($settings['source']) && str_starts_with($item_id, 'sd_canvas_')) {
$settings['source'] = 'canvas';
}
$item_type = !empty($item['type']) ? (string) $item['type'] : 'widget';
if ($slot_widget_id !== '') {
$item_type = 'block_widget_placeholder';
}
$layout_data[$item['id']] = [
'i' => $item['id'],
'id' => $item['id'],
'type' => $item_type,
'title' => (string) ($item['title'] ?? ''),
'x' => (int) ($item['x'] ?? 0),
'y' => (int) ($item['y'] ?? 0),
'w' => (int) ($item['w'] ?? 4),
'h' => (int) ($item['h'] ?? 4),
'settings' => $settings
];
}
}
// Merge CPT canvas blocks into runtime layout so Gutenberg-edited blocks appear in canvas mode.
if (class_exists('\\SystemDeck\\Core\\Services\\CanvasRepository')) {
$canvas_payload = \SystemDeck\Core\Services\CanvasRepository::resolve_for_workspace((string) $ws_id, (int) get_current_user_id());
$canvas_items = \SystemDeck\Core\Services\CanvasRepository::extract_runtime_blocks_from_content((string) ($canvas_payload['content'] ?? ''));
$max_y = 0;
foreach ($layout_data as $existing_item) {
$max_y = max($max_y, (int) ($existing_item['y'] ?? 0) + (int) ($existing_item['h'] ?? 4));
}
$canvas_ids = array_keys($canvas_items);
foreach ($layout_data as $existing_id => $existing_item) {
$source = (string) (($existing_item['settings']['source'] ?? '') ?: '');
if ($source === 'canvas' && !in_array($existing_id, $canvas_ids, true)) {
unset($layout_data[$existing_id]);
}
}
foreach ($canvas_items as $canvas_id => $canvas_item) {
$canvas_widget_id = \SystemDeck\Core\Services\WidgetRuntimeBridge::sanitize_widget_id((string) (($canvas_item['settings']['widgetId'] ?? '')));
if ($canvas_widget_id !== '' && isset($hidden_lookup[$canvas_widget_id])) {
unset($layout_data[$canvas_id]);
continue;
}
if (isset($layout_data[$canvas_id])) {
$layout_data[$canvas_id]['type'] = (string) ($canvas_item['type'] ?? $layout_data[$canvas_id]['type']);
$layout_data[$canvas_id]['title'] = (string) ($canvas_item['title'] ?? $layout_data[$canvas_id]['title']);
$layout_data[$canvas_id]['settings'] = array_merge(
(array) ($layout_data[$canvas_id]['settings'] ?? []),
(array) ($canvas_item['settings'] ?? [])
);
continue;
}
$layout_data[$canvas_id] = [
'i' => $canvas_id,
'id' => $canvas_id,
'type' => (string) ($canvas_item['type'] ?? 'block_html'),
'title' => (string) ($canvas_item['title'] ?? 'Block'),
'x' => (int) ($canvas_item['x'] ?? 0),
'y' => (int) ($canvas_item['y'] ?? $max_y),
'w' => (int) ($canvas_item['w'] ?? 2),
'h' => (int) ($canvas_item['h'] ?? 1),
'settings' => (array) ($canvas_item['settings'] ?? ['source' => 'canvas']),
];
$max_y = max(
$max_y,
(int) ($layout_data[$canvas_id]['y'] ?? 0) + (int) ($layout_data[$canvas_id]['h'] ?? 1)
);
}
}
if (
!empty($ws_data['is_app_workspace']) &&
!empty($ws_data['app_id']) &&
class_exists('\\SystemDeck\\Core\\AppRuntime')
) {
$seed_widget_ids = \SystemDeck\Core\AppRuntime::get_seed_widget_ids((string) $ws_data['app_id']);
if (!empty($seed_widget_ids)) {
$max_y = 0;
$present_widget_ids = [];
foreach ($layout_data as $existing_item) {
$max_y = max($max_y, (int) ($existing_item['y'] ?? 0) + (int) ($existing_item['h'] ?? 4));
$existing_widget_id = \SystemDeck\Core\Services\WidgetRuntimeBridge::sanitize_widget_id((string) (($existing_item['settings']['widgetId'] ?? '') ?: ($existing_item['id'] ?? '')));
if ($existing_widget_id !== '') {
$present_widget_ids[$existing_widget_id] = true;
}
}
foreach ($seed_widget_ids as $index => $seed_widget_id) {
$seed_widget_id = \SystemDeck\Core\Services\WidgetRuntimeBridge::sanitize_widget_id((string) $seed_widget_id);
if ($seed_widget_id === '' || isset($present_widget_ids[$seed_widget_id])) {
continue;
}
$item_id = sprintf('sd_app_%s_%d', sanitize_title($seed_widget_id), $index + 1);
$layout_data[$item_id] = [
'i' => $item_id,
'id' => $item_id,
'type' => 'block_widget_placeholder',
'title' => '',
'x' => 0,
'y' => $max_y,
'w' => 4,
'h' => 8,
'settings' => [
'widgetId' => $seed_widget_id,
'source' => 'app_seed',
],
];
$present_widget_ids[$seed_widget_id] = true;
$max_y += 8;
}
}