Ejemplo n.º 1
0
 /**
  * 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;
     }
 }
Ejemplo n.º 2
0
 /**
  * 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;
     }
 }
Ejemplo n.º 3
0
 /**
  * Test user_update_user.
  */
 public function test_user_update_user()
 {
     global $DB;
     $this->resetAfterTest();
     // Create user and modify user profile.
     $user = $this->getDataGenerator()->create_user();
     $user->firstname = 'Test';
     $user->password = '******';
     // Update user and capture event.
     $sink = $this->redirectEvents();
     user_update_user($user);
     $events = $sink->get_events();
     $sink->close();
     $event = array_pop($events);
     // Test updated value.
     $dbuser = $DB->get_record('user', array('id' => $user->id));
     $this->assertSame($user->firstname, $dbuser->firstname);
     $this->assertNotSame('M00dLe@T', $dbuser->password);
     // Test event.
     $this->assertInstanceOf('\\core\\event\\user_updated', $event);
     $this->assertSame($user->id, $event->objectid);
     $this->assertSame('user_updated', $event->get_legacy_eventname());
     $this->assertEventLegacyData($dbuser, $event);
     $this->assertEquals(context_user::instance($user->id), $event->get_context());
     $expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id=' . $user->id, '');
     $this->assertEventLegacyLogData($expectedlogdata, $event);
     // Update user with no password update.
     $password = $user->password = hash_internal_user_password('M00dLe@T');
     user_update_user($user, false);
     $dbuser = $DB->get_record('user', array('id' => $user->id));
     $this->assertSame($password, $dbuser->password);
 }
Ejemplo n.º 4
0
 /**
  * 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;
     }
 }
/**
 * Update a user with a user object (will compare against the ID)
 * @param object $user - the user to update
 */
function user_update_user($user)
{
    global $DB;
    /// set the timecreate field to the current time
    if (!is_object($user)) {
        $user = (object) $user;
    }
    /// hash the password
    $user->password = hash_internal_user_password($user->password);
    $user->timemodified = time();
    $DB->update_record('user', $user);
}
 /**
  * Returns success or failure
  *
  * @return bool success or failure
  */
 public static function process_magento_request($order_number, $customer, $moodle_courses)
 {
     global $USER, $DB;
     if (get_config('magentoconnector', 'magentoconnectorenabled') == 0) {
         return false;
     }
     $params = self::validate_parameters(self::process_magento_request_parameters(), array('order_number' => $order_number, 'customer' => $customer, 'moodle_courses' => $moodle_courses));
     $context = context_user::instance($USER->id);
     self::validate_context($context);
     if (!($user = $DB->get_record('user', array('email' => $customer['email'])))) {
         $user = new stdClass();
         $user->firstname = $customer['firstname'];
         $user->lastname = $customer['lastname'];
         $user->email = $customer['email'];
         $user->city = $customer['city'];
         $user->country = $customer['country'];
         $user->confirmed = 1;
         $user->policyagreed = 1;
         $user->mnethostid = 1;
         $user->username = local_magentoconnector_generate_username($customer['firstname'], $customer['lastname']);
         $user->timecreated = time();
         $password = generate_password();
         $user->password = hash_internal_user_password($password);
         $userid = $DB->insert_record('user', $user);
     } else {
         $userid = $user->id;
     }
     $roleid = $DB->get_field('role', 'id', array('shortname' => LOCAL_MAGENTOCONNECTOR_STUDENT_SHORTNAME));
     $enrol = enrol_get_plugin('magento');
     foreach ($moodle_courses as $moodle_course) {
         if ($course = $DB->get_record('course', array('idnumber' => $moodle_course['course_id']))) {
             $enrolinstance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'magento'), '*', MUST_EXIST);
             $enrol->enrol_user($enrolinstance, $userid, $roleid);
             $record = new stdClass();
             $record->userid = $userid;
             $record->ordernum = $order_number;
             $record->courseid = $course->id;
             $record->timestamp = time();
             $DB->insert_record('local_magentoconnector_trans', $record);
         } else {
             // no such course ... ?
         }
     }
     if (isset($password)) {
         $enrolinstance->newusername = $user->username;
         $enrolinstance->newaccountpassword = $password;
     }
     $customer = $DB->get_record('user', array('id' => $userid));
     $enrol->email_welcome_message($enrolinstance, $customer);
     return true;
 }
