forked from mwtcmi/frogman
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrogman.class.php
More file actions
3269 lines (3000 loc) · 132 KB
/
Frogman.class.php
File metadata and controls
3269 lines (3000 loc) · 132 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
namespace FreePBX\modules;
class Frogman extends \FreePBX_Helpers implements \BMO {
private $freepbx;
private $db;
private $tools = [];
private $toolsLoaded = false;
// Populated by authenticateRequest. ['user' => string, 'level' => string|null]
// 'level' is set when the auth source carries an explicit permission level
// (token's level column, or localhost-trust = admin). null means "resolve via
// oc_permissions / FreePBX sections from the username".
private $authContext = null;
public function __construct($freepbx = null) {
parent::__construct($freepbx);
$this->freepbx = $freepbx;
$this->db = $freepbx->Database;
}
public function install() {
}
public function uninstall() {
}
public function backup() {
}
public function restore($backup) {
}
public function doConfigPageInit($page) {
}
public function getActionBar($request) {
return [];
}
public function ajaxRequest($req, &$setting) {
switch ($req) {
case 'tool':
case 'catalog':
case 'chat':
// Allow remote access — we handle auth ourselves (session OR API token)
$setting['authenticate'] = false;
$setting['allowremote'] = true;
return true;
case 'audit-feed':
$setting['authenticate'] = true;
$setting['allowremote'] = true;
return true;
case 'download':
$setting['authenticate'] = true;
$setting['allowremote'] = false;
return true;
}
return false;
}
/**
* Authenticate the current request. Stashes the result in $this->authContext
* (which runTool reads to enforce permissions) and returns the username for
* back-compat with callers that ignored the original return value.
*
* Order matters: explicit auth (token, session) wins over the localhost
* fallback so a localhost caller that bothered to send a token gets the
* token's level rather than blanket admin.
*/
private function authenticateRequest() {
// 1. API token via header — explicit identity, carries its own level.
// If the caller bothered to send a token we treat it as their chosen auth
// method: a bad/inactive one fails outright rather than silently falling
// through to localhost trust.
$token = $_SERVER['HTTP_X_FROGMAN_TOKEN'] ?? '';
if (!empty($token)) {
// oc_api_tokens.token stores `sha256$<hash>` — never the raw value. The
// prefix is self-describing and lets install.php run an idempotent migration.
// See GHSA-9xf5-9ghq-p6cw.
$tokenStored = 'sha256$' . hash('sha256', $token);
$sth = $this->db->prepare("SELECT id, username, level, last_used_at FROM oc_api_tokens WHERE token = ? AND active = 1");
$sth->execute([$tokenStored]);
$row = $sth->fetch(\PDO::FETCH_ASSOC);
if ($row) {
// Stamp last_used_at for the Tokens sidebar (stale-badge + recency column).
// Throttled at 60s to keep wallboard-style pollers from hammering the row —
// the dashboard only needs minute-grade freshness, and a write-per-request
// would be wasted I/O on hot tokens.
$now = time();
if ((int)($row['last_used_at'] ?? 0) < $now - 60) {
$upd = $this->db->prepare("UPDATE oc_api_tokens SET last_used_at = ? WHERE id = ?");
$upd->execute([$now, (int)$row['id']]);
}
$this->authContext = ['user' => $row['username'], 'level' => $row['level']];
return $this->authContext['user'];
}
throw new \Exception('Invalid or inactive API token.');
}
// 2. Valid FreePBX session — username is known, level resolves via oc_permissions / sections.
if (!empty($_SESSION['AMP_user'])) {
$user = $_SESSION['AMP_user']->username ?? 'session';
$this->authContext = ['user' => $user, 'level' => null];
return $user;
}
// 3. Localhost fallback — anyone who can reach 127.0.0.1 already has filesystem
// access to this module, so trust them as admin. Matches FreePBX's own local-Apache model.
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
if (in_array($ip, ['127.0.0.1', '::1'])) {
$this->authContext = ['user' => 'localhost', 'level' => 'admin'];
return 'localhost';
}
throw new \Exception('Not authenticated. Provide X-Frogman-Token header or connect from localhost.');
}
public function ajaxHandler() {
$command = isset($_REQUEST['command']) ? $_REQUEST['command'] : '';
switch ($command) {
case 'catalog':
$this->setCorsHeaders();
try {
$this->authenticateRequest();
} catch (\Exception $e) {
return ['status' => 'error', 'message' => $e->getMessage()];
}
return $this->handleCatalog();
case 'audit-feed':
return $this->handleAuditFeed();
default:
return ['status' => 'error', 'message' => 'Unknown command'];
}
}
public function ajaxCustomHandler() {
$command = isset($_REQUEST['command']) ? $_REQUEST['command'] : '';
switch ($command) {
case 'tool':
$this->handleToolRequest();
return true;
case 'chat':
$this->handleChatRequest();
return true;
case 'download':
$this->handleDownload();
return true;
}
return false;
}
// ── HTTP Endpoints ─────────────────────────────────────────
private function setCorsHeaders() {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Frogman-Token');
// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
}
private function handleToolRequest() {
$this->setCorsHeaders();
header('Content-Type: application/json');
try {
$this->authenticateRequest();
} catch (\Exception $e) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
return;
}
$rawBody = file_get_contents('php://input');
$body = json_decode($rawBody, true);
if (empty($body) || empty($body['tool'])) {
http_response_code(400);
echo json_encode([
'status' => 'error',
'message' => 'Request body must be JSON with "tool" field.',
]);
return;
}
$toolName = $body['tool'];
$params = isset($body['params']) ? $body['params'] : [];
$userId = null;
if (isset($_SESSION['AMP_user']) && is_object($_SESSION['AMP_user'])) {
$userId = null; // ampusers has no numeric ID
}
$sessionId = session_id() ?: 'http';
$result = $this->runTool($toolName, $params, $userId, $sessionId);
$httpCode = ($result['status'] === 'success') ? 200 : 400;
if (isset($result['message']) && strpos($result['message'], 'Unknown tool') !== false) {
$httpCode = 404;
}
http_response_code($httpCode);
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
/**
* Handle POST /admin/ajax.php?module=frogman&command=chat
* Accepts JSON body: {"message": "...", "session_id": "..."}
* Parses natural language, executes the matched tool, returns formatted text.
*/
private function handleChatRequest() {
$this->setCorsHeaders();
header('Content-Type: application/json');
try {
$this->authenticateRequest();
} catch (\Exception $e) {
http_response_code(401);
echo json_encode(['reply' => $e->getMessage()]);
return;
}
// Cap chat parsing memory so a parser bug fails fast instead of OOM-killing the worker
ini_set('memory_limit', '256M');
$rawBody = file_get_contents('php://input');
$body = json_decode($rawBody, true);
if (empty($body) || !isset($body['message'])) {
http_response_code(400);
echo json_encode(['reply' => 'Send a JSON body with a "message" field.']);
return;
}
$message = trim($body['message']);
$sessionId = $body['session_id'] ?? 'chat-default';
require_once __DIR__ . '/Tools/ChatParser.php';
$parsed = \FreePBX\modules\Frogman\ChatParser::parse($message, $sessionId);
// If the parser returned a direct text response (help, error, cancel)
if (isset($parsed['response'])) {
echo json_encode(['reply' => $parsed['response']]);
return;
}
// Otherwise it matched a tool
$toolName = $parsed['tool'];
$params = $parsed['params'];
// v1.6.7 — preserve the chat-origin natural language in the audit row.
// $message is what the user typed; $parsed['interpreted_as'] is populated
// by any upstream natural-language normalisation layer that sits between
// the user and ChatParser (e.g. an Interpret/expand pass) — NULL if no
// rewrite occurred or the layer isn't installed. Non-chat invocation
// paths (HTTP API, GraphQL, CLI, MCP) don't pass these args, leaving
// chat_input + interpreted_as NULL in oc_audit_log for those calls.
$interpretedAs = isset($parsed['interpreted_as']) ? $parsed['interpreted_as'] : null;
$result = $this->runTool($toolName, $params, null, $sessionId, $message, $interpretedAs);
// Format the result as human-readable text
$reply = $this->formatToolResult($toolName, $result, $sessionId);
// Offer a follow-up action if applicable
$followUp = $this->getFollowUpOffer($toolName, $result, $params);
if ($followUp) {
require_once __DIR__ . '/Tools/ChatParser.php';
\FreePBX\modules\Frogman\ChatParser::setFollowUp(
$sessionId,
$followUp['tool'],
$followUp['params'],
$followUp['needs_input'] ?? null,
$followUp['input_prompt'] ?? null
);
$reply .= "\n\n" . $followUp['question'] . "\n{{cmd:yes|✅ Yes}} {{cmd:no|❌ No}}";
}
echo json_encode(['reply' => $reply]);
}
/**
* Sanitize a free-form field value before interpolating it into chat output
* that will be wrapped in inline-code backticks. The client's formatMarkdown
* applies escapeHtml only INSIDE its capture groups (backticks, bold, links);
* prose text between patterns is rendered as raw HTML. Wrapping a user-
* controlled value in backticks engages the escape — but a literal backtick
* in the value would let the user break out of the inline-code wrapping, so
* we strip backticks here. Control chars are also stripped defensively.
*
* Pattern: $line = "Field `" . $this->sanitizeForChat($value) . "`";
*
* Background: GHSA-7qvv (v1.6.6) patched escape-on-capture for the known
* markdown patterns, but prose-between-patterns in the chat formatter is
* still raw-HTML territory. Any new formatter case that interpolates a
* free-form field must use this helper + backtick wrapping.
*/
public function sanitizeForChat($value) {
$value = (string)$value;
// Strip control chars (CRLF, NUL, etc.) — could disrupt rendering or
// be used to inject markup pieces.
$value = preg_replace('/[\x00-\x1F\x7F]/', '', $value);
// Neutralize characters that could break out of inline-code wrapping
// OR trigger client-side formatMarkdown patterns that user-controlled
// fields must not invoke:
// ` closes inline-code wrapping (XSS via prose interpolation)
// {{ triggers {{cmd:...|...}} / {{download:...|...}} clickable
// command patterns — UX confusion / indirect command execution
// (e.g. an admin renders a chat audit and sees a fake clickable
// "harmless click" that actually fires `delete extension 101`)
// [ triggers `[text](url)` markdown link pattern — phishing-ish,
// embeds a clickable link in admin chat
return str_replace(['`', '{{', '['], ["'", '{ {', '('], $value);
}
/**
* Map a severity label to a visual icon for chat rendering.
* Used by the fm_audit_* formatter cases.
*/
private function severityIcon($severity) {
switch ($severity) {
case 'critical': return '🚨';
case 'high': return '🔴';
case 'medium': return '🟡';
case 'info': return 'ℹ️';
default: return '•';
}
}
/**
* Return the highest severity present in a severity_counts array, or
* null if all counts are zero. Used by fm_audit_posture to pick an icon
* for each sub-audit's roll-up line.
*/
private function topSeverity($counts) {
foreach (['critical', 'high', 'medium', 'info'] as $sev) {
if (!empty($counts[$sev]) && (int)$counts[$sev] > 0) {
return $sev;
}
}
return null;
}
/**
* Format a tool result into readable chat text.
*/
public function formatToolResult($toolName, $result, $sessionId) {
if ($result['status'] === 'error') {
$oops = ['Oopsy daisy!', 'Well, that didn\'t work.', 'Hmm, hit a snag.', 'Whoops!', 'That didn\'t go as planned.', 'Uh oh.'];
$prefix = $oops[array_rand($oops)];
return "**{$prefix}** " . ($result['message'] ?? 'Unknown error');
}
$data = $result['data'] ?? [];
// If the tool needs root access
if (!empty($data['needs_root'])) {
return "🔒 **Root access required**\n\n"
. "This command needs elevated privileges. To enable, run once as root:\n"
. "`echo 'asterisk ALL=(root) NOPASSWD: /usr/sbin/fwconsole' > /etc/sudoers.d/frogman`\n\n"
. "This allows Frogman to manage FreePBX services from the chat console.";
}
// If it's a dry-run, store pending and prompt for confirm
if (!empty($data['dry_run'])) {
require_once __DIR__ . '/Tools/ChatParser.php';
// The parser already stored the pending confirm when it parsed
// Show dialplan preview for dialplan tools
if (!empty($data['dialplan'])) {
$ctx = $data['context'] ?? 'custom';
return "**Preview — " . $ctx . ":**\n```\n" . $data['dialplan'] . "\n```\n{{cmd:yes|✅ Yes}} {{cmd:no|❌ No}}";
}
// Recording: show mode chips alongside Yes/No so user can swap mode in one click.
if ($toolName === 'fm_set_recording') {
$ext = $data['ext'] ?? null;
if (!$ext) {
// Best-effort recovery from message text "extension {ext}"
if (preg_match('/extension\s+(\d+)/', $data['message'] ?? '', $em)) $ext = $em[1];
}
$msg = preg_replace('/\s*(Pass|Send)\s+confirm[:\s]true\s+to\s+execute\.?\s*/i', '', $data['message'] ?? '');
$chips = $this->recordingModeChips($ext);
return rtrim($msg, '. ') . ".\n\nPick a mode: " . $chips . "\n\n{{cmd:yes|✅ Confirm}} {{cmd:no|❌ Cancel}}";
}
$msg = $data['message'] ?? 'Action requires confirmation.';
// Strip API-oriented confirm instructions — the chat UI handles this
$msg = preg_replace('/\s*(Pass|Send)\s+confirm[:\s]true\s+to\s+execute\.?\s*/i', '', $msg);
$msg = preg_replace('/\s*Reply\s+yes\s+to\s+confirm\.?\s*/i', '', $msg);
$msg = rtrim($msg, '. ') . '.';
// Add warning emoji for destructive actions
$destructiveTools = [
'fm_disable_extension', 'fm_delete_ringgroup', 'fm_remove_inbound_route',
'fm_remove_blacklist', 'fm_remove_misc_dest', 'fm_delete_ivr',
'fm_delete_time_condition', 'fm_dialplan_remove', 'fm_delete_saved_query',
'fm_delete_notification', 'fm_module_uninstall', 'fm_stop',
'fm_clear_followme', 'fm_clear_call_forward', 'fm_disable_voicemail',
'fm_disable_trunk', 'fm_delete_api_token', 'fm_revoke_api_token',
];
$isDestructive = in_array($toolName, $destructiveTools);
if ($isDestructive) {
$msg = preg_replace('/^Would\s+/i', 'This will ', $msg);
}
$prefix = $isDestructive ? '⚠️ ' : '';
return $prefix . $msg . "\n\n{{cmd:yes|✅ Yes}} {{cmd:no|❌ No}}";
}
// Format based on tool
switch ($toolName) {
case 'fm_set_recording':
$ext = $data['ext'] ?? null;
if (!$ext && preg_match('/extension\s+(\d+)/', $data['message'] ?? '', $em)) $ext = $em[1];
$msg = $data['message'] ?? 'Call recording updated.';
if (!empty($data['success']) || !isset($data['success'])) {
$onDemand = $data['on_demand'] ?? 'disabled';
$note = "Applies to all four call directions (inbound/outbound × external/internal). On-demand recording (`*1` feature code) is currently `{$onDemand}` — separate setting, unchanged.";
$link = !empty($data['extension_url'])
? "[Open extension {$ext} → Advanced for per-direction control]({$data['extension_url']})"
: '';
$out = rtrim($msg, '. ') . ".\n\n" . $note . "\n\nChange mode: " . $this->recordingModeChips($ext);
if ($link) $out .= "\n\n" . $link;
return $out;
}
return "⚠️ " . rtrim($msg, '. ') . ".\n\nTry again: " . $this->recordingModeChips($ext);
case 'fm_list_extensions':
if (empty($data['extensions'])) {
return "No extensions found.";
}
$lines = ["**Extensions** ({$data['count']}):"];
foreach ($data['extensions'] as $ext) {
$lines[] = " {{cmd:show extension {$ext['extension']}|{$ext['extension']}}} — {$ext['name']} ({$ext['tech']})";
}
return implode("\n", $lines);
case 'fm_get_extension':
$u = $data['user'] ?? [];
$d = $data['device'] ?? [];
$ext = $data['extension'];
// Live registration cross-reference — handy to know if the phone is actually online.
$contacts = [];
try {
$contacts = \FreePBX::Endpoint()->getpjsipAORContactIpsByExten($ext) ?: [];
} catch (\Throwable $e) {}
$reg = !empty($contacts) ? '✓ registered (' . count($contacts) . ')' : '✗ not registered';
$lines = ["📱 **Extension {$ext}** — " . ($u['name'] ?? '(no name)')];
$lines[] = " Tech: " . ($d['tech'] ?? 'n/a') . " · {$reg}";
if (!empty($d['callerid'])) $lines[] = " Caller ID: {$d['callerid']}";
if (!empty($u['outboundcid'])) $lines[] = " Outbound CID: {$u['outboundcid']}";
if (!empty($d['context']) && $d['context'] !== 'from-internal') $lines[] = " Context: {$d['context']}";
// Voicemail
$vm = $u['voicemail'] ?? '';
if ($vm && $vm !== 'novm') $lines[] = " Voicemail: ✓ ({$vm})";
else $lines[] = " Voicemail: ✗";
// Features
$features = [];
if (($u['callwaiting'] ?? '') === 'enabled') $features[] = 'call waiting';
if (($u['intercom'] ?? '') === 'enabled') $features[] = 'intercom';
if (($u['answermode'] ?? '') === 'enabled') $features[] = 'auto-answer';
if (($u['call_screen'] ?? '0') !== '0') $features[] = 'call screen';
if (!empty($features)) $lines[] = " Features: " . implode(', ', $features);
// Recording (only show if any are non-default)
$recordingFields = ['recording_in_external','recording_out_external','recording_in_internal','recording_out_internal'];
$rec = [];
foreach ($recordingFields as $f) {
$v = $u[$f] ?? 'dontcare';
if ($v !== 'dontcare') {
$label = str_replace(['recording_','_'], ['',' '], $f);
$rec[] = "{$label}={$v}";
}
}
if (!empty($rec)) $lines[] = " Recording: " . implode(', ', $rec);
// Ring timer / no-answer destination
if (!empty($u['ringtimer']) && (int)$u['ringtimer'] > 0) $lines[] = " Ring timer: {$u['ringtimer']}s";
if (!empty($u['noanswer_dest'])) $lines[] = " No-answer dest: {$u['noanswer_dest']}";
// PJSIP NAT triple — useful diagnostic at a glance
if (($d['tech'] ?? '') === 'pjsip') {
$nat = [];
if (isset($d['rtp_symmetric'])) $nat[] = "rtp_symmetric=" . $d['rtp_symmetric'];
if (isset($d['force_rport'])) $nat[] = "force_rport=" . $d['force_rport'];
if (isset($d['rewrite_contact'])) $nat[] = "rewrite_contact=" . $d['rewrite_contact'];
if (!empty($nat)) $lines[] = " NAT: " . implode(' · ', $nat);
if (!empty($d['allow'])) $lines[] = " Codecs: {$d['allow']}";
if (!empty($d['transport'])) $lines[] = " Transport: {$d['transport']}";
}
// Quick-action chips
$lines[] = "";
$lines[] = " {{cmd:diagnose ext {$ext}|🔍 Diagnose}} · {{cmd:health {$ext}|🩺 Health}} · {{cmd:endpoint details {$ext}|🔧 PJSIP detail}} · {{cmd:show forward on {$ext}|↪ Forward}} · {{cmd:show dnd on {$ext}|🌙 DND}}";
return implode("\n", $lines);
case 'fm_get_extension_health':
$reg = $data['registered'] ? 'Registered' : 'Not registered';
return "**Health: Extension {$data['extension']}** ({$data['name']})\n"
. " Configured: Yes\n"
. " Tech: {$data['tech']}\n"
. " Registration: {$reg}\n"
. " Recent calls: {$data['recent_call_count']}";
case 'fm_list_active_calls':
if (empty($data['calls'])) {
return "No active calls.";
}
$lines = ["**Active Calls** ({$data['active_call_count']}):"];
foreach ($data['calls'] as $c) {
$lines[] = " {$c['channel']} — {$c['callerid']} → {$c['extension']} ({$c['state']})";
}
return implode("\n", $lines);
case 'fm_get_cdr':
if (empty($data['records'])) {
return "No CDR records found.";
}
$noteCdr = !empty($data['include_non_calls']) ? ' (including non-call records)' : '';
$lines = ["**CDR** ({$data['count']} records){$noteCdr}:"];
foreach ($data['records'] as $r) {
$src = $this->sanitizeForChat($r['src'] ?? '');
$dst = $this->sanitizeForChat($r['dst'] ?? '');
$disp = $this->sanitizeForChat($r['disposition'] ?? '');
$dur = (int)($r['duration'] ?? 0);
$lines[] = " {$r['calldate']} | `{$src}` → `{$dst}` | `{$disp}` | {$dur}s";
}
return implode("\n", $lines);
case 'fm_get_busiest_extensions':
if (empty($data['extensions'])) {
return "No extension activity found in the window.";
}
$noteB = !empty($data['include_non_calls']) ? ' (including non-call records)' : '';
$lines = ["**Busiest extensions** ({$data['count']}){$noteB}:"];
foreach ($data['extensions'] as $e) {
$ext = $this->sanitizeForChat($e['extension']);
$nm = $e['name'] !== '' ? ' `' . $this->sanitizeForChat($e['name']) . '`' : '';
$mix = [];
if ($e['inbound']) $mix[] = "{$e['inbound']} in";
if ($e['outbound']) $mix[] = "{$e['outbound']} out";
if ($e['internal']) $mix[] = "{$e['internal']} internal";
$mixStr = $mix ? ' (' . implode(', ', $mix) . ')' : '';
$lines[] = " {{cmd:show extension {$ext}|{$ext}}}{$nm} — {$e['calls']} calls{$mixStr} · avg {$e['avg_duration_s']}s";
}
return implode("\n", $lines);
case 'fm_get_peak_hours':
if (empty($data['hours']) || (int)($data['total_calls'] ?? 0) === 0) {
return "No call volume in the window.";
}
$noteP = !empty($data['include_non_calls']) ? ' (including non-call records)' : '';
$rawNote = '';
if (!empty($data['total_raw_rows']) && $data['total_raw_rows'] > $data['total_calls']) {
$collapsed = $data['total_raw_rows'] - $data['total_calls'];
$rawNote = " · {$collapsed} multi-leg rows collapsed";
}
$max = 0;
foreach ($data['hours'] as $h) { if ($h['calls'] > $max) $max = $h['calls']; }
$max = max(1, $max);
$lines = ["**Peak hours** — {$data['total_calls']} calls{$noteP}{$rawNote}:"];
foreach ($data['hours'] as $h) {
if ($h['calls'] === 0) continue;
$barLen = (int) round(($h['calls'] / $max) * 20);
$bar = str_repeat('▇', max(1, $barLen));
$lbl = sprintf('%02d:00', $h['hour']);
$lines[] = " {$lbl} {$bar} {$h['calls']}";
}
return implode("\n", $lines);
case 'fm_get_cdr_stats':
if (empty($data['by_disposition'])) {
return "No CDR activity in the window.";
}
$noteS = !empty($data['include_non_calls']) ? ' (including non-call records)' : '';
$totalCalls = (int)($data['total_calls'] ?? 0);
$totalRaw = (int)($data['total_raw_rows'] ?? 0);
$collapsed = $totalRaw > $totalCalls ? " · {$totalRaw} raw rows ({$totalCalls} after leg-dedup)" : '';
$lines = ["**CDR stats** — {$totalCalls} calls{$noteS}{$collapsed}:"];
foreach ($data['by_disposition'] as $d) {
$disp = $this->sanitizeForChat($d['disposition']);
$lines[] = " `{$disp}` — {$d['count']} calls · avg {$d['avg_duration_s']}s · total {$d['duration_total_s']}s";
}
return implode("\n", $lines);
case 'fm_get_cel':
if (empty($data['rows'])) return "No CEL events in the window.";
// Group raw CEL events into per-call digests by linkedid. CEL emits
// 10-20 events per call (CHAN_START/END, STREAM_*, LOCAL_OPTIMIZE,
// etc.) so an event-per-line render drowns the interesting calls.
// Tool output is unchanged — only chat collapses; MCP/CLI clients
// still receive raw rows for composition.
$calls = [];
foreach ($data['rows'] as $r) {
$lid = (string)($r['linkedid'] ?? '');
if ($lid === '') continue;
if (!isset($calls[$lid])) {
$calls[$lid] = [
'linkedid' => $lid,
'start' => $r['eventtime'],
'end' => $r['eventtime'],
'cid_num' => '',
'cid_dnid' => '',
'answered' => false,
'bridges' => [],
'transfers' => 0,
'parks' => 0,
'pickups' => 0,
'complete' => false,
];
}
$c =& $calls[$lid];
if ($r['eventtime'] < $c['start']) $c['start'] = $r['eventtime'];
if ($r['eventtime'] > $c['end']) $c['end'] = $r['eventtime'];
// First non-empty wins. For typical call flows the parties are
// stable across events; for transfer chains this picks a
// representative party (timeline view is the source of truth).
if ($c['cid_num'] === '' && !empty($r['cid_num'])) $c['cid_num'] = $r['cid_num'];
if ($c['cid_dnid'] === '' && !empty($r['cid_dnid'])) $c['cid_dnid'] = $r['cid_dnid'];
switch ($r['eventtype']) {
case 'ANSWER': $c['answered'] = true; break;
case 'BRIDGE_ENTER':
$bid = (is_array($r['extra']) && isset($r['extra']['bridge_id']))
? $r['extra']['bridge_id'] : null;
if ($bid !== null) $c['bridges'][$bid] = true;
break;
case 'BLINDTRANSFER':
case 'ATTENDEDTRANSFER': $c['transfers']++; break;
case 'PARK_START': $c['parks']++; break;
case 'PICKUP': $c['pickups']++; break;
case 'LINKEDID_END': $c['complete'] = true; break;
}
unset($c);
}
uasort($calls, function($a, $b) { return strcmp($b['start'], $a['start']); });
$lines = ["**CEL events** — {$data['count']} events across " . count($calls) . " calls"];
$ec = $data['event_counts'] ?? [];
if (!empty($ec)) {
$summary = [];
foreach (array_slice($ec, 0, 5, true) as $type => $n) {
$summary[] = "`" . $this->sanitizeForChat($type) . "`:{$n}";
}
$lines[] = " Top types: " . implode(' · ', $summary);
}
$lines[] = "";
foreach (array_slice(array_values($calls), 0, 20) as $c) {
$cid = $this->sanitizeForChat($c['cid_num']);
$dnid = $this->sanitizeForChat($c['cid_dnid']);
$bridgeCount = count($c['bridges']);
$dur = max(0, strtotime($c['end']) - strtotime($c['start']));
$marker = '📞';
if ($c['transfers'] > 0) $marker = '🔀';
elseif ($c['parks'] > 0) $marker = '⏸';
elseif ($c['pickups'] > 0) $marker = '📥';
$ans = $c['answered'] ? '✓ answered' : '✗ no answer';
$brP = $bridgeCount === 1 ? '1 bridge' : "{$bridgeCount} bridges";
$tail = [];
if ($c['transfers'] > 0) $tail[] = $c['transfers'] === 1 ? '1 transfer' : "{$c['transfers']} transfers";
if ($c['parks'] > 0) $tail[] = 'parked';
if ($c['pickups'] > 0) $tail[] = 'picked up';
if (!$c['complete']) $tail[] = 'partial';
$tailStr = $tail ? ' · ' . implode(' · ', $tail) : '';
$rawLid = $c['linkedid'];
$lidChip = (preg_match('/^\d+\.\d+$/', $rawLid) === 1)
? "{{cmd:show call timeline {$rawLid}|details}}"
: '`' . $this->sanitizeForChat($rawLid) . '`';
$arrow = ($cid !== '' || $dnid !== '') ? " — `{$cid}` → `{$dnid}`" : '';
$lines[] = " {$marker} {$c['start']}{$arrow} · {$ans} · {$brP} · {$dur}s{$tailStr} · {$lidChip}";
}
if (count($calls) > 20) $lines[] = " ... " . (count($calls) - 20) . " more";
return implode("\n", $lines);
case 'fm_call_timeline':
if (empty($data['found'])) {
return "**Call timeline** — no events for that linkedid.";
}
$lid = $this->sanitizeForChat($data['linkedid']);
$dur = (int)$data['duration_seconds'];
$lines = ["**Call timeline** `{$lid}` — {$dur}s, {$data['event_count']} CEL events"];
$lines[] = " Started: {$data['started_at']} · Ended: {$data['ended_at']}";
if (!empty($data['channels'])) {
$lines[] = " **Channels** (" . count($data['channels']) . "):";
foreach ($data['channels'] as $c) {
$cn = $this->sanitizeForChat($c['channame']);
$cid = $this->sanitizeForChat($c['cid_num']);
$ans = $c['answered'] ? '✓' : '✗';
$role = $this->sanitizeForChat($c['role']);
$lines[] = " `{$cn}` · cid=`{$cid}` · role=`{$role}` · answered={$ans}";
}
}
if (!empty($data['bridges'])) {
$lines[] = " **Bridges** (" . count($data['bridges']) . "):";
foreach ($data['bridges'] as $b) {
$bid = $this->sanitizeForChat($b['bridge_id']);
$lines[] = " `{$bid}` · " . count($b['participants']) . " participant events";
}
}
if (!empty($data['transfers'])) {
$lines[] = " **Transfers** (" . count($data['transfers']) . "):";
foreach ($data['transfers'] as $t) {
$tt = $this->sanitizeForChat($t['type']);
$te = $this->sanitizeForChat($t['transferer']['ext'] ?? '');
$tn = $t['transferer']['name'] !== '' ? ' `' . $this->sanitizeForChat($t['transferer']['name']) . '`' : '';
$lines[] = " {$t['at']} `{$tt}` by `{$te}`{$tn}";
}
}
if (!empty($data['ivr_legs'])) {
$lines[] = " **IVR legs** (" . count($data['ivr_legs']) . "):";
foreach ($data['ivr_legs'] as $l) {
$app = $this->sanitizeForChat($l['app']);
$d = $l['duration_seconds'] !== null ? "{$l['duration_seconds']}s" : '?';
$lines[] = " `{$app}` · {$d}";
}
}
if (!empty($data['park_events'])) $lines[] = " Park events: " . count($data['park_events']);
if (!empty($data['pickup_events'])) $lines[] = " Pickup events: " . count($data['pickup_events']);
return implode("\n", $lines);
case 'fm_cel_transfers':
if (empty($data['rows'])) return "No transfer events in the window.";
$sum = $data['summary'] ?? [];
$lines = ["**Transfers** ({$data['count']}) — blind: " . ($sum['blind'] ?? 0) . " · attended: " . ($sum['attended'] ?? 0)];
foreach (array_slice($data['rows'], 0, 20) as $r) {
$tt = $this->sanitizeForChat($r['type']);
$te = $this->sanitizeForChat($r['transferer']['ext'] ?? '');
$tn = $r['transferer']['name'] !== '' ? ' `' . $this->sanitizeForChat($r['transferer']['name']) . '`' : '';
$rawLid = (string)($r['linkedid'] ?? '');
$lidPart = (preg_match('/^\d+\.\d+$/', $rawLid) === 1)
? " · {{cmd:show call timeline {$rawLid}|timeline}}"
: " · `" . $this->sanitizeForChat($rawLid) . "`";
$dur = $r['call_duration_before_transfer_s'] !== null ? " · after {$r['call_duration_before_transfer_s']}s" : '';
$lines[] = " {$r['at']} `{$tt}` by `{$te}`{$tn}{$dur}{$lidPart}";
}
if (count($data['rows']) > 20) $lines[] = " ... " . (count($data['rows']) - 20) . " more";
return implode("\n", $lines);
case 'fm_get_queue_log':
if (empty($data['rows'])) {
$note = !empty($data['note']) ? "\n_{$data['note']}_" : '';
return "No queue log events in the window.{$note}";
}
$lines = ["**Queue log** ({$data['count']} events):"];
$ec = $data['event_counts'] ?? [];
if (!empty($ec)) {
$summary = [];
foreach ($ec as $type => $n) { $summary[] = "`" . $this->sanitizeForChat($type) . "`:{$n}"; }
$lines[] = " " . implode(' · ', array_slice($summary, 0, 10));
}
foreach (array_slice($data['rows'], 0, 15) as $r) {
$ev = $this->sanitizeForChat($r['event']);
$qn = $this->sanitizeForChat($r['queuename']);
$ag = $this->sanitizeForChat($r['agent']);
$lines[] = " {$r['time']} q=`{$qn}` `{$ev}` agent=`{$ag}`";
}
if (count($data['rows']) > 15) $lines[] = " ... " . (count($data['rows']) - 15) . " more";
return implode("\n", $lines);
case 'fm_queue_metrics':
if (empty($data['rows'])) {
$note = !empty($data['note']) ? "\n_{$data['note']}_" : '';
return "No queue activity in the window.{$note}";
}
$slT = (int)$data['service_level_threshold_seconds'];
$lines = ["**Queue metrics** — SL threshold {$slT}s · {$data['summary']['total_offered']} offered, {$data['summary']['total_answered']} answered, {$data['summary']['total_abandoned']} abandoned"];
foreach ($data['rows'] as $q) {
$qq = $this->sanitizeForChat($q['queue']);
$qn = $q['name'] !== '' ? ' `' . $this->sanitizeForChat($q['name']) . '`' : '';
$lines[] = " **Queue `{$qq}`**{$qn}";
$lines[] = " Offered: {$q['offered']} · Answered: {$q['answered']} · Abandoned: {$q['abandoned']} ({$q['abandonment_rate_display']})";
$lines[] = " SL: {$q['service_level_display']} · ASA: {$q['asa_display']} · AHT: {$q['aht_display']} · Talk: {$q['talk_time_display']}";
if ($q['longest_wait_answered_seconds'] > 0) {
$lines[] = " Longest wait — answered: {$q['longest_wait_answered_seconds']}s · abandoned: {$q['longest_wait_abandoned_seconds']}s";
}
}
return implode("\n", $lines);
case 'fm_agent_metrics':
if (empty($data['rows'])) {
$note = !empty($data['note']) ? "\n_{$data['note']}_" : '';
return "No agent activity in the window.{$note}";
}
$lines = ["**Agent metrics** ({$data['count']} agents):"];
foreach ($data['rows'] as $a) {
$ext = $this->sanitizeForChat((string)($a['agent']['ext'] ?? ''));
$nm = ($a['agent']['name'] ?? '') !== '' ? ' `' . $this->sanitizeForChat($a['agent']['name']) . '`' : '';
$qs = array_map(function($q) { return $this->sanitizeForChat($q); }, $a['queues']);
$queueList = !empty($qs) ? ' on `' . implode('`,`', $qs) . '`' : '';
$lines[] = " **`{$ext}`**{$nm}{$queueList}";
$lines[] = " Calls: {$a['calls_handled']} · Talk: {$a['talk_time_display']} · RNA: {$a['ring_no_answer_count']} · Occupancy: {$a['occupancy_display']}";
$lines[] = " Session: {$a['session_time_display']} · Available: {$a['available_time_display']} · Paused: {$a['total_pause_display']}";
if (!empty($a['pauses'])) {
$pauseStr = [];
foreach (array_slice($a['pauses'], 0, 4) as $p) {
$reason = $this->sanitizeForChat($p['reason']);
$pauseStr[] = "`{$reason}`:{$p['display']} ({$p['count']}x)";
}
$lines[] = " Pause breakdown: " . implode(' · ', $pauseStr);
}
}
return implode("\n", $lines);
case 'fm_queue_wallboard':
$qs = $data['queues'] ?? [];
if (empty($qs)) return "**Wallboard** — no queues configured.";
$sum = $data['summary'] ?? [];
$lines = ["**Wallboard** — {$sum['total_waiting']} waiting · {$sum['agents_available']} avail · {$sum['agents_on_call']} on call · {$sum['agents_paused']} paused"];
foreach ($qs as $q) {
$qe = $this->sanitizeForChat($q['queue']);
$qn = $q['name'] !== '' ? ' `' . $this->sanitizeForChat($q['name']) . '`' : '';
$lines[] = " **`{$qe}`**{$qn} — {$q['callers_waiting']} waiting · longest {$q['longest_current_wait_display']}";
$av = count($q['agents']['available']);
$oc = count($q['agents']['on_call']);
$pa = count($q['agents']['paused']);
$lines[] = " Agents: {$av} avail · {$oc} on call · {$pa} paused";
foreach ($q['agents']['on_call'] as $a) {
$ax = $this->sanitizeForChat((string)($a['ext'] ?? ''));
$an = ($a['name'] ?? '') !== '' ? ' `' . $this->sanitizeForChat($a['name']) . '`' : '';
$lines[] = " 📞 `{$ax}`{$an} (on call)";
}
foreach ($q['agents']['paused'] as $a) {
$ax = $this->sanitizeForChat((string)($a['ext'] ?? ''));
$an = ($a['name'] ?? '') !== '' ? ' `' . $this->sanitizeForChat($a['name']) . '`' : '';
$reason = $this->sanitizeForChat($a['reason'] ?? 'unspecified');
$lines[] = " ⏸ `{$ax}`{$an} (paused: `{$reason}`)";
}
foreach ($q['agents']['available'] as $a) {
$ax = $this->sanitizeForChat((string)($a['ext'] ?? ''));
$an = ($a['name'] ?? '') !== '' ? ' `' . $this->sanitizeForChat($a['name']) . '`' : '';
$lines[] = " ✓ `{$ax}`{$an} (available)";
}
foreach ($q['callers'] ?? [] as $c) {
$cid = $this->sanitizeForChat($c['caller_id']);
$lines[] = " ⏱ caller `{$cid}` waiting {$c['wait_display']}";
}
}
return implode("\n", $lines);
case 'fm_list_trunks':
if (empty($data['trunks'])) {
return "No trunks configured.";
}
$lines = ["**Trunks** ({$data['count']}):"];
foreach ($data['trunks'] as $t) {
$id = $t['trunkid'];
$isDisabled = ($t['disabled'] !== 'off');
$status = $isDisabled ? ' [DISABLED]' : '';
$action = $isDisabled
? "{{cmd:enable trunk {$id}|Enable}}"
: "{{cmd:disable trunk {$id}|Disable}}";
$lines[] = " {{cmd:show trunk {$id}|{$id}}} — {$t['name']} ({$t['tech']}){$status} • {$action}";
}
return implode("\n", $lines);
case 'fm_list_ringgroups':
if (empty($data['ringgroups'])) {
return "No ring groups configured.";
}
$lines = ["**Ring Groups** ({$data['count']}):"];
foreach ($data['ringgroups'] as $g) {
$lines[] = " {{cmd:show ringgroup {$g['grpnum']}|{$g['grpnum']}}} — {$g['description']}";
}
return implode("\n", $lines);
case 'fm_get_ringgroup':
$memberLinks = [];
foreach ($data['members'] ?? [] as $m) {
$ext = preg_replace('/[^0-9]/', '', $m);
$memberLinks[] = $ext ? "{{cmd:show extension {$ext}|{$m}}}" : $m;
}
$members = implode(', ', $memberLinks);
return "**Ring Group {$data['grpnum']}** — {$data['description']}\n"
. " Strategy: {$data['strategy']}\n"
. " Ring time: {$data['grptime']}s\n"
. " Members ({$data['member_count']}): {$members}";
case 'fm_reload':
return $data['message'] ?? 'Reload complete.';
case 'fm_module_list':
if (empty($data['modules'])) {
if (!empty($data['licensing'])) {
return "No commercial modules installed — nothing to license.";
}
return "No modules found.";
}
$upgCount = $data['upgrades_available'] ?? 0;
// Licensing view: two bulleted groups (Licensed / Unlicensed) plus a
// renewal link. Only emitted when the caller passed licensing:true.
// A module counts as licensed when Sysadmin's license map flags it true
// OR it has a non-expired expiry date from the CommercialLicense table.
if (($data['view'] ?? 'list') === 'licensing') {
$licensed = [];
$unlicensed = [];
foreach ($data['modules'] as $m) {
$hasFutureExpiry = !empty($m['expiry']) && empty($m['expired']);
if ($m['licensed'] === true || $hasFutureExpiry) {
$licensed[] = $m;
} else {
$unlicensed[] = $m;
}
}
$lines = ["**Module Licensing** — {$data['count']} commercial • " . count($licensed) . " licensed, " . count($unlicensed) . " unlicensed"];
$support = $data['support_contract'] ?? null;
if (is_array($support)) {
if (!empty($support['expired'])) {
$lines[] = "❌ Support contract **expired** (" . ($support['expiration_date'] ?: 'date unknown') . ")";
} elseif (!empty($support['expiring_soon'])) {
$lines[] = "⚠️ Support contract expiring soon (" . ($support['expiration_date'] ?: 'date unknown') . ")";
} elseif (!empty($support['expiration_date'])) {
$lines[] = "✅ Support contract active (expires {$support['expiration_date']})";
}
}
if (empty($data['sysadmin_available'])) {
$lines[] = "ℹ️ Sysadmin module not present — registration data unavailable.";
}
$renderRow = function($m) {
$name = $this->sanitizeForChat($m['name']);
$ver = $this->sanitizeForChat($m['version']);
$tail = '';
if (!empty($m['expired'])) {
$tail = " • expired {$m['expiry']}";
} elseif (!empty($m['expiry'])) {
$tail = " • expires {$m['expiry']}";
}
return "- {{cmd:module status {$name}|`{$name}`}} v{$ver}{$tail}";
};
if (!empty($licensed)) {
$lines[] = "\n**✅ Licensed** (" . count($licensed) . ")";
foreach ($licensed as $m) $lines[] = $renderRow($m);
}
if (!empty($unlicensed)) {
$lines[] = "\n**❌ Unlicensed** (" . count($unlicensed) . ")";
foreach ($unlicensed as $m) $lines[] = $renderRow($m);
}
if (!empty($data['renewal_url'])) {
$lines[] = "\n[🔗 Renew at Sangoma portal]({$data['renewal_url']})";
}
$lines[] = "{{cmd:update activation|🔄 Refresh activation}} • {{cmd:list modules|← back to modules}}";
return implode("\n", $lines);
}
// Summary view: counts per license bucket as clickable filters. Avoids dumping
// 100+ modules into chat when the user just typed "list modules".
if (($data['view'] ?? 'list') === 'summary') {
$buckets = ['Commercial' => 0, 'AGPLv3' => 0, 'GPLv3+' => 0, 'GPLv2' => 0, 'Other' => 0];
foreach ($data['modules'] as $m) {
$buckets[$m['bucket'] ?? 'Other']++;
}
$lines = ["**Modules** ({$data['count']} installed)"];
if ($upgCount > 0) {
$lines[0] .= " — ⬆️ {$upgCount} {{cmd:upgrade all modules|upgrade(s) available}}";
}
$lines[] = "\nFilter by license:";
$bucketKey = ['Commercial' => 'commercial', 'AGPLv3' => 'agpl', 'GPLv3+' => 'gpl3', 'GPLv2' => 'gpl2', 'Other' => 'other'];
foreach ($buckets as $name => $cnt) {
if ($cnt === 0) continue;
$key = $bucketKey[$name];
$lines[] = " {{cmd:list modules {$key}|{$name} ({$cnt})}}";
}
$footer = "\n{{cmd:list all modules|Show all}} • {{cmd:check for upgrades|⬆️ Check for upgrades}}";
if (($buckets['Commercial'] ?? 0) > 0) {
$footer .= " • {{cmd:show licensing|🔐 Licensing}}";
}
$lines[] = $footer;
return implode("\n", $lines);
}
// List view: grouped by license. Used when the user filtered or asked for all.
$grouped = ['Commercial' => [], 'AGPLv3' => [], 'GPLv3+' => [], 'GPLv2' => [], 'Other' => []];
foreach ($data['modules'] as $m) {
$grouped[$m['bucket'] ?? 'Other'][] = $m;
}
$header = "**Modules** ({$data['count']} shown)";
if ($upgCount > 0) {
$header .= " — ⬆️ {$upgCount} {{cmd:upgrade all modules|upgrade(s) available}}";
}
$lines = ["{$header}:"];
foreach ($grouped as $license => $mods) {
if (empty($mods)) continue;
$lines[] = "\n**{$license}** (" . count($mods) . "):";
foreach ($mods as $m) {
$upg = '';
if (!empty($m['upgrade_available'])) {
$upg = " ⬆️ {{cmd:upgrade module {$m['name']}|v{$m['upgrade_available']}}}";
}
$lines[] = " {{cmd:module status {$m['name']}|{$m['name']}}} — v{$m['version']}{$upg}";
}
}
return implode("\n", $lines);
case 'fm_check_upgrades':