MDL-40613 auth_ldap: sync custom profile fields

This commit is contained in:
Albert Gasset
2017-12-19 14:13:34 +08:00
committed by Mark Nelson
parent 95b7be7f05
commit 2c977ceb29
4 changed files with 149 additions and 147 deletions
+84
View File
@@ -618,6 +618,90 @@ class auth_plugin_base {
public function postlogout_hook($user) {
}
/**
* Update a local user record from an external source.
* This is a lighter version of the one in moodlelib -- won't do
* expensive ops such as enrolment.
*
* @param string $username username
* @param array $updatekeys fields to update, false updates all fields.
* @param bool $triggerevent set false if user_updated event should not be triggered.
* This will not affect user_password_updated event triggering.
* @return stdClass|bool updated user record or false if there is no new info to update.
*/
protected function update_user_record($username, $updatekeys = false, $triggerevent = false) {
global $CFG, $DB;
require_once($CFG->dirroot.'/user/profile/lib.php');
// Just in case check text case.
$username = trim(core_text::strtolower($username));
// Get the current user record.
$user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id));
if (empty($user)) { // Trouble.
error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
print_error('auth_dbusernotexist', 'auth_db', '', $username);
die;
}
// Load all custom fields into $user->profile.
profile_load_custom_fields($user, false);
// Protect the userid from being overwritten.
$userid = $user->id;
$needsupdate = false;
if ($newinfo = $this->get_userinfo($username)) {
$newinfo = truncate_userinfo($newinfo);
if (empty($updatekeys)) { // All keys? this does not support removing values.
$updatekeys = array_keys($newinfo);
}
if (!empty($updatekeys)) {
$newuser = new stdClass();
$newuser->id = $userid;
$newuser->profile = array();
foreach ($updatekeys as $key) {
if (isset($newinfo[$key])) {
$value = $newinfo[$key];
} else {
$value = '';
}
if (!empty($this->config->{'field_updatelocal_' . $key})) {
if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
// Custom field.
$field = $match[1];
$currentvalue = isset($user->profile[$field]) ? $user->profile[$field] : null;
$newuser->profile[$field] = $value;
} else {
// Standard field.
$currentvalue = isset($user->$key) ? $user->$key : null;
$newuser->$key = $value;
}
// Only update if it's changed.
if ($currentvalue !== $value) {
$needsupdate = true;
}
}
}
}
if ($needsupdate) {
user_update_user($newuser, false, $triggerevent);
profile_save_custom_fields($newuser);
return $DB->get_record('user', array('id' => $userid, 'deleted' => 0));
}
}
return false;
}
/**
* Return the list of enabled identity providers.
*