-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcs-code-block.php
More file actions
4474 lines (4050 loc) · 214 KB
/
cs-code-block.php
File metadata and controls
4474 lines (4050 loc) · 214 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: CloudScale DevTools
* Plugin URI: https://andrewbaker.ninja
* Description: Developer toolkit with syntax-highlighted code blocks, SQL query tool, code migrator, site monitor, and login security (passkeys, TOTP, email 2FA, hide login URL).
* Version: 1.8.56
* Author: Andrew Baker
* Author URI: https://andrewbaker.ninja
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Requires at least: 6.0
* Requires PHP: 7.4
* Text Domain: cloudscale-devtools
*
* @package CloudScale_DevTools
* @since 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
require_once plugin_dir_path( __FILE__ ) . 'includes/class-cs-passkey.php';
// Enable DB query saving only when CS Monitor is active (avoids memory overhead when disabled).
if ( ! defined( 'SAVEQUERIES' ) && get_option( 'cs_devtools_perf_monitor_enabled', '1' ) !== '0' ) {
define( 'SAVEQUERIES', true );
}
/**
* CloudScale Code Block — main plugin class.
*
* Handles block registration, shortcode, admin tools, settings,
* the code block migration tool, and the SQL command tool.
*
* @package CloudScale_DevTools
* @since 1.0.0
*/
class CloudScale_DevTools {
const VERSION = '1.8.56';
const HLJS_VERSION = '11.11.1';
const HLJS_CDN = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/';
const TOOLS_SLUG = 'cloudscale-devtools';
const MIGRATE_NONCE = 'cs_devtools_code_migrate_action';
/**
* Returns the theme registry mapping slugs to CDN filenames and colour values.
*
* Each entry maps a slug to its dark and light CDN filenames,
* display label, and background colours for the wrapper/toolbar.
*
* @since 1.7.0
* @return array<string, array<string, string>>
*/
public static function get_theme_registry(): array {
return [
'atom-one' => [
'label' => 'Atom One',
'dark_css' => 'atom-one-dark',
'light_css' => 'atom-one-light',
'dark_bg' => '#282c34',
'dark_toolbar' => '#21252b',
'light_bg' => '#fafafa',
'light_toolbar'=> '#e8eaed',
],
'github' => [
'label' => 'GitHub',
'dark_css' => 'github-dark',
'light_css' => 'github',
'dark_bg' => '#24292e',
'dark_toolbar' => '#1f2428',
'light_bg' => '#fff',
'light_toolbar'=> '#f6f8fa',
],
'monokai' => [
'label' => 'Monokai',
'dark_css' => 'monokai',
'light_css' => 'atom-one-light',
'dark_bg' => '#272822',
'dark_toolbar' => '#1e1f1c',
'light_bg' => '#fafafa',
'light_toolbar'=> '#e8eaed',
],
'nord' => [
'label' => 'Nord',
'dark_css' => 'nord',
'light_css' => 'atom-one-light',
'dark_bg' => '#2e3440',
'dark_toolbar' => '#272c36',
'light_bg' => '#fafafa',
'light_toolbar'=> '#e8eaed',
],
'dracula' => [
'label' => 'Dracula',
'dark_css' => 'dracula',
'light_css' => 'atom-one-light',
'dark_bg' => '#282a36',
'dark_toolbar' => '#21222c',
'light_bg' => '#fafafa',
'light_toolbar'=> '#e8eaed',
],
'tokyo-night' => [
'label' => 'Tokyo Night',
'dark_css' => 'tokyo-night-dark',
'light_css' => 'tokyo-night-light',
'dark_bg' => '#1a1b26',
'dark_toolbar' => '#16161e',
'light_bg' => '#d5d6db',
'light_toolbar'=> '#c8c9ce',
],
'vs2015' => [
'label' => 'VS 2015 / VS Code',
'dark_css' => 'vs2015',
'light_css' => 'vs',
'dark_bg' => '#1e1e1e',
'dark_toolbar' => '#181818',
'light_bg' => '#fff',
'light_toolbar'=> '#f3f3f3',
],
'stackoverflow' => [
'label' => 'Stack Overflow',
'dark_css' => 'stackoverflow-dark',
'light_css' => 'stackoverflow-light',
'dark_bg' => '#1c1b1b',
'dark_toolbar' => '#151414',
'light_bg' => '#f6f6f6',
'light_toolbar'=> '#e8e8e8',
],
'night-owl' => [
'label' => 'Night Owl',
'dark_css' => 'night-owl',
'light_css' => 'atom-one-light',
'dark_bg' => '#011627',
'dark_toolbar' => '#001122',
'light_bg' => '#fafafa',
'light_toolbar'=> '#e8eaed',
],
'gruvbox' => [
'label' => 'Gruvbox',
'dark_css' => 'base16/gruvbox-dark-hard',
'light_css' => 'base16/gruvbox-light-hard',
'dark_bg' => '#1d2021',
'dark_toolbar' => '#171819',
'light_bg' => '#f9f5d7',
'light_toolbar'=> '#ece8c8',
],
'solarized' => [
'label' => 'Solarized',
'dark_css' => 'base16/solarized-dark',
'light_css' => 'base16/solarized-light',
'dark_bg' => '#002b36',
'dark_toolbar' => '#002530',
'light_bg' => '#fdf6e3',
'light_toolbar'=> '#eee8d5',
],
'panda' => [
'label' => 'Panda',
'dark_css' => 'panda-syntax-dark',
'light_css' => 'panda-syntax-light',
'dark_bg' => '#292a2b',
'dark_toolbar' => '#222324',
'light_bg' => '#e6e6e6',
'light_toolbar'=> '#d9d9d9',
],
'tomorrow' => [
'label' => 'Tomorrow Night',
'dark_css' => 'tomorrow-night-bright',
'light_css' => 'atom-one-light',
'dark_bg' => '#000',
'dark_toolbar' => '#0a0a0a',
'light_bg' => '#fafafa',
'light_toolbar'=> '#e8eaed',
],
'shades-of-purple' => [
'label' => 'Shades of Purple',
'dark_css' => 'shades-of-purple',
'light_css' => 'atom-one-light',
'dark_bg' => '#2d2b55',
'dark_toolbar' => '#252347',
'light_bg' => '#fafafa',
'light_toolbar'=> '#e8eaed',
],
];
}
private static $instance_count = 0;
private static $assets_enqueued = false;
// Performance monitor — static storage.
/** @var array HTTP calls captured during this request. */
private static $perf_http_calls = [];
/** @var float|null Microtime when last HTTP request started. */
private static $perf_http_timer = null;
/** @var array PHP errors captured during this request. */
private static $perf_php_errors = [];
/** @var array|null Active plugin prefix → slug map cache. */
private static $perf_plugin_map = null;
/** @var callable|null Previous PHP error handler to chain into. */
private static $perf_prev_error_handler = null;
/** @var string Template filename captured via template_include filter. */
private static $perf_template = '';
/** @var array Hook fire stats: [ hook => ['count'=>int,'total_ms'=>float,'max_ms'=>float] ] */
private static $perf_hooks = [];
/** @var float|null Timestamp of last hook fire (ms). */
private static $perf_hook_last_ms = null;
/** @var string|null Name of last hook fired. */
private static $perf_hook_last_name = null;
/** @var array Transient stats: [ key => [ gets, hits, sets, deletes ] ] */
private static $perf_transients = [];
/** @var array Template hierarchy candidates captured via *_template_hierarchy filters. */
private static $perf_template_hierarchy = [];
/**
* Registers all plugin hooks.
*
* @since 1.0.0
* @return void
*/
public static function init() {
self::maybe_migrate_prefix();
add_action( 'init', [ __CLASS__, 'load_textdomain' ] );
add_action( 'init', [ __CLASS__, 'register_block' ] );
add_action( 'init', [ __CLASS__, 'register_shortcode' ] );
add_action( 'enqueue_block_editor_assets', [ __CLASS__, 'enqueue_convert_script' ] );
add_action( 'admin_menu', [ __CLASS__, 'add_tools_page' ] );
add_action( 'admin_init', [ __CLASS__, 'register_settings' ] );
add_action( 'admin_init', [ __CLASS__, 'redirect_legacy_slug' ] );
add_action( 'init', [ __CLASS__, 'redirect_legacy_help_url' ], 1 );
add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_admin_assets' ] );
// Migration AJAX
add_action( 'wp_ajax_cs_devtools_migrate_scan', [ __CLASS__, 'ajax_scan' ] );
add_action( 'wp_ajax_cs_devtools_migrate_preview', [ __CLASS__, 'ajax_preview' ] );
add_action( 'wp_ajax_cs_devtools_migrate_single', [ __CLASS__, 'ajax_migrate_single' ] );
add_action( 'wp_ajax_cs_devtools_migrate_all', [ __CLASS__, 'ajax_migrate_all' ] );
// SQL AJAX
add_action( 'wp_ajax_cs_devtools_sql_run', [ __CLASS__, 'ajax_sql_run' ] );
// Settings AJAX
add_action( 'wp_ajax_cs_devtools_save_theme_setting', [ __CLASS__, 'ajax_save_theme_setting' ] );
// Login security AJAX
add_action( 'wp_ajax_cs_devtools_login_save', [ __CLASS__, 'ajax_login_save' ] );
add_action( 'wp_ajax_cs_devtools_totp_setup_start', [ __CLASS__, 'ajax_totp_setup_start' ] );
add_action( 'wp_ajax_cs_devtools_totp_setup_verify', [ __CLASS__, 'ajax_totp_setup_verify' ] );
add_action( 'wp_ajax_cs_devtools_2fa_disable', [ __CLASS__, 'ajax_2fa_disable' ] );
add_action( 'wp_ajax_cs_devtools_email_2fa_enable', [ __CLASS__, 'ajax_email_2fa_enable' ] );
add_action( 'admin_init', [ __CLASS__, 'email_2fa_confirm_check' ] );
add_action( 'after_password_reset', [ __CLASS__, 'on_password_reset' ], 10, 1 );
add_action( 'profile_update', [ __CLASS__, 'on_profile_update' ], 10, 2 );
CS_DevTools_Passkey::register_hooks();
// Login security — URL intercept / 2FA flow (early, priority 1 on init).
add_action( 'init', [ __CLASS__, 'login_serve_custom_slug' ], 1 );
add_action( 'login_init', [ __CLASS__, 'login_block_direct_access' ], 1 );
add_action( 'login_init', [ __CLASS__, 'login_2fa_handle' ] );
add_filter( 'authenticate', [ __CLASS__, 'login_2fa_intercept' ], 100, 3 );
add_filter( 'login_url', [ __CLASS__, 'login_custom_url' ], 10, 3 );
add_filter( 'logout_url', [ __CLASS__, 'login_custom_logout_url' ], 10, 2 );
add_filter( 'lostpassword_url', [ __CLASS__, 'login_custom_lostpassword_url' ], 10, 2 );
add_filter( 'network_site_url', [ __CLASS__, 'login_custom_network_url' ], 10, 3 );
add_filter( 'site_url', [ __CLASS__, 'login_custom_site_url' ], 10, 4 );
// Performance monitor — EXPLAIN endpoint.
add_action( 'wp_ajax_cs_devtools_perf_explain', [ __CLASS__, 'ajax_perf_explain' ] );
add_action( 'wp_ajax_cs_devtools_perf_debug_toggle', [ __CLASS__, 'ajax_perf_debug_toggle' ] );
// Performance monitor — only register data-collection hooks when the monitor is enabled.
// This prevents SAVEQUERIES-scale memory accumulation on every request when disabled.
if ( get_option( 'cs_devtools_perf_monitor_enabled', '1' ) !== '0' ) {
add_filter( 'pre_http_request', [ __CLASS__, 'perf_http_before' ], 10, 3 );
add_action( 'http_api_debug', [ __CLASS__, 'perf_http_after' ], 10, 5 );
// If the user enabled debug logging via the panel, activate PHP error logging
// using ini_set — this works regardless of WP_DEBUG in wp-config.php and
// survives Docker container rebuilds because the setting lives in the DB.
if ( get_option( 'cs_devtools_perf_debug_logging', false ) ) {
// phpcs:ignore WordPress.PHP.IniSet.Risky
@ini_set( 'log_errors', '1' );
// phpcs:ignore WordPress.PHP.IniSet.Risky
@ini_set( 'error_log', WP_CONTENT_DIR . '/debug.log' );
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.prevent_path_disclosure_error_reporting
error_reporting( E_ALL );
}
// Register error handler late (priority 9999 on plugins_loaded) so we sit
// on top of any handler registered by other plugins (e.g. Query Monitor).
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler
add_action( 'plugins_loaded', function () {
self::$perf_prev_error_handler = set_error_handler(
[ __CLASS__, 'perf_error_handler' ],
E_WARNING | E_NOTICE | E_DEPRECATED | E_USER_WARNING | E_USER_NOTICE | E_USER_DEPRECATED
);
}, 9999 );
// Performance monitor — panel rendering (admin pages).
add_action( 'admin_enqueue_scripts', [ __CLASS__, 'perf_enqueue' ] );
add_action( 'admin_footer', [ __CLASS__, 'perf_output_panel' ], 9999 );
// Performance monitor — panel rendering (frontend, admin users only).
add_action( 'wp_enqueue_scripts', [ __CLASS__, 'perf_frontend_enqueue' ] );
add_action( 'wp_footer', [ __CLASS__, 'perf_output_panel' ], 9999 );
// Capture the active template filename for the page-context strip.
add_filter( 'template_include', [ __CLASS__, 'perf_capture_template' ], 9999 );
// Hook timing tracker — fires on every action/filter.
add_action( 'all', [ __CLASS__, 'perf_hook_tracker' ] );
// Transient + template hierarchy observer (single all-hook for both).
add_action( 'all', [ __CLASS__, 'perf_misc_tracker' ] );
add_action( 'setted_transient', [ __CLASS__, 'perf_transient_set' ] );
add_action( 'setted_site_transient', [ __CLASS__, 'perf_transient_set' ] );
add_action( 'deleted_transient', [ __CLASS__, 'perf_transient_delete' ] );
add_action( 'deleted_site_transient', [ __CLASS__, 'perf_transient_delete' ] );
// Scripts & styles — collect at footer time (after everything is enqueued).
add_action( 'admin_footer', [ __CLASS__, 'perf_capture_assets' ], 1 );
add_action( 'wp_footer', [ __CLASS__, 'perf_capture_assets' ], 1 );
}
}
/* ==================================================================
0. TEXT DOMAIN
================================================================== */
/**
* Loads the plugin text domain for translations.
*
* @since 1.0.0
* @return void
*/
public static function load_textdomain(): void {
load_plugin_textdomain(
'cloudscale-devtools',
false,
dirname( plugin_basename( __FILE__ ) ) . '/languages'
);
}
/* ==================================================================
1. BLOCK REGISTRATION
================================================================== */
/**
* Registers the block type and all its scripts and stylesheets.
*
* @since 1.0.0
* @return void
*/
public static function register_block() {
$cdn = self::HLJS_CDN . self::HLJS_VERSION;
wp_register_script(
'hljs-core',
$cdn . '/highlight.min.js',
[],
self::HLJS_VERSION,
true
);
// Register both theme stylesheets from the selected pair
$pair_slug = get_option( 'cs_devtools_code_theme_pair', 'atom-one' );
$registry = self::get_theme_registry();
$pair = isset( $registry[ $pair_slug ] ) ? $registry[ $pair_slug ] : $registry['atom-one'];
wp_register_style(
'hljs-theme-dark',
$cdn . '/styles/' . $pair['dark_css'] . '.min.css',
[],
self::HLJS_VERSION
);
wp_register_style(
'hljs-theme-light',
$cdn . '/styles/' . $pair['light_css'] . '.min.css',
[],
self::HLJS_VERSION
);
wp_register_style(
'cs-code-block-frontend',
plugins_url( 'assets/cs-code-block.css', __FILE__ ),
[ 'hljs-theme-dark', 'hljs-theme-light' ],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-code-block.css' )
);
wp_register_script(
'cs-code-block-frontend',
plugins_url( 'assets/cs-code-block.js', __FILE__ ),
[ 'hljs-core' ],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-code-block.js' ),
true
);
wp_register_style(
'cs-code-block-editor',
plugins_url( 'assets/cs-code-block-editor.css', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-code-block-editor.css' )
);
wp_register_script(
'cloudscale-code-block-editor-script',
plugins_url( 'blocks/code/editor.js', __FILE__ ),
[ 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-data', 'wp-hooks' ],
filemtime( plugin_dir_path( __FILE__ ) . 'blocks/code/editor.js' ),
true
);
register_block_type(
__DIR__ . '/blocks/code',
[
'render_callback' => [ __CLASS__, 'render_block' ],
'editor_script' => 'cloudscale-code-block-editor-script',
]
);
}
/* ==================================================================
1b. CONVERT SCRIPT
================================================================== */
/**
* Enqueues the block editor auto-convert script and attaches the toast inline style.
*
* @since 1.5.0
* @return void
*/
public static function enqueue_convert_script() {
wp_enqueue_script(
'cs-code-block-convert',
plugins_url( 'assets/cs-convert.js', __FILE__ ),
[ 'wp-blocks', 'wp-data' ],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-convert.js' ),
true
);
wp_add_inline_style( 'cs-code-block-editor', self::get_convert_toast_css() );
}
/**
* Returns the CSS string for the block editor convert-all toast notification.
*
* @since 1.7.17
* @return string
*/
private static function get_convert_toast_css(): string {
return '#cs-convert-all-toast{'
. 'position:fixed;bottom:24px;right:24px;z-index:999999;'
. 'background:linear-gradient(135deg,#1e3a5f 0%,#0d9488 100%);'
. 'color:#fff;padding:16px 20px;border-radius:10px;'
. 'box-shadow:0 8px 32px rgba(0,0,0,0.3);'
. 'display:flex;align-items:center;gap:16px;'
. 'font-size:14px;font-weight:500;'
. 'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;'
. 'animation:cs-toast-in 0.3s ease-out;'
. '}'
. '#cs-convert-all-toast button{'
. 'background:#fff;color:#1e3a5f;font-weight:700;border-radius:6px;'
. 'padding:10px 24px;font-size:14px;border:none;white-space:nowrap;'
. 'cursor:pointer;box-shadow:0 2px 8px rgba(0,0,0,0.15);font-family:inherit;'
. '}'
. '#cs-convert-all-toast button:hover{background:#f0fdf4;}'
. '@keyframes cs-toast-in{'
. 'from{opacity:0;transform:translateY(20px);}'
. 'to{opacity:1;transform:translateY(0);}'
. '}';
}
/* ==================================================================
2. RENDER (shared by block + shortcode)
================================================================== */
/**
* Renders a code block on the frontend.
*
* @since 1.0.0
* @param array $attributes Block attributes.
* @param string $block_content Existing block content (unused).
* @return string HTML output.
*/
public static function render_block( $attributes, $block_content = '' ) {
self::maybe_enqueue_frontend();
self::$instance_count++;
$id = 'cs-code-' . self::$instance_count;
$code = isset( $attributes['content'] ) ? $attributes['content'] : '';
$lang = isset( $attributes['language'] ) ? $attributes['language'] : '';
$title = isset( $attributes['title'] ) ? $attributes['title'] : '';
$theme = isset( $attributes['theme'] ) ? $attributes['theme'] : '';
return self::build_html( $id, $code, $lang, $title, $theme );
}
/**
* Builds the full HTML markup for a code block.
*
* @since 1.0.0
* @param string $id Unique HTML element ID.
* @param string $code Code content to display.
* @param string $lang Language identifier for highlight.js, or empty for auto-detect.
* @param string $title Optional filename or title label.
* @param string $theme Per-block colour-theme override slug, or empty for site default.
* @return string HTML markup.
*/
private static function build_html( $id, $code, $lang, $title, $theme ) {
$lang_class = $lang ? 'language-' . esc_attr( $lang ) : '';
$cloudscale_link = '<a class="cs-code-brand" href="https://andrewbaker.ninja/2026/02/27/building-a-better-code-block-for-wordpress-cloudscale-code-block-plugin/" target="_blank" rel="noopener noreferrer"><span class="cs-brand-bolt">⚡</span> Powered by CloudScale</a>';
$title_html = '';
if ( $title ) {
$title_html = '<div class="cs-code-title">' . esc_html( $title ) . '</div>';
}
ob_start();
?>
<div class="cs-code-wrapper" id="<?php echo esc_attr( $id ); ?>"<?php if ( $theme ) { echo ' data-theme="' . esc_attr( $theme ) . '"'; } ?>>
<div class="cs-code-toolbar">
<?php echo wp_kses_post( $cloudscale_link ); ?>
<?php echo wp_kses_post( $title_html ); ?>
<div class="cs-code-actions">
<span class="cs-code-lang-badge"></span>
<button class="cs-code-lines-toggle" title="<?php esc_attr_e( 'Toggle line numbers', 'cloudscale-devtools' ); ?>" aria-label="<?php esc_attr_e( 'Toggle line numbers', 'cloudscale-devtools' ); ?>">
<svg class="cs-icon-lines" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><text x="4" y="7" font-size="7" fill="currentColor" stroke="none" font-family="monospace">1</text><text x="4" y="13" font-size="7" fill="currentColor" stroke="none" font-family="monospace">2</text><text x="4" y="19" font-size="7" fill="currentColor" stroke="none" font-family="monospace">3</text></svg>
</button>
<button class="cs-code-theme-toggle" title="<?php esc_attr_e( 'Toggle light/dark mode', 'cloudscale-devtools' ); ?>" aria-label="<?php esc_attr_e( 'Toggle theme', 'cloudscale-devtools' ); ?>">
<svg class="cs-icon-sun" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
<svg class="cs-icon-moon" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
</button>
<button class="cs-code-copy" title="<?php esc_attr_e( 'Copy to clipboard', 'cloudscale-devtools' ); ?>" aria-label="<?php esc_attr_e( 'Copy code', 'cloudscale-devtools' ); ?>">
<svg class="cs-icon-copy" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<svg class="cs-icon-check" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
<span class="cs-copy-label"><?php esc_html_e( 'Copy', 'cloudscale-devtools' ); ?></span>
</button>
</div>
</div>
<div class="cs-code-body">
<pre><code class="<?php echo esc_attr( $lang_class ); ?>"><?php echo str_replace( [ '[', ']' ], [ '[', ']' ], esc_html( $code ) ); ?></code></pre>
</div>
</div>
<?php
return ob_get_clean();
}
/**
* Enqueues frontend scripts and styles on first block render, then localises config.
*
* @since 1.0.0
* @return void
*/
private static function maybe_enqueue_frontend() {
if ( self::$assets_enqueued ) {
return;
}
self::$assets_enqueued = true;
wp_enqueue_style( 'hljs-theme-dark' );
wp_enqueue_style( 'hljs-theme-light' );
wp_enqueue_style( 'cs-code-block-frontend' );
wp_enqueue_script( 'hljs-core' );
wp_enqueue_script( 'cs-code-block-frontend' );
$default_theme = get_option( 'cs_devtools_code_default_theme', 'dark' );
$pair_slug = get_option( 'cs_devtools_code_theme_pair', 'atom-one' );
$registry = self::get_theme_registry();
$pair = isset( $registry[ $pair_slug ] ) ? $registry[ $pair_slug ] : $registry['atom-one'];
wp_localize_script( 'cs-code-block-frontend', 'csDevtoolsCodeConfig', [
'defaultTheme' => $default_theme,
'themePair' => $pair_slug,
'darkBg' => $pair['dark_bg'],
'darkToolbar' => $pair['dark_toolbar'],
'lightBg' => $pair['light_bg'],
'lightToolbar' => $pair['light_toolbar'],
] );
}
/* ==================================================================
3. SHORTCODE [cs_devtools_code]
================================================================== */
/**
* Registers the [cs_devtools_code] shortcode.
*
* @since 1.0.0
* @return void
*/
public static function register_shortcode() {
add_shortcode( 'cs_devtools_code', [ __CLASS__, 'render_shortcode' ] );
}
/**
* Renders the [cs_devtools_code] shortcode.
*
* @since 1.0.0
* @param array $atts Shortcode attributes.
* @param string|null $content Shortcode content.
* @return string HTML output.
*/
public static function render_shortcode( $atts, $content = null ) {
$atts = shortcode_atts( [
'lang' => '',
'theme' => '',
'title' => '',
], $atts, 'cs_devtools_code' );
$code = self::decode_shortcode_content( $content );
return self::render_block( [
'content' => $code,
'language' => $atts['lang'],
'title' => $atts['title'],
'theme' => $atts['theme'],
] );
}
/**
* Decodes WordPress-mangled HTML entities and line breaks from shortcode content.
*
* @since 1.0.0
* @param string|null $content Raw shortcode content.
* @return string Plain-text code with entities decoded.
*/
private static function decode_shortcode_content( $content ) {
$content = preg_replace( '#^<p>|</p>$#i', '', trim( $content ) );
$content = str_replace(
[ '<br />', '<br/>', '<br>', '“', '”', '‘', '’', ' ', '&' ],
[ "\n", "\n", "\n", '"', '"', "'", "'", ' ', '&' ],
$content
);
$content = html_entity_decode( $content, ENT_QUOTES, 'UTF-8' );
return trim( $content );
}
/* ==================================================================
4. SETTINGS
================================================================== */
/**
* Registers plugin settings with sanitise callbacks.
*
* @since 1.0.0
* @return void
*/
public static function register_settings() {
register_setting( 'cs_devtools_code_settings', 'cs_devtools_code_default_theme', [
'type' => 'string',
'sanitize_callback' => function ( $val ) {
return in_array( $val, [ 'dark', 'light' ] ) ? $val : 'dark';
},
'default' => 'dark',
] );
$valid_themes = array_keys( self::get_theme_registry() );
register_setting( 'cs_devtools_code_settings', 'cs_devtools_code_theme_pair', [
'type' => 'string',
'sanitize_callback' => function ( $val ) use ( $valid_themes ) {
return in_array( $val, $valid_themes, true ) ? $val : 'atom-one';
},
'default' => 'atom-one',
] );
register_setting( 'cs_devtools_code_settings', 'cs_devtools_perf_monitor_enabled', [
'type' => 'string',
'sanitize_callback' => function ( $val ) {
return '0' === $val ? '0' : '1';
},
'default' => '1',
] );
// Login security settings
register_setting( 'cs_devtools_login_settings', 'cs_devtools_login_hide_enabled', [
'type' => 'string',
'sanitize_callback' => function ( $v ) { return '1' === $v ? '1' : '0'; },
'default' => '0',
] );
register_setting( 'cs_devtools_login_settings', 'cs_devtools_login_slug', [
'type' => 'string',
'sanitize_callback' => function ( $v ) {
$slug = sanitize_title( $v );
// Disallow WP reserved slugs
$reserved = [ 'wp-login', 'wp-admin', 'login', 'admin', 'dashboard' ];
return in_array( $slug, $reserved, true ) ? '' : $slug;
},
'default' => '',
] );
register_setting( 'cs_devtools_login_settings', 'cs_devtools_2fa_method', [
'type' => 'string',
'sanitize_callback' => function ( $v ) {
return in_array( $v, [ 'off', 'email', 'totp' ], true ) ? $v : 'off';
},
'default' => 'off',
] );
register_setting( 'cs_devtools_login_settings', 'cs_devtools_2fa_force_admins', [
'type' => 'string',
'sanitize_callback' => function ( $v ) { return '1' === $v ? '1' : '0'; },
'default' => '0',
] );
}
/* ==================================================================
5. COMBINED TOOLS PAGE (Code Block Migrator + SQL Command)
================================================================== */
/**
* Adds the combined Tools page to the WordPress admin menu.
*
* @since 1.6.0
* @return void
*/
/**
* Redirects legacy ?page=cloudscale-code-sql URLs to the new slug.
*
* @since 1.8.56
* @return void
*/
/**
* Redirects the old help page URL to the current one.
*
* @since 1.8.56
* @return void
*/
public static function redirect_legacy_help_url() {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$uri = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '';
if ( strpos( $uri, 'code-block-help' ) !== false ) {
wp_redirect( home_url( '/wordpress-plugin-help/cloudscale-devtools-help/' ), 301 );
exit;
}
}
public static function redirect_legacy_slug() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['page'] ) && $_GET['page'] === 'cloudscale-code-sql' ) {
$args = $_GET;
$args['page'] = self::TOOLS_SLUG;
wp_safe_redirect( add_query_arg( $args, admin_url( 'tools.php' ) ) );
exit;
}
}
public static function add_tools_page() {
add_management_page(
'CloudScale DevTools',
'🌩️ CloudScale DevTools',
'manage_options',
self::TOOLS_SLUG,
[ __CLASS__, 'render_tools_page' ]
);
}
/**
* Conditionally enqueues admin assets on the plugin tools page only.
*
* @since 1.6.0
* @param string $hook Current admin page hook suffix.
* @return void
*/
public static function enqueue_admin_assets( $hook ) {
if ( $hook !== 'tools_page_' . self::TOOLS_SLUG ) {
return;
}
// Tabs CSS
wp_enqueue_style(
'cs-admin-tabs',
plugins_url( 'assets/cs-admin-tabs.css', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-admin-tabs.css' )
);
// Migrate CSS + JS
wp_enqueue_style(
'cs-code-migrate',
plugins_url( 'assets/cs-code-migrate.css', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-code-migrate.css' )
);
wp_enqueue_script(
'cs-code-migrate',
plugins_url( 'assets/cs-code-migrate.js', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-code-migrate.js' ),
true
);
wp_localize_script( 'cs-code-migrate', 'csDevtoolsMigrate', [
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( self::MIGRATE_NONCE ),
] );
// Settings save JS
wp_enqueue_script(
'cs-admin-settings',
plugins_url( 'assets/cs-admin-settings.js', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-admin-settings.js' ),
true
);
wp_localize_script( 'cs-admin-settings', 'csDevtoolsAdminSettings', [
'nonce' => wp_create_nonce( 'cs_devtools_code_settings_inline' ),
] );
// SQL editor JS
wp_enqueue_script(
'cs-sql-editor',
plugins_url( 'assets/cs-sql-editor.js', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-sql-editor.js' ),
true
);
wp_localize_script( 'cs-sql-editor', 'csDevtoolsSqlEditor', [
'nonce' => wp_create_nonce( 'cs_devtools_sql_nonce' ),
] );
// Login security JS (only loaded on the login tab)
$active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'migrate'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( $active_tab === 'login' ) {
wp_enqueue_script(
'cs-qrcode',
plugins_url( 'assets/qrcode.min.js', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/qrcode.min.js' ),
true
);
wp_enqueue_script(
'cs-login',
plugins_url( 'assets/cs-login.js', __FILE__ ),
[ 'cs-qrcode' ],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-login.js' ),
true
);
wp_localize_script( 'cs-login', 'csDevtoolsLogin', [
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'cs_devtools_login_nonce' ),
'currentUser' => get_current_user_id(),
] );
wp_enqueue_script(
'cs-passkey',
plugins_url( 'assets/cs-passkey.js', __FILE__ ),
[ 'cs-login' ],
filemtime( plugin_dir_path( __FILE__ ) . 'assets/cs-passkey.js' ),
true
);
}
}
/**
* Renders the combined Code Migrator and SQL Command tools page.
*
* @since 1.6.0
* @return void
*/
public static function render_tools_page() {
$active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'migrate';
$base_url = admin_url( 'tools.php?page=' . self::TOOLS_SLUG );
?>
<div class="wrap">
<div id="cs-app">
<!-- Banner -->
<div id="cs-banner">
<div>
<div id="cs-banner-title">⚡ CloudScale DevTools</div>
<div id="cs-banner-sub"><?php esc_html_e( 'Code blocks, SQL tools, code migrator, site monitor & login security', 'cloudscale-devtools' ); ?> · v<?php echo esc_html( self::VERSION ); ?></div>
</div>
<div id="cs-banner-right">
<span class="cs-badge cs-badge-green">✅ <?php esc_html_e( 'Totally Free', 'cloudscale-devtools' ); ?></span>
<a href="https://andrewbaker.ninja" target="_blank" rel="noopener noreferrer" class="cs-badge cs-badge-orange" style="text-decoration:none">andrewbaker.ninja</a>
<a href="https://andrewbaker.ninja/wordpress-plugin-help/cloudscale-devtools-help/" target="_blank" rel="noopener noreferrer" class="cs-badge cs-badge-help" style="text-decoration:none">❓ <?php esc_html_e( 'Help', 'cloudscale-devtools' ); ?></a>
</div>
</div>
<!-- Tab bar -->
<div id="cs-tab-bar">
<a href="<?php echo esc_url( $base_url . '&tab=migrate' ); ?>"
class="cs-tab <?php echo $active_tab === 'migrate' ? 'active' : ''; ?>">
🔄 <?php esc_html_e( 'Code Migrator', 'cloudscale-devtools' ); ?>
</a>
<a href="<?php echo esc_url( $base_url . '&tab=sql' ); ?>"
class="cs-tab <?php echo $active_tab === 'sql' ? 'active' : ''; ?>">
🗄️ <?php esc_html_e( 'SQL Command', 'cloudscale-devtools' ); ?>
</a>
<a href="<?php echo esc_url( $base_url . '&tab=login' ); ?>"
class="cs-tab <?php echo $active_tab === 'login' ? 'active' : ''; ?>">
🔐 <?php esc_html_e( 'Login Security', 'cloudscale-devtools' ); ?>
</a>
</div>
<?php if ( $active_tab === 'migrate' ) : ?>
<div class="cs-tab-content active">
<?php self::render_settings_panel(); ?>
<?php self::render_migrate_panel(); ?>
</div>
<?php elseif ( $active_tab === 'sql' ) : ?>
<div class="cs-tab-content active">
<?php self::render_sql_panel(); ?>
</div>
<?php elseif ( $active_tab === 'login' ) : ?>
<div class="cs-tab-content active">
<?php self::render_login_panel(); ?>
</div>
<?php endif; ?>
</div>
</div>
<?php
}
/* ==================================================================
5a. Settings panel (inline on Migrator tab)
================================================================== */
/**
* Renders the Code Block Settings panel (colour theme and default mode selectors).
*
* @since 1.6.0
* @return void
*/
/**
* Renders an "Explain…" button and its associated modal for a panel header.
*
* @param string $id Unique slug used to build element IDs.
* @param string $title Modal title.
* @param array $items Array of ['name'=>'', 'rec'=>'', 'desc'=>''] entries.
*/
private static function render_explain_btn( string $id, string $title, array $items ): void {
$btn_id = 'cs-explain-btn-' . $id;
$modal_id = 'cs-explain-modal-' . $id;
?>
<button type="button" id="<?php echo esc_attr( $btn_id ); ?>"
onclick="document.getElementById('<?php echo esc_attr( $modal_id ); ?>').style.display='flex'"
style="background:rgba(0,0,0,0.28)!important;border:1px solid rgba(255,255,255,0.55)!important;border-radius:5px!important;color:#fff!important;font-size:12px!important;font-weight:700!important;padding:5px 14px!important;cursor:pointer!important;margin-left:auto!important;flex-shrink:0!important;display:block!important;box-shadow:none!important;text-shadow:0 1px 2px rgba(0,0,0,0.4)!important;text-transform:none!important;letter-spacing:normal!important;line-height:1.4!important">
Explain…
</button>
<div id="<?php echo esc_attr( $modal_id ); ?>"
style="display:none;position:fixed;inset:0;z-index:100002;background:rgba(0,0,0,0.55);align-items:center;justify-content:center;padding:16px;text-transform:none;letter-spacing:normal;font-weight:normal"
onclick="if(event.target===this)this.style.display='none'">
<div style="background:#fff;border-radius:10px;max-width:600px;width:100%;max-height:88vh;overflow-y:auto;box-shadow:0 8px 32px rgba(0,0,0,0.25)">
<div style="padding:18px 22px 12px;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;gap:10px">
<strong style="font-size:15px;color:#111"><?php echo esc_html( $title ); ?></strong>
<button type="button"
onclick="document.getElementById('<?php echo esc_attr( $modal_id ); ?>').style.display='none'"
style="margin-left:auto;background:none;border:none;font-size:20px;cursor:pointer;color:#888;line-height:1;padding:0">×</button>
</div>
<div style="padding:16px 22px 20px">
<?php foreach ( $items as $item ) :
$rec = $item['rec'];
$is_on = str_contains( $rec, 'Recommended' );
$is_opt = str_contains( $rec, 'Optional' );
$bg = $is_on ? '#edfaef' : ( $is_opt ? '#f6f7f7' : '#f0f6fc' );
$col = $is_on ? '#1a7a34' : ( $is_opt ? '#50575e' : '#1a4a7a' );
$bdr = $is_on ? '#1a7a34' : ( $is_opt ? '#c3c4c7' : '#2271b1' );
?>
<div style="border:1px solid #e0e0e0;border-radius:6px;padding:12px 14px;margin-bottom:10px">
<div style="display:flex;align-items:center;gap:10px;margin-bottom:5px;flex-wrap:wrap">
<strong style="font-size:13px"><?php echo esc_html( $item['name'] ); ?></strong>
<span style="background:<?php echo esc_attr( $bg ); ?>;color:<?php echo esc_attr( $col ); ?>;border:1px solid <?php echo esc_attr( $bdr ); ?>;border-radius:4px;font-size:11px;font-weight:600;padding:1px 8px;white-space:nowrap"><?php echo esc_html( $rec ); ?></span>
</div>
<p style="margin:0;color:#50575e;font-size:12px;line-height:1.5;white-space:pre-line"><?php echo esc_html( $item['desc'] ); ?></p>
</div>
<?php endforeach; ?>
</div>
<div style="padding:10px 22px 16px;border-top:1px solid #e5e7eb;text-align:right">
<button type="button"
onclick="document.getElementById('<?php echo esc_attr( $modal_id ); ?>').style.display='none'"
style="background:#f3f4f6;border:1px solid #d1d5db;border-radius:5px;padding:6px 18px;font-size:12px;font-weight:600;cursor:pointer;color:#374151">
<?php esc_html_e( 'Got it', 'cloudscale-devtools' ); ?>
</button>
</div>
</div>
</div>
<?php
}
private static function render_settings_panel() {
$theme = get_option( 'cs_devtools_code_default_theme', 'dark' );
$pair_slug = get_option( 'cs_devtools_code_theme_pair', 'atom-one' );
$perf_on = get_option( 'cs_devtools_perf_monitor_enabled', '1' ) !== '0';
$registry = self::get_theme_registry();
?>
<div class="cs-panel" id="cs-panel-code-settings">
<div class="cs-section-header cs-section-header-teal">
<span>🎨 CODE BLOCK SETTINGS</span>
<?php self::render_explain_btn( 'code-settings', 'Code Block Settings', [
[ 'name' => 'Theme Pair', 'rec' => 'Recommended', 'desc' => 'Choose a light/dark colour-scheme pair for syntax-highlighted code blocks. The pair is applied automatically based on the visitor\'s OS colour preference.' ],
[ 'name' => 'Default Mode', 'rec' => 'Optional', 'desc' => 'Force all code blocks to always use light or dark mode, ignoring the visitor\'s system preference. Leave unset to follow the OS setting.' ],
[ 'name' => 'Performance Monitor', 'rec' => 'Optional', 'desc' => 'Enables the CS Monitor DevTools panel, which tracks database queries, HTTP requests, and PHP errors on every page load. Keep disabled in production unless actively debugging.' ],
] ); ?>
</div>
<div class="cs-panel-body">
<div class="cs-field-row">
<div class="cs-field">
<label class="cs-label" for="cs-settings-pair"><?php esc_html_e( 'Color Theme:', 'cloudscale-devtools' ); ?></label>
<select id="cs-settings-pair" name="cs_devtools_code_theme_pair" class="cs-input">
<?php foreach ( $registry as $slug => $info ) : ?>
<option value="<?php echo esc_attr( $slug ); ?>" <?php selected( $pair_slug, $slug ); ?>>
<?php echo esc_html( $info['label'] ); ?>
</option>