Ejemplo n.º 7
0
function xmldb_local_lae_install()
{
    global $CFG, $DB;
    $dbman = $DB->get_manager();
    // Migrate the old config setting, if present.
    if (!empty($CFG->forum_anonymous)) {
        set_config('forum_enableanonymousposts', $CFG->forum_anonymous);
        set_config('forum_anonymous', null);
    }
    // Extend forum tables.
    $table = new xmldb_table('forum');
    $field = new xmldb_field('anonymous');
    $field->set_attributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'completionposts');
    if (!$dbman->field_exists($table, $field)) {
        $dbman->add_field($table, $field);
    }
    $table = new xmldb_table('forum_posts');
    $field = new xmldb_field('hiddenuserid');
    $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, 'mailnow');
    if (!$dbman->field_exists($table, $field)) {
        $dbman->add_field($table, $field);
    }
    // Add anonymous user.
    if (empty($CFG->anonymous_userid)) {
        $anon_user = new stdClass();
        $anon_user->username = '******';
        // The password needs strings.
        $anon_user->password = hash_internal_user_password(str_shuffle($anon_user->username) . (string) mt_rand());
        $anon_user->auth = 'nologin';
        $anon_user->firstname = get_string('auser_firstname', 'local_lae');
        $anon_user->lastname = get_string('auser_lastname', 'local_lae');
        $anon_user->mnethostid = $CFG->mnet_localhost_id;
        $anon_user->email = get_string('auser_email', 'local_lae');
        if ($result = $DB->insert_record('user', $anon_user)) {
            set_config('anonymous_userid', $result);
            context_user::instance($result);
        } else {
            print_error("Failed to create anonymous user");
            return false;
        }
    }
    // Update course table to support display defaults
    $table = new xmldb_table('course');
    $field = new xmldb_field('filedisplaydefault', XMLDB_TYPE_INTEGER, '2', null, null, null, null, null);
    if (!$dbman->field_exists($table, $field)) {
        $dbman->add_field($table, $field);
    }
    return true;
}
Ejemplo n.º 8
0
 /**
  * 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)
 {
     $user->password = hash_internal_user_password($user->password);
     if (!($user->id = insert_record('user', $user))) {
         print_error('auth_emailnoinsert', 'auth');
     }
     if (!send_confirmation_email($user)) {
         print_error('auth_emailnoemail', 'auth');
     }
     if ($notify) {
         global $CFG;
         $emailconfirm = get_string('emailconfirm');
         print_header($emailconfirm, $emailconfirm, $emailconfirm);
         notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
     } else {
         return true;
     }
 }
Ejemplo n.º 9
0
/**
 * @param int $oldversion the version we are upgrading from
 * @return bool result
 */
function xmldb_auth_manual_upgrade($oldversion)
{
    global $CFG, $DB, $OUTPUT;
    if ($oldversion < 2011022700) {
        // force creation of missing passwords
        $createpassword = hash_internal_user_password('');
        $rs = $DB->get_recordset('user', array('password' => $createpassword, 'auth' => 'manual'));
        foreach ($rs as $user) {
            if (validate_email($user->email)) {
                $DB->set_field('user', 'password', 'to be created', array('id' => $user->id));
                unset_user_preference('auth_forcepasswordchange', $user);
                set_user_preference('create_password', 1, $user);
            }
        }
        $rs->close();
        upgrade_plugin_savepoint(true, 2011022700, 'auth', 'manual');
    }
    return true;
}
Ejemplo n.º 10
0
 /**
  * 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');
}
Ejemplo n.º 12
0
 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['firstname'] = $user->firstname;
     $userinfo['lastname'] = $user->lastname;
     $userinfo['email'] = $user->email;
     $userinfo['block'] = 1;
     \core\event\user_created::create_from_userid($user->id)->trigger();
     if (!send_confirmation_email($user)) {
         print_error('auth_emailnoemail', 'auth');
     }
     if ($notify) {
         $emailconfirm = get_string('emailconfirm');
         $PAGE->set_url('/auth/joomdle/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;
     }
 }
Ejemplo n.º 13
0
 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;
     }
 }
Ejemplo n.º 14
0
 /**
  * Test function hash_internal_user_password().
  */
 public function test_hash_internal_user_password()
 {
     $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\\"', 'ĩńťėŕňăţĩōŋāĹ');
     // Check that some passwords that we convert to hashes can
     // be validated.
     foreach ($passwords as $password) {
         $hash = hash_internal_user_password($password);
         $fasthash = hash_internal_user_password($password, true);
         $user = new stdClass();
         $user->auth = 'manual';
         $user->password = $hash;
         $this->assertTrue(validate_internal_user_password($user, $password));
         // They should not be in md5 format.
         $this->assertFalse(password_is_legacy_hash($hash));
         // Check that cost factor in hash is correctly set.
         $this->assertRegExp('/\\$10\\$/', $hash);
         $this->assertRegExp('/\\$04\\$/', $fasthash);
     }
 }
