-
Notifications
You must be signed in to change notification settings - Fork 133
/
main.php
1833 lines (1637 loc) · 76.5 KB
/
main.php
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/>.
/**
* User sync feature.
*
* @package local_o365
* @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/)
*/
namespace local_o365\feature\usersync;
use core_text;
use core_user;
use local_o365\oauth2\clientdata;
use local_o365\httpclient;
use local_o365\oauth2\token;
use local_o365\obj\o365user;
use local_o365\rest\unified;
use local_o365\utils;
use moodle_exception;
use stdClass;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/user/lib.php');
require_once($CFG->dirroot . '/user/profile/lib.php');
require_once($CFG->dirroot . '/local/o365/lib.php');
require_once($CFG->dirroot . '/auth/oidc/lib.php');
/**
* User sync feature.
*/
class main {
/**
* @var clientdata|null
*/
protected $clientdata = null;
/**
* @var httpclient|null
*/
protected $httpclient = null;
/**
* Constructor
*
* @param clientdata|null $clientdata $clientdata The client data to use for API construction.
* @param httpclient|null $httpclient $httpclient The HTTP client to use for API construction.
*
* @throws moodle_exception
*/
public function __construct(clientdata $clientdata = null, httpclient $httpclient = null) {
if (!PHPUNIT_TEST && !defined('BEHAT_SITE_RUNNING')) {
$this->clientdata = (!empty($clientdata))
? $clientdata
: clientdata::instance_from_oidc();
$this->httpclient = (!empty($httpclient))
? $httpclient
: new httpclient();
}
}
/**
* Determine whether any sync-related options are enabled.
*
* @return bool Enabled/disabled.
*/
public static function is_enabled() {
$usersyncsettings = get_config('local_o365', 'usersync');
if (empty($usersyncsettings) || $usersyncsettings === 'photosynconlogin' || $usersyncsettings === 'tzsynconlogin') {
return false;
}
return true;
}
/**
* Construct a user API client, accounting for Microsoft Graph API presence, and fall back to system api user if desired.
*
* @return unified A constructed unified API client, or false if error.
* @throws moodle_exception
*/
public function construct_user_api() {
$tokenresource = unified::get_tokenresource();
$token = utils::get_application_token($tokenresource, $this->clientdata, $this->httpclient);
if (empty($token)) {
throw new moodle_exception('errornotokenforusersync', 'local_o365');
}
return new unified($token, $this->httpclient);
}
/**
* Get information on the app.
*
* @return array|null Array of app service information, or null if failure.
*/
public function get_application_serviceprincipal_info() {
$apiclient = $this->construct_user_api();
return $apiclient->get_application_serviceprincipal_info();
}
/**
* Assign user to application.
*
* @param int $muserid The Moodle user ID.
* @param string $userobjectid Object ID of user.
* @return array|null Array of user information, or null if failure.
*/
public function assign_user($muserid, $userobjectid) {
// Not supported in unit tests at the moment.
if (PHPUNIT_TEST || defined('BEHAT_SITE_RUNNING')) {
return null;
}
$this->mtrace('Assigning Moodle user '.$muserid.' (objectid '.$userobjectid.') to application');
// Get object ID on first call.
static $appobjectid = null;
if (empty($objectid)) {
$appinfo = $this->get_application_serviceprincipal_info();
if (empty($appinfo)) {
return null;
}
$appobjectid = (unified::is_configured())
? $appinfo['value'][0]['id']
: $appinfo['value'][0]['objectId'];
}
$apiclient = $this->construct_user_api();
$result = $apiclient->assign_user($muserid, $userobjectid, $appobjectid);
if (!empty($result['odata.error'])) {
$error = '';
$code = '';
if (!empty($result['odata.error']['code'])) {
$code = $result['odata.error']['code'];
}
if (!empty($result['odata.error']['message']['value'])) {
$error = $result['odata.error']['message']['value'];
}
$user = core_user::get_user($muserid);
$this->mtrace('Error assigning users "'.$user->username.'" Reason: '.$code.' '.$error);
} else {
$this->mtrace('User assigned to application.');
}
return $result;
}
/**
* Assign photo to Moodle user account.
*
* @param int $muserid
* @param string $upn
* @return boolean True on photo updated.
*/
public function assign_photo(int $muserid, string $upn = '') {
global $DB, $CFG;
$result = false;
$apiclient = $this->construct_user_api();
if (empty($upn)) {
$o365user = o365user::instance_from_muserid($muserid);
$upn = $o365user->upn;
}
$muser = core_user::get_user($muserid, 'id, picture', MUST_EXIST);
$context = \context_user::instance($muserid, MUST_EXIST);
try {
$image = $apiclient->get_photo($upn);
// Check if json error message was returned.
if (!preg_match('/^{/', $image)) {
// Update profile picture.
$tempfile = tempnam($CFG->tempdir.'/', 'profileimage').'.jpg';
if (!$fp = fopen($tempfile, 'w+b')) {
@unlink($tempfile);
return false;
}
fwrite($fp, $image);
fclose($fp);
require_once("$CFG->libdir/gdlib.php");
$newpicture = process_new_icon($context, 'user', 'icon', 0, $tempfile);
if ($newpicture != $muser->picture) {
$DB->set_field('user', 'picture', $newpicture, array('id' => $muser->id));
$result = true;
}
@unlink($tempfile);
}
// Update appassign record.
$record = $DB->get_record('local_o365_appassign', array('muserid' => $muserid));
if (empty($record)) {
$record = new stdClass();
$record->muserid = $muserid;
$record->assigned = 0;
}
$record->photoupdated = time();
if (empty($record->id)) {
$DB->insert_record('local_o365_appassign', $record);
} else {
$DB->update_record('local_o365_appassign', $record);
}
} catch (moodle_exception $e) {
if ($e->getMessage() === get_string('erroro365nophoto', 'local_o365')) {
// User has no photo - if the user has an existing photo in Moodle profile, delete it.
if (!empty($muser->picture)) {
// User has no photo. Deleting previous profile photo.
$fs = \get_file_storage();
$fs->delete_area_files($context->id, 'user', 'icon');
$DB->set_field('user', 'picture', 0, array('id' => $muser->id));
}
}
}
return $result;
}
/**
* Sync timezone of user from Outlook to Moodle.
*
* @param int $muserid
* @param string $upn
* @return void
* @throws moodle_exception
*/
public function sync_timezone(int $muserid, string $upn = '') {
$tokenresource = unified::get_tokenresource();
$token = utils::get_application_token($tokenresource, $this->clientdata, $this->httpclient);
if (empty($token)) {
throw new moodle_exception('errornotokenforusersync', 'local_o365');
}
$apiclient = new unified($token, $this->httpclient);
if (empty($upn)) {
$o365user = o365user::instance_from_muserid($muserid);
$upn = $o365user->upn;
}
$remotetimezone = $apiclient->get_user_timezone_by_upn($upn);
if (is_array($remotetimezone) && !empty($remotetimezone['value'])) {
$remotetimezonesetting = $remotetimezone['value'];
$moodletimezone = \core_date::normalise_timezone($remotetimezonesetting);
$etcgmttimezonemappings = [
'Etc/GMT+12' => 'Pacific/Fiji',
'Etc/GMT+11' => 'Pacific/Pago_Pago',
'Etc/GMT+10' => 'Pacific/Honolulu',
'Etc/GMT+9' => 'America/Anchorage',
'Etc/GMT+8' => 'America/Los_Angeles',
'Etc/GMT+7' => 'America/Denver',
'Etc/GMT+6' => 'America/Chicago',
'Etc/GMT+5' => 'America/New_York',
'Etc/GMT+4' => 'America/Antigua',
'Etc/GMT+3' => 'America/Buenos_Aires',
'Etc/GMT+2' => 'Atlantic/Noronha',
'Etc/GMT+1' => 'Atlantic/Cape_Verde',
'Etc/GMT' => 'Europe/London',
'Etc/GMT-1' => 'Europe/Paris',
'Etc/GMT-2' => 'Europe/Helsinki',
'Etc/GMT-3' => 'Asia/Qatar',
'Etc/GMT-4' => 'Asia/Baku',
'Etc/GMT-5' => 'Asia/Karachi',
'Etc/GMT-6' => 'Asia/Dhaka',
'Etc/GMT-7' => 'Asia/Bangkok',
'Etc/GMT-8' => 'Asia/Hong_Kong',
'Etc/GMT-9' => 'Asia/Tokyo',
'Etc/GMT-10' => 'Pacific/Guam',
'Etc/GMT-11' => 'Asia/Sakhalin',
'Etc/GMT-12' => 'Pacific/Auckland',
'Etc/GMT-13' => 'Pacific/Tongatapu',
'Etc/GMT-14' => 'Pacific/Kiritimati',
];
if (isset($etcgmttimezonemappings[$moodletimezone])) {
$moodletimezone = $etcgmttimezonemappings[$moodletimezone];
}
$moodletimezone = clean_param($moodletimezone, PARAM_TIMEZONE);
if ($moodletimezone) {
$existinguser = core_user::get_user($muserid);
$existinguser->timezone = $moodletimezone;
user_update_user($existinguser, false, true);
}
}
}
/**
* Extract a parameter value from a URL.
*
* @param string $link A URL.
* @param string $param Parameter name.
* @return string|null The extracted deltalink value, or null if none found.
*/
protected function extract_param_from_link($link, $param) {
$link = parse_url($link);
if (isset($link['query'])) {
$output = [];
parse_str($link['query'], $output);
if (isset($output[$param])) {
return $output[$param];
}
}
return null;
}
/**
* Get Entra ID data for a single user.
*
* @param string $objectid
* @param bool $guestuser if the user is a guest user in Microsoft tenant
*
* @return array|null Array of user information, or null if failure.
*/
public function get_user(string $objectid, bool $guestuser = false) {
$apiclient = $this->construct_user_api();
$result = $apiclient->get_user($objectid, $guestuser);
if (!empty($result) && is_array($result)) {
return $result;
}
return [];
}
/**
* Get all users in the configured directory.
*
* @param string|array $params Requested user parameters.
* @return array Array of user information.
*/
public function get_users($params = 'default') {
$apiclient = $this->construct_user_api();
$users = $apiclient->get_users($params);
return $users;
}
/**
* Return the users search delta, along with skip token and delta tokens.
*
* @param string $params
* @param null $deltatoken
* @return array
* @throws moodle_exception
*/
public function get_users_delta($params = 'default', $deltatoken = null) {
$tokenresource = unified::get_tokenresource();
$token = utils::get_application_token($tokenresource, $this->clientdata, $this->httpclient);
if (empty($token)) {
throw new moodle_exception('errornotokenforusersync', 'local_o365');
}
$apiclient = new unified($token, $this->httpclient);
return $apiclient->get_users_delta($params, $deltatoken);
}
/**
* Return the $field of the manager of the Microsoft 365 user with the given oid.
*
* @param string $userobjectid
* @param string $field
*
* @return mixed|string
*/
public function get_user_manager(string $userobjectid, string $field = 'displayName') {
$apiclient = $this->construct_user_api();
$result = $apiclient->get_user_manager($userobjectid);
if ($result && isset($result[$field])) {
return $result[$field];
} else {
return '';
}
}
/**
* Return the names of groups that the Microsoft 365 user with the given oid are in, joined by comma.
*
* @param string $userobjectid
*
* @return string
*/
public function get_user_group_names($userobjectid) {
$apiclient = $this->construct_user_api();
$usergroups = $apiclient->get_user_groups($userobjectid);
$groupnames = [];
foreach ($usergroups as $usergroup) {
$groupnames[] = $usergroup['displayName'];
}
return join(',', $groupnames);
}
/**
* Return the names of teams that the Microsoft 365 user with the given oid are in, joined by comma.
*
* @param string $userobjectid
*
* @return string
*/
public function get_user_teams($userobjectid) {
$apiclient = $this->construct_user_api();
$userteams = $apiclient->get_user_teams($userobjectid);
$teamnames = [];
foreach ($userteams as $userteam) {
$teamnames[] = $userteam['displayName'];
}
return join(',', $teamnames);
}
/**
* Return the names of roles that the Microsoft 365 user with the given oid has, joined by comma.
*
* @param string $userobjectid
*
* @return string
*/
public function get_user_roles($userobjectid) {
$apiclient = $this->construct_user_api();
$objectsids = $apiclient->get_user_objects($userobjectid);
$roles = [];
if (!empty($objectsids)) {
$results = $apiclient->get_directory_objects($objectsids);
foreach ($results as $result) {
if (stripos($result['@odata.type'], 'role') !== false) {
$roles[] = $result['displayName'];
}
}
}
return join(',', $roles);
}
/**
* Return the preferred name of the Microsoft 365 user with the given oid.
*
* @param string $userobjectid
*
* @return mixed
*/
public function get_preferred_name($userobjectid) {
$apiclient = $this->construct_user_api();
$result = $apiclient->get_user($userobjectid);
if (isset($result['preferredName'])) {
return $result['preferredName'];
}
}
/**
* Apply the configured field map.
*
* @param array $entraiduserdata User data from Microsoft Entra ID.
* @param stdClass $user Moodle user data.
* @param string $eventtype 'login', or 'create'
*
* @return stdClass Modified Moodle user data.
*/
public static function apply_configured_fieldmap(array $entraiduserdata, stdClass $user, $eventtype) {
global $CFG;
require_once($CFG->dirroot . '/auth/oidc/lib.php');
if (PHPUNIT_TEST || defined('BEHAT_SITE_RUNNING')) {
$fieldmappings = [
'firstname' => [
'field_map' => 'givenName',
'field_lock' => 'unlocked',
'update_local' => 'always',
],
'lastname' => [
'field_map' => 'surname',
'field_lock' => 'unlocked',
'update_local' => 'always',
],
'email' => [
'field_map' => 'mail',
'field_lock' => 'unlocked',
'update_local' => 'always',
],
'idnumber' => [
'field_map' => 'userPrincipalName',
'field_lock' => 'unlocked',
'update_local' => 'always',
],
'city' => [
'field_map' => 'city',
'field_lock' => 'unlocked',
'update_local' => 'always',
],
'country' => [
'field_map' => 'country',
'field_lock' => 'unlocked',
'update_local' => 'always',
],
'department' => [
'field_map' => 'department',
'field_lock' => 'unlocked',
'update_local' => 'always',
],
];
} else {
$fieldmappings = auth_oidc_get_field_mappings();
}
if (isset($user->lang)) {
$originallangsetting = $user->lang;
} else {
$originallangsetting = $CFG->lang;
}
if (unified::is_configured() && (array_key_exists('id', $entraiduserdata) && $entraiduserdata['id'])) {
$objectidfieldname = 'id';
$userobjectid = $entraiduserdata['id'];
} else if (array_key_exists('objectId', $entraiduserdata) && $entraiduserdata['objectId']) {
$objectidfieldname = 'objectId';
$userobjectid = $entraiduserdata['objectId'];
} else {
$objectidfieldname = 'userPrincipalName';
$userobjectid = $entraiduserdata['userPrincipalName'];
}
$usersync = new self();
foreach ($fieldmappings as $localfield => $fieldmapping) {
$remotefield = $fieldmapping['field_map'];
$behavior = $fieldmapping['update_local'];
if ($behavior !== 'on' . $eventtype && $behavior !== 'always') {
// Field mapping doesn't apply to this event type.
continue;
}
if ($remotefield == 'objectId') {
$remotefield = $objectidfieldname;
}
if (isset($entraiduserdata[$remotefield])) {
switch ($remotefield) {
case 'country':
// Update country with two-letter country code.
$incoming = strtoupper($entraiduserdata[$remotefield]);
$countrymap = get_string_manager()->get_list_of_countries();
if (isset($countrymap[$incoming])) {
$countrycode = $incoming;
} else {
$countrycode = array_search($entraiduserdata[$remotefield], get_string_manager()->get_list_of_countries());
}
$user->$localfield = (!empty($countrycode)) ? $countrycode : '';
break;
case 'businessPhones':
$user->$localfield = implode(', ', $entraiduserdata[$remotefield]);
break;
default:
$user->$localfield = $entraiduserdata[$remotefield];
}
}
if (!PHPUNIT_TEST && !defined('BEHAT_SITE_RUNNING')) {
switch ($remotefield) {
case 'manager':
$user->$localfield = $usersync->get_user_manager($userobjectid, 'displayName');
break;
case 'manager_email':
$user->$localfield = $usersync->get_user_manager($userobjectid, 'mail');
break;
case 'groups':
$user->$localfield = $usersync->get_user_group_names($userobjectid);
break;
case 'teams':
$user->$localfield = $usersync->get_user_teams($userobjectid);
break;
case 'roles':
$user->$localfield = $usersync->get_user_roles($userobjectid);
break;
case 'preferredName':
if (!isset($entraiduserdata[$remotefield])) {
if (stripos($entraiduserdata['userPrincipalName'], '_ext_') !== false) {
$user->$localfield = $usersync->get_preferred_name($userobjectid);
}
}
break;
default:
if (substr($remotefield, 0, 18) == 'extensionAttribute') {
$extensionattributeid = substr($remotefield, 18);
if (ctype_digit($extensionattributeid) && $extensionattributeid >= 1 && $extensionattributeid <= 15) {
if (isset($entraiduserdata['onPremisesExtensionAttributes']) &&
isset($entraiduserdata['onPremisesExtensionAttributes'][$remotefield])) {
$user->$localfield = $entraiduserdata['onPremisesExtensionAttributes'][$remotefield];
}
}
}
}
}
}
// Validate language sync.
if (array_key_exists('lang', $fieldmappings) && ($behavior === 'on' . $eventtype || $behavior === 'always')) {
if (!get_string_manager()->translation_exists($originallangsetting, false)) {
$originallangsetting = $CFG->lang;
}
if (!isset($user->lang) || !$user->lang) {
// If the user's new language setting is empty, use original setting.
$user->lang = $originallangsetting;
} else {
$newlangsetting = strtolower(str_replace('-', '_' , $user->lang));
$newlangsettingwp = $newlangsetting . '_wp';
$newlangsettingsimple = substr($newlangsetting, 0, 2);
$validlangsettings = [];
if (!get_string_manager()->translation_exists($newlangsettingwp, false)) {
$newlangsettingwp = null;
} else {
$validlangsettings[] = 'newlangsettingwp';
}
if (!get_string_manager()->translation_exists($newlangsetting, false)) {
$newlangsetting = null;
} else {
$validlangsettings[] = 'newlangsetting';
}
if (!get_string_manager()->translation_exists($newlangsettingsimple, false)) {
$newlangsettingsimple = null;
} else {
$validlangsettings[] = 'newlangsettingsimple';
}
if (!$validlangsettings) {
// No version of the new language setting exists, keep existing setting.
$user->lang = $originallangsetting;
} else {
// At least one version exists, update settings.
if ($newlangsettingwp && $originallangsetting == $newlangsettingwp) {
$user->lang = $newlangsettingwp;
} else if ($newlangsetting) {
$user->lang = $newlangsetting;
} else {
$user->lang = $newlangsettingsimple;
}
if (!$user->lang) {
$user->lang = $originallangsetting;
}
}
}
}
return $user;
}
/**
* Check if any of the fields in the field map configuration would require calling Graph API function to get user details.
*
* @param string $eventtype
*
* @return bool
*/
public static function fieldmap_require_graph_api_call($eventtype) {
global $CFG;
require_once($CFG->dirroot . '/auth/oidc/lib.php');
// Microsoft Identity Platform can only get user profile from Graph API.
if (get_config('auth_oidc', 'idptype') == AUTH_OIDC_IDP_TYPE_MICROSOFT_IDENTITY_PLATFORM) {
return true;
} else {
$fieldmappings = auth_oidc_get_field_mappings();
$idtokenfields = ['givenName', 'surname', 'mail', 'objectId', 'userPrincipalName'];
foreach ($fieldmappings as $fieldmapping) {
$remotefield = $fieldmapping['field_map'];
if (!in_array($remotefield, $idtokenfields)) {
if ($fieldmapping['update_local'] == 'always' || $fieldmapping['update_local'] == 'on' . $eventtype) {
return true;
}
}
}
}
return false;
}
/**
* Check the configured user creation restriction and determine whether a user can be created.
*
* @param array $entraiduserdata Array of user data from Microsoft Entra ID.
* @return bool Whether the user can be created.
*/
protected function check_usercreationrestriction($entraiduserdata) {
$restriction = get_config('local_o365', 'usersynccreationrestriction');
if (empty($restriction)) {
return true;
}
$restriction = @unserialize($restriction);
if (empty($restriction) || !is_array($restriction)) {
return true;
}
if (empty($restriction['remotefield']) || empty($restriction['value'])) {
return true;
}
$useregex = (!empty($restriction['useregex'])) ? true : false;
if ($restriction['remotefield'] === 'o365group') {
if (unified::is_configured() !== true) {
utils::debug('graph api is not configured.', __METHOD__);
return false;
}
$apiclient = $this->construct_user_api();
try {
$group = $apiclient->get_group_by_name($restriction['value']);
if (empty($group) || !isset($group['id'])) {
utils::debug('Could not find group (1)', __METHOD__, $group);
return false;
}
$usergroups = $apiclient->get_user_transitive_groups($entraiduserdata['id']);
foreach ($usergroups as $usergroup) {
if ($group['id'] === $usergroup) {
return true;
}
}
return false;
} catch (moodle_exception $e) {
utils::debug('Could not find group (2)', __METHOD__, $e);
return false;
}
} else if ($restriction['remotefield'] === 'o365groupid') {
if (unified::is_configured() !== true) {
utils::debug('graph api is not configured.', __METHOD__);
return false;
}
$apiclient = $this->construct_user_api();
try {
$group = $apiclient->get_group($restriction['value']);
if (empty($group) || !isset($group['id'])) {
utils::debug('Could not find group (1)', __METHOD__, $group);
return false;
}
$usergroups = $apiclient->get_user_transitive_groups($entraiduserdata['id']);
foreach ($usergroups as $usergroup) {
if ($group['id'] === $usergroup) {
return true;
}
}
return false;
} catch (moodle_exception $e) {
utils::debug('Could not find group (2)', __METHOD__, $e);
return false;
}
} else if (substr($restriction['remotefield'], 0, 18) == 'extensionAttribute') {
$extensionattributeid = substr($restriction['remotefield'], 18);
if (ctype_digit($extensionattributeid) && $extensionattributeid >= 1 && $extensionattributeid <= 15) {
if (isset($entraiduserdata['onPremisesExtensionAttributes']) &&
isset($entraiduserdata['onPremisesExtensionAttributes'][$restriction['remotefield']])) {
$fieldval = $entraiduserdata['onPremisesExtensionAttributes'][$restriction['remotefield']];
$restrictionval = $restriction['value'];
if ($useregex === true) {
$count = @preg_match('/' . $restrictionval . '/', $fieldval, $matches);
if (!empty($count)) {
return true;
}
} else {
if ($fieldval === $restrictionval) {
return true;
}
}
}
return false;
} else {
utils:debug('Invalid extension attribute ID', __METHOD__);
return false;
}
} else {
if (!isset($entraiduserdata[$restriction['remotefield']])) {
return false;
}
$fieldval = $entraiduserdata[$restriction['remotefield']];
$restrictionval = $restriction['value'];
if ($useregex === true) {
$count = @preg_match('/' . $restrictionval . '/', $fieldval, $matches);
if (!empty($count)) {
return true;
}
} else {
if ($fieldval === $restrictionval) {
return true;
}
}
}
return false;
}
/**
* Create a Moodle user from Microsoft Entra ID user data.
*
* @param array $entraiduserdata Array of Microsoft Entra ID user data.
* @param array $syncoptions
* @return stdClass|bool An object representing the created Moodle user.
*/
public function create_user_from_entra_id_data($entraiduserdata, $syncoptions) {
global $CFG, $DB;
$creationallowed = $this->check_usercreationrestriction($entraiduserdata);
if ($creationallowed !== true) {
$this->mtrace('Cannot create user because they do not meet the configured user creation restrictions.');
return false;
}
// Locate country code.
if (isset($entraiduserdata['country'])) {
$countries = get_string_manager()->get_list_of_countries(true, 'en');
foreach ($countries as $code => $name) {
if ($entraiduserdata['country'] == $name) {
$entraiduserdata['country'] = $code;
}
}
if (strlen($entraiduserdata['country']) > 2) {
// Limit string to 2 chars to prevent sql error.
$entraiduserdata['country'] = substr($entraiduserdata['country'], 0, 2);
}
}
$username = $entraiduserdata['userPrincipalName'];
if (isset($entraiduserdata['convertedupn']) && $entraiduserdata['convertedupn']) {
$username = $entraiduserdata['convertedupn'];
}
$newuser = (object)[
'auth' => 'oidc',
'username' => trim(core_text::strtolower($username)),
'confirmed' => 1,
'timecreated' => time(),
'mnethostid' => $CFG->mnet_localhost_id,
];
// Determine if the newly created user needs to be suspended.
if (isset($syncoptions['disabledsync'])) {
if (isset($entraiduserdata['accountEnabled']) && $entraiduserdata['accountEnabled'] == false) {
$newuser->suspended = 1;
}
}
$newuser = static::apply_configured_fieldmap($entraiduserdata, $newuser, 'create');
$password = null;
if (!isset($newuser->idnumber)) {
$newuser->idnumber = $newuser->username;
}
if (!empty($newuser->email)) {
if (email_is_not_allowed($newuser->email)) {
unset($newuser->email);
}
}
$newuser->timemodified = $newuser->timecreated;
$newuser->id = user_create_user($newuser, false, false);
// Save user profile data.
profile_save_data($newuser);
$user = get_complete_user_data('id', $newuser->id);
// Set the password.
update_internal_user_password($user, $password);
// Add o365 object.
if (!$DB->record_exists('local_o365_objects', ['type' => 'user', 'moodleid' => $newuser->id])) {
if (unified::is_configured()) {
$userobjectid = $entraiduserdata['id'];
} else {
$userobjectid = $entraiduserdata['objectId'];
}
$now = time();
$userobjectdata = (object)[
'type' => 'user',
'subtype' => '',
'objectid' => $userobjectid,
'o365name' => $entraiduserdata['userPrincipalName'],
'moodleid' => $newuser->id,
'tenant' => '',
'timecreated' => $now,
'timemodified' => $now,
];
$userobjectdata->id = $DB->insert_record('local_o365_objects', $userobjectdata);
}
// Trigger event.
\core\event\user_created::create_from_userid($newuser->id)->trigger();
return $user;
}
/**
* Updates a Moodle user from Microsoft Entra ID user data.
*
* @param array $entraiduserdata Array of Microsoft Entra ID user data.
* @param object $fullexistinguser
*
* @return bool An boolean indicating that was created Moodle user.
*/
public function update_user_from_entra_id_data($entraiduserdata, $fullexistinguser) {
// Locate country code.
if (isset($entraiduserdata['country'])) {
$countries = get_string_manager()->get_list_of_countries(true, 'en');
foreach ($countries as $code => $name) {
if ($entraiduserdata['country'] == $name) {
$entraiduserdata['country'] = $code;
}
}
if (strlen($entraiduserdata['country']) > 2) {
// Limit string to 2 chars to prevent sql error.
$entraiduserdata['country'] = substr($entraiduserdata['country'], 0, 2);
}
}
$existinguser = static::apply_configured_fieldmap($entraiduserdata, $fullexistinguser, 'login');
if (!empty($existinguser->email)) {
if (email_is_not_allowed($existinguser->email)) {
unset($existinguser->email);
}
} else {
// Email is originally pulled (optionally) from UPN, so an empty email should not wipe out Moodle email.
unset($existinguser->email);
}
$existinguser->timemodified = time();
// Update a user with a user object (will compare against the ID).
user_update_user($existinguser, false, false);
// Save user profile data.
profile_save_data($existinguser);
// Trigger event.
\core\event\user_updated::create_from_userid($existinguser->id)->trigger();
return true;
}
/**
* Selectively run mtrace.
*
* @param string $msg The message.
*/
public static function mtrace($msg) {
if (!PHPUNIT_TEST && !defined('BEHAT_SITE_RUNNING')) {
mtrace('......... '.$msg);
}
}
/**
* Get an array of sync options.
*
* @return array Sync options
*/
public static function get_sync_options() {
$usersyncsettings = get_config('local_o365', 'usersync');
$usersyncsettings = array_flip(explode(',', $usersyncsettings));
return $usersyncsettings;
}
/**
* Determine whether a sync option is enabled.
*
* @param string $option The option to check.
* @return bool Whether the option is enabled.
*/
public static function sync_option_enabled($option) {
$options = static::get_sync_options();
return isset($options[$option]);
}