I'm trying to import some users into Drupal programmatically as blocked. I found two methods to do this: user_save and drupal_execute. However, the first one doesn't send notification email with the link to reset the password while the other method does send the mail, but when clicking the link I get a denied access.
I tried the code in 2 environments (Ubuntu and Windows) with one fresh installation. Here is the code I'm actually using:
// register a new user
$form_state['values']['name'] = 'username';
$form_state['values']['mail'] = '[email protected]';
// generate and assign password
$pass = user_password(8);
$form_state['values']['pass'] = array (
'pass1' => $pass,
'pass2' => $pass
);
$form_state['values']['status'] = 0; // add user as blocked
$form_state['values']['notify'] = 1; // send notification with reset link
$form_state['values']['op'] = t('Create new account');
// check if user it's not already imported
$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query($sql, $form_state['values']['name'] );
$data = db_result($result);
#print_r($data);
if (!$data) { // if the user does not exist, add it
drupal_execute('user_register', $form_state);
}
The user is added correctly in the database as blocked, I receive the notification email but when I click on the reset link I get access denied (which, by the way, it's appearing twice: all the elements of my theme twice with the error as content; really nasty bug... don't know why, anyone?)
Here goes the second code:
// user details
$users = array(
'name' => 'username',
'pass' => user_password(8),
'mail' => '[email protected]',
'access' => '0',
'status' => 0,
'notify' => 1,
'timezone' => 7200,
'init' => '[email protected]'
);
$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query( $sql, $users['name'] );
$data = db_result( $result );
#print_r($data);
if (!$data)
user_save( NULL, $users, NULL );
}
With this method, everything works fine but I don't get the email, which is pointless because the users are blocked.
I don't know if this is a hard question (only for Drupal gurus), but I would appreciate any help.
Thank you!