From 7ec9a6daa79264d498a6e64df0b13472f110a398 Mon Sep 17 00:00:00 2001 From: Juan Leyva Date: Mon, 30 Oct 2017 17:42:03 +0100 Subject: [PATCH] MDL-51945 core_user: Prevent duplicated emails in update_users WS --- user/externallib.php | 10 ++++++++++ user/tests/externallib_test.php | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/user/externallib.php b/user/externallib.php index db818d14004..51ccf4da605 100644 --- a/user/externallib.php +++ b/user/externallib.php @@ -548,6 +548,16 @@ class core_user_external extends external_api { if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) { continue; } + // Check duplicated emails. + if (isset($user['email']) && $user['email'] !== $existinguser->email) { + if (!validate_email($user['email'])) { + continue; + } else if (empty($CFG->allowaccountssameemail) && + $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $CFG->mnet_localhost_id))) { + continue; + } + } + user_update_user($user, true, false); // Update user picture if it was specified for this user. diff --git a/user/tests/externallib_test.php b/user/tests/externallib_test.php index be52830487f..dd78fd7137d 100644 --- a/user/tests/externallib_test.php +++ b/user/tests/externallib_test.php @@ -676,6 +676,31 @@ class core_user_externallib_testcase extends externallib_advanced_testcase { core_user_external::update_users(array($user1)); } + /** + * Test update_users using duplicated email. + */ + public function test_update_users_duplicated_email() { + global $DB, $CFG; + + $this->resetAfterTest(true); + $this->setAdminUser(); + + $user1 = self::getDataGenerator()->create_user(); + $user2 = self::getDataGenerator()->create_user(); + $user2toupdate = array( + 'id' => $user2->id, + 'email' => $user1->email, + ); + // E-mail duplicated not allowed. + $CFG->allowaccountssameemail = 0; + core_user_external::update_users(array($user2toupdate)); + $this->assertNotEquals($user1->email, $DB->get_field('user', 'email', array('id' => $user2->id))); + // E-mail duplicated allowed. + $CFG->allowaccountssameemail = 1; + core_user_external::update_users(array($user2toupdate)); + $this->assertEquals($user1->email, $DB->get_field('user', 'email', array('id' => $user2->id))); + } + /** * Test add_user_private_files */