-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.php
More file actions
1564 lines (1344 loc) · 49.8 KB
/
lib.php
File metadata and controls
1564 lines (1344 loc) · 49.8 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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library functions for Moodle MCP.
*
* @package local_moodlemcp
* @copyright 2026 Studio LXD <hello@studiolxd.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// Include generated service function definitions.
require_once(__DIR__ . '/db/service_functions.php');
/**
* Returns the base URL for the MoodleMCP API.
*
* @return string
*/
function local_moodlemcp_api_base_url(): string {
return 'https://moodlemcp.com';
}
// Note: local_moodlemcp_get_service_definitions() is now defined in db/service_functions.php
/**
* Ensures the MoodleMCP services exist (creates missing ones only).
*
* @return int Number of services created.
*/
function local_moodlemcp_ensure_services(): int {
global $DB;
$created = 0;
$now = time();
foreach (local_moodlemcp_get_service_definitions() as $service) {
if ($DB->record_exists('external_services', ['shortname' => $service['shortname']])) {
continue;
}
$record = new stdClass();
$record->name = $service['name'];
$record->shortname = $service['shortname'];
$record->enabled = 1;
$record->restrictedusers = 1;
$record->requiredcapability = '';
$record->component = 'local_moodlemcp';
$record->timecreated = $now;
$record->timemodified = $now;
$serviceid = $DB->insert_record('external_services', $record);
local_moodlemcp_set_service_functions($serviceid, $service['functions']);
$created++;
}
return $created;
}
/**
* Restores a service's function list to the baseline definitions.
*
* @param string $shortname
* @return bool
*/
function local_moodlemcp_restore_service_baseline(string $shortname): bool {
global $DB;
$definition = null;
foreach (local_moodlemcp_get_service_definitions() as $service) {
if ($service['shortname'] === $shortname) {
$definition = $service;
break;
}
}
if ($definition === null) {
return false;
}
$record = $DB->get_record('external_services', ['shortname' => $shortname], 'id', IGNORE_MISSING);
if (!$record) {
return false;
}
local_moodlemcp_set_service_functions((int) $record->id, $definition['functions']);
return true;
}
/**
* Updates the function whitelist for a service.
*
* @param int $serviceid
* @param string[] $functions
* @return void
*/
function local_moodlemcp_set_service_functions(int $serviceid, array $functions): void {
global $DB;
$DB->delete_records('external_services_functions', ['externalserviceid' => $serviceid]);
foreach ($functions as $functionname) {
// Only add functions that exist in this Moodle installation.
if ($DB->record_exists('external_functions', ['name' => $functionname])) {
$sf = new stdClass();
$sf->externalserviceid = $serviceid;
$sf->functionname = $functionname;
$DB->insert_record('external_services_functions', $sf);
}
}
}
/**
* Syncs functions for ALL services based on their definitions.
* Called during install and upgrade.
*
* @return void
*/
function local_moodlemcp_sync_all_service_functions(): void {
foreach (local_moodlemcp_get_service_definitions() as $service) {
local_moodlemcp_restore_service_baseline($service['shortname']);
}
}
/**
* Returns a list of available external functions for form selection.
*
* @return array<string,string>
*/
function local_moodlemcp_get_external_function_choices(): array {
global $DB;
$records = $DB->get_records('external_functions', null, 'name ASC', 'name,component');
$choices = [];
foreach ($records as $record) {
$component = $record->component !== '' ? $record->component : 'core';
$choices[$record->name] = $record->name . ' (' . $component . ')';
}
return $choices;
}
/**
* Determines whether a user has any of the given role shortnames at system context.
*
* @param int $userid
* @param string[] $shortnames
* @return bool
*/
function local_moodlemcp_user_has_system_role(int $userid, array $shortnames): bool {
global $DB;
if (empty($shortnames)) {
return false;
}
$systemcontext = context_system::instance();
list($insql, $params) = $DB->get_in_or_equal($shortnames, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$params['contextid'] = $systemcontext->id;
$sql = "SELECT 1
FROM {role_assignments} ra
JOIN {role} r ON r.id = ra.roleid
WHERE ra.userid = :userid
AND ra.contextid = :contextid
AND r.shortname {$insql}";
return $DB->record_exists_sql($sql, $params);
}
/**
* Determines whether a user has any of the given role shortnames in any course context.
*
* @param int $userid
* @param string[] $shortnames
* @return bool
*/
function local_moodlemcp_user_has_course_role(int $userid, array $shortnames): bool {
global $DB;
if (empty($shortnames)) {
return false;
}
list($insql, $params) = $DB->get_in_or_equal($shortnames, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$params['contextlevel'] = CONTEXT_COURSE;
$sql = "SELECT 1
FROM {role_assignments} ra
JOIN {role} r ON r.id = ra.roleid
JOIN {context} c ON c.id = ra.contextid
WHERE ra.userid = :userid
AND r.shortname {$insql}
AND c.contextlevel = :contextlevel";
return $DB->record_exists_sql($sql, $params);
}
/**
* Calculates the effective role array for a Moodle user.
*
* @param int $userid
* @return string[]
*/
function local_moodlemcp_get_effective_roles(int $userid): array {
$roles = [];
if (is_siteadmin($userid)) {
$roles[] = 'admin';
}
// Check for manager role at system level OR course level
if (
local_moodlemcp_user_has_system_role($userid, ['manager']) ||
local_moodlemcp_user_has_course_role($userid, ['manager'])
) {
$roles[] = 'manager';
}
$haseditingteacher = local_moodlemcp_user_has_course_role($userid, ['editingteacher']);
if ($haseditingteacher) {
$roles[] = 'editingteacher';
}
$hasnonediting = local_moodlemcp_user_has_course_role($userid, ['teacher', 'noneditingteacher']);
if ($hasnonediting) {
$roles[] = 'teacher';
}
if (local_moodlemcp_user_has_course_role($userid, ['student'])) {
$roles[] = 'student';
}
$hascourse = in_array('editingteacher', $roles, true) ||
in_array('teacher', $roles, true) ||
in_array('student', $roles, true);
if (!$hascourse) {
$roles[] = 'user';
}
return array_values(array_unique($roles));
}
/**
* Returns the role name from a MoodleMCP service shortname.
*
* @param string $shortname
* @return string
*/
function local_moodlemcp_role_from_service(string $shortname): string {
if (substr($shortname, 0, 10) === 'moodlemcp_') {
return substr($shortname, 10);
}
if (substr($shortname, 0, 7) === 'moodle_') {
return substr($shortname, 7);
}
return $shortname;
}
/**
* Checks if auto-sync is enabled for a specific service.
*
* @param string $service Service shortname (e.g., 'moodlemcp_admin', 'moodlemcp_teacher')
* @return bool
*/
function local_moodlemcp_is_auto_sync_enabled_for_service(string $service): bool {
$role = local_moodlemcp_role_from_service($service);
$config_key = 'auto_sync_' . $role;
return (int) get_config('local_moodlemcp', $config_key) === 1;
}
/**
* Checks if auto-sync is enabled for any MoodleMCP service.
*
* @return bool
*/
function local_moodlemcp_has_any_auto_sync_enabled(): bool {
foreach (local_moodlemcp_get_service_definitions() as $service) {
if (local_moodlemcp_is_auto_sync_enabled_for_service($service['shortname'])) {
return true;
}
}
// Backward compatibility for legacy global flag.
return (int) get_config('local_moodlemcp', 'auto_sync') === 1;
}
/**
* Gets the human-readable name for a service.
*
* @param string $service Service shortname (e.g., 'moodlemcp_admin')
* @return string
*/
function local_moodlemcp_get_service_display_name(string $service): string {
$role = local_moodlemcp_role_from_service($service);
$string_key = 'service_name_' . $role;
if (get_string_manager()->string_exists($string_key, 'local_moodlemcp')) {
return get_string($string_key, 'local_moodlemcp');
}
// Fallback to service shortname
return $service;
}
/**
* Determines whether a user is eligible for a MoodleMCP service.
*
* @param int $userid
* @param string $shortname
* @return bool
*/
function local_moodlemcp_user_is_eligible_for_service(int $userid, string $shortname): bool {
$role = local_moodlemcp_role_from_service($shortname);
switch ($role) {
case 'admin':
return is_siteadmin($userid);
case 'manager':
return local_moodlemcp_user_has_system_role($userid, ['manager']) ||
local_moodlemcp_user_has_course_role($userid, ['manager']);
case 'editingteacher':
return local_moodlemcp_user_has_course_role($userid, ['editingteacher']);
case 'teacher':
// Checks for non-editing teacher role (legacy names: teacher, noneditingteacher)
return local_moodlemcp_user_has_course_role($userid, ['teacher', 'noneditingteacher']);
case 'student':
return local_moodlemcp_user_has_course_role($userid, ['student']);
case 'user':
return true;
default:
return false;
}
}
/**
* Maps a role name to the corresponding MoodleMCP service shortname.
*
* @param string $role
* @return string
*/
function local_moodlemcp_service_for_role(string $role): string {
return 'moodlemcp_' . $role;
}
/**
* Returns the service shortnames required for the given roles.
*
* @param string[] $roles
* @return string[]
*/
function local_moodlemcp_services_for_roles(array $roles): array {
$services = [];
foreach ($roles as $role) {
$services[] = local_moodlemcp_service_for_role($role);
}
return array_values(array_unique($services));
}
/**
* Picks the primary service shortname for a user based on role priority.
*
* @param string[] $roles
* @return string
*/
function local_moodlemcp_primary_service_for_roles(array $roles): string {
return local_moodlemcp_service_for_role(local_moodlemcp_primary_role_for_roles($roles));
}
/**
* Picks the primary role name for a user based on role priority.
*
* @param string[] $roles
* @return string
*/
function local_moodlemcp_primary_role_for_roles(array $roles): string {
$priority = ['admin', 'manager', 'editingteacher', 'teacher', 'student', 'user'];
foreach ($priority as $role) {
if (in_array($role, $roles, true)) {
return $role;
}
}
return 'user';
}
/**
* Ensures a user is authorized for a service.
*
* @param int $userid
* @param int $serviceid
* @return void
*/
function local_moodlemcp_authorize_user_for_service(int $userid, int $serviceid): void {
global $DB;
if (
$DB->record_exists('external_services_users', [
'externalserviceid' => $serviceid,
'userid' => $userid,
])
) {
return;
}
$record = new stdClass();
$record->externalserviceid = $serviceid;
$record->userid = $userid;
$DB->insert_record('external_services_users', $record);
}
/**
* Removes a user from all MoodleMCP services except the given service id.
*
* @param int $userid
* @param int $serviceid
* @return void
*/
function local_moodlemcp_remove_user_from_other_services(int $userid, int $serviceid): void {
global $DB;
$serviceids = local_moodlemcp_get_moodlemcp_service_ids();
if (empty($serviceids)) {
return;
}
$serviceids = array_values(array_diff($serviceids, [$serviceid]));
if (empty($serviceids)) {
return;
}
list($insql, $params) = $DB->get_in_or_equal($serviceids, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$DB->delete_records_select('external_services_users', "userid = :userid AND externalserviceid {$insql}", $params);
}
/**
* Revokes tokens for a user and service.
*
* @param int $userid
* @param int $serviceid
* @return void
*/
function local_moodlemcp_revoke_user_tokens(int $userid, int $serviceid): void {
global $DB;
$DB->delete_records('external_tokens', [
'userid' => $userid,
'externalserviceid' => $serviceid,
]);
}
/**
* Revokes all MoodleMCP tokens for a user except the given service id.
*
* @param int $userid
* @param int $serviceid
* @return void
*/
function local_moodlemcp_revoke_other_service_tokens(int $userid, int $serviceid): void {
global $DB;
$serviceids = local_moodlemcp_get_moodlemcp_service_ids();
if (empty($serviceids)) {
return;
}
$serviceids = array_values(array_diff($serviceids, [$serviceid]));
if (empty($serviceids)) {
return;
}
list($insql, $params) = $DB->get_in_or_equal($serviceids, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$DB->delete_records_select('external_tokens', "userid = :userid AND externalserviceid {$insql}", $params);
}
/**
* Revokes all MoodleMCP tokens for a user across all MoodleMCP services.
*
* @param int $userid
* @return void
*/
function local_moodlemcp_revoke_moodlemcp_tokens(int $userid): void {
global $DB;
$serviceids = local_moodlemcp_get_moodlemcp_service_ids();
if (empty($serviceids)) {
return;
}
list($insql, $params) = $DB->get_in_or_equal($serviceids, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$DB->delete_records_select('external_tokens', "userid = :userid AND externalserviceid {$insql}", $params);
}
/**
* Creates a new Moodle web service token for a user/service, rotating any previous one.
*
* @param int $userid
* @param int $serviceid
* @param int $validuntil
* @return string
*/
function local_moodlemcp_rotate_user_token(int $userid, int $serviceid, int $validuntil = 0): string {
global $CFG;
require_once($CFG->dirroot . '/webservice/lib.php');
require_once($CFG->libdir . '/externallib.php');
$systemcontext = context_system::instance();
local_moodlemcp_revoke_user_tokens($userid, $serviceid);
return external_generate_token(EXTERNAL_TOKEN_PERMANENT, $serviceid, $userid, $systemcontext, $validuntil, '');
}
/**
* Returns an existing token for a user/service pair.
*
* @param int $userid
* @param int $serviceid
* @return string|null
*/
function local_moodlemcp_get_user_service_token(int $userid, int $serviceid): ?string {
global $DB;
$record = $DB->get_record('external_tokens', [
'userid' => $userid,
'externalserviceid' => $serviceid,
], 'token', IGNORE_MISSING);
return $record ? (string) $record->token : null;
}
/**
* Revokes a Moodle token by its raw value.
*
* @param string $token
* @return void
*/
function local_moodlemcp_revoke_token_value(string $token): void {
global $DB;
if ($token === '') {
return;
}
$DB->delete_records('external_tokens', ['token' => $token]);
}
/**
* Returns a user record based on a Moodle web service token.
*
* @param string $token
* @return stdClass|null
*/
function local_moodlemcp_get_user_by_token(string $token): ?stdClass {
global $DB;
if ($token === '') {
return null;
}
$tokerecord = $DB->get_record('external_tokens', ['token' => $token], 'userid', IGNORE_MISSING);
if (!$tokerecord) {
return null;
}
return $DB->get_record('user', ['id' => $tokerecord->userid, 'deleted' => 0], '*', IGNORE_MISSING) ?: null;
}
/**
* Returns the external service id for a MoodleMCP service shortname.
*
* @param string $shortname
* @return int|null
*/
function local_moodlemcp_get_service_id(string $shortname): ?int {
global $DB;
$record = $DB->get_record('external_services', ['shortname' => $shortname], 'id', IGNORE_MISSING);
return $record ? (int) $record->id : null;
}
/**
* Returns all MoodleMCP service ids that exist.
*
* @return int[]
*/
function local_moodlemcp_get_moodlemcp_service_ids(): array {
global $DB;
$shortnames = array_column(local_moodlemcp_get_service_definitions(), 'shortname');
if (empty($shortnames)) {
return [];
}
list($insql, $params) = $DB->get_in_or_equal($shortnames, SQL_PARAMS_NAMED);
$records = $DB->get_records_select('external_services', "shortname {$insql}", $params, '', 'id');
$ids = [];
foreach ($records as $record) {
$ids[] = (int) $record->id;
}
return $ids;
}
/**
* Deletes MCP keys for a user in the panel and removes their Moodle tokens.
*
* @param int $userid
* @return void
*/
function local_moodlemcp_delete_user_keys(int $userid): void {
global $DB;
$serviceids = local_moodlemcp_get_moodlemcp_service_ids();
if (empty($serviceids)) {
return;
}
list($insql, $params) = $DB->get_in_or_equal($serviceids, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$tokens = $DB->get_records_select('external_tokens', "userid = :userid AND externalserviceid {$insql}", $params);
if (empty($tokens)) {
return;
}
$tokenvalues = [];
foreach ($tokens as $token) {
if (!empty($token->token)) {
$tokenvalues[] = (string) $token->token;
}
}
$keymap = [];
$list = local_moodlemcp_panel_list_keys();
if ($list['ok'] && !empty($list['data']['keys']) && is_array($list['data']['keys'])) {
foreach ($list['data']['keys'] as $key) {
if (!empty($key['moodleToken']) && !empty($key['mcpKey'])) {
$keymap[(string) $key['moodleToken']] = (string) $key['mcpKey'];
}
}
}
foreach ($tokenvalues as $tokenvalue) {
if (isset($keymap[$tokenvalue])) {
local_moodlemcp_panel_delete_key($keymap[$tokenvalue]);
}
local_moodlemcp_revoke_token_value($tokenvalue);
}
}
/**
* Recalculates and updates the user's MCP key based on their remaining service assignments.
*
* Use this after removing a user from a service to ensure their key downgrades to
* the next available role or is revoked if no services remain.
*
* @param int $userid
* @return array{ok:bool,data:array|null,error:string|null}
*/
function local_moodlemcp_recalculate_user_key(int $userid): array {
global $DB;
// 1. Get all MoodleMCP services
$serviceids = local_moodlemcp_get_moodlemcp_service_ids();
if (empty($serviceids)) {
return ['ok' => false, 'data' => null, 'error' => 'no_services_defined'];
}
// 2. Find which of these the user is assigned to
list($insql, $params) = $DB->get_in_or_equal($serviceids, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$assignments = $DB->get_records_select(
'external_services_users',
"userid = :userid AND externalserviceid {$insql}",
$params
);
if (empty($assignments)) {
// User has no remaining MoodleMCP services. DELETE everything (cleanup).
local_moodlemcp_delete_user_keys($userid);
// Return OK since deletion was successful/intended
return ['ok' => true, 'data' => null, 'error' => 'key_deleted'];
}
// 3. Determine the best remaining role
$assignedserviceids = array_column($assignments, 'externalserviceid');
$definitions = local_moodlemcp_get_service_definitions();
$userroles = [];
foreach ($definitions as $def) {
$sid = local_moodlemcp_get_service_id($def['shortname']);
if ($sid && in_array($sid, $assignedserviceids)) {
$userroles[] = local_moodlemcp_role_from_service($def['shortname']);
}
}
$primaryrole = local_moodlemcp_primary_role_for_roles($userroles);
$targetservice = local_moodlemcp_service_for_role($primaryrole);
$targetserviceid = local_moodlemcp_get_service_id($targetservice);
if (!$targetserviceid) {
return ['ok' => false, 'data' => null, 'error' => 'no_target_service'];
}
// 4. Ensure token points to this target service
// Important: if the token changes (e.g. upgraded service), the old key on the panel might remain orphaned
// unless the API handles token updates by user/license.
// To be safe, we check if the token changed and if so, we should remove the old one from the panel?
// Actually, local_moodlemcp_revoke_other_service_tokens handles the token removal locally.
// We need to identify if there are other keys on the panel for this user that DO NOT match the new token.
// Helper to cleanup orphans on the panel:
local_moodlemcp_cleanup_orphan_keys_on_panel($userid, $targetserviceid);
local_moodlemcp_revoke_other_service_tokens($userid, $targetserviceid);
$token = local_moodlemcp_get_user_service_token($userid, $targetserviceid);
if (!$token) {
$token = local_moodlemcp_rotate_user_token($userid, $targetserviceid, 0);
}
// 5. Update the Panel with the set of roles
return local_moodlemcp_panel_create_key($token, $userroles, null);
}
/**
* Clean up keys on the panel that belong to a user but don't match their primary service token.
*
* @param int $userid
* @param int $targetserviceid
* @return void
*/
function local_moodlemcp_cleanup_orphan_keys_on_panel(int $userid, int $targetserviceid): void {
global $DB;
// Get all valid tokens for this user across all moodlemcp services
$serviceids = local_moodlemcp_get_moodlemcp_service_ids();
if (empty($serviceids)) {
return;
}
list($insql, $params) = $DB->get_in_or_equal($serviceids, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$tokens = $DB->get_records_select('external_tokens', "userid = :userid AND externalserviceid {$insql}", $params);
$tokensrevocable = [];
foreach ($tokens as $t) {
if ((int) $t->externalserviceid !== $targetserviceid) {
$tokensrevocable[] = (string) $t->token;
}
}
if (empty($tokensrevocable)) {
return;
}
$list = local_moodlemcp_panel_list_keys();
if ($list['ok'] && !empty($list['data']['keys']) && is_array($list['data']['keys'])) {
foreach ($list['data']['keys'] as $key) {
if (!empty($key['moodleToken']) && in_array((string) $key['moodleToken'], $tokensrevocable, true)) {
if (!empty($key['mcpKey'])) {
local_moodlemcp_panel_delete_key((string) $key['mcpKey']);
}
}
}
}
}
/**
* Sends the MCP key email to a user.
*
* @param stdClass $user
* @param string $mcpkey
* @param string $mcpurl
* @return bool
*/
function local_moodlemcp_send_key_email(stdClass $user, string $mcpkey, string $mcpurl): bool {
$subjecttemplate = (string) get_config('local_moodlemcp', 'email_subject');
$bodytemplate = (string) get_config('local_moodlemcp', 'email_body');
$replacements = [
'{$a->firstname}' => $user->firstname ?? '',
'{$a->lastname}' => $user->lastname ?? '',
'{$a->username}' => $user->username ?? '',
'{$a->email}' => $user->email ?? '',
'{$a->mcpkey}' => $mcpkey,
'{$a->mcpurl}' => $mcpurl,
];
$subject = strtr($subjecttemplate, $replacements);
$body = strtr($bodytemplate, $replacements);
return email_to_user($user, core_user::get_noreply_user(), $subject, $body);
}
/**
* Revokes MCP keys for a user in the panel and removes their Moodle tokens.
*
* @param int $userid
* @return void
*/
function local_moodlemcp_revoke_user_keys(int $userid): void {
global $DB;
$serviceids = local_moodlemcp_get_moodlemcp_service_ids();
if (empty($serviceids)) {
return;
}
list($insql, $params) = $DB->get_in_or_equal($serviceids, SQL_PARAMS_NAMED);
$params['userid'] = $userid;
$tokens = $DB->get_records_select('external_tokens', "userid = :userid AND externalserviceid {$insql}", $params);
if (empty($tokens)) {
return;
}
$tokenvalues = [];
foreach ($tokens as $token) {
if (!empty($token->token)) {
$tokenvalues[] = (string) $token->token;
}
}
$keymap = [];
$list = local_moodlemcp_panel_list_keys();
if ($list['ok'] && !empty($list['data']['keys']) && is_array($list['data']['keys'])) {
foreach ($list['data']['keys'] as $key) {
if (!empty($key['moodleToken']) && !empty($key['mcpKey'])) {
$keymap[(string) $key['moodleToken']] = (string) $key['mcpKey'];
}
}
}
foreach ($tokenvalues as $tokenvalue) {
if (isset($keymap[$tokenvalue])) {
local_moodlemcp_panel_revoke_key($keymap[$tokenvalue]);
}
local_moodlemcp_revoke_token_value($tokenvalue);
}
}
/**
* Calls a MoodleMCP panel API endpoint.
*
* @param string $path
* @param array $payload
* @return array{ok:bool,data:array|null,error:string|null}
*/
function local_moodlemcp_call_panel_api(string $path, array $payload): array {
global $CFG;
require_once($CFG->libdir . '/filelib.php');
$curl = new curl(['timeout' => 15]);
$curl->setHeader('Accept: application/json');
$curl->setHeader('Content-Type: application/json');
$response = $curl->post(local_moodlemcp_api_base_url() . $path, json_encode($payload));
$info = $curl->get_info();
if (!empty($curl->error)) {
$errormsg = $curl->error . ' (Status: ' . ($info['http_code'] ?? 'N/A') . ') Payload: ' . json_encode($payload);
debugging('local_moodlemcp: API call to ' . $path . ' failed: ' . $errormsg, DEBUG_DEVELOPER);
return ['ok' => false, 'data' => null, 'error' => $errormsg];
}
$decoded = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
$errormsg = 'invalid_json: ' . substr($response, 0, 200) . ' (Status: ' . ($info['http_code'] ?? 'N/A')
. ') Payload: ' . json_encode($payload);
debugging('local_moodlemcp: API call to ' . $path . ' returned invalid JSON: ' . $errormsg, DEBUG_DEVELOPER);
return ['ok' => false, 'data' => null, 'error' => $errormsg];
}
if (isset($decoded['error'])) {
$message = is_string($decoded['error']) ? $decoded['error'] : 'api_error';
if (isset($decoded['message']) && is_string($decoded['message'])) {
$message = $decoded['message'];
}
debugging('local_moodlemcp: API call to ' . $path . ' returned error: ' . $message, DEBUG_DEVELOPER);
return ['ok' => false, 'data' => $decoded, 'error' => $message];
}
if (array_key_exists('success', $decoded) && empty($decoded['success'])) {
debugging('local_moodlemcp: API call to ' . $path . ' returned success=false', DEBUG_DEVELOPER);
return ['ok' => false, 'data' => $decoded, 'error' => 'api_error'];
}
return ['ok' => true, 'data' => $decoded, 'error' => null];
}
/**
* Returns the configured license key.
*
* @return string
*/
function local_moodlemcp_get_license_key(): string {
return (string) get_config('local_moodlemcp', 'license_key');
}
/**
* Returns whether the license is validated.
*
* @return bool
*/
function local_moodlemcp_license_is_valid(): bool {
return get_config('local_moodlemcp', 'license_status') === 'ok';
}
/**
* Creates or updates a MCP key on the panel.
*
* @param string $moodletoken
* @param string|array $moodleroles Single role string or array of role strings
* @param string|null $expireson
* @return array{ok:bool,data:array|null,error:string|null}
*/
function local_moodlemcp_panel_create_key(string $moodletoken, $moodleroles, ?string $expireson): array {
$license = local_moodlemcp_get_license_key();
if ($license === '' || !local_moodlemcp_license_is_valid()) {
return ['ok' => false, 'data' => null, 'error' => 'invalid_license'];
}
$user = local_moodlemcp_get_user_by_token($moodletoken);
$username = $user ? $user->username : '';
// Ensure we send an array
$roles = is_array($moodleroles) ? $moodleroles : [$moodleroles];
$payload = [
'licenseKey' => $license,
'moodleToken' => $moodletoken,
'moodleRoles' => $roles,
'moodleUsername' => $username,
'expiresOn' => $expireson ?: null,
];
return local_moodlemcp_call_panel_api('/api/mcp/create', $payload);
}
/**
* Fetches all keys for this license from the panel.
*
* @return array{ok:bool,data:array|null,error:string|null}
*/
function local_moodlemcp_panel_list_keys(): array {
$license = local_moodlemcp_get_license_key();
if ($license === '' || !local_moodlemcp_license_is_valid()) {
return ['ok' => false, 'data' => null, 'error' => 'invalid_license'];
}
return local_moodlemcp_call_panel_api('/api/mcp/list', ['licenseKey' => $license]);
}
/**
* Revokes a key in the panel.
*
* @param string $mcpkey
* @return array{ok:bool,data:array|null,error:string|null}
*/
function local_moodlemcp_panel_revoke_key(string $mcpkey): array {
$license = local_moodlemcp_get_license_key();
if ($license === '' || $mcpkey === '' || !local_moodlemcp_license_is_valid()) {
return ['ok' => false, 'data' => null, 'error' => 'invalid_license'];
}
$payload = [
'licenseKey' => $license,
'mcpKey' => $mcpkey,
];
return local_moodlemcp_call_panel_api('/api/mcp/revoke', $payload);
}
/**
* Deletes a key in the panel.