-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathlib.php
More file actions
1170 lines (1031 loc) · 43.5 KB
/
Copy pathlib.php
File metadata and controls
1170 lines (1031 loc) · 43.5 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/>.
/**
* Plugin library.
*
* @package auth_oidc
* @author James McQuillan <james.mcquillan@remote-learner.net>
* @author Lai Wei <lai.wei@enovation.ie>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright (C) 2014 onwards Microsoft, Inc. (http://microsoft.com/)
*/
use auth_oidc\jwt;
use auth_oidc\utils;
use core\context\system;
use core\context\user;
use core\url;
// IdP types.
/**
* Microsoft Entra ID identity provider type.
*/
const AUTH_OIDC_IDP_TYPE_MICROSOFT_ENTRA_ID = 1;
/**
* Microsoft Identity Platform identity provider type.
*/
const AUTH_OIDC_IDP_TYPE_MICROSOFT_IDENTITY_PLATFORM = 2;
/**
* Other identity provider type.
*/
const AUTH_OIDC_IDP_TYPE_OTHER = 3;
// Microsoft Entra ID / Microsoft endpoint version.
/**
* Unknown Microsoft endpoint version.
*/
const AUTH_OIDC_MICROSOFT_ENDPOINT_VERSION_UNKNOWN = 0;
/**
* Microsoft endpoint version 1.
*/
const AUTH_OIDC_MICROSOFT_ENDPOINT_VERSION_1 = 1;
/**
* Microsoft endpoint version 2.
*/
const AUTH_OIDC_MICROSOFT_ENDPOINT_VERSION_2 = 2;
// OIDC application authentication method.
/**
* OIDC application authentication method using secret.
*/
const AUTH_OIDC_AUTH_METHOD_SECRET = 1;
/**
* OIDC application authentication method using certificate.
*/
const AUTH_OIDC_AUTH_METHOD_CERTIFICATE = 2;
// OIDC application auth certificate source.
/**
* OIDC application authentication certificate source from text.
*/
const AUTH_OIDC_AUTH_CERT_SOURCE_TEXT = 1;
/**
* OIDC application authentication certificate source from file.
*/
const AUTH_OIDC_AUTH_CERT_SOURCE_FILE = 2;
/**
* File extensions accepted for the 'auth_oidc/customicon' upload setting.
*
* SVG is deliberately excluded: unlike the plugin's own bundled stock icons, this file is
* admin-uploaded and served as-is from dataroot, so allowing SVG here would let an admin
* upload active content (script/event handlers). Shared by the setting's file picker
* (settings.php) and the extension allow-list checked before copying the file into
* pix_plugins (auth_oidc_initialize_customicon()) so the two can't drift apart.
*/
const AUTH_OIDC_CUSTOMICON_ALLOWED_EXTENSIONS = ['png', 'jpg', 'gif'];
/**
* Callback invoked when application credentials or endpoint settings are updated.
*
* Clears cached application tokens and the setup verification result so that
* the connection is re-validated with the new values.
*
* @param string $settingname The full name of the setting that was updated.
* @return void
*/
function auth_oidc_reset_app_tokens($settingname) {
// Use a static flag so cache purging and token clearing only happen once per request,
// even when multiple settings with this callback change in the same save.
static $cachespurged = false;
if (!$cachespurged) {
unset_config('apptokens', 'local_o365');
unset_config('azuresetupresult', 'local_o365');
purge_all_caches();
$cachespurged = true;
}
if (auth_oidc_is_local_365_installed()) {
$idptype = get_config('auth_oidc', 'idptype');
if ($idptype && $idptype != AUTH_OIDC_IDP_TYPE_OTHER) {
// Use a static flag so only one notification is queued per request,
// even when multiple settings with this callback change in the same save.
static $notificationqueued = false;
if (!$notificationqueued) {
$localo365configurl = new \core\url('/admin/settings.php', ['section' => 'local_o365']);
\core\notification::warning(
get_string('application_updated_microsoft_notify', 'auth_oidc', $localo365configurl->out())
);
$notificationqueued = true;
}
}
}
}
/**
* Validate authentication settings for invalid combinations.
*
* Checks for invalid combinations that could break authentication:
* - Certificate auth with Entra v1/Other IdP types (not supported)
* - Secret auth without a configured client secret
* - Certificate auth without required cert/key fields
*
* @param string $settingname The full name of the setting that was updated.
* @return void
*/
function auth_oidc_validate_auth_settings(string $settingname) {
auth_oidc_validate_binding_username_claim();
$idptype = get_config('auth_oidc', 'idptype');
$clientauthmethod = get_config('auth_oidc', 'clientauthmethod');
if (empty($idptype) || empty($clientauthmethod)) {
return;
}
$errors = [];
// Validate clientauthmethod according to idptype.
if (in_array($idptype, [AUTH_OIDC_IDP_TYPE_MICROSOFT_ENTRA_ID, AUTH_OIDC_IDP_TYPE_OTHER])) {
if ($clientauthmethod != AUTH_OIDC_AUTH_METHOD_SECRET) {
$errors[] = get_string('error_invalid_client_authentication_method', 'auth_oidc');
}
} else if ($idptype == AUTH_OIDC_IDP_TYPE_MICROSOFT_IDENTITY_PLATFORM) {
if (!in_array($clientauthmethod, [AUTH_OIDC_AUTH_METHOD_SECRET, AUTH_OIDC_AUTH_METHOD_CERTIFICATE])) {
$errors[] = get_string('error_invalid_client_authentication_method', 'auth_oidc');
}
}
// Validate authentication-method-specific requirements.
if ($clientauthmethod == AUTH_OIDC_AUTH_METHOD_SECRET) {
$clientsecret = get_config('auth_oidc', 'clientsecret');
if (empty($clientsecret)) {
$errors[] = get_string('error_empty_client_secret', 'auth_oidc');
}
} else if ($clientauthmethod == AUTH_OIDC_AUTH_METHOD_CERTIFICATE) {
$clientcertsource = get_config('auth_oidc', 'clientcertsource');
if ($clientcertsource == AUTH_OIDC_AUTH_CERT_SOURCE_TEXT) {
$clientprivatekey = get_config('auth_oidc', 'clientprivatekey');
$clientcert = get_config('auth_oidc', 'clientcert');
if (empty($clientprivatekey)) {
$errors[] = get_string('error_empty_client_private_key', 'auth_oidc');
}
if (empty($clientcert)) {
$errors[] = get_string('error_empty_client_cert', 'auth_oidc');
}
} else if ($clientcertsource == AUTH_OIDC_AUTH_CERT_SOURCE_FILE) {
$clientprivatekeyfile = get_config('auth_oidc', 'clientprivatekeyfile');
$clientcertfile = get_config('auth_oidc', 'clientcertfile');
if (empty($clientprivatekeyfile)) {
$errors[] = get_string('error_empty_client_private_key_file', 'auth_oidc');
}
if (empty($clientcertfile)) {
$errors[] = get_string('error_empty_client_cert_file', 'auth_oidc');
}
}
}
// Notify admin if validation errors are found.
if (!empty($errors)) {
$message = get_string('auth_settings_validation_error', 'auth_oidc') . '<ul>';
foreach ($errors as $error) {
$message .= '<li>' . $error . '</li>';
}
$message .= '</ul>';
\core\notification::error($message);
}
}
/**
* Warn the admin if the stored "Custom" binding username claim is no longer supported for the
* currently configured IdP type and user sync setting.
*
* @return void
*/
function auth_oidc_validate_binding_username_claim() {
$idptype = get_config('auth_oidc', 'idptype');
if (empty($idptype) || get_config('auth_oidc', 'bindingusernameclaim') !== 'custom') {
return;
}
$mstypes = [AUTH_OIDC_IDP_TYPE_MICROSOFT_ENTRA_ID, AUTH_OIDC_IDP_TYPE_MICROSOFT_IDENTITY_PLATFORM];
if (in_array($idptype, $mstypes) && auth_oidc_is_local_365_installed() && auth_oidc_is_user_sync_enabled()) {
$bindingclaimurl = new url('/admin/settings.php', ['section' => 'auth_oidc_binding_username_claim']);
\core\notification::warning(
get_string('warning_binding_username_claim_custom_unsupported', 'auth_oidc', $bindingclaimurl->out())
);
}
}
/**
* Initialize custom icon for OIDC authentication.
*
* This function sets up a custom icon for the OIDC plugin by creating necessary directories
* and copying the file into the specified location in Moodle's data directory.
*
* @param string $filefullname Full name of the custom icon file.
* @return bool False if the file is missing or is a directory; void otherwise.
*/
function auth_oidc_initialize_customicon($filefullname) {
global $CFG;
$file = get_config('auth_oidc', 'customicon');
$systemcontext = system::instance();
$fullpath = "/{$systemcontext->id}/auth_oidc/customicon/0{$file}";
$fs = get_file_storage();
if (!($file = $fs->get_file_by_hash(sha1($fullpath))) || $file->is_directory()) {
return false;
}
$pixpluginsdir = 'pix_plugins/auth/oidc/0';
$pixpluginsdirparts = explode('/', $pixpluginsdir);
$curdir = $CFG->dataroot;
foreach ($pixpluginsdirparts as $dir) {
$curdir .= '/' . $dir;
if (!file_exists($curdir)) {
mkdir($curdir);
}
}
if (file_exists($CFG->dataroot . '/pix_plugins/auth/oidc/0')) {
// Remove any previously stored custom icon so a stale file with a different
// extension can't take priority when the theme resolves the icon image.
$oldiconfiles = glob($CFG->dataroot . '/pix_plugins/auth/oidc/0/customicon.*');
foreach ($oldiconfiles ?: [] as $oldiconfile) {
// A failed unlink (e.g. permissions, or the file already being gone) isn't fatal
// here: copy_content_to() below will still overwrite/create the current extension's
// file, so at worst a stale file of a different extension is left behind.
@unlink($oldiconfile);
}
$extension = strtolower(pathinfo($file->get_filename(), PATHINFO_EXTENSION));
if (!in_array($extension, AUTH_OIDC_CUSTOMICON_ALLOWED_EXTENSIONS, true)) {
// Unexpected/empty extension: don't create a weird or unvalidated file under
// pix_plugins. The stale files for previously-valid extensions were already
// removed above, so this leaves no custom icon in place.
return false;
}
$file->copy_content_to($CFG->dataroot . "/pix_plugins/auth/oidc/0/customicon.{$extension}");
theme_reset_all_caches();
}
}
/**
* Check for connection abilities.
*
* @param int $userid Moodle user id to check permissions for.
* @param string $mode Mode to check
* 'connect' to check for connect specific capability
* 'disconnect' to check for disconnect capability.
* 'both' to check for disconnect and connect capability.
* @param boolean $require Use require_capability rather than has_capability.
*
* @return boolean True if has capability.
*/
function auth_oidc_connectioncapability($userid, $mode = 'connect', $require = false) {
$check = 'has_capability';
if ($require) {
// If requiring the capability and user has manageconnection than checking connect and disconnect is not needed.
$check = 'require_capability';
if (has_capability('auth/oidc:manageconnection', user::instance($userid), $userid)) {
return true;
}
} else if ($check('auth/oidc:manageconnection', user::instance($userid), $userid)) {
return true;
}
$result = false;
switch ($mode) {
case "connect":
$result = $check('auth/oidc:manageconnectionconnect', user::instance($userid), $userid);
break;
case "disconnect":
$result = $check('auth/oidc:manageconnectiondisconnect', user::instance($userid), $userid);
break;
case "both":
$result = $check('auth/oidc:manageconnectionconnect', user::instance($userid), $userid);
$result = $result && $check('auth/oidc:manageconnectiondisconnect', user::instance($userid), $userid);
}
if ($require) {
return true;
}
return $result;
}
/**
* Determine if local_o365 plugins is installed.
*
* @return bool
*/
function auth_oidc_is_local_365_installed() {
global $CFG, $DB;
$dbmanager = $DB->get_manager();
return file_exists($CFG->dirroot . '/local/o365/version.php') &&
$DB->record_exists('config_plugins', ['plugin' => 'local_o365', 'name' => 'version']) &&
$dbmanager->table_exists('local_o365_objects') &&
$dbmanager->table_exists('local_o365_connections');
}
/**
* Return details of all auth_oidc tokens having empty Moodle user IDs.
*
* @return array
*/
function auth_oidc_get_tokens_with_empty_ids() {
global $DB;
$emptyuseridtokens = [];
$records = $DB->get_records('auth_oidc_token', ['userid' => '0']);
foreach ($records as $record) {
$item = new stdClass();
$item->id = $record->id;
$item->oidcusername = $record->oidcusername;
$item->useridentifier = $record->useridentifier;
$item->moodleusername = $record->username;
$item->userid = 0;
$item->oidcuniqueid = $record->oidcuniqid;
$item->matchingstatus = get_string('unmatched', 'auth_oidc');
$item->details = get_string('na', 'auth_oidc');
$deletetokenurl = new url('/auth/oidc/cleanupoidctokens.php', ['id' => $record->id, 'sesskey' => sesskey()]);
$item->action = html_writer::link($deletetokenurl, get_string('delete_token', 'auth_oidc'));
$emptyuseridtokens[$record->id] = $item;
}
return $emptyuseridtokens;
}
/**
* Return details of all auth_oidc tokens with matching Moodle user IDs, but mismatched usernames.
*
* @return array
*/
function auth_oidc_get_tokens_with_mismatched_usernames() {
global $DB;
$mismatchedtokens = [];
$sql = 'SELECT tok.id AS id, tok.userid AS tokenuserid, tok.username AS tokenusername, tok.oidcusername AS oidcusername,
tok.useridentifier, tok.oidcuniqid as oidcuniqid, u.id AS muserid, u.username AS musername
FROM {auth_oidc_token} tok
JOIN {user} u ON u.id = tok.userid
WHERE tok.userid != 0
AND LOWER(u.username) != LOWER(tok.username)';
$records = $DB->get_recordset_sql($sql);
foreach ($records as $record) {
$item = new stdClass();
$item->id = $record->id;
$item->oidcusername = $record->oidcusername;
$item->useridentifier = $record->useridentifier;
$item->userid = $record->muserid;
$item->oidcuniqueid = $record->oidcuniqid;
$item->matchingstatus = get_string('mismatched', 'auth_oidc');
$item->details = get_string(
'mismatched_details',
'auth_oidc',
['tokenusername' => s($record->tokenusername), 'moodleusername' => s($record->musername)]
);
$deletetokenurl = new url('/auth/oidc/cleanupoidctokens.php', ['id' => $record->id, 'sesskey' => sesskey()]);
$item->action = html_writer::link($deletetokenurl, get_string('delete_token_and_reference', 'auth_oidc'));
$mismatchedtokens[$record->id] = $item;
}
return $mismatchedtokens;
}
/**
* Delete the auth_oidc token with the ID.
*
* @param int $tokenid
*/
function auth_oidc_delete_token(int $tokenid): void {
global $DB;
if (auth_oidc_is_local_365_installed()) {
$sql = 'SELECT obj.id, obj.objectid, tok.token, u.id AS userid, u.email
FROM {local_o365_objects} obj
JOIN {auth_oidc_token} tok ON obj.o365name = tok.username
JOIN {user} u ON obj.moodleid = u.id
WHERE obj.type = :type AND tok.id = :tokenid';
if (
$objectrecord = $DB->get_record_sql(
$sql,
['type' => 'user', 'tokenid' => $tokenid],
IGNORE_MULTIPLE
)
) {
// Delete record from local_o365_objects.
$DB->delete_records('local_o365_objects', ['id' => $objectrecord->id]);
// Delete record from local_o365_token.
$DB->delete_records('local_o365_token', ['user_id' => $objectrecord->userid]);
// Delete record from local_o365_connections.
$DB->delete_records_select(
'local_o365_connections',
'muserid = :userid OR LOWER(entraidupn) = :email',
['userid' => $objectrecord->userid, 'email' => $objectrecord->email]
);
}
}
$DB->delete_records('auth_oidc_token', ['id' => $tokenid]);
}
/**
* Get validated custom claim names from configuration.
*
* Parses the customclaims configuration, validates claim name format, and returns
* the list of valid claim names to be used for token claim extraction and field mapping.
*
* @return array Array of validated custom claim names.
*/
function auth_oidc_get_validated_custom_claim_names() {
$customclaimsconfig = get_config('auth_oidc', 'customclaims');
if (empty($customclaimsconfig)) {
return [];
}
// Split by space, trim, remove empty values, and remove duplicates.
$customclaims = array_filter(array_map('trim', explode(' ', $customclaimsconfig)));
$customclaims = array_unique($customclaims);
$validated = [];
foreach ($customclaims as $claimname) {
// Validate claim name format (alphanumeric, underscore, hyphen only).
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $claimname)) {
debugging("Invalid custom claim name skipped: $claimname", DEBUG_DEVELOPER);
continue;
}
$validated[] = $claimname;
}
return $validated;
}
/**
* Process and add custom claims to remote fields array with validation.
*
* @param array $remotefields Existing remote fields array
* @return array Updated remote fields array with validated custom claims
*/
function auth_oidc_process_custom_claims($remotefields) {
$customclaims = auth_oidc_get_validated_custom_claim_names();
// Get all existing field names as reserved to prevent overriding.
$reserved = array_keys($remotefields);
foreach ($customclaims as $claimname) {
// Prevent overriding existing fields.
if (in_array($claimname, $reserved, true)) {
debugging("Reserved custom claim name skipped: $claimname", DEBUG_DEVELOPER);
continue;
}
$remotefields[$claimname] = $claimname;
}
return $remotefields;
}
/**
* Return the list of remote field options in field mapping.
*
* @return array
*/
function auth_oidc_get_remote_fields() {
if (auth_oidc_is_local_365_installed()) {
$remotefields = [
'' => get_string('settings_fieldmap_feild_not_mapped', 'auth_oidc'),
'bindingusernameclaim' => get_string('settings_fieldmap_field_bindingusernameclaim', 'auth_oidc'),
'objectId' => get_string('settings_fieldmap_field_objectId', 'auth_oidc'),
'userPrincipalName' => get_string('settings_fieldmap_field_userPrincipalName', 'auth_oidc'),
'displayName' => get_string('settings_fieldmap_field_displayName', 'auth_oidc'),
'givenName' => get_string('settings_fieldmap_field_givenName', 'auth_oidc'),
'surname' => get_string('settings_fieldmap_field_surname', 'auth_oidc'),
'mail' => get_string('settings_fieldmap_field_mail', 'auth_oidc'),
'onPremisesSamAccountName' => get_string('settings_fieldmap_field_onPremisesSamAccountName', 'auth_oidc'),
'streetAddress' => get_string('settings_fieldmap_field_streetAddress', 'auth_oidc'),
'city' => get_string('settings_fieldmap_field_city', 'auth_oidc'),
'postalCode' => get_string('settings_fieldmap_field_postalCode', 'auth_oidc'),
'state' => get_string('settings_fieldmap_field_state', 'auth_oidc'),
'country' => get_string('settings_fieldmap_field_country', 'auth_oidc'),
'jobTitle' => get_string('settings_fieldmap_field_jobTitle', 'auth_oidc'),
'department' => get_string('settings_fieldmap_field_department', 'auth_oidc'),
'companyName' => get_string('settings_fieldmap_field_companyName', 'auth_oidc'),
'preferredLanguage' => get_string('settings_fieldmap_field_preferredLanguage', 'auth_oidc'),
'employeeId' => get_string('settings_fieldmap_field_employeeId', 'auth_oidc'),
'businessPhones' => get_string('settings_fieldmap_field_businessPhones', 'auth_oidc'),
'faxNumber' => get_string('settings_fieldmap_field_faxNumber', 'auth_oidc'),
'mobilePhone' => get_string('settings_fieldmap_field_mobilePhone', 'auth_oidc'),
'officeLocation' => get_string('settings_fieldmap_field_officeLocation', 'auth_oidc'),
'preferredName' => get_string('settings_fieldmap_field_preferredName', 'auth_oidc'),
'manager' => get_string('settings_fieldmap_field_manager', 'auth_oidc'),
'manager_email' => get_string('settings_fieldmap_field_manager_email', 'auth_oidc'),
'teams' => get_string('settings_fieldmap_field_teams', 'auth_oidc'),
'groups' => get_string('settings_fieldmap_field_groups', 'auth_oidc'),
'roles' => get_string('settings_fieldmap_field_roles', 'auth_oidc'),
];
$order = 0;
while ($order++ < 15) {
$remotefields['extensionAttribute' . $order] = get_string(
'settings_fieldmap_field_extensionattribute',
'auth_oidc',
$order
);
}
// SDS profile sync.
[$sdsprofilesyncenabled, $schoolid, $schoolname] =
local_o365\feature\sds\utils::get_profile_sync_status_with_id_name();
if ($sdsprofilesyncenabled) {
$remotefields['sds_school_id'] = get_string(
'settings_fieldmap_field_sds_school_id',
'auth_oidc',
get_config('local_o365', 'sdsprofilesync', $schoolid)
);
$remotefields['sds_school_name'] = get_string(
'settings_fieldmap_field_sds_school_name',
'auth_oidc',
$schoolname
);
$remotefields['sds_school_role'] = get_string('settings_fieldmap_field_sds_school_role', 'auth_oidc');
$remotefields['sds_student_externalId'] = get_string('settings_fieldmap_field_sds_student_externalId', 'auth_oidc');
$remotefields['sds_student_birthDate'] = get_string('settings_fieldmap_field_sds_student_birthDate', 'auth_oidc');
$remotefields['sds_student_grade'] = get_string('settings_fieldmap_field_sds_student_grade', 'auth_oidc');
$remotefields['sds_student_graduationYear'] = get_string(
'settings_fieldmap_field_sds_student_graduationYear',
'auth_oidc'
);
$remotefields['sds_student_studentNumber'] = get_string(
'settings_fieldmap_field_sds_student_studentNumber',
'auth_oidc'
);
$remotefields['sds_teacher_externalId'] = get_string('settings_fieldmap_field_sds_teacher_externalId', 'auth_oidc');
$remotefields['sds_teacher_teacherNumber'] = get_string(
'settings_fieldmap_field_sds_teacher_teacherNumber',
'auth_oidc'
);
}
// Add custom claims if configured, with validation.
$remotefields = auth_oidc_process_custom_claims($remotefields);
} else {
$remotefields = [
'' => get_string('settings_fieldmap_feild_not_mapped', 'auth_oidc'),
'bindingusernameclaim' => get_string('settings_fieldmap_field_bindingusernameclaim', 'auth_oidc'),
'objectId' => get_string('settings_fieldmap_field_objectId', 'auth_oidc'),
'userPrincipalName' => get_string('settings_fieldmap_field_userPrincipalName', 'auth_oidc'),
'givenName' => get_string('settings_fieldmap_field_givenName', 'auth_oidc'),
'surname' => get_string('settings_fieldmap_field_surname', 'auth_oidc'),
'mail' => get_string('settings_fieldmap_field_mail', 'auth_oidc'),
];
// Add custom claims if configured, with validation.
$remotefields = auth_oidc_process_custom_claims($remotefields);
}
return $remotefields;
}
/**
* Return the list of available remote fields to map email field.
*
* @return array
*/
function auth_oidc_get_email_remote_fields() {
$remotefields = [
'mail' => get_string('settings_fieldmap_field_mail', 'auth_oidc'),
'userPrincipalName' => get_string('settings_fieldmap_field_userPrincipalName', 'auth_oidc'),
];
return $remotefields;
}
/**
* Return the current field mapping settings in an array.
*
* @return array
*/
function auth_oidc_get_field_mappings() {
$fieldmappings = [];
$userfields = auth_oidc_get_all_user_fields();
$authoidcconfig = get_config('auth_oidc');
foreach ($userfields as $userfield) {
$fieldmapsettingname = 'field_map_' . $userfield;
if (property_exists($authoidcconfig, $fieldmapsettingname) && $authoidcconfig->$fieldmapsettingname) {
$fieldsetting = [];
$fieldsetting['field_map'] = $authoidcconfig->$fieldmapsettingname;
$fieldlocksettingname = 'field_lock_' . $userfield;
if (property_exists($authoidcconfig, $fieldlocksettingname)) {
$fieldsetting['field_lock'] = $authoidcconfig->$fieldlocksettingname;
} else {
$fieldsetting['field_lock'] = 'unlocked';
}
$fieldupdatelocksettignname = 'field_updatelocal_' . $userfield;
if (property_exists($authoidcconfig, $fieldupdatelocksettignname)) {
$fieldsetting['update_local'] = $authoidcconfig->$fieldupdatelocksettignname;
} else {
$fieldsetting['update_local'] = 'always';
}
$fieldmappings[$userfield] = $fieldsetting;
}
}
if (!array_key_exists('email', $fieldmappings)) {
$fieldmappings['email'] = auth_oidc_apply_default_email_mapping();
}
return $fieldmappings;
}
/**
* Apply default email mapping settings.
*
* @return array
*/
function auth_oidc_apply_default_email_mapping() {
$existingsetting = get_config('auth_oidc', 'field_map_email');
if ($existingsetting != 'mail') {
add_to_config_log('field_map_email', $existingsetting, 'mail', 'auth_oidc');
}
set_config('field_map_email', 'mail', 'auth_oidc');
$authoidcconfig = get_config('auth_oidc');
$fieldsetting = [];
$fieldsetting['field_map'] = 'mail';
if (property_exists($authoidcconfig, 'field_lock_email')) {
$fieldsetting['field_lock'] = $authoidcconfig->field_lock_email;
} else {
$fieldsetting['field_lock'] = 'unlocked';
}
if (property_exists($authoidcconfig, 'field_updatelocal_email')) {
$fieldsetting['update_local'] = $authoidcconfig->field_updatelocal_email;
} else {
$fieldsetting['update_local'] = 'always';
}
return $fieldsetting;
}
/**
* Helper function used to print mapping and locking for auth_oidc plugin on admin pages.
*
* @param stdclass $settings Moodle admin settings instance
* @param string $auth authentication plugin shortname
* @param array $userfields user profile fields
* @param string $helptext help text to be displayed at top of form
* @param boolean $mapremotefields Map fields or lock only.
* @param boolean $updateremotefields Allow remote updates
* @param array $customfields list of custom profile fields
*/
function auth_oidc_display_auth_lock_options(
$settings,
$auth,
$userfields,
$helptext,
$mapremotefields,
$updateremotefields,
$customfields = []
) {
global $DB;
// Introductory explanation and help text.
if ($mapremotefields) {
$settings->add(
new admin_setting_heading($auth . '/data_mapping', new lang_string('auth_data_mapping', 'auth'), $helptext)
);
} else {
$settings->add(
new admin_setting_heading($auth . '/auth_fieldlocks', new lang_string('auth_fieldlocks', 'auth'), $helptext)
);
}
// Generate the list of options.
$lockoptions = [
'unlocked' => get_string('unlocked', 'auth'),
'unlockedifempty' => get_string('unlockedifempty', 'auth'),
'locked' => get_string('locked', 'auth'),
];
if (auth_oidc_is_local_365_installed()) {
$alwaystext = get_string('update_oncreate_and_onlogin_and_usersync', 'auth_oidc');
$onlogintext = get_string('update_onlogin_and_usersync', 'auth_oidc');
} else {
$alwaystext = get_string('update_oncreate_and_onlogin', 'auth_oidc');
$onlogintext = get_string('update_onlogin', 'auth');
}
$updatelocaloptions = [
'always' => $alwaystext,
'oncreate' => get_string('update_oncreate', 'auth'),
'onlogin' => $onlogintext,
];
$updateextoptions = [
'0' => get_string('update_never', 'auth'),
'1' => get_string('update_onupdate', 'auth'),
];
// Generate the list of profile fields to allow updates / lock.
if (!empty($customfields)) {
$userfields = array_merge($userfields, $customfields);
$customfieldname = $DB->get_records('user_info_field', null, '', 'shortname, name');
}
$remotefields = auth_oidc_get_remote_fields();
$emailremotefields = auth_oidc_get_email_remote_fields();
foreach ($userfields as $field) {
// Define the fieldname we display to the user.
// this includes special handling for some profile fields.
$fieldname = $field;
$fieldnametoolong = false;
if ($fieldname === 'lang') {
$fieldname = get_string('language');
} else if (!empty($customfields) && in_array($field, $customfields)) {
// If custom field then pick name from database.
$fieldshortname = str_replace('profile_field_', '', $fieldname);
$fieldname = $customfieldname[$fieldshortname]->name;
if (core_text::strlen($fieldshortname) > 67) {
// If custom profile field name is longer than 67 characters we will not be able to store the setting
// such as 'field_updateremote_profile_field_NOTSOSHORTSHORTNAME' in the database because the character
// limit for the setting name is 100.
$fieldnametoolong = true;
}
} else if ($fieldname == 'url') {
$fieldname = get_string('webpage');
} else {
$fieldname = get_string($fieldname);
}
// Generate the list of fields / mappings.
if ($fieldnametoolong) {
// Display a message that the field can not be mapped because it's too long.
$url = new url('/user/profile/index.php');
$a = (object)['fieldname' => s($fieldname), 'shortname' => s($field), 'charlimit' => 67, 'link' => $url->out()];
$settings->add(new admin_setting_heading(
$auth . '/field_not_mapped_' . sha1($field),
'',
get_string('cannotmapfield', 'auth', $a)
));
} else if ($mapremotefields) {
// We are mapping to a remote field here.
// Mapping.
if ($field == 'email') {
$settings->add(new admin_setting_configselect(
"auth_oidc/field_map_{$field}",
get_string('auth_fieldmapping', 'auth', $fieldname),
'',
null,
$emailremotefields
));
} else {
$settings->add(new admin_setting_configselect(
"auth_oidc/field_map_{$field}",
get_string('auth_fieldmapping', 'auth', $fieldname),
'',
null,
$remotefields
));
}
// Update local.
$settings->add(new admin_setting_configselect(
"auth_{$auth}/field_updatelocal_{$field}",
get_string('auth_updatelocalfield', 'auth', $fieldname),
'',
'always',
$updatelocaloptions
));
// Update remote.
if ($updateremotefields) {
$settings->add(new admin_setting_configselect(
"auth_{$auth}/field_updateremote_{$field}",
get_string('auth_updateremotefield', 'auth', $fieldname),
'',
0,
$updateextoptions
));
}
// Lock fields.
$settings->add(new admin_setting_configselect(
"auth_{$auth}/field_lock_{$field}",
get_string('auth_fieldlockfield', 'auth', $fieldname),
'',
'unlocked',
$lockoptions
));
} else {
// Lock fields Only.
$settings->add(new admin_setting_configselect(
"auth_{$auth}/field_lock_{$field}",
get_string('auth_fieldlockfield', 'auth', $fieldname),
'',
'unlocked',
$lockoptions
));
}
}
}
/**
* Return all user profile field names in an array.
*
* @return array|string[]|null
*/
function auth_oidc_get_all_user_fields() {
$authplugin = get_auth_plugin('oidc');
$userfields = $authplugin->userfields;
$userfields = array_merge($userfields, $authplugin->get_custom_user_profile_fields());
return $userfields;
}
/**
* Determine the endpoint version of the given Microsoft Entra ID / Microsoft authorization or token endpoint.
*
* @param string $endpoint The URL of the endpoint to be checked.
* @return int The version of the Microsoft endpoint (1 or 2) or unknown.
*/
function auth_oidc_determine_endpoint_version(string $endpoint) {
$endpointversion = AUTH_OIDC_MICROSOFT_ENDPOINT_VERSION_UNKNOWN;
if (strpos($endpoint, 'https://login.microsoftonline.com/') === 0) {
if (strpos($endpoint, 'oauth2/v2.0/') !== false) {
$endpointversion = AUTH_OIDC_MICROSOFT_ENDPOINT_VERSION_2;
} else if (strpos($endpoint, 'oauth2') !== false) {
$endpointversion = AUTH_OIDC_MICROSOFT_ENDPOINT_VERSION_1;
}
}
return $endpointversion;
}
/**
* Return formatted form element name to be used by configuration variables in custom forms.
*
* @param string $stringid
* @return string
*/
function auth_oidc_config_name_in_form(string $stringid) {
$formatedformitemname = get_string($stringid, 'auth_oidc') .
html_writer::span('auth_oidc | ' . $stringid, 'form-shortname d-block small text-muted');
return $formatedformitemname;
}
/**
* Check if the auth_oidc plugin has been configured with the minimum settings for the SSO integration to work.
*
* @return bool
*/
function auth_oidc_is_setup_complete() {
$pluginconfig = get_config('auth_oidc');
if (empty($pluginconfig->clientid) || empty($pluginconfig->idptype) || empty($pluginconfig->clientauthmethod)) {
return false;
}
switch ($pluginconfig->clientauthmethod) {
case AUTH_OIDC_AUTH_METHOD_SECRET:
if (empty($pluginconfig->clientsecret)) {
return false;
}
break;
case AUTH_OIDC_AUTH_METHOD_CERTIFICATE:
if (!isset($pluginconfig->clientcertsource)) {
$existingclientcertsource = get_config('auth_oidc', 'clientcertsource');
if ($existingclientcertsource != AUTH_OIDC_AUTH_CERT_SOURCE_TEXT) {
add_to_config_log('clientcertsource', $existingclientcertsource, AUTH_OIDC_AUTH_CERT_SOURCE_TEXT, 'auth_oidc');
}
set_config('clientcertsource', AUTH_OIDC_AUTH_CERT_SOURCE_TEXT, 'auth_oidc');
$pluginconfig->clientcertsource = AUTH_OIDC_AUTH_CERT_SOURCE_TEXT;
}
switch ($pluginconfig->clientcertsource) {
case AUTH_OIDC_AUTH_CERT_SOURCE_FILE:
if (!utils::get_certpath() || !utils::get_keypath()) {
return false;
}
break;
case AUTH_OIDC_AUTH_CERT_SOURCE_TEXT:
if (empty($pluginconfig->clientcert) || empty($pluginconfig->clientprivatekey)) {
return false;
}
break;
}
break;
}
if (empty($pluginconfig->authendpoint) || empty($pluginconfig->tokenendpoint)) {
return false;
}
return true;
}
/**
* Return the name of the configured IdP type.
*
* @return lang_string|string
*/
function auth_oidc_get_idp_type_name() {
$idptypename = '';
switch (get_config('auth_oidc', 'idptype')) {
case AUTH_OIDC_IDP_TYPE_MICROSOFT_ENTRA_ID:
$idptypename = get_string('idp_type_microsoft_entra_id', 'auth_oidc');
break;
case AUTH_OIDC_IDP_TYPE_MICROSOFT_IDENTITY_PLATFORM:
$idptypename = get_string('idp_type_microsoft_identity_platform', 'auth_oidc');
break;
case AUTH_OIDC_IDP_TYPE_OTHER:
$idptypename = get_string('idp_type_other', 'auth_oidc');
break;
}
return $idptypename;
}
/**
* Return the name of the configured authentication method.
*
* @return lang_string|string
*/
function auth_oidc_get_client_auth_method_name() {
$authmethodname = '';
switch (get_config('auth_oidc', 'clientauthmethod')) {
case AUTH_OIDC_AUTH_METHOD_SECRET:
$authmethodname = get_string('auth_method_secret', 'auth_oidc');
break;
case AUTH_OIDC_AUTH_METHOD_CERTIFICATE:
$authmethodname = get_string('auth_method_certificate', 'auth_oidc');
break;
}
return $authmethodname;
}