/** * Sign up a new user ready for confirmation. * Password is passed in plaintext. * * @param object $user new user object (with system magic quotes) * @param boolean $notify print notice with link and terminate */ function user_signup($user, $notify = true) { global $CFG; require_once $CFG->dirroot . '/user/profile/lib.php'; $user->password = hash_internal_user_password($user->password); if (!($user->id = insert_record('user', $user))) { print_error('auth_emailnoinsert', 'auth'); } /// Save any custom profile field information profile_save_data($user); $user = get_record('user', 'id', $user->id); events_trigger('user_created', $user); if (!send_confirmation_email($user)) { print_error('auth_emailnoemail', 'auth'); } if ($notify) { global $CFG; $emailconfirm = get_string('emailconfirm'); $navlinks = array(); $navlinks[] = array('name' => $emailconfirm, 'link' => null, 'type' => 'misc'); $navigation = build_navigation($navlinks); print_header($emailconfirm, $emailconfirm, $navigation); notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php"); } else { return true; } }
/** * Sign up a new user ready for confirmation. * Password is passed in plaintext. * * @param object $user new user object * @param boolean $notify print notice with link and terminate */ function user_signup($user, $notify = true) { global $CFG, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; $user->password = hash_internal_user_password($user->password); $user->id = $DB->insert_record('user', $user); /// Save any custom profile field information profile_save_data($user); $user = $DB->get_record('user', array('id' => $user->id)); events_trigger('user_created', $user); if (!send_confirmation_email($user)) { print_error('auth_emailnoemail', 'auth_email'); } if ($notify) { global $CFG, $PAGE, $OUTPUT; $emailconfirm = get_string('emailconfirm'); $PAGE->navbar->add($emailconfirm); $PAGE->set_title($emailconfirm); $PAGE->set_heading($PAGE->course->fullname); echo $OUTPUT->header(); notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php"); } else { return true; } }
/** * Sign up a new user ready for confirmation. * Password is passed in plaintext. * * @param object $user new user object * @param boolean $notify print notice with link and terminate */ public function user_signup($user, $notify = true) { global $CFG, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; $plainpassword = $user->password; $user->password = hash_internal_user_password($user->password); if (empty($user->calendartype)) { $user->calendartype = $CFG->calendartype; } $user->id = user_create_user($user, false, false); user_add_password_history($user->id, $plainpassword); // Save any custom profile field information. profile_save_data($user); // Trigger event. \core\event\user_created::create_from_userid($user->id)->trigger(); if (!send_confirmation_email($user)) { print_error('auth_emailnoemail, auth_email'); } if ($notify) { global $CFG, $PAGE, $OUTPUT; $emailconfirm = get_string('emailconfirm'); $PAGE->navbar->add($emailconfirm); $PAGE->set_title($emailconfirm); $PAGE->set_heading($PAGE->course->fullname); echo $OUTPUT->header(); notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php"); } else { return true; } }
/** * Sign up a new user ready for confirmation. * Password is passed in plaintext. * * @param object $user new user object (with system magic quotes) * @param boolean $notify print notice with link and terminate */ function user_signup($user, $notify = true) { global $CFG; require_once $CFG->dirroot . '/user/profile/lib.php'; $user->password = hash_internal_user_password($user->password); if (!($user->id = insert_record('user', $user))) { print_error('auth_emailnoinsert', 'auth'); } /// Save any custom profile field information profile_save_data($user); //Added by JAM: 12.02.2010 - Call the set user time-zone for WS, cannot set time-zone until, user is created setWSUserDefaultTimeZone($user->username, $user); $user = get_record('user', 'id', $user->id); events_trigger('user_created', $user); //Added by JAM: 01.06.2011 - this is where the user id exists if (!addQSUser($user)) { admin_signuperror_email($user); // Added: JAM - 01.06.2011 //error('An error has occured, please try again shortly.'); } if (!send_confirmation_email($user)) { print_error('auth_emailnoemail', 'auth'); } if ($notify) { global $CFG; $emailconfirm = get_string('emailconfirm'); $navlinks = array(); $navlinks[] = array('name' => $emailconfirm, 'link' => null, 'type' => 'misc'); $navigation = build_navigation($navlinks); print_header($emailconfirm, $emailconfirm, $navigation); // Added by SMS: 7/28/2011 $data = new object(); $data->useremail = $user->email; $supportuser = generate_email_supportuser(); $data->adminemail = $supportuser->email; // Edited by SMS: 7/28/2011 // notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php"); notice(get_string('emailconfirmsent', '', $data), "{$CFG->wwwroot}/index.php"); } else { return true; } }
function application_user_signup($user) { // Derived from email->user_signup global $CFG, $PAGE, $OUTPUT; $user->password = hash_internal_user_password($user->password); if (empty($user->calendartype)) { $user->calendartype = $CFG->calendartype; } $user->id = user_create_user($user, false, false); // Save any custom profile field information profile_save_data($user); // Save contact information write_contact_details($user->id, $user); // Trigger event \core\event\user_created::create_from_userid($user->id)->trigger(); if (!send_application_confirmation_email($user)) { print_error('auth_emailnoemail', 'auth_email'); } $PAGE->set_title($CFG->pageheading . ': ' . get_string('emailconfirm')); echo $OUTPUT->header(); notice(get_string('emailconfirmsent', '', $user->email), $CFG->wwwroot . '/local/obu_application/login.php'); }
function user_signup($user, $notify = true) { global $CFG, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; $password_clear = $user->password; $user->password = hash_internal_user_password($user->password); if (!($user->id = $DB->insert_record('user', $user))) { print_error('auth_emailnoinsert', 'auth'); } /// Save any custom profile field information profile_save_data($user); $conditions = array('id' => $user->id); $user = $DB->get_record('user', $conditions); /* Create user in Joomla */ $userinfo['username'] = $user->username; $userinfo['password'] = $password_clear; $userinfo['password2'] = $password_clear; $userinfo['name'] = $user->firstname . " " . $user->lastname; $userinfo['email'] = $user->email; $userinfo['block'] = 1; $this->call_method("createUser", $userinfo); events_trigger('user_created', $user); if (!send_confirmation_email($user)) { print_error('auth_emailnoemail', 'auth'); } if ($notify) { global $CFG; $emailconfirm = get_string('emailconfirm'); $navlinks = array(); $navlinks[] = array('name' => $emailconfirm, 'link' => null, 'type' => 'misc'); $navigation = build_navigation($navlinks); print_header($emailconfirm, $emailconfirm, $navigation); notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php"); } else { return true; } }
/** * Test that {@link user_not_fully_set_up()} takes required custom fields into account. */ public function test_profile_has_required_custom_fields_set() { global $CFG, $DB; require_once $CFG->dirroot . '/mnet/lib.php'; $this->resetAfterTest(); // Add a required, visible, unlocked custom field. $DB->insert_record('user_info_field', ['shortname' => 'house', 'name' => 'House', 'required' => 1, 'visible' => 1, 'locked' => 0, 'categoryid' => 1, 'datatype' => 'text']); // Add an optional, visible, unlocked custom field. $DB->insert_record('user_info_field', ['shortname' => 'pet', 'name' => 'Pet', 'required' => 0, 'visible' => 1, 'locked' => 0, 'categoryid' => 1, 'datatype' => 'text']); // Add required but invisible custom field. $DB->insert_record('user_info_field', ['shortname' => 'secretid', 'name' => 'Secret ID', 'required' => 1, 'visible' => 0, 'locked' => 0, 'categoryid' => 1, 'datatype' => 'text']); // Add required but locked custom field. $DB->insert_record('user_info_field', ['shortname' => 'muggleborn', 'name' => 'Muggle-born', 'required' => 1, 'visible' => 1, 'locked' => 1, 'categoryid' => 1, 'datatype' => 'checkbox']); // Create some student accounts. $hermione = $this->getDataGenerator()->create_user(); $harry = $this->getDataGenerator()->create_user(); $ron = $this->getDataGenerator()->create_user(); $draco = $this->getDataGenerator()->create_user(); // Hermione has all available custom fields filled (of course she has). profile_save_data((object) ['id' => $hermione->id, 'profile_field_house' => 'Gryffindor']); profile_save_data((object) ['id' => $hermione->id, 'profile_field_pet' => 'Crookshanks']); // Harry has only the optional field filled. profile_save_data((object) ['id' => $harry->id, 'profile_field_pet' => 'Hedwig']); // Draco has only the required field filled. profile_save_data((object) ['id' => $draco->id, 'profile_field_house' => 'Slytherin']); // Only students with required fields filled should be considered as fully set up in the default (strict) mode. $this->assertFalse(user_not_fully_set_up($hermione)); $this->assertFalse(user_not_fully_set_up($draco)); $this->assertTrue(user_not_fully_set_up($harry)); $this->assertTrue(user_not_fully_set_up($ron)); // In the lax mode, students do not need to have required fields filled. $this->assertFalse(user_not_fully_set_up($hermione, false)); $this->assertFalse(user_not_fully_set_up($draco, false)); $this->assertFalse(user_not_fully_set_up($harry, false)); $this->assertFalse(user_not_fully_set_up($ron, false)); // Lack of required core field is seen as a problem in either mode. unset($hermione->email); $this->assertTrue(user_not_fully_set_up($hermione, true)); $this->assertTrue(user_not_fully_set_up($hermione, false)); // When confirming remote MNet users, we do not have custom fields available. $roamingharry = mnet_strip_user($harry, ['firstname', 'lastname', 'email']); $roaminghermione = mnet_strip_user($hermione, ['firstname', 'lastname', 'email']); $this->assertTrue(user_not_fully_set_up($roamingharry, true)); $this->assertFalse(user_not_fully_set_up($roamingharry, false)); $this->assertTrue(user_not_fully_set_up($roaminghermione, true)); $this->assertTrue(user_not_fully_set_up($roaminghermione, false)); }
/** * Sign up a new user ready for confirmation. * Password is passed in plaintext. * * @param object $user new user object * @param boolean $notify print notice with link and terminate */ function user_signup($user, $notify=true) { global $CFG, $DB, $PAGE, $OUTPUT; require_once($CFG->dirroot.'/user/profile/lib.php'); if ($this->user_exists($user->username)) { print_error('auth_ldap_user_exists', 'auth_ldap'); } $plainslashedpassword = $user->password; unset($user->password); if (! $this->user_create($user, $plainslashedpassword)) { print_error('auth_ldap_create_error', 'auth_ldap'); } $user->id = $DB->insert_record('user', $user); // Save any custom profile field information profile_save_data($user); $this->update_user_record($user->username); update_internal_user_password($user, $plainslashedpassword); $user = $DB->get_record('user', array('id'=>$user->id)); events_trigger('user_created', $user); if (! send_confirmation_email($user)) { print_error('noemail', 'auth_ldap'); } if ($notify) { $emailconfirm = get_string('emailconfirm'); $PAGE->set_url('/auth/ldap/auth.php'); $PAGE->navbar->add($emailconfirm); $PAGE->set_title($emailconfirm); $PAGE->set_heading($emailconfirm); echo $OUTPUT->header(); notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php"); } else { return true; } }
/** * 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; }
/** * Create one or more users. * * @throws invalid_parameter_exception * @param array $users An array of users to create. * @return array An array of arrays * @since Moodle 2.2 */ public static function create_users($users) { global $CFG, $DB; require_once $CFG->dirroot . "/lib/weblib.php"; 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(); self::validate_context($context); require_capability('moodle/user:create', $context); // Do basic automatic PARAM checks on incoming data, using params description. // If any problems are found then exceptions are thrown with helpful error messages. $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users)); $availableauths = core_component::get_plugin_list('auth'); unset($availableauths['mnet']); // These would need mnethostid too. unset($availableauths['webservice']); // We do not want new webservice users for now. $availablethemes = core_component::get_plugin_list('theme'); $availablelangs = get_string_manager()->get_list_of_translations(); $transaction = $DB->start_delegated_transaction(); $userids = array(); foreach ($params['users'] as $user) { // Make sure that the username doesn't already exist. if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) { throw new invalid_parameter_exception('Username already exists: ' . $user['username']); } // Make sure auth is valid. if (empty($availableauths[$user['auth']])) { throw new invalid_parameter_exception('Invalid authentication type: ' . $user['auth']); } // Make sure lang is valid. if (empty($availablelangs[$user['lang']])) { throw new invalid_parameter_exception('Invalid language code: ' . $user['lang']); } // Make sure lang is valid. if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL, // so no default value // We need to test if the client sent it // => !empty($user['theme']). throw new invalid_parameter_exception('Invalid theme: ' . $user['theme']); } $user['confirmed'] = true; $user['mnethostid'] = $CFG->mnet_localhost_id; // Start of user info validation. // 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 ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) { throw new invalid_parameter_exception('Email address already exists: ' . $user['email']); } } // End of user info validation. // Create the user data now! $user['id'] = user_create_user($user, true, false); // 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_created::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']); } } //var_dump(array('id' => $user['id'], 'username' => $user['username'])); $userids[] = array('id' => $user['id'], 'username' => $user['username']); } $transaction->allow_commit(); return $userids; }
/** * Test that modifying a Moodle user also updates the corresponding PM user. */ public function test_modifyingmoodleuserupdatespmuser() { global $CFG, $DB; require_once $CFG->dirroot . '/admin/tool/uploaduser/locallib.php'; $this->load_csv_data(); // Update a record. $src = new stdClass(); $src->id = 100; $src->firstname = 'Testuser'; $src->lastname = 'One'; $src->profile_field_sometext = 'boo'; $src->profile_field_sometextfrompm = 'bla'; $DB->update_record('user', $src); $mdluser = $DB->get_record('user', array('id' => 100)); $mcopy = clone $src; $mcopy = uu_pre_process_custom_profile_data($mcopy); profile_save_data($mcopy); events_trigger('user_updated', $mdluser); // Read the PM user and compare. $retr = new user(103, null, array(), false, array()); $retr->reset_custom_field_list(); $this->assertEquals($mdluser->firstname, $retr->firstname); $this->assertEquals($mdluser->lastname, $retr->lastname); // Check custom fields. $result = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(); $result->addTable(new moodle_recordset_phpunit_datatable(field_data_int::TABLE, $DB->get_recordset(field_data_int::TABLE, null, '', 'contextid, fieldid, data'))); $result->addTable(new moodle_recordset_phpunit_datatable(field_data_char::TABLE, $DB->get_recordset(field_data_char::TABLE, null, '', 'contextid, fieldid, data'))); $result->addTable(new moodle_recordset_phpunit_datatable(field_data_text::TABLE, $DB->get_recordset(field_data_text::TABLE, null, '', 'contextid, fieldid, data'))); $usercontext = \local_elisprogram\context\user::instance(103); $dataset = new PHPUnit_Extensions_Database_DataSet_CsvDataSet(); $dataset->addTable(field_data_int::TABLE, elispm::file('tests/fixtures/user_field_data_int.csv')); $dataset->addTable(field_data_char::TABLE, elispm::file('tests/fixtures/user_field_data_char.csv')); $dataset->addTable(field_data_text::TABLE, elispm::file('tests/fixtures/user_field_data_text.csv')); $dataset = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($dataset); $dataset->addFullReplacement('##USERCTXID##', $usercontext->id); $dataset->addFullReplacement('##USERCTXLVL##', CONTEXT_ELIS_USER); // Only the first text field should be changed; everything else should be the same. $dataset->addFullReplacement('First text entry field', $src->profile_field_sometext); $ret = $dataset->addFullReplacement('Second text entry field', $src->profile_field_sometextfrompm); $this->assertDataSetsEqual($dataset, $result); }
/** * Get additional information about a user from Azure AD. * * @param int $userid The ID of the user we want more information about. * @param string $eventtype The type of event that triggered this call. "login" or "create". * @return bool Success/Failure. */ public static function get_additional_user_info($userid, $eventtype) { global $DB; try { // Azure AD must be configured for us to fetch data. if (\local_o365\rest\azuread::is_configured() !== true) { return true; } $aadresource = \local_o365\rest\azuread::get_resource(); $sql = 'SELECT tok.* FROM {auth_oidc_token} tok JOIN {user} u ON tok.username = u.username WHERE u.id = ? AND tok.resource = ?'; $params = [$userid, $aadresource]; $tokenrec = $DB->get_record_sql($sql, $params); if (empty($tokenrec)) { // No OIDC token for this user and resource - maybe not an Azure AD user. return false; } $httpclient = new \local_o365\httpclient(); $clientdata = \local_o365\oauth2\clientdata::instance_from_oidc(); $token = \local_o365\oauth2\token::instance($userid, $aadresource, $clientdata, $httpclient); $apiclient = new \local_o365\rest\azuread($token, $httpclient); $aaduserdata = $apiclient->get_user($tokenrec->oidcuniqid); $updateduser = new \stdClass(); $updateduser = \local_o365\feature\usersync\main::apply_configured_fieldmap($aaduserdata, $updateduser, $eventtype); if (!empty($updateduser)) { $updateduser->id = $userid; $DB->update_record('user', $updateduser); profile_save_data($updateduser); } return true; } catch (\Exception $e) { \local_o365\utils::debug($e->getMessage()); } return false; }
/** * Create a Moodle user from Azure AD user data. * * @param array $aaddata Array of Azure AD user data. * @return \stdClass An object representing the created Moodle user. */ public function create_user_from_aaddata($aaddata) { global $CFG; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; $newuser = (object) ['auth' => 'oidc', 'username' => trim(\core_text::strtolower($aaddata['userPrincipalName'])), 'email' => isset($aaddata['mail']) ? $aaddata['mail'] : '', 'firstname' => isset($aaddata['givenName']) ? $aaddata['givenName'] : '', 'lastname' => isset($aaddata['surname']) ? $aaddata['surname'] : '', 'city' => isset($aaddata['city']) ? $aaddata['city'] : '', 'country' => isset($aaddata['country']) ? $aaddata['country'] : '', 'department' => isset($aaddata['department']) ? $aaddata['department'] : '', 'lang' => isset($aaddata['preferredLanguage']) ? substr($aaddata['preferredLanguage'], 0, 2) : 'en', 'confirmed' => 1, 'timecreated' => time(), 'mnethostid' => $CFG->mnet_localhost_id]; $password = null; $newuser->idnumber = $newuser->username; if (!empty($newuser->email)) { if (email_is_not_allowed($newuser->email)) { unset($newuser->email); } } if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) { $newuser->lang = $CFG->lang; } $newuser->timemodified = $newuser->timecreated; $newuser->id = user_create_user($newuser, false, false); // Save user profile data. profile_save_data($newuser); $user = get_complete_user_data('id', $newuser->id); if (!empty($CFG->{'auth_' . $newuser->auth . '_forcechangepassword'})) { set_user_preference('auth_forcepasswordchange', 1, $user); } // Set the password. update_internal_user_password($user, $password); // Trigger event. \core\event\user_created::create_from_userid($newuser->id)->trigger(); return $user; }
function update_profile_fields($user, $data) { profile_load_data($user); $user->profile_field_state = $data->state; $user->profile_field_companyName = $data->companyName; $user->profile_field_website = $data->website; $user->profile_field_zone = $data->zone; //echo "<br/>-".$data->zone."-"; profile_save_data($user); }
function moodle_user_update_users($client) { global $DB, $CFG; //Set test data //a full user: user1 $user1 = new stdClass(); $user1->username = '******'; $user1->password = '******'; $user1->firstname = 'testfirstname1'; $user1->lastname = 'testlastname1'; $user1->email = '*****@*****.**'; $user1->auth = 'manual'; $user1->idnumber = 'testidnumber1'; $user1->lang = 'en'; $user1->theme = 'standard'; $user1->timezone = 99; $user1->mailformat = 0; $user1->description = 'Hello World!'; $user1->city = 'testcity1'; $user1->country = 'au'; $preferencename1 = 'preference1'; $preferencename2 = 'preference2'; $user1->preferences = array( array('type' => $preferencename1, 'value' => 'preferencevalue1'), array('type' => $preferencename2, 'value' => 'preferencevalue2')); $customfieldname1 = 'testdatacustom1'; $customfieldname2 = 'testdatacustom2'; $user1->customfields = array( array('type' => $customfieldname1, 'value' => 'customvalue'), array('type' => $customfieldname2, 'value' => 'customvalue2')); //a small user: user2 $user2 = new stdClass(); $user2->username = '******'; $user2->password = '******'; $user2->firstname = 'testfirstname2'; $user2->lastname = 'testlastname2'; $user2->email = '*****@*****.**'; $users = array($user1, $user2); //can run this test only if test usernames don't exist $searchusers = $DB->get_records_list('user', 'username', array($user1->username, $user1->username)); if (count($searchusers) == 0) { //create two users require_once($CFG->dirroot."/user/lib.php"); require_once($CFG->dirroot."/user/profile/lib.php"); $user1->id = user_create_user($user1); //unset field created by user_create_user unset($user1->timemodified); unset($user1->timecreated); // custom fields if(!empty($user1->customfields)) { foreach($user1->customfields as $customfield) { $customuser1->id = $user1->id; $customuser1->{"profile_field_".$customfield['type']} = $customfield['value']; } profile_save_data((object) $customuser1); } //preferences if (!empty($user1->preferences)) { foreach($user1->preferences as $preference) { set_user_preference($preference['type'], $preference['value'],$user1->id); } } $user2->id = user_create_user($user2); unset($user2->timemodified); unset($user2->timecreated); //create the custom fields $customfield = new stdClass(); $customfield->shortname = $customfieldname1; $customfield->name = $customfieldname1; $customfield->datatype = 'text'; $DB->insert_record('user_info_field', $customfield); $customfield = new stdClass(); $customfield->shortname = $customfieldname2; $customfield->name = $customfieldname2; $customfield->datatype = 'text'; $DB->insert_record('user_info_field', $customfield); //search for them => TEST they exists $searchusers = $DB->get_records_list('user', 'username', array($user1->username, $user2->username)); $this->assertEqual(count($users), count($searchusers)); //update the test data $user1->username = '******'; $user1->password = '******'; $user1->firstname = 'testfirstname1_updated'; $user1->lastname = 'testlastname1_updated'; $user1->email = '*****@*****.**'; $user1->auth = 'manual'; $user1->idnumber = 'testidnumber1_updated'; $user1->lang = 'en'; $user1->theme = 'standard'; $user1->timezone = 98; $user1->mailformat = 1; $user1->description = 'Hello World!_updated'; $user1->city = 'testcity1_updated'; $user1->country = 'au'; $preferencename1 = 'preference1'; $preferencename2 = 'preference2'; $user1->preferences = array( array('type' => $preferencename1, 'value' => 'preferencevalue1_updated'), array('type' => $preferencename2, 'value' => 'preferencevalue2_updated')); $customfieldname1 = 'testdatacustom1'; $customfieldname2 = 'testdatacustom2'; $user1->customfields = array( array('type' => $customfieldname1, 'value' => 'customvalue_updated'), array('type' => $customfieldname2, 'value' => 'customvalue2_updated')); $user2->username = '******'; $user2->password = '******'; $user2->firstname = 'testfirstname2_updated'; $user2->lastname = 'testlastname2_updated'; $user2->email = '*****@*****.**'; $users = array($user1, $user2); //update the users by web service $function = 'moodle_user_update_users'; $params = array('users' => $users); $client->call($function, $params); //compare DB user with the test data $dbuser1 = $DB->get_record('user', array('username' => $user1->username)); $this->assertEqual($dbuser1->firstname, $user1->firstname); $this->assertEqual($dbuser1->password, hash_internal_user_password($user1->password)); $this->assertEqual($dbuser1->lastname, $user1->lastname); $this->assertEqual($dbuser1->email, $user1->email); $this->assertEqual($dbuser1->auth, $user1->auth); $this->assertEqual($dbuser1->idnumber, $user1->idnumber); $this->assertEqual($dbuser1->lang, $user1->lang); $this->assertEqual($dbuser1->theme, $user1->theme); $this->assertEqual($dbuser1->timezone, $user1->timezone); $this->assertEqual($dbuser1->mailformat, $user1->mailformat); $this->assertEqual($dbuser1->description, $user1->description); $this->assertEqual($dbuser1->city, $user1->city); $this->assertEqual($dbuser1->country, $user1->country); $user1preference1 = get_user_preferences($user1->preferences[0]['type'], null, $dbuser1->id); $this->assertEqual($user1->preferences[0]['value'], $user1preference1); $user1preference2 = get_user_preferences($user1->preferences[1]['type'], null, $dbuser1->id); $this->assertEqual($user1->preferences[1]['value'], $user1preference2); require_once($CFG->dirroot . "/user/profile/lib.php"); $customfields = profile_user_record($dbuser1->id); $customfields = (array) $customfields; $customfieldname1 = $user1->customfields[0]['type']; $customfieldname2 = $user1->customfields[1]['type']; $this->assertEqual($customfields[$customfieldname1], $user1->customfields[0]['value']); $this->assertEqual($customfields[$customfieldname2], $user1->customfields[1]['value']); $dbuser2 = $DB->get_record('user', array('username' => $user2->username)); $this->assertEqual($dbuser2->firstname, $user2->firstname); $this->assertEqual($dbuser2->password, hash_internal_user_password($user2->password)); $this->assertEqual($dbuser2->lastname, $user2->lastname); $this->assertEqual($dbuser2->email, $user2->email); //unset preferences $DB->delete_records('user_preferences', array('userid' => $dbuser1->id)); //clear custom fields data $DB->delete_records('user_info_data', array('userid' => $dbuser1->id)); //delete custom fields $DB->delete_records_list('user_info_field', 'shortname', array($customfieldname1, $customfieldname2)); //delete users from DB $DB->delete_records_list('user', 'id', array($dbuser1->id, $dbuser2->id)); } }
/** * Sign up a new user ready for confirmation. * Password is passed in plaintext. * * @param object $user new user object * @param boolean $notify print notice with link and terminate */ function user_signup($user, $notify = true) { global $CFG, $DB, $SESSION; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; if (isset($SESSION->wantsurl)) { $wantsurl = $SESSION->wantsurl; } $plainpassword = $user->password; $user->password = hash_internal_user_password($user->password); if (empty($user->calendartype)) { $user->calendartype = $CFG->calendartype; } $user->confirmed = 1; $user->id = user_create_user($user, false, false); user_add_password_history($user->id, $plainpassword); // Save any custom profile field information. profile_save_data($user); // Trigger event. \core\event\user_created::create_from_userid($user->id)->trigger(); $thisuser = authenticate_user_login($user->username, $plainpassword, false, $errorcode); if ($thisuser == false) { print_error('authfailure'); } else { complete_user_login($thisuser); if (isset($wantsurl)) { $urltogo = $wantsurl; if (isset($_SESSION["fiaction"]) && isset($_SESSION["ficourseid"]) && is_numeric($_SESSION["ficourseid"]) && $_SESSION["fiaction"] == "enroll") { $urltogo = $CFG->wwwroot . '/course/enrol.php?id=' . $_SESSION["ficourseid"]; unset($_SESSION['fiaction']); unset($_SESSION['ficourseid']); unset($SESSION->wantsurl); } } else { $urltogo = $CFG->wwwroot . '/'; } redirect($urltogo); } // if ($notify) { // global $CFG, $PAGE, $OUTPUT; // $emailconfirm = get_string('emailconfirm'); // $PAGE->navbar->add($emailconfirm); // $PAGE->set_title($emailconfirm); // $PAGE->set_heading($PAGE->course->fullname); // echo $OUTPUT->header(); // notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php"); // } else { // return true; // } }
public static function process_login(\core\event\user_loggedin $event) { global $CFG, $DB; // we just received the event from the authentication system; check if well-formed: if (!$event->userid) { // didn't get an user ID, return as there is nothing we can do return true; } if (in_array('shibboleth', get_enabled_auth_plugins()) && $_SERVER['SCRIPT_FILENAME'] == $CFG->dirroot . '/auth/shibboleth/index.php') { // we did get this event from the Shibboleth authentication plugin, // so let's try to make the relevant mappings, ensuring that necessary profile fields exist and Shibboleth attributes are provided: $customfieldrecords = $DB->get_records('user_info_field'); $customfields = array(); foreach ($customfieldrecords as $customfieldrecord) { $customfields[] = $customfieldrecord->shortname; } $mapping = array(); $mappings_str = explode("\n", str_replace("\r", '', get_config('enrol_attributes', 'mappings'))); foreach ($mappings_str as $mapping_str) { if (preg_match('/^\\s*([^: ]+)\\s*:\\s*([^: ]+)\\s*$/', $mapping_str, $matches) && in_array($matches[2], $customfields) && array_key_exists($matches[1], $_SERVER)) { $mapping[$matches[1]] = $matches[2]; } } if (count($mapping)) { // now update user profile data from Shibboleth params received as part of the event: $user = $DB->get_record('user', ['id' => $event->userid], '*', MUST_EXIST); foreach ($mapping as $shibattr => $fieldname) { if (isset($_SERVER[$shibattr])) { $propertyname = 'profile_field_' . $fieldname; $user->{$propertyname} = $_SERVER[$shibattr]; } } require_once $CFG->dirroot . '/user/profile/lib.php'; profile_save_data($user); } } // last, process the actual enrolments, whether we're using Shibboleth authentication or not: self::process_enrolments($event); }
/** * Proceed with the import of the user. * * @return void */ public function proceed() { if (!$this->prepared) { throw new coding_exception('The course has not been prepared.'); } else { if ($this->has_errors()) { throw new moodle_exception('Cannot proceed, errors were detected.'); } else { if ($this->processstarted) { throw new coding_exception('The process has already been started.'); } } } $this->processstarted = true; if ($this->do === self::DO_DELETE) { $this->finaldata = $this->existing; try { $success = delete_user($this->existing); } catch (moodle_exception $e) { $success = false; } if (!$success) { $this->error('usernotdeletederror', new lang_string('usernotdeletederror', 'tool_uploadusercli')); return false; } $this->set_status('userdeleted', new lang_string('userdeleted', 'tool_uploaduser')); return true; } else { if ($this->do === self::DO_CREATE) { try { $this->finaldata->id = user_create_user($this->finaldata, false, false); } catch (Exception $e) { $this->error('errorcreatinguser', new lang_string('errorcreatinguser', 'tool_uploadusercli')); return false; } if ($this->needpasswordchange) { set_user_preference('auth_forcepasswordchange', 1, $this->finaldata); $this->set_status('forcepasswordchange', new lang_string('forcepasswordchange', 'tool_uploadusercli')); } if ($this->finaldata->password === 'to be generated') { set_user_preference('create_password', 1, $this->finaldata); } $this->set_status('useradded', new lang_string('newuser')); } else { if ($this->do === self::DO_UPDATE) { try { user_update_user($this->finaldata, false, false); } catch (Exception $e) { $this->error('usernotupdatederror', new lang_string('usernotupdatederror', 'error')); return false; } if ($this->dologout) { \core\session\manager::kill_user_sessions($this->finaldata->id); } $this->set_status('useraccountupdated', new lang_string('useraccountupdated', 'tool_uploaduser')); } } } if ($this->do === self::DO_UPDATE || $this->do === self::DO_CREATE) { if (!$this->isremote) { $this->finaldata = uu_pre_process_custom_profile_data($this->finaldata); profile_save_data($this->finaldata); } $success = $this->add_to_cohort(); $success = $success && $this->add_to_egr(); if (!$success) { return false; } } return true; }
/** * Function to synchronize the curriculum data with the Moodle data. * * @param boolean $tomoodle Optional direction to synchronize the data. * */ function synchronize_moodle_user($tomoodle = true, $createnew = false) { global $CFG, $CURMAN; static $mu_loop_detect = array(); // Create a new Moodle user record to update with. if (!($muserid = get_field('user', 'id', 'idnumber', $this->idnumber, 'mnethostid', $CFG->mnet_localhost_id, 'deleted', 0)) && !$createnew) { return false; } if ($tomoodle) { if ($createnew && !$muserid) { /// Add a new user $record = new stdClass(); $record->idnumber = $this->idnumber; $record->username = $this->username; /// Check if already hashed... (not active now) if (!empty($CURMAN->passwordnothashed)) { $record->password = hash_internal_user_password($this->password); } else { $record->password = $this->password; } $record->firstname = $this->firstname; $record->lastname = $this->lastname; $record->email = $this->email; $record->confirmed = 1; $record->mnethostid = $CFG->mnet_localhost_id; $record->address = $this->address; $record->city = $this->city; $record->country = $this->country; $record->timemodified = time(); $record->lang = $this->language; $record->id = insert_record('user', $record); } else { if ($muserid) { /// Update an existing user $record = new stdClass(); $record->id = $muserid; $record->idnumber = $this->idnumber; $record->username = $this->username; /// Check if already hashed... (not active now) if (!empty($CURMAN->passwordnothashed)) { $record->password = hash_internal_user_password($this->password); } else { $record->password = $this->password; } $record->firstname = $this->firstname; $record->lastname = $this->lastname; $record->email = $this->email; $record->address = $this->address; $record->city = $this->city; $record->country = $this->country; $record->timemodified = time(); $record->lang = $this->language; update_record('user', $record); } else { return true; } } // avoid update loops if (isset($mu_loop_detect[$this->id])) { return $record->id; } $mu_loop_detect[$this->id] = true; // synchronize profile fields $origrec = clone $record; profile_load_data($origrec); $fields = field::get_for_context_level(context_level_base::get_custom_context_level('user', 'block_curr_admin')); $mfields = $CURMAN->db->get_records('user_info_field', '', '', '', 'shortname'); $fields = $fields ? $fields : array(); $changed = false; require_once CURMAN_DIRLOCATION . '/plugins/moodle_profile/custom_fields.php'; foreach ($fields as $field) { $field = new field($field); if (isset($field->owners['moodle_profile']) && $field->owners['moodle_profile']->exclude == cm_moodle_profile::sync_to_moodle && isset($mfields[$field->shortname])) { $shortname = $field->shortname; $fieldname = "field_{$shortname}"; $mfieldname = "profile_{$fieldname}"; $mfieldvalue = isset($origrec->{$mfieldname}) ? $origrec->{$mfieldname} : null; if (isset($this->{$fieldname}) && $mfieldvalue != $this->{$fieldname}) { $record->{$mfieldname} = $this->{$fieldname}; $changed = true; } } } profile_save_data(addslashes_recursive($record)); if ($muserid) { if ($changed) { events_trigger('user_updated', $record); } } else { events_trigger('user_created', $record); } unset($mu_loop_detect[$this->id]); return $record->id; } }
/** * Function to synchronize the curriculum data with the Moodle data. * * @param boolean $tomoodle Optional direction to synchronize the data. * @param boolean $strict_match Whether we should use the association table rather * than just check idnumbers when comparing to Moodle users * */ function synchronize_moodle_user($tomoodle = true, $createnew = false, $strict_match = true) { global $CFG; require_once $CFG->dirroot . '/admin/tool/uploaduser/locallib.php'; require_once elispm::lib('data/usermoodle.class.php'); require_once elis::lib('lib.php'); static $mu_loop_detect = array(); // Create a new Moodle user record to update with. if (!($muser = $this->get_moodleuser($strict_match)) && !$createnew) { return false; } $muserid = $muser ? $muser->id : false; if ($tomoodle) { // map PM user fields to Moodle user fields $mdlfieldmap = array('idnumber' => 'idnumber', 'username' => 'username', 'firstname' => 'firstname', 'lastname' => 'lastname', 'email' => 'email', 'address' => 'address', 'city' => 'city', 'country' => 'country', 'language' => 'lang'); // determine if the user is already noted as having been associated to a PM user if ($um = usermoodle::find(new field_filter('cuserid', $this->id))) { if ($um->valid()) { $um = $um->current(); // determine if the PM user idnumber was updated if ($um->idnumber != $this->idnumber) { // update the Moodle user with the new idnumber $muser = new stdClass(); $muser->id = $um->muserid; $muser->idnumber = $this->idnumber; $this->_db->update_record('user', $muser); // update the association table with the new idnumber $um->idnumber = $this->idnumber; $um->save(); } } } //try to update the idnumber of a matching Moodle user that //doesn't have an idnumber set yet $exists_params = array('username' => $this->username, 'mnethostid' => $CFG->mnet_localhost_id); if ($moodle_user = $this->_db->get_record('user', $exists_params)) { if (empty($moodle_user->idnumber)) { //potentially old data, so set the idnumber $moodle_user->idnumber = $this->idnumber; $this->_db->update_record('user', $moodle_user); $muserid = $moodle_user->id; } else { if ($this->idnumber != $moodle_user->idnumber) { //the username points to a pre-existing Moodle user //with a non-matching idnumber, so something horrible //happened return; } } } if ($createnew && !$muserid) { /// Add a new user $record = new stdClass(); foreach ($mdlfieldmap as $pmfield => $mdlfield) { if (isset($this->{$pmfield})) { $record->{$mdlfield} = $this->{$pmfield}; } } $record->password = $this->password === null ? '' : $this->password; $record->confirmed = 1; $record->mnethostid = $CFG->mnet_localhost_id; $record->timemodified = time(); $record->id = $this->_db->insert_record('user', $record); } else { if ($muserid) { /// Update an existing user $record = new stdClass(); $record->id = $muserid; foreach ($mdlfieldmap as $pmfield => $mdlfield) { if (isset($this->{$pmfield})) { $record->{$mdlfield} = $this->{$pmfield}; } } if (!empty($this->password)) { $record->password = $this->password; } $record->timemodified = time(); $this->_db->update_record('user', $record); } else { return true; } } // avoid update loops if (isset($mu_loop_detect[$this->id])) { return $record->id; } $mu_loop_detect[$this->id] = true; // synchronize profile fields $origrec = clone $record; profile_load_data($origrec); fix_moodle_profile_fields($origrec); $fields = field::get_for_context_level(CONTEXT_ELIS_USER); $mfields = $this->_db->get_records('user_info_field', array(), '', 'shortname'); $fields = $fields ? $fields : array(); $changed = false; require_once elis::plugin_file('elisfields_moodleprofile', 'custom_fields.php'); foreach ($fields as $field) { $field = new field($field); if (!moodle_profile_can_sync($field->shortname)) { continue; } if (isset($field->owners['moodle_profile']) && $field->owners['moodle_profile']->exclude == pm_moodle_profile::sync_to_moodle && isset($mfields[$field->shortname])) { $shortname = $field->shortname; $fieldname = "field_{$shortname}"; $mfieldname = "profile_{$fieldname}"; $mfieldvalue = isset($origrec->{$mfieldname}) ? $origrec->{$mfieldname} : null; if ($mfieldvalue != $this->{$fieldname}) { $record->{$mfieldname} = $this->{$fieldname}; $changed = true; sync_profile_field_settings_to_moodle($field); } } } $record = uu_pre_process_custom_profile_data($record); profile_save_data($record); if ($muserid) { if ($changed) { events_trigger('user_updated', $record); } } else { // if no user association record exists, create one $um = new usermoodle(); $um->cuserid = $this->id; $um->muserid = $record->id; $um->idnumber = $this->idnumber; $um->save(); events_trigger('user_created', $record); } unset($mu_loop_detect[$this->id]); return $record->id; } }
/** * 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) { if (empty($user['country'])) { //Allowing empty country leads to login issues. Let's not allow such updates continue; } user_update_user($user); //update user custom fields if (!empty($user['customfields'])) { foreach ($user['customfields'] as $customfield) { $user["profile_field_" . $customfield['type']] = $customfield['value']; //profile_save_data() saves profile file //it's expecting a user with the correct id, //and custom field to be named profile_field_"shortname" } profile_save_data((object) $user); events_trigger('user_updated', (object) $user); } //preferences if (!empty($user['preferences'])) { foreach ($user['preferences'] as $preference) { set_user_preference($preference['type'], $preference['value'], $user['id']); } } } $transaction->allow_commit(); return null; }
/** * Test badges observer when user_updated event is fired. */ public function test_badges_observer_profile_criteria_review() { global $CFG, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; // Add a custom field of textarea type. $customprofileid = $DB->insert_record('user_info_field', array('shortname' => 'newfield', 'name' => 'Description of new field', 'categoryid' => 1, 'datatype' => 'textarea')); $this->preventResetByRollback(); // Messaging is not compatible with transactions. $badge = new badge($this->coursebadge); $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY)); $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id)); $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address', 'field_aim' => 'aim', 'field_' . $customprofileid => $customprofileid)); // Assert the badge will not be issued to the user as is. $badge = new badge($this->coursebadge); $badge->review_all_criteria(); $this->assertFalse($badge->is_issued($this->user->id)); // Set the required fields and make sure the badge got issued. $this->user->address = 'Test address'; $this->user->aim = '999999999'; $sink = $this->redirectEmails(); profile_save_data((object) array('id' => $this->user->id, 'profile_field_newfield' => 'X')); user_update_user($this->user, false); $this->assertCount(1, $sink->get_messages()); $sink->close(); // Check if badge is awarded. $this->assertDebuggingCalled('Error baking badge image!'); $this->assertTrue($badge->is_issued($this->user->id)); }
/** * Sign up a new user ready for confirmation. * Password is passed in plaintext. * * @param object $user new user object * @param boolean $notify print notice with link and terminate * @return boolean success */ function user_signup($user, $notify = true) { global $CFG, $DB, $PAGE, $OUTPUT; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; if ($this->user_exists($user->username)) { print_error('auth_ldap_user_exists', 'auth_ldap'); } $plainslashedpassword = $user->password; unset($user->password); if (!$this->user_create($user, $plainslashedpassword)) { print_error('auth_ldap_create_error', 'auth_ldap'); } $user->id = user_create_user($user, false, false); user_add_password_history($user->id, $plainslashedpassword); // Save any custom profile field information profile_save_data($user); $this->update_user_record($user->username); // This will also update the stored hash to the latest algorithm // if the existing hash is using an out-of-date algorithm (or the // legacy md5 algorithm). update_internal_user_password($user, $plainslashedpassword); $user = $DB->get_record('user', array('id' => $user->id)); \core\event\user_created::create_from_userid($user->id)->trigger(); if (!send_confirmation_email($user)) { print_error('noemail', 'auth_ldap'); } if ($notify) { $emailconfirm = get_string('emailconfirm'); $PAGE->set_url('/auth/ldap/auth.php'); $PAGE->navbar->add($emailconfirm); $PAGE->set_title($emailconfirm); $PAGE->set_heading($emailconfirm); echo $OUTPUT->header(); notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php"); } else { return true; } }
$weakpasswords++; $upt->track('password', $strinvalidpasswordpolicy, 'warning'); } $forcechangepassword = true; } $user->password = hash_internal_user_password($user->password); } } else { $user->password = '******'; $upt->track('password', '-', 'normal', false); } // create user - insert_record ignores any extra properties $user->id = $DB->insert_record('user', $user); $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id' => $user->id)), s($user->username)), 'normal', false); // save custom profile fields data profile_save_data($user); if ($forcechangepassword) { set_user_preference('auth_forcepasswordchange', 1, $user); } if ($user->password === 'to be generated') { set_user_preference('create_password', 1, $user); } $upt->track('status', $struseradded); $upt->track('id', $user->id, 'normal', false); $usersnew++; // make sure user context exists get_context_instance(CONTEXT_USER, $user->id); events_trigger('user_created', $user); if ($bulk == UU_BULK_NEW or $bulk == UU_BULK_ALL) { if (!in_array($user->id, $SESSION->bulk_users)) { $SESSION->bulk_users[] = $user->id;
/** * 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); }
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 //TODO: move the functions somewhere else as //they are "user" related // Ensure the current user is allowed to run this function $context = get_context_instance(CONTEXT_SYSTEM); 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); //update user custom fields if(!empty($user['customfields'])) { foreach($user['customfields'] as $customfield) { $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file //it's expecting a user with the correct id, //and custom field to be named profile_field_"shortname" } profile_save_data((object) $user); } //preferences if (!empty($user['preferences'])) { foreach($user['preferences'] as $preference) { set_user_preference($preference['type'], $preference['value'],$user['id']); } } } $transaction->allow_commit(); return null; }
function create_joomdle_user_record($username, $password, $auth = 'joomdle') { global $CFG, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; // Just in case check text case. $username = trim(core_text::strtolower($username)); $authplugin = get_auth_plugin($auth); $customfields = $authplugin->get_custom_user_profile_fields(); $newuser = new stdClass(); if ($newinfo = $authplugin->get_userinfo($username)) { $newinfo = truncate_userinfo($newinfo); foreach ($newinfo as $key => $value) { if (in_array($key, $authplugin->userfields) || in_array($key, $customfields)) { $newuser->{$key} = $value; } } } if (!empty($newuser->email)) { if (email_is_not_allowed($newuser->email)) { unset($newuser->email); } } if (!isset($newuser->city)) { $newuser->city = ''; } $newuser->auth = $auth; $newuser->username = $username; // Fix for MDL-8480 // user CFG lang for user if $newuser->lang is empty // or $user->lang is not an installed language. if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) { $newuser->lang = $CFG->lang; } $newuser->confirmed = 1; $newuser->lastip = getremoteaddr(); $newuser->timecreated = time(); $newuser->timemodified = $newuser->timecreated; $newuser->mnethostid = $CFG->mnet_localhost_id; $newuser->id = user_create_user($newuser, false, false); // Save user profile data. profile_save_data($newuser); /* $user = get_complete_user_data('id', $newuser->id); if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) { set_user_preference('auth_forcepasswordchange', 1, $user); } // Set the password. update_internal_user_password($user, $password); */ // Trigger event. \core\event\user_created::create_from_userid($newuser->id)->trigger(); return $newuser; }
company::initialise_departments($companyid); $company->id = $companyid; // Set up a profiles field category for this company. $catdata = new object(); $catdata->sortorder = $DB->count_records('user_info_category') + 1; $catdata->name = $company->shortname; $DB->insert_record('user_info_category', $catdata, false); // Set up course category for company. $coursecat = new object(); $coursecat->name = $company->name; $coursecat->sortorder = 999; $coursecat->id = $DB->insert_record('course_categories', $coursecat); $coursecat->context = context_coursecat::instance($coursecat->id); $categorycontext = $coursecat->context; mark_context_dirty($coursecat->context->path); $DB->update_record('course_categories', $coursecat); fix_course_sortorder(); $companydetails = $DB->get_record('company', array('id' => $company->id)); $companydetails->category = $coursecat->id; $DB->update_record('company', $companydetails); } // Add user to default company department. $USER->profile_field_company = $company->shortname; profile_save_data($USER); $companydepartment = company::get_company_parentnode($company->id); company::assign_user_to_department($companydepartment->id, $USER->id); } if ($invoice->status == INVOICESTATUS_PAID) { processor::trigger_onordercomplete($invoice); } echo $OUTPUT->footer();
// Update preferences. useredit_update_user_preference($usernew); // 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))) {
/** * Create one or more users * * @param array $users An array of users to create. * @return array An array of arrays */ public static function create_users($users) { global $CFG, $DB; require_once $CFG->dirroot . "/lib/weblib.php"; require_once $CFG->dirroot . "/user/lib.php"; require_once $CFG->dirroot . "/user/profile/lib.php"; //required for customfields related function //TODO: move the functions somewhere else as //they are "user" related // Ensure the current user is allowed to run this function $context = get_context_instance(CONTEXT_SYSTEM); self::validate_context($context); require_capability('moodle/user:create', $context); // Do basic automatic PARAM checks on incoming data, using params description // If any problems are found then exceptions are thrown with helpful error messages $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users)); $availableauths = get_plugin_list('auth'); unset($availableauths['mnet']); // these would need mnethostid too unset($availableauths['webservice']); // we do not want new webservice users for now $availablethemes = get_plugin_list('theme'); $availablelangs = get_string_manager()->get_list_of_translations(); $transaction = $DB->start_delegated_transaction(); $userids = array(); foreach ($params['users'] as $user) { // Start of user info validation. // // Make sure that the username doesn't already exist if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) { $a = array('idnumber' => $user['idnumber'], 'username' => $user['username']); throw new moodle_exception('username_already_exists', 'local_sistemaaulaws', '', $a); } // Make sure auth is valid if (empty($availableauths[$user['auth']])) { $a = array('idnumber' => $user['idnumber'], 'username' => $user['username'], 'auth' => $user['auth']); throw new moodle_exception('invalid_authentication_type', 'local_sistemaaulaws', '', $a); } // Make sure lang is valid if (empty($availablelangs[$user['lang']])) { $a = new stdClass(); $a->idnumber = $user['idnumber']; $a->name = $user['username']; $a->lang = $user['lang']; $a->object = get_string('object_name_user', 'local_sistemaaulaws'); $a->object_text_name = get_string('object_text_name_user', 'local_sistemaaulaws'); throw new modle('invalid_language_code', 'local_sistemaaulaws', '', $a); } // Make sure lang is valid if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { //theme is VALUE_OPTIONAL, // so no default value. // We need to test if the client sent it // => !empty($user['theme']) $a = new stdClass(); $a->idnumber = $user['idnumber']; $a->name = $user['username']; $a->theme = $user['theme']; $a->object = get_string('object_name_user', 'local_sistemaaulaws'); $a->object_text_name = get_string('object_text_name_user', 'local_sistemaaulaws'); throw new modle_exception('invalid_theme', 'local_sistemaaulaws', '', $a); } if (!empty($user['email'])) { if (!validate_email($user['email'])) { $a = new stdClass(); $a->idnumber = $user['idnumber']; $a->name = $user['username']; $a->email = $user['email']; throw new moodle_exception('email_address_is_invalid', 'local_sistemaaulaws', $a); } else { if ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) { $a = new stdClass(); $a->idnumber = $user['idnumber']; $a->name = $user['username']; $a->email = $user['email']; throw new moodle_exception('email_address_already_exists', 'local_sistemaaulaws', $a); } } } // // End of user info validation. // CDCP: Achei válido deixar esta verificação em nossa função, // CDCP: é importante não perder nenhum dado. // CDCP: eles devem ser enviados no tamanho certo. // // make sure there is no data loss during truncation $truncated = truncate_userinfo($user); foreach ($truncated as $key => $value) { if ($truncated[$key] !== $user[$key]) { $a = array('idnumber' => $user['idnumber'], 'username', 'key' => $key, 'value' => $user[$key]); throw new moodle_exception('property_is_too_long', 'local_sistemaaulaws', '', $a); } } $user['confirmed'] = true; $user['mnethostid'] = $CFG->mnet_localhost_id; $user['id'] = user_create_user($user); // custom fields if (!empty($user['customfields'])) { foreach ($user['customfields'] as $customfield) { $user["profile_field_" . $customfield['type']] = $customfield['value']; //profile_save_data() saves profile file //it's expecting a user with the correct id, //and custom field to be named profile_field_"shortname" } profile_save_data((object) $user); } //preferences if (!empty($user['preferences'])) { foreach ($user['preferences'] as $preference) { set_user_preference($preference['type'], $preference['value'], $user['id']); } } $userids[] = array('id' => $user['id'], 'idnumber' => $user['idnumber'], 'username' => $user['username']); } $transaction->allow_commit(); return $userids; }