Ejemplo n.º 15
0
 /**
  * Create a test user
  * @param array|stdClass $record
  * @param array $options
  * @return stdClass user record
  */
 public function create_user($record = null, array $options = null)
 {
     global $DB, $CFG;
     $this->usercounter++;
     $i = $this->usercounter;
     $record = (array) $record;
     if (!isset($record['auth'])) {
         $record['auth'] = 'manual';
     }
     if (!isset($record['firstname']) and !isset($record['lastname'])) {
         $country = rand(0, 5);
         $firstname = rand(0, 4);
         $lastname = rand(0, 4);
         $female = rand(0, 1);
         $record['firstname'] = $this->firstnames[$country * 10 + $firstname + $female * 5];
         $record['lastname'] = $this->lastnames[$country * 10 + $lastname + $female * 5];
     } else {
         if (!isset($record['firstname'])) {
             $record['firstname'] = 'Firstname' . $i;
         } else {
             if (!isset($record['lastname'])) {
                 $record['lastname'] = 'Lastname' . $i;
             }
         }
     }
     if (!isset($record['idnumber'])) {
         $record['idnumber'] = '';
     }
     if (!isset($record['mnethostid'])) {
         $record['mnethostid'] = $CFG->mnet_localhost_id;
     }
     if (!isset($record['username'])) {
         $record['username'] = '******' . $i;
         $j = 2;
         while ($DB->record_exists('user', array('username' => $record['username'], 'mnethostid' => $record['mnethostid']))) {
             $record['username'] = '******' . $i . '_' . $j;
             $j++;
         }
     }
     if (!isset($record['password'])) {
         $record['password'] = '******';
     }
     if (!isset($record['email'])) {
         $record['email'] = $record['username'] . '@example.com';
     }
     if (!isset($record['confirmed'])) {
         $record['confirmed'] = 1;
     }
     if (!isset($record['lang'])) {
         $record['lang'] = 'en';
     }
     if (!isset($record['maildisplay'])) {
         $record['maildisplay'] = 1;
     }
     if (!isset($record['deleted'])) {
         $record['deleted'] = 0;
     }
     $record['timecreated'] = time();
     $record['timemodified'] = $record['timecreated'];
     $record['lastip'] = '0.0.0.0';
     $record['password'] = hash_internal_user_password($record['password']);
     if ($record['deleted']) {
         $delname = $record['email'] . '.' . time();
         while ($DB->record_exists('user', array('username' => $delname))) {
             $delname++;
         }
         $record['idnumber'] = '';
         $record['email'] = md5($record['username']);
         $record['username'] = $delname;
         $record['picture'] = 0;
     }
     $userid = $DB->insert_record('user', $record);
     if (!$record['deleted']) {
         context_user::instance($userid);
     }
     return $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
 }
