diff --git a/local/o365/classes/feature/usersync/main.php b/local/o365/classes/feature/usersync/main.php index 74d5e03ef..dc3c5b6ed 100644 --- a/local/o365/classes/feature/usersync/main.php +++ b/local/o365/classes/feature/usersync/main.php @@ -983,10 +983,14 @@ public function sync_users(array $aadusers = array()) { return true; } - $select = 'SELECT LOWER(u.username) AS username,'; - if (isset($aadsync['emailsync'])) { - $select .= ' LOWER(u.email) AS email,'; - } + /* In order to find existing user accounts using isset($existingusers[$aadupn]) we have to index the array + * by email address if we match AAD UPNs against Moodle email addresses! + * TODO: We may run into problems if we have multiple accounts with the same mail address! + * See setting `allowaccountssameemail`. + */ + $select = isset($aadsync['emailsync']) ? + "SELECT LOWER(u.email) AS email, LOWER(u.username) AS username," : + "SELECT LOWER(u.username) AS username"; $sql = "$select u.id as muserid,