/** * Update a user with a user object (will compare against the ID) * * @param stdClass $user the user to update * @param bool $updatepassword if true, authentication plugin will update password. * @param bool $triggerevent set false if user_updated event should not be triggred. */ function user_update_user($user, $updatepassword = true, $triggerevent = true) { global $DB; // set the timecreate field to the current time if (!is_object($user)) { $user = (object) $user; } //check username if (isset($user->username)) { if ($user->username !== core_text::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== clean_param($user->username, PARAM_USERNAME)) { throw new moodle_exception('invalidusername'); } } } // Unset password here, for updating later, if password update is required. if ($updatepassword && isset($user->password)) { //check password toward the password policy if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $passwd = $user->password; unset($user->password); } // Make sure calendartype, if set, is valid. if (!empty($user->calendartype)) { $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types(); // If it doesn't exist, then unset this value, we do not want to update the user's value. if (empty($availablecalendartypes[$user->calendartype])) { unset($user->calendartype); } } else { // Unset this variable, must be an empty string, which we do not want to update the calendartype to. unset($user->calendartype); } $user->timemodified = time(); $DB->update_record('user', $user); if ($updatepassword) { // Get full user record. $updateduser = $DB->get_record('user', array('id' => $user->id)); // if password was set, then update its hash if (isset($passwd)) { $authplugin = get_auth_plugin($updateduser->auth); if ($authplugin->can_change_password()) { $authplugin->user_update_password($updateduser, $passwd); } } } // Trigger event if required. if ($triggerevent) { \core\event\user_updated::create_from_userid($user->id)->trigger(); } }
// Update interests. if (isset($usernew->interests)) { useredit_update_interests($usernew, $usernew->interests); } // Update user picture. if (empty($CFG->disableuserimages)) { useredit_update_picture($usernew, $userform, $filemanageroptions); } // Update mail bounces. useredit_update_bounces($user, $usernew); // Update forum track preference. useredit_update_trackforums($user, $usernew); // Save custom profile fields data. profile_save_data($usernew); // Trigger event. \core\event\user_updated::create_from_userid($user->id)->trigger(); // If email was changed and confirmation is required, send confirmation email now to the new address. if ($emailchanged && $CFG->emailchangeconfirmation) { $tempuser = $DB->get_record('user', array('id' => $user->id), '*', MUST_EXIST); $tempuser->email = $usernew->preference_newemail; $a = new stdClass(); $a->url = $CFG->wwwroot . '/user/emailupdate.php?key=' . $usernew->preference_newemailkey . '&id=' . $user->id; $a->site = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))); $a->fullname = fullname($tempuser, true); $emailupdatemessage = get_string('emailupdatemessage', 'auth', $a); $emailupdatetitle = get_string('emailupdatetitle', 'auth', $a); // Email confirmation directly rather than using messaging so they will definitely get an email. $supportuser = core_user::get_support_user(); if (!($mailresults = email_to_user($tempuser, $supportuser, $emailupdatetitle, $emailupdatemessage))) { die("could not send email!"); }
/** * Sets specified user's password and send the new password to the user via email. * * @param stdClass $user A {@link $USER} object * @param bool $fasthash If true, use a low cost factor when generating the hash for speed. * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error */ function setnew_password_and_mail($user, $fasthash = false) { global $CFG, $DB; // We try to send the mail in language the user understands, // unfortunately the filter_string() does not support alternative langs yet // so multilang will not work properly for site->fullname. $lang = empty($user->lang) ? $CFG->lang : $user->lang; $site = get_site(); $supportuser = core_user::get_support_user(); $newpassword = generate_password(); $hashedpassword = hash_internal_user_password($newpassword, $fasthash); $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id)); $user->password = $hashedpassword; // Trigger event. $event = \core\event\user_updated::create(array('objectid' => $user->id, 'context' => context_user::instance($user->id))); $event->add_record_snapshot('user', $user); $event->trigger(); $a = new stdClass(); $a->firstname = fullname($user, true); $a->sitename = format_string($site->fullname); $a->username = $user->username; $a->newpassword = $newpassword; $a->link = $CFG->wwwroot . '/login/'; $a->signoff = generate_email_signoff(); $message = (string) new lang_string('newusernewpasswordtext', '', $a, $lang); $subject = format_string($site->fullname) . ': ' . (string) new lang_string('newusernewpasswordsubj', '', $a, $lang); // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber. return email_to_user($user, $supportuser, $subject, $message); }
/** * Will update a local user record from an external source (MNET users can not be updated using this method!). * * @param int $id user id * @return stdClass A complete user object */ function update_user_record_by_id($id) { global $DB, $CFG; require_once $CFG->dirroot . "/user/profile/lib.php"; require_once $CFG->dirroot . '/user/lib.php'; $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0); $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST); $newuser = array(); $userauth = get_auth_plugin($oldinfo->auth); if ($newinfo = $userauth->get_userinfo($oldinfo->username)) { $newinfo = truncate_userinfo($newinfo); $customfields = $userauth->get_custom_user_profile_fields(); foreach ($newinfo as $key => $value) { $iscustom = in_array($key, $customfields); if (!$iscustom) { $key = strtolower($key); } if (!property_exists($oldinfo, $key) && !$iscustom or $key === 'username' or $key === 'id' or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') { // Unknown or must not be changed. continue; } $confval = $userauth->config->{'field_updatelocal_' . $key}; $lockval = $userauth->config->{'field_lock_' . $key}; if (empty($confval) || empty($lockval)) { continue; } if ($confval === 'onlogin') { // MDL-4207 Don't overwrite modified user profile values with // empty LDAP values when 'unlocked if empty' is set. The purpose // of the setting 'unlocked if empty' is to allow the user to fill // in a value for the selected field _if LDAP is giving // nothing_ for this field. Thus it makes sense to let this value // stand in until LDAP is giving a value for this field. if (!(empty($value) && $lockval === 'unlockedifempty')) { if ($iscustom || in_array($key, $userauth->userfields) && (string) $oldinfo->{$key} !== (string) $value) { $newuser[$key] = (string) $value; } } } } if ($newuser) { $newuser['id'] = $oldinfo->id; $newuser['timemodified'] = time(); user_update_user((object) $newuser, false, false); // Save user profile data. profile_save_data((object) $newuser); // Trigger event. \core\event\user_updated::create_from_userid($newuser['id'])->trigger(); } } return get_complete_user_data('id', $oldinfo->id); }
/** * will update a local user record from an external source. * is a lighter version of the one in moodlelib -- won't do * expensive ops such as enrolment. * * If you don't pass $updatekeys, there is a performance hit and * values removed from DB won't be removed from moodle. * * @param string $username username * @param bool $updatekeys * @return stdClass */ function update_user_record($username, $updatekeys = false) { global $CFG, $DB; //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("Cannot update non-existent user: {$username}"); print_error('auth_dbusernotexist', 'auth_db', $username); die; } // Ensure userid is not overwritten. $userid = $user->id; $updated = 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); } foreach ($updatekeys as $key) { if (isset($newinfo[$key])) { $value = $newinfo[$key]; } else { $value = ''; } if (!empty($this->config->{'field_updatelocal_' . $key})) { if (isset($user->{$key}) and $user->{$key} != $value) { // Only update if it's changed. $DB->set_field('user', $key, $value, array('id' => $userid)); $updated = true; } } } } if ($updated) { $DB->set_field('user', 'timemodified', time(), array('id' => $userid)); // Trigger user_updated event. \core\event\user_updated::create_from_userid($userid)->trigger(); } return $DB->get_record('user', array('id' => $userid, 'deleted' => 0)); }
/** * Update users * * @param array $users * @return null * @since Moodle 2.2 */ public static function update_users($users) { global $CFG, $DB; require_once $CFG->dirroot . "/user/lib.php"; require_once $CFG->dirroot . "/user/profile/lib.php"; // Required for customfields related function. // Ensure the current user is allowed to run this function. $context = context_system::instance(); require_capability('moodle/user:update', $context); self::validate_context($context); $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users)); $transaction = $DB->start_delegated_transaction(); foreach ($params['users'] as $user) { user_update_user($user, true, false); // Update user custom fields. if (!empty($user['customfields'])) { foreach ($user['customfields'] as $customfield) { // Profile_save_data() saves profile file it's expecting a user with the correct id, // and custom field to be named profile_field_"shortname". $user["profile_field_" . $customfield['type']] = $customfield['value']; } profile_save_data((object) $user); } // Trigger event. \core\event\user_updated::create_from_userid($user['id'])->trigger(); // Preferences. if (!empty($user['preferences'])) { foreach ($user['preferences'] as $preference) { set_user_preference($preference['type'], $preference['value'], $user['id']); } } } $transaction->allow_commit(); return null; }
/** * Update users * * @param array $users * @return null * @since Moodle 2.2 */ public static function update_users($users) { global $CFG, $DB; require_once $CFG->dirroot . "/user/lib.php"; require_once $CFG->dirroot . "/user/profile/lib.php"; // Required for customfields related function. // Ensure the current user is allowed to run this function. $context = context_system::instance(); require_capability('moodle/user:update', $context); self::validate_context($context); $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users)); $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image'); $transaction = $DB->start_delegated_transaction(); foreach ($params['users'] as $user) { user_update_user($user, true, false); // Update user picture if it was specified for this user. if (empty($CFG->disableuserimages) && isset($user['userpicture'])) { $userobject = (object) $user; $userobject->deletepicture = null; if ($user['userpicture'] == 0) { $userobject->deletepicture = true; } else { $userobject->imagefile = $user['userpicture']; } core_user::update_picture($userobject, $filemanageroptions); } // Update user custom fields. if (!empty($user['customfields'])) { foreach ($user['customfields'] as $customfield) { // Profile_save_data() saves profile file it's expecting a user with the correct id, // and custom field to be named profile_field_"shortname". $user["profile_field_" . $customfield['type']] = $customfield['value']; } profile_save_data((object) $user); } // Trigger event. \core\event\user_updated::create_from_userid($user['id'])->trigger(); // Preferences. if (!empty($user['preferences'])) { foreach ($user['preferences'] as $preference) { set_user_preference($preference['type'], $preference['value'], $user['id']); } } } $transaction->allow_commit(); return null; }
/** * Update a user with a user object (will compare against the ID) * * @param stdClass $user the user to update * @param bool $updatepassword if true, authentication plugin will update password. */ function user_update_user($user, $updatepassword = true) { global $DB; // set the timecreate field to the current time if (!is_object($user)) { $user = (object) $user; } //check username if (isset($user->username)) { if ($user->username !== core_text::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== clean_param($user->username, PARAM_USERNAME)) { throw new moodle_exception('invalidusername'); } } } // Unset password here, for updating later, if password update is required. if ($updatepassword && isset($user->password)) { //check password toward the password policy if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $passwd = $user->password; unset($user->password); } $user->timemodified = time(); $DB->update_record('user', $user); if ($updatepassword) { // Get full user record. $updateduser = $DB->get_record('user', array('id' => $user->id)); // if password was set, then update its hash if (isset($passwd)) { $authplugin = get_auth_plugin($updateduser->auth); if ($authplugin->can_change_password()) { $authplugin->user_update_password($updateduser, $passwd); } } } // Trigger event. $event = \core\event\user_updated::create(array('objectid' => $user->id, 'context' => context_user::instance($user->id))); $event->trigger(); }
/** * Update a user with a user object (will compare against the ID) * * @throws moodle_exception * @param stdClass $user the user to update * @param bool $updatepassword if true, authentication plugin will update password. * @param bool $triggerevent set false if user_updated event should not be triggred. * This will not affect user_password_updated event triggering. */ function user_update_user($user, $updatepassword = true, $triggerevent = true) { global $DB; // Set the timecreate field to the current time. if (!is_object($user)) { $user = (object) $user; } // Check username. if (isset($user->username)) { if ($user->username !== core_text::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== core_user::clean_field($user->username, 'username')) { throw new moodle_exception('invalidusername'); } } } // Unset password here, for updating later, if password update is required. if ($updatepassword && isset($user->password)) { // Check password toward the password policy. if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $passwd = $user->password; unset($user->password); } // Make sure calendartype, if set, is valid. if (empty($user->calendartype)) { // Unset this variable, must be an empty string, which we do not want to update the calendartype to. unset($user->calendartype); } $user->timemodified = time(); // Validate user data object. $uservalidation = core_user::validate($user); if ($uservalidation !== true) { foreach ($uservalidation as $field => $message) { debugging("The property '{$field}' has invalid data and has been cleaned.", DEBUG_DEVELOPER); $user->{$field} = core_user::clean_field($user->{$field}, $field); } } $DB->update_record('user', $user); if ($updatepassword) { // Get full user record. $updateduser = $DB->get_record('user', array('id' => $user->id)); // If password was set, then update its hash. if (isset($passwd)) { $authplugin = get_auth_plugin($updateduser->auth); if ($authplugin->can_change_password()) { $authplugin->user_update_password($updateduser, $passwd); } } } // Trigger event if required. if ($triggerevent) { \core\event\user_updated::create_from_userid($user->id)->trigger(); } }
/** * Cron function for sync grades * @return void */ function local_ltiprovider_cron() { global $DB, $CFG; require_once $CFG->dirroot . "/local/ltiprovider/locallib.php"; require_once $CFG->dirroot . "/local/ltiprovider/ims-blti/OAuth.php"; require_once $CFG->dirroot . "/local/ltiprovider/ims-blti/OAuthBody.php"; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->dirroot . '/grade/querylib.php'; // TODO - Add a global setting for this $synctime = 60 * 60; // Every 1 hour grades are sync $timenow = time(); mtrace('Running cron for ltiprovider'); mtrace('Deleting LTI tools assigned to deleted courses'); if ($tools = $DB->get_records('local_ltiprovider')) { foreach ($tools as $tool) { local_ltiprovider_check_missing_course($tool); } } // Grades service. if ($tools = $DB->get_records_select('local_ltiprovider', 'disabled = ? AND sendgrades = ?', array(0, 1))) { foreach ($tools as $tool) { if ($tool->lastsync + $synctime < $timenow) { mtrace(" Starting sync tool for grades id {$tool->id} course id {$tool->courseid}"); if ($tool->requirecompletion) { mtrace(" Grades require activity or course completion"); } $user_count = 0; $send_count = 0; $error_count = 0; $completion = new completion_info(get_course($tool->courseid)); if ($users = $DB->get_records('local_ltiprovider_user', array('toolid' => $tool->id))) { foreach ($users as $user) { $user_count = $user_count + 1; // This can happen is the sync process has an unexpected error if (strlen($user->serviceurl) < 1) { mtrace(" Empty serviceurl"); continue; } if (strlen($user->sourceid) < 1) { mtrace(" Empty sourceid"); continue; } if ($user->lastsync > $tool->lastsync) { mtrace(" Skipping user {$user->id} due to recent sync"); continue; } $grade = false; if ($context = $DB->get_record('context', array('id' => $tool->contextid))) { if ($context->contextlevel == CONTEXT_COURSE) { if ($tool->requirecompletion and !$completion->is_course_complete($user->userid)) { mtrace(" Skipping user {$user->userid} since he didn't complete the course"); continue; } if ($grade = grade_get_course_grade($user->userid, $tool->courseid)) { $grademax = floatval($grade->item->grademax); $grade = $grade->grade; } } else { if ($context->contextlevel == CONTEXT_MODULE) { $cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST); if ($tool->requirecompletion) { $data = $completion->get_data($cm, false, $user->userid); if ($data->completionstate != COMPLETION_COMPLETE_PASS and $data->completionstate != COMPLETION_COMPLETE) { mtrace(" Skipping user {$user->userid} since he didn't complete the activity"); continue; } } $grades = grade_get_grades($cm->course, 'mod', $cm->modname, $cm->instance, $user->userid); if (empty($grades->items[0]->grades)) { $grade = false; } else { $grade = reset($grades->items[0]->grades); if (!empty($grade->item)) { $grademax = floatval($grade->item->grademax); } else { $grademax = floatval($grades->items[0]->grademax); } $grade = $grade->grade; } } } if ($grade === false || $grade === NULL || strlen($grade) < 1) { mtrace(" Invalid grade {$grade}"); continue; } // No need to be dividing by zero if ($grademax == 0.0) { $grademax = 100.0; } // TODO: Make lastgrade should be float or string - but it is integer so we truncate // TODO: Then remove those intval() calls // Don't double send if (intval($grade) == $user->lastgrade) { mtrace(" Skipping, last grade send is equal to current grade"); continue; } // We sync with the external system only when the new grade differs with the previous one // TODO - Global setting for check this if ($grade >= 0 and $grade <= $grademax) { $float_grade = $grade / $grademax; $body = local_ltiprovider_create_service_body($user->sourceid, $float_grade); try { $response = ltiprovider\sendOAuthBodyPOST('POST', $user->serviceurl, $user->consumerkey, $user->consumersecret, 'application/xml', $body); } catch (Exception $e) { mtrace(" " . $e->getMessage()); $error_count = $error_count + 1; continue; } // TODO - Check for errors in $retval in a correct way (parsing xml) if (strpos(strtolower($response), 'success') !== false) { $DB->set_field('local_ltiprovider_user', 'lastsync', $timenow, array('id' => $user->id)); $DB->set_field('local_ltiprovider_user', 'lastgrade', intval($grade), array('id' => $user->id)); mtrace(" User grade sent to remote system. userid: {$user->userid} grade: {$float_grade}"); $send_count = $send_count + 1; } else { mtrace(" User grade send failed. userid: {$user->userid} grade: {$float_grade}: " . $response); $error_count = $error_count + 1; } } else { mtrace(" User grade for user {$user->userid} out of range: grade = " . $grade); $error_count = $error_count + 1; } } else { mtrace(" Invalid context: contextid = " . $tool->contextid); } } } mtrace(" Completed sync tool id {$tool->id} course id {$tool->courseid} users={$user_count} sent={$send_count} errors={$error_count}"); $DB->set_field('local_ltiprovider', 'lastsync', $timenow, array('id' => $tool->id)); } } } $timenow = time(); // Automatic course restaurations. if ($croncourses = get_config('local_ltiprovider', 'croncourses')) { $croncourses = unserialize($croncourses); if (is_array($croncourses)) { mtrace('Starting restauration of pending courses'); foreach ($croncourses as $key => $course) { mtrace('Starting restoration of ' . $key); // We limit the backups to 1 hour, then retry. if ($course->restorestart and $timenow < $course->restorestart + 3600) { mtrace('Skipping restoration in process for: ' . $key); continue; } $course->restorestart = time(); $croncourses[$key] = $course; $croncoursessafe = serialize($croncourses); set_config('croncourses', $croncoursessafe, 'local_ltiprovider'); if ($destinationcourse = $DB->get_record('course', array('id' => $course->destinationid))) { // Duplicate course + users. local_ltiprovider_duplicate_course($course->id, $destinationcourse, 1, $options = array(array('name' => 'users', 'value' => 1)), $course->userrestoringid, $course->context); mtrace('Restoration for ' . $key . ' finished'); } else { mtrace('Restoration for ' . $key . ' finished (destination course not exists)'); } unset($croncourses[$key]); $croncoursessafe = serialize($croncourses); set_config('croncourses', $croncoursessafe, 'local_ltiprovider'); } } } // Membership service. $timenow = time(); $userphotos = array(); if ($tools = $DB->get_records('local_ltiprovider', array('disabled' => 0, 'syncmembers' => 1))) { mtrace('Starting sync of member using the memberships service'); $consumers = array(); foreach ($tools as $tool) { $lastsync = get_config('local_ltiprovider', 'membershipslastsync-' . $tool->id); if (!$lastsync) { $lastsync = 0; } if ($lastsync + $tool->syncperiod < $timenow) { mtrace('Starting sync of tool: ' . $tool->id); // We check for all the users, notice that users can access the same tool from different consumers. if ($users = $DB->get_records('local_ltiprovider_user', array('toolid' => $tool->id), 'lastaccess DESC')) { $response = ""; foreach ($users as $user) { if (!$user->membershipsurl or !$user->membershipsid) { continue; } $consumer = md5($user->membershipsurl . ':' . $user->membershipsid . ':' . $user->consumerkey . ':' . $user->consumersecret); if (in_array($consumer, $consumers)) { // We had syncrhonized with this consumer yet. continue; } $consumers[] = $consumer; $params = array('lti_message_type' => 'basic-lis-readmembershipsforcontext', 'id' => $user->membershipsid, 'lti_version' => 'LTI-1p0'); mtrace('Calling memberships url: ' . $user->membershipsurl . ' with body: ' . json_encode($params)); try { $response = ltiprovider\sendOAuthParamsPOST('POST', $user->membershipsurl, $user->consumerkey, $user->consumersecret, 'application/x-www-form-urlencoded', $params); } catch (Exception $e) { mtrace("Exception: " . $e->getMessage()); $response = false; } if ($response) { $data = new SimpleXMLElement($response); if (!empty($data->statusinfo)) { if (strpos(strtolower($data->statusinfo->codemajor), 'success') !== false) { $members = $data->memberships->member; mtrace(count($members) . ' members received'); $currentusers = array(); foreach ($members as $member) { $username = local_ltiprovider_create_username($user->consumerkey, $member->user_id); $userobj = $DB->get_record('user', array('username' => $username)); if (!$userobj) { // Old format. $oldusername = '******' . md5($user->consumerkey . ':' . $member->user_id); $userobj = $DB->get_record('user', array('username' => $oldusername)); if ($userobj) { $DB->set_field('user', 'username', $username, array('id' => $userobj->id)); } $userobj = $DB->get_record('user', array('username' => $username)); } if ($userobj) { $currentusers[] = $userobj->id; $userobj->firstname = clean_param($member->person_name_given, PARAM_TEXT); $userobj->lastname = clean_param($member->person_name_family, PARAM_TEXT); $userobj->email = clean_param($member->person_contact_email_primary, PARAM_EMAIL); $userobj->timemodified = time(); $DB->update_record('user', $userobj); $userphotos[$userobj->id] = $member->user_image; // Trigger event. $event = \core\event\user_updated::create(array('objectid' => $userobj->id, 'relateduserid' => $userobj->id, 'context' => context_user::instance($userobj->id))); $event->trigger(); } else { // New members. if ($tool->syncmode == 1 or $tool->syncmode == 2) { // We have to enrol new members so we have to create it. $userobj = new stdClass(); // clean_param , email username text $auth = get_config('local_ltiprovider', 'defaultauthmethod'); if ($auth) { $userobj->auth = $auth; } else { $userobj->auth = 'nologin'; } $username = local_ltiprovider_create_username($user->consumerkey, $member->user_id); $userobj->username = $username; $userobj->password = md5(uniqid(rand(), 1)); $userobj->firstname = clean_param($member->person_name_given, PARAM_TEXT); $userobj->lastname = clean_param($member->person_name_family, PARAM_TEXT); $userobj->email = clean_param($member->person_contact_email_primary, PARAM_EMAIL); $userobj->city = $tool->city; $userobj->country = $tool->country; $userobj->institution = $tool->institution; $userobj->timezone = $tool->timezone; $userobj->maildisplay = $tool->maildisplay; $userobj->mnethostid = $CFG->mnet_localhost_id; $userobj->confirmed = 1; $userobj->lang = $tool->lang; $userobj->timecreated = time(); if (!$userobj->lang) { // TODO: This should be changed for detect the course lang $userobj->lang = current_language(); } $userobj->id = $DB->insert_record('user', $userobj); // Reload full user $userobj = $DB->get_record('user', array('id' => $userobj->id)); $userphotos[$userobj->id] = $member->user_image; // Trigger event. $event = \core\event\user_created::create(array('objectid' => $userobj->id, 'relateduserid' => $userobj->id, 'context' => context_user::instance($userobj->id))); $event->trigger(); $currentusers[] = $userobj->id; } } // 1 -> Enrol and unenrol, 2 -> enrol if ($tool->syncmode == 1 or $tool->syncmode == 2) { // Enroll the user in the course. We don't know if it was previously unenrolled. $roles = explode(',', strtolower($member->roles)); local_ltiprovider_enrol_user($tool, $userobj, $roles, true); } } // Now we check if we have to unenrol users for keep both systems sync. if ($tool->syncmode == 1 or $tool->syncmode == 3) { // Unenrol users also. $context = context_course::instance($tool->courseid); $eusers = get_enrolled_users($context); foreach ($eusers as $euser) { if (!in_array($euser->id, $currentusers)) { local_ltiprovider_unenrol_user($tool, $euser); } } } } else { mtrace('Error recived from the remote system: ' . $data->statusinfo->codemajor . ' ' . $data->statusinfo->severity . ' ' . $data->statusinfo->codeminor); } } else { mtrace('Error parsing the XML received' . substr($response, 0, 125) . '... (Displaying only 125 chars)'); } } else { mtrace('No response received from ' . $user->membershipsurl); } } } set_config('membershipslastsync-' . $tool->id, $timenow, 'local_ltiprovider'); } else { $last = format_time(time() - $lastsync); mtrace("Tool {$tool->id} synchronized {$last} ago"); } mtrace('Finished sync of member using the memberships service'); } } // Sync of user photos. mtrace("Sync user profile images"); $counter = 0; if ($userphotos) { foreach ($userphotos as $userid => $url) { if ($url) { $result = local_ltiprovider_update_user_profile_image($userid, $url); if ($result === true) { $counter++; mtrace("Profile image succesfully downloaded and created from {$url}"); } else { mtrace($result); } } } } mtrace("{$counter} profile images updated"); }
$title = isset($usernew->usertitle) ? $usernew->usertitle : 0; assign_department_and_title_to_user($companyid, $department, $title, $usernew->id); } } // Reload from db. $usernew = $DB->get_record('user', array('id' => $usernew->id)); // Trigger events. if ($usercreated) { // Set default message preferences. if (!message_set_default_message_preferences($usernew)) { print_error('cannotsavemessageprefs', 'message'); } $event = \core\event\user_created::create_from_userid($usernew->id); $event->trigger(); } else { $event = \core\event\user_updated::create(array('context' => $systemcontext, 'userid' => $usernew->id, 'relateduserid' => $USER->id)); $event->trigger(); } if ($user->id == $USER->id) { // Override old $USER session variable. foreach ((array) $usernew as $variable => $value) { $USER->{$variable} = $value; } if (!empty($USER->newadminuser)) { unset($USER->newadminuser); // Apply defaults again - some of them might depend on admin user info, backup, roles, etc.. admin_apply_default_settings(null, false); // Redirect to admin/ to continue with installation. redirect("{$CFG->wwwroot}/{$CFG->admin}/"); } else { redirect("{$CFG->wwwroot}/user/view.php?id={$USER->id}&course={$course->id}");
/** * Update details for the current user * Password is passed in plaintext. * * @param object $user current user object * @param boolean $notify print notice with link and terminate */ public function user_update_details($user) { global $CFG, $DB, $USER; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; if ($user->password == $user->confirmpassword and !empty($user->password)) { $plainpassword = $user->password; echo $plainpassword; $user->password = hash_internal_user_password($user->password); $this->user_update_password($user, $user->password); user_add_password_history($user->id, $plainpassword); } if (empty($user->calendartype)) { $user->calendartype = $CFG->calendartype; } try { $transaction = $DB->start_delegated_transaction(); user_update_user($user, false, false); $user->profile_field_yearlevel = empty($user->profile_field_yearlevel) ? 'N/A' : $user->profile_field_yearlevel; $user->profile_field_yearofbirth = empty($user->profile_field_yearofbirth) ? 'N/A' : $user->profile_field_yearofbirth; $user->profile_field_whereareyoufrom = empty($user->profile_field_whereareyoufrom) ? 'Perth' : $user->profile_field_whereareyoufrom; $USER->profile['yearlevel'] = $user->profile_field_yearlevel; $USER->profile['yearofbirth'] = $user->profile_field_yearofbirth; $USER->profile['whereareyoufrom'] = $user->profile_field_whereareyoufrom; profile_save_data($user); // Trigger event. \core\event\user_updated::create_from_userid($user->id)->trigger(); // Assuming the both inserts work, we get to the following line. $transaction->allow_commit(); } catch (Exception $e) { $transaction->rollback($e); return false; } return $this->update_user_session($user); }
public static function user_updated(\core\event\user_updated $event) { global $CFG, $DB; $sync_to_joomla = get_config('auth/joomdle', 'sync_to_joomla'); if (!$sync_to_joomla) { return true; } $user = $event->get_record_snapshot('user', $event->objectid); if ($user->auth != 'joomdle') { return true; } $auth_joomdle = new auth_plugin_joomdle(); /* Update user info in Joomla */ $userinfo['username'] = $user->username; $userinfo['name'] = $user->firstname . " " . $user->lastname; $userinfo['email'] = $user->email; $userinfo['firstname'] = $user->firstname; $userinfo['lastname'] = $user->lastname; $userinfo['city'] = $user->city; $userinfo['country'] = $user->country; $userinfo['lang'] = $user->lang; $userinfo['timezone'] = $user->timezone; $userinfo['phone1'] = $user->phone1; $userinfo['phone2'] = $user->phone2; $userinfo['address'] = $user->address; $userinfo['description'] = $user->description; $userinfo['institution'] = $user->institution; $userinfo['url'] = $user->url; $userinfo['icq'] = $user->icq; $userinfo['skype'] = $user->skype; $userinfo['aim'] = $user->aim; $userinfo['yahoo'] = $user->yahoo; $userinfo['msn'] = $user->msn; $userinfo['idnumber'] = $user->idnumber; $userinfo['department'] = $user->department; $userinfo['picture'] = $user->picture; $userinfo['lastnamephonetic'] = $user->lastnamephonetic; $userinfo['firstnamephonetic'] = $user->firstnamephonetic; $userinfo['middlename'] = $user->middlename; $userinfo['alternatename'] = $user->alternatename; $id = $user->id; $usercontext = context_user::instance($id); $context_id = $usercontext->id; if ($user->picture) { $userinfo['pic_url'] = $CFG->wwwroot . "/pluginfile.php/{$context_id}/user/icon/f1"; } $userinfo['block'] = 0; /* Custom fields */ $query = "SELECT f.id, d.data \n\t\t\t\t\tFROM {$CFG->prefix}user_info_field as f, {$CFG->prefix}user_info_data d \n\t\t\t\t\tWHERE f.id=d.fieldid and userid = ?"; $params = array($id); $records = $DB->get_records_sql($query, $params); $i = 0; $userinfo['custom_fields'] = array(); foreach ($records as $field) { $userinfo['custom_fields'][$i]['id'] = $field->id; $userinfo['custom_fields'][$i]['data'] = $field->data; $i++; } $auth_joomdle->call_method("updateUser", $userinfo); return true; }
if ($isinternalauth && $updatepasswords) { if (empty($existinguser->password)) { set_user_preference('create_password', 1, $existinguser->id); set_user_preference('auth_forcepasswordchange', 1, $existinguser->id); $upt->track('password', get_string('new')); } else { if ($forcechangepassword) { set_user_preference('auth_forcepasswordchange', 1, $existinguser->id); } } } $upt->track('status', $struserupdated); $usersupdated++; // Save custom profile fields data from csv file. profile_save_data($existinguser); \core\event\user_updated::create(array('context' => $systemcontext, 'relateduserid' => $USER->id, 'userid' => $existinguser->id))->trigger(); } if ($bulk == 2 or $bulk == 3) { if (!in_array($user->id, $SESSION->bulk_users)) { $SESSION->bulk_users[] = $user->id; } } } else { // Save the user to the database. $user->confirmed = 1; $user->timemodified = time(); $user->timecreated = time(); if (isset($user->auth) && empty($user->auth)) { $user->auth = 'manual'; } $auth = get_auth_plugin($user->auth);
$user = new stdClass(); local_ltiprovider_populate($user, $context, $tool); if (local_ltiprovider_user_match($user, $dbuser)) { $user = $dbuser; } else { $user = $dbuser; $userprofileupdate = get_config('local_ltiprovider', 'userprofileupdate'); if ($userprofileupdate == -1) { // Check the tool setting. $userprofileupdate = $tool->userprofileupdate; } if ($userprofileupdate) { local_ltiprovider_populate($user, $context, $tool); $DB->update_record('user', $user); // Trigger event. $event = \core\event\user_updated::create(array('objectid' => $user->id, 'relateduserid' => $user->id, 'context' => context_user::instance($user->id))); $event->trigger(); } } } // Update user image. if (!empty($context->info['user_image']) or !empty($context->info['custom_user_image'])) { $userimageurl = !empty($context->info['user_image']) ? $context->info['user_image'] : $context->info['custom_user_image']; local_ltiprovider_update_user_profile_image($user->id, $userimageurl); } // Enrol user in course and activity if needed if (!($moodlecontext = $DB->get_record('context', array('id' => $tool->contextid)))) { print_error("invalidcontext"); } if ($moodlecontext->contextlevel == CONTEXT_COURSE) { $courseid = $moodlecontext->instanceid;