MDL-64774 user: Make email query case-insensitive
authorJun Pataleta <jun@moodle.com>
Thu, 21 Feb 2019 07:24:56 +0000 (15:24 +0800)
committerJun Pataleta <jun@moodle.com>
Fri, 1 Mar 2019 15:29:00 +0000 (23:29 +0800)
user/externallib.php

index 84adf0f..0d7daad 100644 (file)
@@ -205,9 +205,17 @@ class core_user_external extends external_api {
             // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
             if (!validate_email($user['email'])) {
                 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
-            } else if (empty($CFG->allowaccountssameemail) &&
-                    $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
-                throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
+            } else if (empty($CFG->allowaccountssameemail)) {
+                // Make a case-insensitive query for the given email address.
+                $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
+                $params = array(
+                    'email' => $user['email'],
+                    'mnethostid' => $user['mnethostid']
+                );
+                // If there are other user(s) that already have the same email, throw an error.
+                if ($DB->record_exists_select('user', $select, $params)) {
+                    throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
+                }
             }
             // End of user info validation.
 
@@ -587,9 +595,18 @@ class core_user_external extends external_api {
             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;
+                } else if (empty($CFG->allowaccountssameemail)) {
+                    // Make a case-insensitive query for the given email address and make sure to exclude the user being updated.
+                    $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
+                    $params = array(
+                        'email' => $user['email'],
+                        'mnethostid' => $CFG->mnet_localhost_id,
+                        'userid' => $user['id']
+                    );
+                    // Skip if there are other user(s) that already have the same email.
+                    if ($DB->record_exists_select('user', $select, $params)) {
+                        continue;
+                    }
                 }
             }