Skip to content

Commit

Permalink
MDL-51182 webservices: generate passwords and mail them to new users
Browse files Browse the repository at this point in the history
  • Loading branch information
danielneis committed Sep 18, 2015
1 parent d230899 commit e71a336
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions user/externallib.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ public static function create_users_parameters() {
'username' =>
new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.'),
'password' =>
new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL),
'createpassword' =>
new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
VALUE_OPTIONAL),
'firstname' =>
new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
'lastname' =>
Expand Down Expand Up @@ -149,6 +152,7 @@ public static function create_users($users) {
$transaction = $DB->start_delegated_transaction();

$userids = array();
$createpassword = false;
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))) {
Expand All @@ -173,6 +177,11 @@ public static function create_users($users) {
throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
}

// Make sure we have a password or have to create one.
if (empty($user['password']) && empty($user['createpassword'])) {
throw new invalid_parameter_exception('Invalid password: you must inform a password or set createpassword.');
}

$user['confirmed'] = true;
$user['mnethostid'] = $CFG->mnet_localhost_id;

Expand All @@ -185,8 +194,17 @@ public static function create_users($users) {
}
// End of user info validation.

$createpassword = !empty($user['createpassword']);
unset($user['createpassword']);
if ($createpassword) {
$user['password'] = '';
$updatepassword = false;
} else {
$updatepassword = true;
}

// Create the user data now!
$user['id'] = user_create_user($user, true, false);
$user['id'] = user_create_user($user, $updatepassword, false);

// Custom fields.
if (!empty($user['customfields'])) {
Expand All @@ -198,6 +216,13 @@ public static function create_users($users) {
profile_save_data((object) $user);
}

if ($createpassword) {
$userobject = (object)$user;
setnew_password_and_mail($userobject);
unset_user_preference('create_password', $userobject);
set_user_preference('auth_forcepasswordchange', 1, $userobject);
}

// Trigger event.
\core\event\user_created::create_from_userid($user['id'])->trigger();

Expand Down

0 comments on commit e71a336

Please sign in to comment.