-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathm.php
More file actions
2029 lines (1884 loc) · 94.6 KB
/
Copy pathm.php
File metadata and controls
2029 lines (1884 loc) · 94.6 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
declare(strict_types=1);
// Let the PHP built-in server serve real static files (CSS, SVG, JS, etc.) directly.
// Returning false tells the server to fall back to its own static-file handler.
if (PHP_SAPI === 'cli-server') {
$reqPath = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '');
if ($reqPath !== '/' && is_file(__DIR__ . $reqPath)) {
return false;
}
}
session_start();
set_time_limit(0);
chdir(__DIR__);
// ── Token-only endpoints (called before command registry) ────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_GET['set_token'])) {
$t = trim($_POST['sonar_token'] ?? '');
if ($t !== '') {
$_SESSION['sonar_token'] = $t;
}
header('Content-Type: text/plain');
echo 'ok';
exit;
}
if (isset($_GET['clear_token'])) {
unset($_SESSION['sonar_token']);
header('Content-Type: text/plain');
echo 'ok';
exit;
}
if (isset($_GET['set_gh_token'])) {
$t = trim($_POST['github_token'] ?? '');
$_SESSION['github_token'] = $t;
header('Content-Type: text/plain');
echo 'ok';
exit;
}
}
// ── Vulnerability Log (SQLite) ────────────────────────────────────────────────
function sqliteAvailable(): bool
{
return in_array('sqlite', PDO::getAvailableDrivers(), true);
}
function getVulnDb(): PDO
{
static $db = null;
if ($db !== null) {
return $db;
}
$db = new PDO('sqlite:' . __DIR__ . '/snyk-resolved.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->exec(<<<SQL
CREATE TABLE IF NOT EXISTS vuln_resolved (
id INTEGER PRIMARY KEY AUTOINCREMENT,
snyk_id TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
severity TEXT NOT NULL DEFAULT 'MEDIUM',
category TEXT NOT NULL DEFAULT '',
file_path TEXT NOT NULL DEFAULT '',
reason TEXT NOT NULL DEFAULT '',
advisory_url TEXT NOT NULL DEFAULT '',
false_pos INTEGER NOT NULL DEFAULT 0,
ai_related INTEGER NOT NULL DEFAULT 0,
threat_vec TEXT NOT NULL DEFAULT '',
resolved_date TEXT NOT NULL DEFAULT (date('now')),
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
SQL);
// Seed from .snyk policy entries on first run
if ((int) $db->query('SELECT COUNT(*) FROM vuln_resolved')->fetchColumn() === 0) {
seedVulnDb($db);
}
return $db;
}
function seedVulnDb(PDO $db): void
{
// Pre-populated from .snyk ignore list — advisory_url uses CWE references
$seed = [
['SNYK-CODE-09045b5d-96a4-401a-87d4-95b6ac56af1a',
'Country code data flagged as hardcoded password',
'MEDIUM','False Positive — Hardcoded Secret',
'src/Invoice/Helpers/Country-list/ar/country.php',
'ISO 3166-1 alpha-2 country codes in legitimate reference data, not actual passwords',
'https://cwe.mitre.org/data/definitions/798.html', 1, 0, 'Hardcoded Secrets'],
['SNYK-CODE-ce50f6ff-6712-414c-9c98-0364f1e6fe44',
'MD5 use flagged — Peppol SML DNS lookup spec',
'MEDIUM','False Positive — Weak Hash',
'src/Invoice/Peppol/SmpResolver.php',
'MD5 is required by the Peppol SML DNS spec for participant ID hashing; RFC-compliant, not a security hash',
'https://cwe.mitre.org/data/definitions/327.html', 1, 0, 'Cryptography — Weak Algorithm'],
['SNYK-CODE-df6503fc-3e50-4b9f-b496-f7fb03985431',
'XXE risk in loadXML — Peppol trait (1 of 2)',
'HIGH','False Positive — XXE',
'src/Invoice/Inv/Trait/Peppol.php',
'PHP 8.0+ disables external entity loading by default; project minimum is PHP 8.4',
'https://cwe.mitre.org/data/definitions/611.html', 1, 0, 'XXE — XML External Entity'],
['SNYK-CODE-88498c5a-ad8f-4904-a307-fb408293928d',
'XXE risk in loadXML — Peppol trait (2 of 2)',
'HIGH','False Positive — XXE',
'src/Invoice/Inv/Trait/Peppol.php',
'PHP 8.0+ disables external entity loading by default; project minimum is PHP 8.4',
'https://cwe.mitre.org/data/definitions/611.html', 1, 0, 'XXE — XML External Entity'],
['SNYK-CODE-ac3f0ded-f59b-4a8e-8fff-4fe5e073f542',
'Hardcoded credential — unit test fixture',
'LOW','False Positive — Test Fixture',
'Tests/Unit/Invoice/Entity/UserEntityTest.php',
"'newlogin' is an assertSame fixture value, not a production credential",
'https://cwe.mitre.org/data/definitions/798.html', 1, 0, 'Hardcoded Secrets'],
['SNYK-CODE-5f593a3f-ee1f-486b-ab02-e1b5ea879747',
'XSS — exception echo in CLI benchmark script',
'MEDIUM','False Positive — CLI Tool',
'benchmarks/run.php',
'CLI script; exception message echoed to terminal stdout, never to a browser',
'https://cwe.mitre.org/data/definitions/79.html', 1, 0, 'XSS — Cross-Site Scripting'],
['SNYK-CODE-816cf0ce-bb64-4b3c-8a4d-2dac8f88e723',
'XSS — error echo in CLI benchmark script',
'MEDIUM','False Positive — CLI Tool',
'benchmarks/run.php',
'CLI script; error string echoed to terminal stdout, never to a browser',
'https://cwe.mitre.org/data/definitions/79.html', 1, 0, 'XSS — Cross-Site Scripting'],
['SNYK-CODE-b8c80a7c-dfc0-4e89-9b8b-4b09dfe4341d',
'XSS in sonar-issues.php CLI tool (1 of 3)',
'MEDIUM','False Positive — CLI Tool',
'sonar-issues.php',
'CLI developer tool; output to terminal stdout, not rendered as HTML',
'https://cwe.mitre.org/data/definitions/79.html', 1, 0, 'XSS — Cross-Site Scripting'],
['SNYK-CODE-3b503f93-bacc-45e5-94fb-f57a7a74ee91',
'XSS in sonar-issues.php CLI tool (2 of 3)',
'MEDIUM','False Positive — CLI Tool',
'sonar-issues.php',
'CLI developer tool; output to terminal stdout, not rendered as HTML',
'https://cwe.mitre.org/data/definitions/79.html', 1, 0, 'XSS — Cross-Site Scripting'],
['SNYK-CODE-63aacd20-88fc-4892-a2ac-86b37eea41b6',
'XSS in sonar-issues.php CLI tool (3 of 3)',
'MEDIUM','False Positive — CLI Tool',
'sonar-issues.php',
'CLI developer tool; output to terminal stdout, not rendered as HTML',
'https://cwe.mitre.org/data/definitions/79.html', 1, 0, 'XSS — Cross-Site Scripting'],
['SNYK-CODE-11be5bd0-027f-4aea-8377-27b0d6192d5c',
'XSS — binary PDF echoed via file_get_contents',
'MEDIUM','False Positive — Content-Disposition',
'src/Invoice/Inv/Trait/PdfTrait.php',
'PDF binary served with Content-Disposition: attachment and Content-Type: application/pdf; cannot execute as HTML',
'https://cwe.mitre.org/data/definitions/79.html', 1, 0, 'XSS — Cross-Site Scripting'],
['SNYK-CODE-0311cb06-61c1-4ec4-a45c-7e06061d896f',
'Hardcoded secret — Peppol postal address config key',
'LOW','False Positive — Config Key Name',
'src/Invoice/Helpers/Peppol/PeppolHelper.php',
"'SupplierPartyIdentificationPostalAddress' is an array key name for a postal address structure, not a cryptographic secret",
'https://cwe.mitre.org/data/definitions/798.html', 1, 0, 'Hardcoded Secrets'],
['GH-114-web-token-jwt-framework',
'JWSVerifier algorithm confusion via unprotected header (web-token/jwt-framework <=4.2.99)',
'HIGH','False Positive — Transitive Dependency, Unreachable Code',
'composer.lock',
'Transitive dep via rossaddison/yii-auth-client; project uses phpseclib4 directly in GovUk.php — JWSVerifier and JWEDecrypter are never instantiated; no attack vector reachable. No patched version as at June 2026. Update snyk_id once Snyk assigns a SNYK-PHP-xxx ID.',
'https://cwe.mitre.org/data/definitions/290.html', 1, 0, 'Algorithm Confusion — JWT JWS/JWE'],
['GHSA-3prj-6hqw-cm82',
'PBES2 p2c unbounded iteration count — CPU-amplification DoS (web-token/jwt-framework)',
'HIGH','Resolved — Fixed in installed version 4.1.7',
'composer.lock',
'Affected versions <= 4.1.6. Installed version is 4.1.7, which already contains the fix: DEFAULT_MAX_COUNT = 1_000_000 constant and p2c > max_count guard in PBES2AESKW::checkHeaderAdditionalParameters(). Additionally, the project never registers PBES2 algorithms — GovUk.php uses phpseclib4 directly. Both the installed vendor and the 4.2.x upstream branch contain the fix; no PR required.',
'https://cwe.mitre.org/data/definitions/400.html', 0, 0, 'Uncontrolled Resource Consumption — PBKDF2 DoS'],
];
$stmt = $db->prepare(
'INSERT OR IGNORE INTO vuln_resolved
(snyk_id,title,severity,category,file_path,reason,advisory_url,false_pos,ai_related,threat_vec)
VALUES (?,?,?,?,?,?,?,?,?,?)'
);
foreach ($seed as $row) {
$stmt->execute($row);
}
}
// CRUD handlers for vulnerability log
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['add_vuln'])) {
if (!sqliteAvailable()) { header('Location: ?menu=snyk_resolved'); exit; }
$db = getVulnDb();
$db->prepare(
'INSERT INTO vuln_resolved
(snyk_id,title,severity,category,file_path,reason,advisory_url,false_pos,ai_related,threat_vec)
VALUES (:snyk_id,:title,:severity,:category,:file_path,:reason,:advisory_url,:false_pos,:ai_related,:threat_vec)'
)->execute([
'snyk_id' => trim($_POST['snyk_id'] ?? ''),
'title' => trim($_POST['title'] ?? ''),
'severity' => trim($_POST['severity'] ?? 'MEDIUM'),
'category' => trim($_POST['category'] ?? ''),
'file_path' => trim($_POST['file_path'] ?? ''),
'reason' => trim($_POST['reason'] ?? ''),
'advisory_url' => trim($_POST['advisory_url'] ?? ''),
'false_pos' => isset($_POST['false_pos']) ? 1 : 0,
'ai_related' => isset($_POST['ai_related']) ? 1 : 0,
'threat_vec' => trim($_POST['threat_vec'] ?? ''),
]);
header('Location: ?menu=snyk_resolved');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['del_vuln'])) {
if (!sqliteAvailable()) { header('Location: ?menu=snyk_resolved'); exit; }
$id = (int) ($_POST['id'] ?? 0);
if ($id > 0) {
getVulnDb()->prepare('DELETE FROM vuln_resolved WHERE id = ?')->execute([$id]);
}
header('Location: ?menu=snyk_resolved');
exit;
}
// ── Command registry ──────────────────────────────────────────────────────────
// cmd = shell template; {key} placeholders replaced with form inputs
// params = ['key' => 'label shown in form']
// confirm = non-null triggers JS confirm() before running
// bg = true → spawn detached window, don't capture output
// open = URL to mention in bg output
// env = env var names to inject from session
// filter = special post-processing key
$CMDS = [
// Psalm
'psalm_full' => ['cmd' => 'php vendor/bin/psalm --force-jit'],
'psalm_file' => ['cmd' => 'php vendor/bin/psalm {file}',
'params' => ['file' => 'File path (e.g. src/Invoice/Inv/InvController.php)']],
'psalm_dir' => ['cmd' => 'php vendor/bin/psalm {dir}',
'params' => ['dir' => 'Directory path (e.g. src/Invoice/Inv/)']],
'psalm_cache' => ['cmd' => 'php vendor/bin/psalm --clear-cache'],
'psalm_info' => ['cmd' => 'php vendor/bin/psalm --show-info'],
// Composer
'comp_outdated' => ['cmd' => 'composer outdated --ansi'],
'comp_whynot' => ['cmd' => 'composer why-not {package} {version}',
'params' => ['package' => 'Package (e.g. vendor/package)', 'version' => 'Version (e.g. ^1.0)']],
'comp_cache_lock' => ['cmd' => 'composer clear-cache --ansi && composer update --lock --ansi'],
'comp_validate' => ['cmd' => 'composer validate --ansi --strict'],
'comp_dump' => ['cmd' => 'composer dump-autoload -o --ansi'],
'comp_audit' => ['cmd' => 'composer audit --ansi'],
'comp_update' => ['cmd' => 'composer update --ansi'],
'comp_req_check' => ['cmd' => 'php -d memory_limit=512M vendor/bin/composer-require-checker'],
// Node
'node_install' => ['cmd' => 'npm install'],
'node_ncu' => ['cmd' => 'npx npm-check-updates -u && npm install'],
'node_nvm' => ['cmd' => 'echo Download nvm-windows from: https://github.com/coreybutler/nvm-windows/releases'],
'node_audit' => ['cmd' => 'npm audit && npm cache clean --force && npm list --depth=0'],
'node_audit_fix' => ['cmd' => 'npm audit fix'],
'node_outdated' => ['cmd' => 'npm run upgrade:check'],
'node_safe' => ['cmd' => 'npm run upgrade:safe'],
'node_minor' => ['cmd' => 'npm run upgrade:minor'],
'node_major' => ['cmd' => 'npm run upgrade:major'],
'node_es2024' => ['cmd' => 'npm run es2024:verify'],
'node_build' => ['cmd' => 'npm run build'],
// TypeScript
'ts_prod' => ['cmd' => 'npm run build:prod'],
'ts_dev' => ['cmd' => 'npm run build:dev'],
'ts_watch' => ['cmd' => 'start cmd /k npm run build:watch', 'bg' => true],
'ts_check' => ['cmd' => 'npm run type-check'],
'ts_lint' => ['cmd' => 'npm run lint'],
'ts_format' => ['cmd' => 'npm run format:check && npm run format'],
// Testing
'test_entity' => ['cmd' => 'php vendor/bin/phpunit Tests/Unit/Invoice/Entity/ --no-coverage --testdox --colors=always'],
'test_unit' => ['cmd' => 'php vendor/bin/phpunit Tests/Unit/ --no-coverage --testdox --colors=always'],
'test_func' => ['cmd' => 'php vendor/bin/phpunit Tests/Functional/ Tests/Integration/ Tests/PHPUnit/ --no-coverage --testdox --colors=always'],
'test_cc_func' => ['cmd' => 'php vendor/bin/codecept run Functional'],
'test_cc_acc' => ['cmd' => 'php vendor/bin/codecept run Acceptance'],
'test_cc_all' => ['cmd' => 'php vendor/bin/codecept run'],
'testo_all' => ['cmd' => 'php vendor/bin/testo'],
'testo_unit' => ['cmd' => 'php vendor/bin/testo --suite=Unit'],
'testo_sources' => ['cmd' => 'php vendor/bin/testo --suite=Sources'],
// PHP-CS-Fixer
'fixer_dry' => ['cmd' => 'php vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run --show-progress=bar --verbose --ansi'],
'fixer_fix' => ['cmd' => 'php vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --ansi'],
// PHPCS
'phpcs_full' => ['cmd' => 'php vendor/bin/phpcs -d memory_limit=1024M --standard=phpcs.xml.dist --colors'],
'phpcs_file' => ['cmd' => 'php vendor/bin/phpcs -d memory_limit=1024M --standard=Generic --sniffs=Generic.Files.LineLength --runtime-set lineLimit 85 --runtime-set absoluteLineLimit 85 --colors {file}',
'params' => ['file' => 'File path (e.g. src/Invoice/Invoice.php)']],
'phpcs_dir' => ['cmd' => 'php vendor/bin/phpcs -d memory_limit=1024M --standard=Generic --sniffs=Generic.Files.LineLength --runtime-set lineLimit 85 --runtime-set absoluteLineLimit 85 --colors {dir}',
'params' => ['dir' => 'Directory path (e.g. src/Invoice/)']],
'phpcs_report' => ['cmd' => 'php vendor/bin/phpcs -d memory_limit=1024M --standard=phpcs.xml.dist --report=full --report-width=120 --colors'],
// Rector
'rector_dry' => ['cmd' => 'php vendor/bin/rector process --dry-run --output-format=console --ansi'],
'rector_apply' => ['cmd' => 'php vendor/bin/rector --ansi'],
// SonarCloud
'sonar_all' => ['cmd' => 'php sonar-issues.php', 'env' => ['SONAR_TOKEN']],
'sonar_pr' => ['cmd' => 'php sonar-issues.php --pr={pr}', 'env' => ['SONAR_TOKEN'], 'params' => ['pr' => 'PR number']],
'sonar_type' => ['cmd' => 'php sonar-issues.php --type={type}', 'env' => ['SONAR_TOKEN'], 'params' => ['type' => 'BUG / VULNERABILITY / CODE_SMELL']],
'sonar_sev' => ['cmd' => 'php sonar-issues.php --severity={sev}', 'env' => ['SONAR_TOKEN'], 'params' => ['sev' => 'BLOCKER / CRITICAL / MAJOR / MINOR / INFO']],
'sonar_hotspots' => ['cmd' => 'php sonar-issues.php --hotspots', 'env' => ['SONAR_TOKEN']],
'sonar_combined' => ['cmd' => 'php sonar-issues.php --type={type} --severity={sev}','env' => ['SONAR_TOKEN'], 'params' => ['type' => 'Type', 'sev' => 'Severity']],
'sonar_rule' => ['cmd' => 'php sonar-issues.php --rule={rule}', 'env' => ['SONAR_TOKEN'], 'params' => ['rule' => 'Rule']],
'sonar_file' => ['cmd' => 'php sonar-issues.php --file={file}', 'env' => ['SONAR_TOKEN'], 'params' => ['file' => 'File path (e.g. src/Invoice/Inv/InvController.php)']],
'sonar_reliability' => ['cmd' => 'php sonar-issues.php --type=BUG', 'env' => ['SONAR_TOKEN']],
'sonar_rely_grp' => ['cmd' => 'php sonar-issues.php --type=BUG --grouped', 'env' => ['SONAR_TOKEN']],
'sonar_all_grp' => ['cmd' => 'php sonar-issues.php --grouped', 'env' => ['SONAR_TOKEN']],
'sonar_lang' => ['cmd' => 'php sonar-issues.php --language={lang}', 'env' => ['SONAR_TOKEN'], 'params' => ['lang' => 'typescript / php / javascript / css / xml']],
// Yii
'yii_serve' => ['cmd' => 'start cmd /k php yii serve', 'bg' => true, 'open' => 'http://localhost:8080'],
'yii_user' => ['cmd' => 'php yii user/create {user} {pass}',
'params' => ['user' => 'Username', 'pass' => 'Password']],
'yii_role' => ['cmd' => 'php yii user/assignRole {role} {uid}',
'params' => ['role' => 'Role (e.g. admin)', 'uid' => 'User ID']],
'yii_routes' => ['cmd' => 'php yii router/list'],
'yii_routes_ctrl' => ['cmd' => 'php yii router/list --controller={controller}',
'params' => ['controller' => 'Controller name prefix (e.g. Inv, Client, Quote) — leave blank to just add the Controller column']],
'yii_translate' => ['cmd' => 'php yii translator/translate {text} {lang}',
'params' => ['text' => 'Source text', 'lang' => 'Target language code (e.g. fr)']],
'yii_items' => ['cmd' => 'php yii invoice/items'],
'yii_check_php' => ['cmd' => 'php yii system/check-php-version'],
'yii_trunc_setting' => ['cmd' => 'php yii invoice/setting/truncate', 'confirm' => 'DELETE all settings permanently?'],
'yii_trunc_gen' => ['cmd' => 'php yii invoice/generator/truncate', 'confirm' => 'DELETE generator data permanently?'],
'yii_trunc1' => ['cmd' => 'php yii invoice/inv/truncate1', 'confirm' => 'DELETE all invoices permanently?'],
'yii_trunc2' => ['cmd' => 'php yii invoice/quote/truncate2', 'confirm' => 'DELETE all quotes permanently?'],
'yii_trunc3' => ['cmd' => 'php yii invoice/salesorder/truncate3', 'confirm' => 'DELETE all sales orders permanently?'],
'yii_trunc4' => ['cmd' => 'php yii invoice/nonuserrelated/truncate4', 'confirm' => 'DELETE all non-user-related data permanently?'],
'yii_trunc5' => ['cmd' => 'php yii invoice/userrelated/truncate5', 'confirm' => 'DELETE all user-related data permanently?'],
'yii_trunc6' => ['cmd' => 'php yii invoice/autoincrementsettooneafter/truncate6', 'confirm' => 'RESET auto-increment counters permanently?'],
// GitHub
'gh_install' => ['cmd' => 'winget install --id GitHub.cli'],
'gh_status' => ['cmd' => 'gh auth status'],
'gh_copilot' => ['cmd' => 'gh --version && gh api user/copilot_seat_details'],
// Peppol
'peppol_check' => ['cmd' => 'php bin/check-peppol-codelists.php', 'env' => ['GITHUB_TOKEN']],
// Benchmarks
'bench_all' => ['cmd' => 'php benchmarks/run.php'],
'bench_di' => ['cmd' => 'php benchmarks/run.php --suite=di'],
'bench_injector' => ['cmd' => 'php benchmarks/run.php --suite=injector'],
'bench_router' => ['cmd' => 'php benchmarks/run.php --suite=router'],
'bench_strings' => ['cmd' => 'php benchmarks/run.php --suite=strings'],
'bench_dry' => ['cmd' => 'php benchmarks/run.php --dry-run'],
'bench_dashboard' => ['cmd' => 'start cmd /k php -S localhost:8080 -t benchmarks', 'bg' => true,
'open' => 'http://localhost:8080/dashboard/'],
// Snyk
'snyk_install' => ['cmd' => 'npm install -g snyk'],
'snyk_auth' => ['cmd' => 'start cmd /k snyk auth', 'bg' => true],
'snyk_whoami' => ['cmd' => 'snyk whoami'],
'snyk_quick' => ['cmd' => 'npm run security:quick'],
'snyk_full' => ['cmd' => 'npm run security:full'],
'snyk_deps' => ['cmd' => 'npm run security:deps'],
'snyk_file' => ['cmd' => 'snyk code test --file={file}',
'params' => ['file' => 'File path (e.g. src/Invoice/Inv/InvController.php)']],
'snyk_summary' => ['cmd' => 'snyk code test --no-color', 'filter' => 'snyk_summary'],
'snyk_json' => ['cmd' => 'snyk code test --json'],
'snyk_report' => ['cmd' => 'snyk code test'],
// System
'sys_versions' => ['cmd' => 'php -v && composer --version && node -v && npm -v && npx tsc --version && composer check-platform-reqs && npm list --depth=0'],
'sys_assets' => ['cmd' => 'powershell -Command "Get-ChildItem -Path public/assets -Exclude .gitignore | Remove-Item -Recurse -Force; Write-Host \'Assets cache cleared.\'"'],
'sys_extensions' => ['cmd' => 'php scripts\extension-checker.php'],
'sys_dl_icons' => ['cmd' => 'php bin/download-cli-icons.php'],
'sys_cookie_secret' => ['cmd' => 'php -r "echo bin2hex(random_bytes(32));"'],
];
// ── Menus (each item: [label, cmdKey]) ────────────────────────────────────────
$MENUS = [
'psalm' => [
'title' => 'Psalm — Static Analysis',
'items' => [
['Run Psalm (Full)', 'psalm_full'],
['Psalm on File', 'psalm_file'],
['Psalm on Directory', 'psalm_dir'],
['Clear Psalm Cache', 'psalm_cache'],
['Show Config / Plugins', 'psalm_info'],
],
],
'composer' => [
'title' => 'Composer — PHP Dependencies',
'items' => [
['Outdated Packages', 'comp_outdated'],
['why-not (version conflict)', 'comp_whynot'],
['Cache Clear + Lock Resolve', 'comp_cache_lock'],
['Validate composer.json', 'comp_validate'],
['Dump Autoload', 'comp_dump'],
['Audit (security)', 'comp_audit'],
['Update', 'comp_update'],
['Require Checker', 'comp_req_check'],
],
],
'node' => [
'title' => 'Node — npm Packages',
'items' => [
['Install (npm install)', 'node_install'],
['Update Modules (npm-check-updates)', 'node_ncu'],
['nvm-windows Download Link', 'node_nvm'],
['Audit + Clean + List', 'node_audit'],
['Audit Fix', 'node_audit_fix'],
['Check Outdated', 'node_outdated'],
['Safe Update (patch only)', 'node_safe'],
['Minor Update', 'node_minor'],
['Major Update (interactive)', 'node_major'],
['ES2024 Feature Verify', 'node_es2024'],
['Build (npm run build)', 'node_build'],
],
],
'typescript' => [
'title' => 'TypeScript',
'items' => [
['Build Production (minified)', 'ts_prod'],
['Build Development (source maps)', 'ts_dev'],
['Watch Mode (opens new window)', 'ts_watch'],
['Type Check', 'ts_check'],
['Lint', 'ts_lint'],
['Format Check + Fix', 'ts_format'],
],
],
'testing' => [
'title' => 'Testing — PHPUnit + Codeception + Testo',
'items' => [
['Entity Tests (Tests/Unit/Invoice/Entity/)', 'test_entity'],
['All Unit Tests (Tests/Unit/)', 'test_unit'],
['Functional / Integration', 'test_func'],
['Codeception: Functional Suite', 'test_cc_func'],
['Codeception: Acceptance Suite', 'test_cc_acc'],
['Codeception: All Suites', 'test_cc_all'],
['Testo: All Suites (Tests/Testo/ + src/)', 'testo_all'],
['Testo: Unit Suite (Tests/Testo/)', 'testo_unit'],
['Testo: Sources Suite (inline tests)', 'testo_sources'],
],
],
'fixer' => [
'title' => 'PHP-CS-Fixer',
'items' => [
['Dry Run (see proposed changes)', 'fixer_dry'],
['Apply Fix', 'fixer_fix'],
],
],
'phpcs' => [
'title' => 'PHPCS — Code Style Checker',
'items' => [
['Check Full Project (85-char limit)', 'phpcs_full'],
['Check Specific File', 'phpcs_file'],
['Check Specific Directory', 'phpcs_dir'],
['Detailed Report', 'phpcs_report'],
],
],
'rector' => [
'title' => 'Rector — Automated Refactoring',
'items' => [
['Dry Run (see proposed changes)', 'rector_dry'],
['Apply Changes', 'rector_apply'],
],
],
'sonar' => [
'title' => 'SonarCloud — rossaddison_invoice',
'items' => [
['CI Pipeline Progress', '__nav__:ci_pipeline'],
['All Open Issues', 'sonar_all'],
['Issues on a Specific PR', 'sonar_pr'],
['Filter by Type', 'sonar_type'],
['Filter by Severity', 'sonar_sev'],
['Security Hotspots', 'sonar_hotspots'],
['Combine Type + Severity', 'sonar_combined'],
['Filter by Rule Key', 'sonar_rule'],
['Filter by File Path', 'sonar_file'],
['Reliability Issues (BUG)', 'sonar_reliability'],
['Reliability Grouped by Rule', 'sonar_rely_grp'],
['All Issues Grouped by Rule', 'sonar_all_grp'],
['Filter by Language', 'sonar_lang'],
],
],
'yii' => [
'title' => 'Yii — Console Commands',
'items' => [
['PHP Built-in Serve (opens new window)', 'yii_serve'],
['user/create', 'yii_user'],
['user/assignRole', 'yii_role'],
['router/list', 'yii_routes'],
['router/list --controller=<name>', 'yii_routes_ctrl'],
['translator/translate', 'yii_translate'],
['invoice/items', 'yii_items'],
['system/check-php-version', 'yii_check_php'],
['TRUNCATE: invoice/setting', 'yii_trunc_setting'],
['TRUNCATE: invoice/generator', 'yii_trunc_gen'],
['TRUNCATE: invoice/inv (invoices)', 'yii_trunc1'],
['TRUNCATE: invoice/quote', 'yii_trunc2'],
['TRUNCATE: invoice/salesorder', 'yii_trunc3'],
['TRUNCATE: invoice/nonuserrelated', 'yii_trunc4'],
['TRUNCATE: invoice/userrelated', 'yii_trunc5'],
['TRUNCATE: autoincrementsettooneafter', 'yii_trunc6'],
],
],
'github' => [
'title' => 'GitHub CLI',
'items' => [
['Install GitHub CLI (winget)', 'gh_install'],
['Auth Status', 'gh_status'],
['Copilot / Version', 'gh_copilot'],
],
],
'peppol' => [
'title' => 'Peppol — Code-List Currency Check',
'items' => [
['Check Peppol Code Lists', 'peppol_check'],
],
],
'bench' => [
'title' => 'Performance Benchmarks',
'items' => [
['Run All Suites (saves to history.json)', 'bench_all'],
['DI Container Suite', 'bench_di'],
['Injector Suite', 'bench_injector'],
['Router Suite', 'bench_router'],
['String Helpers Suite', 'bench_strings'],
['Dry Run (no save)', 'bench_dry'],
['Serve Dashboard (localhost:8080)', 'bench_dashboard'],
],
],
'snyk' => [
'title' => 'Snyk Security Scanner',
'items' => [
['Resolved Vulnerabilities Index', '__nav__:snyk_resolved'],
['[SETUP 1] Install Snyk CLI', 'snyk_install'],
['[SETUP 2] Authenticate (browser login)', 'snyk_auth'],
['[SETUP 3] Verify auth (whoami)', 'snyk_whoami'],
['Quick Scan (high-severity only)', 'snyk_quick'],
['Full Scan (code + dependencies)', 'snyk_full'],
['Dependencies Only', 'snyk_deps'],
['Code Scan on File', 'snyk_file'],
['Issue Count Summary', 'snyk_summary'],
['JSON Output', 'snyk_json'],
['Full Scan + Save to snyk-report.txt', 'snyk_report'],
],
],
'system' => [
'title' => 'System — Versions + Utilities',
'items' => [
['Version Info (PHP, Composer, Node, TS)', 'sys_versions'],
['Clear Public Assets Cache', 'sys_assets'],
['PHP Extension Checker', 'sys_extensions'],
['Download Menu Icons', 'sys_dl_icons'],
['Generate COOKIE_SECRET_KEY (.env)', 'sys_cookie_secret'],
],
],
];
// ── SonarCloud quick-rule reference (shown as clickable badges) ───────────────
$SONAR_RULES = [
'php:S1192' => 'String literals duplicated 3+',
'php:S3776' => 'Cognitive complexity',
'php:S107' => 'Too many parameters',
'php:S116' => 'Field name convention',
'php:S100' => 'Function name convention',
'php:S1155' => 'Use empty() not count()==0',
'php:S6600' => 'Unnecessary echo parens',
'php:S2003' => 'Use require_once',
'php:S7735' => 'Avoid negated conditions',
'php:S1848' => 'Objects not dropped immediately',
'php:S1172' => 'Unused parameter',
'php:S3358' => 'Nested ternaries',
'php:S2583' => 'Always-true/false conditions',
'php:S905' => 'No-op statements',
'php:S2681' => 'Multiline blocks need braces',
'php:S2234' => 'Args match params',
'php:S4144' => 'Identical method implementations',
'php:S1117' => 'Local var shadows field',
'typescript:S7785' => 'Async IIFE → top-level await',
'typescript:S7647' => 'Empty lifecycle methods',
'typescript:S7764' => 'globalThis not window',
'javascript:S7647' => 'Empty lifecycle methods (JS)',
'shelldre:S1066' => 'Merge nested if statements',
];
// Group $SONAR_RULES by language → ['php' => ['1192' => 'desc', ...], ...]
$SONAR_RULES_BY_LANG = [];
foreach ($SONAR_RULES as $ruleKey => $desc) {
[$lang, $code] = explode(':', $ruleKey, 2);
$num = ltrim($code, 'S');
$SONAR_RULES_BY_LANG[$lang][$num] = $desc;
}
// ── API: live failing rules from SonarCloud ──────────────────────────────────
// Returns JSON: {"php":{"1192":"String literals…"}, "typescript":{"7764":"globalThis…"}}
if (isset($_GET['api']) && $_GET['api'] === 'failing_rules') {
header('Content-Type: application/json; charset=utf-8');
$token = $_SESSION['sonar_token'] ?? '';
if ($token === '') {
echo json_encode(['error' => 'no_token']);
exit;
}
$baseEnv = is_array($e = getenv()) ? $e : [];
$childEnv = array_merge($baseEnv, ['SONAR_TOKEN' => $token]);
$descr = [0 => ['file','nul','r'], 1 => ['pipe','w'], 2 => ['file','nul','w']];
$proc = proc_open(
'php ' . escapeshellarg(__DIR__ . '/sonar-issues.php') . ' --grouped',
$descr, $pipes, __DIR__, $childEnv
);
$out = '';
if (is_resource($proc)) {
$out = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($proc);
}
// Parse lines like: "php:S1192 42 String literals duplicated 3+"
$grouped = [];
foreach (explode("\n", $out) as $line) {
if (preg_match('/^([a-zA-Z]+):S(\d+)\s+\d+\s+(.+)$/', trim($line), $m)) {
$grouped[$m[1]][$m[2]] = trim($m[3]);
}
}
echo json_encode($grouped);
exit;
}
// ── API: CI pipeline status ──────────────────────────────────────────────────
// Polls GitHub Actions (invoice_build.yml) and SonarCloud CE task in one call.
if (isset($_GET['api']) && $_GET['api'] === 'ci_status') {
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store');
$ghToken = $_SESSION['github_token'] ?? '';
$sonarToken = $_SESSION['sonar_token'] ?? '';
$ciGet = static function(string $url, array $headers): array {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERAGENT => 'rossaddison-invoice-devtools/1.0',
CURLOPT_FOLLOWLOCATION => true,
]);
$raw = curl_exec($ch);
curl_close($ch);
if (!is_string($raw) || $raw === '') {
return [];
}
$data = json_decode($raw, true);
return is_array($data) ? $data : [];
};
$ghHeaders = [
'Accept: application/vnd.github+json',
'X-GitHub-Api-Version: 2022-11-28',
];
if ($ghToken !== '') {
$ghHeaders[] = 'Authorization: Bearer ' . $ghToken;
}
$sonarHeaders = $sonarToken !== '' ? ['Authorization: Bearer ' . $sonarToken] : [];
// 1. Latest invoice_build run on main
$runs = $ciGet(
'https://api.github.com/repos/rossaddison/invoice/actions/workflows'
. '/invoice_build.yml/runs?per_page=1&branch=main',
$ghHeaders
);
$run = $runs['workflow_runs'][0] ?? null;
$runOut = null;
$jobs = [];
if ($run !== null) {
$runOut = [
'id' => $run['id'],
'name' => $run['name'] ?? '',
'status' => $run['status'] ?? '',
'conclusion' => $run['conclusion'] ?? null,
'html_url' => $run['html_url'] ?? '',
'created_at' => $run['created_at'] ?? '',
'head_commit' => $run['head_commit']['message'] ?? '',
];
// 2. Jobs for this run
$jobData = $ciGet(
'https://api.github.com/repos/rossaddison/invoice/actions/runs/'
. (int) $run['id'] . '/jobs',
$ghHeaders
);
foreach ($jobData['jobs'] ?? [] as $j) {
$jobs[] = [
'name' => $j['name'] ?? '',
'status' => $j['status'] ?? '',
'conclusion' => $j['conclusion'] ?? null,
'html_url' => $j['html_url'] ?? '',
];
}
}
// 3. SonarCloud CE task (most recent)
$ceData = $ciGet(
'https://sonarcloud.io/api/ce/activity?component=rossaddison_invoice&ps=1',
$sonarHeaders
);
$ceTask = $ceData['tasks'][0] ?? null;
$ceOut = $ceTask !== null ? [
'status' => $ceTask['status'] ?? '',
'submittedAt' => $ceTask['submittedAt'] ?? '',
'executedAt' => $ceTask['executedAt'] ?? null,
'errorMessage' => $ceTask['errorMessage'] ?? null,
] : null;
// 4. Quality gate
$gateData = $ciGet(
'https://sonarcloud.io/api/qualitygates/project_status?projectKey=rossaddison_invoice',
$sonarHeaders
);
$gateOut = isset($gateData['projectStatus']) ? [
'status' => $gateData['projectStatus']['status'] ?? 'NONE',
] : null;
echo json_encode([
'run' => $runOut,
'jobs' => $jobs,
'sonar_ce' => $ceOut,
'sonar_gate' => $gateOut,
]);
exit;
}
// ── POST handler (AJAX command runner) ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: text/plain; charset=utf-8');
$key = trim($_POST['cmd'] ?? '');
if (!isset($CMDS[$key])) {
http_response_code(400);
echo "Unknown command: " . htmlspecialchars($key);
exit;
}
$def = $CMDS[$key];
$cmd = $def['cmd'];
// Substitute params — escapeshellarg() prevents command injection (SonarQube S2083)
foreach ($def['params'] ?? [] as $p => $_label) {
$val = escapeshellarg(trim($_POST[$p] ?? ''));
$cmd = str_replace('{' . $p . '}', $val, $cmd);
}
// Inject env vars from session
foreach ($def['env'] ?? [] as $varName) {
$val = '';
if ($varName === 'SONAR_TOKEN') {
$posted = trim($_POST['sonar_token'] ?? '');
if ($posted !== '') {
$_SESSION['sonar_token'] = $posted;
}
$val = $_SESSION['sonar_token'] ?? '';
} elseif ($varName === 'GITHUB_TOKEN') {
$posted = trim($_POST['github_token'] ?? '');
if ($posted !== '') {
$_SESSION['github_token'] = $posted;
}
$val = $_SESSION['github_token'] ?? '';
}
if ($val !== '') {
putenv("$varName=$val");
}
}
if (!empty($def['bg'])) {
pclose(popen('cmd /c ' . $cmd, 'r'));
echo 'Started in background window.';
if (isset($def['open'])) {
echo "\nOpen: " . $def['open'];
}
exit;
}
// Force ANSI colour output in child processes.
// proc_open pipes are not a TTY so tools suppress colour by default.
// putenv() only updates the CRT env block on Windows, not the Win32 env block
// that CreateProcess reads — so we must pass env explicitly as the 5th argument.
// FORCE_COLOR=1 → Node/npm tools + Symfony Console ≥ 5.4 (Composer/Psalm/Rector/Fixer)
// CLICOLOR_FORCE → many Unix-style CLIs
// TERM → general terminal-type hint
$baseEnv = is_array($e = getenv()) ? $e : [];
$childEnv = array_merge($baseEnv, [
'FORCE_COLOR' => '1',
'CLICOLOR_FORCE' => '1',
'TERM' => 'xterm-256color',
'COLORTERM' => 'truecolor',
]);
// Stream stdout to browser via proc_open.
// stdin is explicitly closed (nul) so interactive tools can't block waiting for input.
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-cache, no-store');
header('X-Accel-Buffering: no');
ob_implicit_flush(true);
while (ob_get_level() > 0) {
ob_end_clean();
}
$descriptors = [
0 => ['file', 'nul', 'r'], // stdin: closed (Windows /dev/null)
1 => ['pipe', 'w'], // stdout
2 => ['file', 'nul', 'w'], // stderr discarded — merged into stdout via 2>&1
];
$process = proc_open('cmd /c ' . $cmd . ' 2>&1', $descriptors, $pipes, __DIR__, $childEnv);
if (!is_resource($process)) {
echo 'ERROR: Could not start process.';
exit;
}
$needsFilter = ($def['filter'] ?? '') === 'snyk_summary';
$fullOutput = '';
while (!feof($pipes[1])) {
$chunk = fread($pipes[1], 4096);
if ($chunk === false || $chunk === '') {
continue;
}
if ($needsFilter) {
$fullOutput .= $chunk;
} else {
echo $chunk;
flush();
}
}
fclose($pipes[1]);
proc_close($process);
if ($needsFilter) {
$lines = explode("\n", $fullOutput);
$lines = array_filter($lines, static fn(string $l): bool => str_contains($l, 'Total issues'));
$lines = array_map(static fn(string $l): string => preg_replace('/[^\x20-\x7E]/', '', $l) ?? $l, $lines);
echo implode("\n", $lines) ?: 'No "Total issues" line found in output.';
}
exit;
}
// ── Page state ────────────────────────────────────────────────────────────────
$menu = $_GET['menu'] ?? 'main';
$isMain = ($menu === 'main');
$menuDef = $isMain ? null : ($MENUS[$menu] ?? null);
$pageTitle = $menuDef ? $menuDef['title'] : 'Invoice System (Yii3-i)';
if ($menu === 'ci_pipeline') { $pageTitle = 'CI Pipeline Progress'; }
// Cascade data keyed by command → param name.
// ['rule' => ['php' => ['1192' => 'desc', ...], ...]]
// Defined here (after $SONAR_RULES_BY_LANG) so PHP arrays are in scope.
$PARAM_CASCADE = [
'sonar_rule' => ['rule' => $SONAR_RULES_BY_LANG],
];
// Build slim JS command map (only what JS needs — no cmd strings)
$jsCommands = [];
foreach ($CMDS as $k => $def) {
$jsCommands[$k] = [
'params' => array_keys($def['params'] ?? []),
'paramLabels' => $def['params'] ?? [],
'paramPrefix' => $def['paramPrefix'] ?? [],
'paramSelect' => $def['paramSelect'] ?? [],
'paramSelectSuffix' => $def['paramSelectSuffix'] ?? [],
'paramCascade' => $PARAM_CASCADE[$k] ?? [],
'confirm' => $def['confirm'] ?? null,
'bg' => !empty($def['bg']),
'needsSonar' => in_array('SONAR_TOKEN', $def['env'] ?? [], true),
'needsGithub' => in_array('GITHUB_TOKEN', $def['env'] ?? [], true),
];
}
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Yii3-i Dev Tools<?= $isMain ? '' : ' — ' . htmlspecialchars($pageTitle) ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<style>
body{background:#0d1117;color:#e6edf3;min-height:100vh}
.navbar{background:#161b22!important;border-bottom:1px solid #30363d}
.card-cat{cursor:pointer;border:1px solid #30363d;background:#161b22;transition:border-color .15s,transform .1s;text-decoration:none;display:block}
.card-cat:hover{border-color:#58a6ff;transform:translateY(-2px);color:inherit}
.card-cat h6{color:#58a6ff;margin-bottom:.2rem}
.card-cat small{color:#8b949e}
.cli-menu-pop .popover-header{background:#161b22;color:#58a6ff;border-bottom:1px solid #30363d;font-size:.82em}
.cli-menu-pop .popover-body{background:#0d1117;color:#c9d1d9;font-size:.8em;line-height:1.6;padding:.45rem .6rem}
.cli-menu-pop{border:1px solid #30363d!important;max-width:240px}
.cli-menu-pop .popover-arrow::before{border-top-color:#30363d!important}
.cli-menu-pop .popover-arrow::after{border-top-color:#0d1117!important}
.btn-cmd{text-align:left;border-color:#30363d;color:#e6edf3;background:#161b22;width:100%;padding:.55rem 1rem}
.btn-cmd:hover{border-color:#58a6ff;color:#58a6ff;background:#161b22}
.btn-danger-cmd{text-align:left;border-color:#f85149;color:#f85149;background:#161b22;width:100%;padding:.55rem 1rem}
.btn-danger-cmd:hover{background:rgba(248,81,73,.07)}
#out-panel{position:fixed;bottom:0;left:0;right:0;background:#0d1117;border-top:2px solid #30363d;z-index:1050;display:none;max-height:55vh}
.out-hdr{padding:.4rem 1rem;border-bottom:1px solid #30363d;display:flex;justify-content:space-between;align-items:center;background:#161b22}
#out-pre{margin:0;padding:1rem;font-size:.82em;font-family:'Courier New',monospace;overflow-y:auto;max-height:calc(55vh - 38px);color:#e6edf3;background:#0d1117;white-space:pre-wrap;word-break:break-word}
#out-pre span[style*="background"]{padding:.1em .35em;border-radius:3px}
body.panel-open{padding-bottom:55vh}
.divider-label{font-size:.68rem;text-transform:uppercase;letter-spacing:.08em;color:#8b949e;margin:1rem 0 .4rem;padding-top:.8rem;border-top:1px solid #30363d}
.rule-badge{cursor:pointer;font-size:.72em;font-family:monospace}
.inp{background:#0d1117!important;border-color:#30363d!important;color:#e6edf3!important}
.inp:focus{border-color:#58a6ff!important;box-shadow:none!important}
.token-bar{background:#161b22;border:1px solid #30363d;border-radius:6px;padding:.75rem 1rem;margin-bottom:1rem}
.snyk-notice{background:#161b22;border:1px solid #30363d;border-radius:6px;padding:.6rem 1rem;margin-bottom:1rem;font-size:.85em;color:#8b949e}
</style>
</head>
<body>
<nav class="navbar px-3 py-2">
<a class="navbar-brand fw-bold text-light text-decoration-none" href="?menu=main">⚡ Yii3-i Dev Tools</a>
<?php if (!$isMain): ?>
<a href="?menu=main" class="btn btn-sm btn-outline-secondary">← Main Menu</a>
<?php endif; ?>
</nav>
<div class="container-fluid p-3">
<?php if ($isMain): ?>
<p class="text-secondary mb-3 small">Select a category</p>
<div class="row g-2">
<?php
$mainItems = [
['psalm', 'Psalm', 'Static analysis'],
['composer', 'Composer', 'PHP dependencies'],
['node', 'Node', 'npm packages'],
['typescript', 'TypeScript', 'TS build tools'],
['testing', 'Testing', 'PHPUnit + Codeception + Testo'],
['snyk', 'Snyk', 'Security scanning'],
['fixer', 'PHP-CS-Fixer', 'Code style fixer'],
['phpcs', 'PHPCS', 'Code style checker'],
['rector', 'Rector', 'Automated refactoring'],
['sonar', 'SonarCloud', 'Cloud code quality'],
['yii', 'Yii', 'Console commands'],
['github', 'GitHub', 'GitHub CLI'],
['peppol', 'Peppol', 'e-invoicing code lists'],
['bench', 'Benchmarks', 'Performance benchmarks'],
['system', 'System', 'Versions + utilities'],
];
$ICON_MAP = [
'psalm' => 'psalm',
'composer' => 'composer',
'node' => 'nodejs',
'typescript' => 'typescript',
'testing' => 'testing',
'snyk' => 'snyk',
'fixer' => 'phpcs-fixer',
'phpcs' => 'phpcs',
'rector' => 'rector',
'sonar' => 'sonarcloud',
'yii' => 'yii',
'github' => 'github',
'peppol' => 'peppol',
'bench' => 'benchmarks',
'system' => 'system',
];
foreach ($mainItems as [$key, $label, $desc]):
$iconSlug = $ICON_MAP[$key] ?? $key;
$iconRel = 'public/img/cli/' . $iconSlug . '.svg';
$hasIcon = is_file(__DIR__ . '/' . $iconRel);
// Brand logos that carry their own colours — don't invert to white
$noInvert = ['yii'];
$iconFilter = in_array($iconSlug, $noInvert, true)
? 'opacity:.9'
: 'filter:brightness(0)invert(1);opacity:.8';
$subLabels = array_column($MENUS[$key]['items'] ?? [], 0);
$menuTitle = $MENUS[$key]['title'] ?? $label;
?>
<div class="col-6 col-sm-4 col-md-3 col-lg-2">
<a href="?menu=<?= $key ?>" class="card-cat p-3 h-100"
data-menu-title="<?= htmlspecialchars($menuTitle, ENT_QUOTES) ?>"
data-submenu-items="<?= htmlspecialchars((string) json_encode($subLabels, JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>">
<?php if ($hasIcon): ?>
<img src="/<?= $iconRel ?>" height="48" alt=""
class="mb-2 d-block" style="width:auto;max-width:100%;<?= $iconFilter ?>">
<?php endif; ?>
<h6><?= htmlspecialchars($label) ?></h6>
<small><?= htmlspecialchars($desc) ?></small>
</a>
</div>
<?php endforeach; ?>
</div>
<?php elseif ($menu === 'snyk_resolved'):
$sqliteOk = sqliteAvailable();
?>
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
<h5 class="mb-0">Resolved Vulnerabilities Index</h5>
<a href="?menu=snyk" class="btn btn-sm btn-outline-secondary">← Snyk</a>
</div>
<?php if (!$sqliteOk): ?>
<!-- ── SQLite setup guide ── -->
<?php
$cliIni = php_ini_loaded_file() ?: '';
$cliVersion = PHP_VERSION;
$cliDrivers = implode(', ', PDO::getAvailableDrivers()) ?: '(none)';
?>
<!-- Version-conflict banner -->
<div class="p-3 mb-3" style="background:#3d1f00;border:1px solid #f0883e;border-radius:6px">
<h6 class="mb-2" style="color:#f0883e">⚠ CLI PHP ≠ WAMP Apache PHP — read this first</h6>
<p class="small mb-1" style="color:#e6c48a">
<code>m.bat</code> launches <code>php -S</code> using the <strong>CLI PHP</strong>
(currently <strong>PHP <?= htmlspecialchars($cliVersion) ?></strong>).
The WAMP system tray manages extensions for the <strong>Apache PHP</strong>,
which may be a different version entirely.