Ejemplo n.º 16
0
 $usernew->timemodified = time();
 $createpassword = false;
 if ($usernew->id == -1) {
     unset($usernew->id);
     $createpassword = !empty($usernew->createpassword);
     unset($usernew->createpassword);
     $usernew = file_postupdate_standard_editor($usernew, 'description', $editoroptions, null, 'user', 'profile', null);
     $usernew->mnethostid = $CFG->mnet_localhost_id;
     // Always local user.
     $usernew->confirmed = 1;
     $usernew->timecreated = time();
     if ($authplugin->is_internal()) {
         if ($createpassword or empty($usernew->newpassword)) {
             $usernew->password = '';
         } else {
             $usernew->password = hash_internal_user_password($usernew->newpassword);
         }
     } else {
         $usernew->password = AUTH_PASSWORD_NOT_CACHED;
     }
     $usernew->id = user_create_user($usernew, false, false);
     if (!$authplugin->is_internal() and $authplugin->can_change_password() and !empty($usernew->newpassword)) {
         if (!$authplugin->user_update_password($usernew, $usernew->newpassword)) {
             // Do not stop here, we need to finish user creation.
             debugging(get_string('cannotupdatepasswordonextauth', '', '', $usernew->auth), DEBUG_NONE);
         }
     }
     $usercreated = true;
 } else {
     $usernew = file_postupdate_standard_editor($usernew, 'description', $editoroptions, $usercontext, 'user', 'profile', 0);
     // Pass a true old $user here.
Ejemplo n.º 17
0
/**
 * Update password hash in user object (if necessary).
 *
 * The password is updated if:
 * 1. The password has changed (the hash of $user->password is different
 *    to the hash of $password).
 * 2. The existing hash is using an out-of-date algorithm (or the legacy
 *    md5 algorithm).
 *
 * Updating the password will modify the $user object and the database
 * record to use the current hashing algorithm.
 * It will remove Web Services user tokens too.
 *
 * @param stdClass $user User object (password property may be updated).
 * @param string $password Plain text password.
 * @param bool $fasthash If true, use a low cost factor when generating the hash
 *                       This is much faster to generate but makes the hash
 *                       less secure. It is used when lots of hashes need to
 *                       be generated quickly.
 * @return bool Always returns true.
 */
function update_internal_user_password($user, $password, $fasthash = false)
{
    global $CFG, $DB;
    // Figure out what the hashed password should be.
    if (!isset($user->auth)) {
        debugging('User record in update_internal_user_password() must include field auth', DEBUG_DEVELOPER);
        $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
    }
    $authplugin = get_auth_plugin($user->auth);
    if ($authplugin->prevent_local_passwords()) {
        $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
    } else {
        $hashedpassword = hash_internal_user_password($password, $fasthash);
    }
    $algorithmchanged = false;
    if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
        // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
        $passwordchanged = $user->password !== $hashedpassword;
    } else {
        if (isset($user->password)) {
            // If verification fails then it means the password has changed.
            $passwordchanged = !password_verify($password, $user->password);
            $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
        } else {
            // While creating new user, password in unset in $user object, to avoid
            // saving it with user_create()
            $passwordchanged = true;
        }
    }
    if ($passwordchanged || $algorithmchanged) {
        $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
        $user->password = $hashedpassword;
        // Trigger event.
        $user = $DB->get_record('user', array('id' => $user->id));
        \core\event\user_password_updated::create_from_user($user)->trigger();
        // Remove WS user tokens.
        if (!empty($CFG->passwordchangetokendeletion)) {
            require_once $CFG->dirroot . '/webservice/lib.php';
            webservice::delete_user_ws_tokens($user->id);
        }
    }
    return true;
}
Ejemplo n.º 18
0
 while (!feof($fp)) {
     $errors = '';
     $user = new object();
     // by default, use the local mnet id (this may be changed in the file)
     $user->mnethostid = $CFG->mnet_localhost_id;
     $line = explode($csv_delimiter, fgets($fp, LINE_MAX_SIZE));
     ++$linenum;
     // add fields to user object
     foreach ($line as $key => $value) {
         if ($value !== '') {
             $key = $headers[$key];
             //decode encoded commas
             $value = str_replace($csv_encode, $csv_delimiter, trim($value));
             // special fields: password and username
             if ($key == 'password' && !empty($value)) {
                 $user->{$key} = hash_internal_user_password($value);
             } else {
                 if ($key == 'username') {
                     $value = $textlib->strtolower(addslashes($value));
                     if (empty($CFG->extendedusernamechars)) {
                         $value = eregi_replace('[^(-\\.[:alnum:])]', '', $value);
                     }
                     @$newusernames[$value]++;
                     $user->{$key} = $value;
                 } else {
                     $user->{$key} = addslashes($value);
                 }
             }
         }
     }
     // add default values for remaining fields
Ejemplo n.º 19
0
/**
 * Update pssword hash in user object.
 *
 * @param object user
 * @param string plain text password
 * @param bool store changes also in db, default true
 * @return true if hash changed
 */
function update_internal_user_password(&$user, $password)
{
    global $CFG;
    $authplugin = get_auth_plugin($user->auth);
    if ($authplugin->prevent_local_passwords()) {
        $hashedpassword = '******';
    } else {
        $hashedpassword = hash_internal_user_password($password);
    }
    return set_field('user', 'password', $hashedpassword, 'id', $user->id);
}
Ejemplo n.º 20
0
/**
 * Sets specified user's password and send the new password to the user via email.
 *
 * @global object
 * @global object
 * @param user $user A {@link $USER} object
 * @return boolean|string Returns "true" if mail was sent OK and "false" if there was an error
 */
function setnew_password_and_mail($user)
{
    global $CFG, $DB;
    $site = get_site();
    $supportuser = generate_email_supportuser();
    $newpassword = generate_password();
    $DB->set_field('user', 'password', hash_internal_user_password($newpassword), array('id' => $user->id));
    $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 = get_string('newusernewpasswordtext', '', $a);
    $subject = format_string($site->fullname) . ': ' . get_string('newusernewpasswordsubj');
    //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);
}
/**
 * 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);
}
Ejemplo n.º 22
0
/**
 * Main post-install tasks to be executed after the BD schema is available
 *
 * This function is automatically executed after Moodle core DB has been
 * created at initial install. It's in charge of perform the initial tasks
 * not covered by the {@link install.xml} file, like create initial users,
 * roles, templates, moving stuff from other plugins...
 *
 * Note that the function is only invoked once, at install time, so if new tasks
 * are needed in the future, they will need to be added both here (for new sites)
 * and in the corresponding {@link upgrade.php} file (for existing sites).
 *
 * All plugins within Moodle (modules, blocks, reports...) support the existence of
 * their own install.php file, using the "Frankenstyle" component name as
 * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example:
 *     - {@link xmldb_page_install()}. (modules don't require the plugintype ("mod_") to be used.
 *     - {@link xmldb_enrol_meta_install()}.
 *     - {@link xmldb_workshopform_accumulative_install()}.
 *     - ....
 *
 * Finally, note that it's also supported to have one uninstall.php file that is
 * executed also once, each time one plugin is uninstalled (before the DB schema is
 * deleted). Those uninstall files will contain one function, using the "Frankenstyle"
 * naming conventions, like {@link xmldb_enrol_meta_uninstall()} or {@link xmldb_workshop_uninstall()}.
 */
function xmldb_main_install()
{
    global $CFG, $DB, $SITE, $OUTPUT;
    // Make sure system context exists
    $syscontext = context_system::instance(0, MUST_EXIST, false);
    if ($syscontext->id != SYSCONTEXTID) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new system context id!');
    }
    // Create site course
    if ($DB->record_exists('course', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create frontpage course, courses already exist.');
    }
    $newsite = new stdClass();
    $newsite->fullname = '';
    $newsite->shortname = '';
    $newsite->summary = NULL;
    $newsite->newsitems = 3;
    $newsite->numsections = 1;
    $newsite->category = 0;
    $newsite->format = 'site';
    // Only for this course
    $newsite->timecreated = time();
    $newsite->timemodified = $newsite->timecreated;
    if (defined('SITEID')) {
        $newsite->id = SITEID;
        $DB->import_record('course', $newsite);
        $DB->get_manager()->reset_sequence('course');
    } else {
        $newsite->id = $DB->insert_record('course', $newsite);
        define('SITEID', $newsite->id);
    }
    // set the field 'numsections'. We can not use format_site::update_format_options() because
    // the file is not loaded
    $DB->insert_record('course_format_options', array('courseid' => SITEID, 'format' => 'site', 'sectionid' => 0, 'name' => 'numsections', 'value' => $newsite->numsections));
    $SITE = get_site();
    if ($newsite->id != $SITE->id) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new site course id!');
    }
    // Make sure site course context exists
    context_course::instance($SITE->id);
    // Update the global frontpage cache
    $SITE = $DB->get_record('course', array('id' => $newsite->id), '*', MUST_EXIST);
    // Create default course category
    if ($DB->record_exists('course_categories', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default course category, categories already exist.');
    }
    $cat = new stdClass();
    $cat->name = get_string('miscellaneous');
    $cat->depth = 1;
    $cat->sortorder = MAX_COURSES_IN_CATEGORY;
    $cat->timemodified = time();
    $catid = $DB->insert_record('course_categories', $cat);
    $DB->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid));
    // Make sure category context exists
    context_coursecat::instance($catid);
    $defaults = array('rolesactive' => '0', 'auth' => 'email', 'auth_pop3mailbox' => 'INBOX', 'enrol_plugins_enabled' => 'manual,guest,self,cohort', 'theme' => theme_config::DEFAULT_THEME, 'filter_multilang_converted' => 1, 'siteidentifier' => random_string(32) . get_host_from_url($CFG->wwwroot), 'backup_version' => 2008111700, 'backup_release' => '2.0 dev', 'mnet_dispatcher_mode' => 'off', 'sessiontimeout' => 7200, 'stringfilters' => '', 'filterall' => 0, 'texteditors' => 'atto,tinymce,textarea', 'upgrade_minmaxgradestepignored' => 1, 'upgrade_extracreditweightsstepignored' => 1, 'upgrade_calculatedgradeitemsignored' => 1);
    foreach ($defaults as $key => $value) {
        set_config($key, $value);
    }
    // Bootstrap mnet
    $mnethost = new stdClass();
    $mnethost->wwwroot = $CFG->wwwroot;
    $mnethost->name = '';
    $mnethost->name = '';
    $mnethost->public_key = '';
    if (empty($_SERVER['SERVER_ADDR'])) {
        // SERVER_ADDR is only returned by Apache-like webservers
        preg_match("@^(?:http[s]?://)?([A-Z0-9\\-\\.]+).*@i", $CFG->wwwroot, $matches);
        $my_hostname = $matches[1];
        $my_ip = gethostbyname($my_hostname);
        // Returns unmodified hostname on failure. DOH!
        if ($my_ip == $my_hostname) {
            $mnethost->ip_address = 'UNKNOWN';
        } else {
            $mnethost->ip_address = $my_ip;
        }
    } else {
        $mnethost->ip_address = $_SERVER['SERVER_ADDR'];
    }
    $mnetid = $DB->insert_record('mnet_host', $mnethost);
    set_config('mnet_localhost_id', $mnetid);
    // Initial insert of mnet applications info
    $mnet_app = new stdClass();
    $mnet_app->name = 'moodle';
    $mnet_app->display_name = 'Moodle';
    $mnet_app->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/mnet/land.php';
    $mnet_app->sso_jump_url = '/auth/mnet/jump.php';
    $moodleapplicationid = $DB->insert_record('mnet_application', $mnet_app);
    $mnet_app = new stdClass();
    $mnet_app->name = 'mahara';
    $mnet_app->display_name = 'Mahara';
    $mnet_app->xmlrpc_server_url = '/api/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/xmlrpc/land.php';
    $mnet_app->sso_jump_url = '/auth/xmlrpc/jump.php';
    $DB->insert_record('mnet_application', $mnet_app);
    // Set up the probably-to-be-removed-soon 'All hosts' record
    $mnetallhosts = new stdClass();
    $mnetallhosts->wwwroot = '';
    $mnetallhosts->ip_address = '';
    $mnetallhosts->public_key = '';
    $mnetallhosts->public_key_expires = 0;
    $mnetallhosts->last_connect_time = 0;
    $mnetallhosts->last_log_id = 0;
    $mnetallhosts->deleted = 0;
    $mnetallhosts->name = 'All Hosts';
    $mnetallhosts->applicationid = $moodleapplicationid;
    $mnetallhosts->id = $DB->insert_record('mnet_host', $mnetallhosts, true);
    set_config('mnet_all_hosts_id', $mnetallhosts->id);
    // Create guest record - do not assign any role, guest user gets the default guest role automatically on the fly
    if ($DB->record_exists('user', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default users, users already exist.');
    }
    $guest = new stdClass();
    $guest->auth = 'manual';
    $guest->username = '******';
    $guest->password = hash_internal_user_password('guest');
    $guest->firstname = get_string('guestuser');
    $guest->lastname = ' ';
    $guest->email = 'root@localhost';
    $guest->description = get_string('guestuserinfo');
    $guest->mnethostid = $CFG->mnet_localhost_id;
    $guest->confirmed = 1;
    $guest->lang = $CFG->lang;
    $guest->timemodified = time();
    $guest->id = $DB->insert_record('user', $guest);
    if ($guest->id != 1) {
        echo $OUTPUT->notification('Unexpected id generated for the Guest account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    // Store guest id
    set_config('siteguest', $guest->id);
    // Make sure user context exists
    context_user::instance($guest->id);
    // Now create admin user
    $admin = new stdClass();
    $admin->auth = 'manual';
    $admin->firstname = get_string('admin');
    $admin->lastname = get_string('user');
    $admin->username = '******';
    $admin->password = '******';
    $admin->email = '';
    $admin->confirmed = 1;
    $admin->mnethostid = $CFG->mnet_localhost_id;
    $admin->lang = $CFG->lang;
    $admin->maildisplay = 1;
    $admin->timemodified = time();
    $admin->lastip = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr();
    // installation hijacking prevention
    $admin->id = $DB->insert_record('user', $admin);
    if ($admin->id != 2) {
        echo $OUTPUT->notification('Unexpected id generated for the Admin account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    if ($admin->id != $guest->id + 1) {
        echo $OUTPUT->notification('Nonconsecutive id generated for the Admin account. Your database configuration or clustering setup may not be fully supported.', 'notifyproblem');
    }
    // Store list of admins
    set_config('siteadmins', $admin->id);
    // Make sure user context exists
    context_user::instance($admin->id);
    // Install the roles system.
    $managerrole = create_role('', 'manager', '', 'manager');
    $coursecreatorrole = create_role('', 'coursecreator', '', 'coursecreator');
    $editteacherrole = create_role('', 'editingteacher', '', 'editingteacher');
    $noneditteacherrole = create_role('', 'teacher', '', 'teacher');
    $studentrole = create_role('', 'student', '', 'student');
    $guestrole = create_role('', 'guest', '', 'guest');
    $userrole = create_role('', 'user', '', 'user');
    $frontpagerole = create_role('', 'frontpage', '', 'frontpage');
    // Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
    update_capabilities('moodle');
    // Default allow role matrices.
    foreach ($DB->get_records('role') as $role) {
        foreach (array('assign', 'override', 'switch') as $type) {
            $function = 'allow_' . $type;
            $allows = get_default_role_archetype_allows($type, $role->archetype);
            foreach ($allows as $allowid) {
                $function($role->id, $allowid);
            }
        }
    }
    // Set up the context levels where you can assign each role.
    set_role_contextlevels($managerrole, get_default_contextlevels('manager'));
    set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator'));
    set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher'));
    set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher'));
    set_role_contextlevels($studentrole, get_default_contextlevels('student'));
    set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
    set_role_contextlevels($userrole, get_default_contextlevels('user'));
    // Init theme and JS revisions
    set_config('themerev', time());
    set_config('jsrev', time());
    // No admin setting for this any more, GD is now required, remove in Moodle 2.6.
    set_config('gdversion', 2);
    // Install licenses
    require_once $CFG->libdir . '/licenselib.php';
    license_manager::install_licenses();
    // Init profile pages defaults
    if ($DB->record_exists('my_pages', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default profile pages, records already exist.');
    }
    $mypage = new stdClass();
    $mypage->userid = NULL;
    $mypage->name = '__default';
    $mypage->private = 0;
    $mypage->sortorder = 0;
    $DB->insert_record('my_pages', $mypage);
    $mypage->private = 1;
    $DB->insert_record('my_pages', $mypage);
    // Set a sensible default sort order for the most-used question types.
    set_config('multichoice_sortorder', 1, 'question');
    set_config('truefalse_sortorder', 2, 'question');
    set_config('match_sortorder', 3, 'question');
    set_config('shortanswer_sortorder', 4, 'question');
    set_config('numerical_sortorder', 5, 'question');
    set_config('essay_sortorder', 6, 'question');
}
Ejemplo n.º 23
0
/**
 * Install Moodle DB,
 * config.php must exist, there must not be any tables in db yet.
 *
 * @param array $options adminpass is mandatory
 * @param bool $interactive
 * @return void
 */
function install_cli_database(array $options, $interactive)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/environmentlib.php';
    require_once $CFG->libdir . '/upgradelib.php';
    // show as much debug as possible
    @error_reporting(E_ALL | E_STRICT);
    @ini_set('display_errors', '1');
    $CFG->debug = E_ALL | E_STRICT;
    $CFG->debugdisplay = true;
    $CFG->version = '';
    $CFG->release = '';
    $CFG->branch = '';
    $version = null;
    $release = null;
    $branch = null;
    // read $version and $release
    require $CFG->dirroot . '/version.php';
    if ($DB->get_tables()) {
        cli_error(get_string('clitablesexist', 'install'));
    }
    if (empty($options['adminpass'])) {
        cli_error('Missing required admin password');
    }
    // test environment first
    list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
    if (!$envstatus) {
        $errors = environment_get_errors($environment_results);
        cli_heading(get_string('environment', 'admin'));
        foreach ($errors as $error) {
            list($info, $report) = $error;
            echo "!! {$info} !!\n{$report}\n\n";
        }
        exit(1);
    }
    if (!$DB->setup_is_unicodedb()) {
        if (!$DB->change_db_encoding()) {
            // If could not convert successfully, throw error, and prevent installation
            cli_error(get_string('unicoderequired', 'admin'));
        }
    }
    if ($interactive) {
        cli_separator();
        cli_heading(get_string('databasesetup'));
    }
    // install core
    install_core($version, true);
    set_config('release', $release);
    set_config('branch', $branch);
    if (PHPUNIT_TEST) {
        // mark as test database as soon as possible
        set_config('phpunittest', 'na');
    }
    // install all plugins types, local, etc.
    upgrade_noncore(true);
    // set up admin user password
    $DB->set_field('user', 'password', hash_internal_user_password($options['adminpass']), array('username' => 'admin'));
    // rename admin username if needed
    if (isset($options['adminuser']) and $options['adminuser'] !== 'admin' and $options['adminuser'] !== 'guest') {
        $DB->set_field('user', 'username', $options['adminuser'], array('username' => 'admin'));
    }
    // indicate that this site is fully configured
    set_config('rolesactive', 1);
    upgrade_finished();
    // log in as admin - we need do anything when applying defaults
    $admins = get_admins();
    $admin = reset($admins);
    session_set_user($admin);
    // apply all default settings, do it twice to fill all defaults - some settings depend on other setting
    admin_apply_default_settings(NULL, true);
    admin_apply_default_settings(NULL, true);
    set_config('registerauth', '');
    // set the site name
    if (isset($options['shortname']) and $options['shortname'] !== '') {
        $DB->set_field('course', 'shortname', $options['shortname'], array('format' => 'site'));
    }
    if (isset($options['fullname']) and $options['fullname'] !== '') {
        $DB->set_field('course', 'fullname', $options['fullname'], array('format' => 'site'));
    }
}
Ejemplo n.º 24
0
 // start table
 while ($line = $cir->next()) {
     $upt->flush();
     $linenum++;
     $upt->track('line', $linenum);
     $user = new object();
     // by default, use the local mnet id (this may be changed in the file)
     $user->mnethostid = $CFG->mnet_localhost_id;
     // add fields to user object
     foreach ($line as $key => $value) {
         if ($value !== '') {
             $key = $columns[$key];
             // password is special field
             if ($key == 'password') {
                 if ($value !== '') {
                     $user->password = hash_internal_user_password($value);
                     if (!empty($CFG->passwordpolicy) and !check_password_policy($value, $errmsg)) {
                         $forcechangepassword++;
                     }
                 }
             } else {
                 $user->{$key} = $value;
                 if (in_array($key, $upt->columns)) {
                     $upt->track($key, $value);
                 }
             }
         }
     }
     // get username, first/last name now - we need them in templates!!
     if ($optype == UU_UPDATE) {
         // when updating only username is required
Ejemplo n.º 25
0
/**
 * Sets specified user's password and send the new password to the user via email.
 *
 * @global object
 * @global object
 * @param user $user A {@link $USER} object
 * @return boolean|string Returns "true" if mail was sent OK and "false" if there was an error
 */
function setnew_password_and_mail($user)
{
    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 = generate_email_supportuser();
    $newpassword = generate_password();
    $DB->set_field('user', 'password', hash_internal_user_password($newpassword), array('id' => $user->id));
    $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);
}
Ejemplo n.º 26
0
 /**
  * Initialize a new user description object
  */
 protected function inituser()
 {
     global $CFG, $DB, $USER;
     $data = array('idnumber' => '__fcH__TESTID001__', 'username' => '__fcH__testuser1__', 'firstname' => 'Test', 'lastname' => 'User1', 'email' => '*****@*****.**', 'country' => 'us');
     $newuser = new user($data);
     $newuser->save();
     $this->tuserid = $newuser->id;
     $usernew = new stdClass();
     $usernew->username = '******';
     $usernew->idnumber = '__fcH__testuser__';
     $usernew->firstname = 'Test';
     $usernew->lastname = 'User';
     $usernew->email = '*****@*****.**';
     $usernew->confirmed = 1;
     $usernew->auth = 'manual';
     $usernew->mnethostid = $CFG->mnet_localhost_id;
     $usernew->confirmed = 1;
     $usernew->timecreated = time();
     $usernew->password = hash_internal_user_password('testpassword');
     $this->mdluserid = $DB->insert_record('user', $usernew);
     // Setup the global user to be this new test user we have created.
     $USER = $DB->get_record('user', array('id' => $this->mdluserid));
     $USER->access = get_user_accessdata($USER->id);
 }
Ejemplo n.º 27
0
 /**
  * Test function update_internal_user_password().
  */
 public function test_update_internal_user_password()
 {
     global $DB;
     $this->resetAfterTest();
     $passwords = array('password', '1234', 'changeme', '****');
     foreach ($passwords as $password) {
         $user = $this->getDataGenerator()->create_user(array('auth' => 'manual'));
         update_internal_user_password($user, $password);
         // The user object should have been updated.
         $this->assertTrue(validate_internal_user_password($user, $password));
         // The database field for the user should also have been updated to the
         // same value.
         $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
     }
     $user = $this->getDataGenerator()->create_user(array('auth' => 'manual'));
     // Manually set the user's password to the md5 of the string 'password'.
     $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
     // Update the password.
     update_internal_user_password($user, 'password');
     if (password_compat_not_supported()) {
         // If bcrypt not properly supported the password should remain as an md5 hash.
         $expected_hash = hash_internal_user_password('password', true);
         $this->assertSame($user->password, $expected_hash);
         $this->assertTrue(password_is_legacy_hash($user->password));
     } else {
         // Otherwise password should have been updated to a bcrypt hash.
         $this->assertFalse(password_is_legacy_hash($user->password));
     }
 }
Ejemplo n.º 28
0
/**
 * Creates an User with given information. Required fields are:
 * -username
 * -idnumber
 * -firstname
 * -lastname
 * -email
 *
 * And there's some interesting fields:
 * -password
 * -auth
 * -confirmed
 * -timezone
 * -country
 * -emailstop
 * -theme
 * -lang
 * -mailformat
 *
 * @param assoc array or object $user
 *
 * @return string or thrown exceptions
 */
function create_user($user)
{
    global $CFG, $DB;
    /// WS: convert user array into an user object
    if (is_array($user)) {
        $user = (object) $user;
    }
    /// check auth fields
    if (!isset($user->auth)) {
        $user->auth = 'manual';
    } else {
        /// check that the auth value exists
        $authplugin = get_directory_list($CFG->dirroot . "/auth", '', false, true, false);
        if (array_search($user->auth, $authplugin) === false) {
            throw new moodle_exception('authnotexisting');
        }
    }
    $required = array('username', 'firstname', 'lastname', 'email', 'password');
    foreach ($required as $req) {
        if (!isset($user->{$req})) {
            throw new moodle_exception('missingrequiredfield');
        }
    }
    $password = hash_internal_user_password($user->password);
    $record = create_user_record($user->username, $password, $user->auth);
    if ($record) {
        $user->id = $record->id;
        if ($DB->update_record('user', $user)) {
            return $record->id;
        } else {
            //we could not update properly the newly created user, we need to delete it
            $DB->delete_record('user', array('id' => $record->id));
            throw new moodle_exception('usernotcreated');
        }
    }
    throw new moodle_exception('usernotcreated');
}
Ejemplo n.º 29
0
             $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
             $upt->track('status', $strusernotaddederror, 'error');
             $userserrors++;
             continue;
         }
     } else {
         $errmsg = null;
         $weak = !check_password_policy($user->password, $errmsg);
         if ($resetpasswords == UU_PWRESET_ALL or $resetpasswords == UU_PWRESET_WEAK and $weak) {
             if ($weak) {
                 $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);
Ejemplo n.º 30
0
/**
 * Sets specified user's password and send the new password to the user via email.
 *
 * @uses $CFG
 * @param user $user A {@link $USER} object
 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
 *          was blocked by user and "false" if there was another sort of error.
 */
function setnew_password_and_mail($user)
{
    global $CFG;
    $site = get_site();
    $supportuser = generate_email_supportuser();
    $newpassword = generate_password();
    if (!set_field('user', 'password', hash_internal_user_password($newpassword), 'id', $user->id)) {
        trigger_error('Could not set user password!');
        return false;
    }
    $a = new object();
    $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 = get_string('newusernewpasswordtext', '', $a);
    $subject = format_string($site->fullname) . ': ' . get_string('newusernewpasswordsubj');
    return email_to_user($user, $supportuser, $subject, $message);
}