db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);
// Save user roles (delete just to be safe).
if (isset($array['roles']) && is_array($array['roles'])) {
db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
foreach (array_keys($array['roles']) as $rid) {
if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
}
}
}
// Build the finished user object.
$user = user_load(array('uid' => $array['uid']));
}
// Save distributed authentication mappings.
$authmaps = array();
foreach ($array as $key => $value) {
if (substr($key, 0, 4) == 'auth') {
$authmaps[$key] = $value;
}
}
if (sizeof($authmaps) > 0) {
user_set_authmaps($user, $authmaps);
}
return $user;
}
/**
* Verify the syntax of the given name.
*/
function user_validate_name($name) {
if (!strlen($name)) return t('You must enter a username.');
if (substr($name, 0, 1) == ' ') return t('The username cannot begin with a space.');
if (substr($name, -1) == ' ') return t('The username cannot end with a space.');
if (strpos($name, ' ') !== FALSE) return t('The username cannot contain multiple spaces in a row.');
if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.');
if (preg_match('/[\x{80}-\x{A0}'. // Non-printable ISO-8859-1 + NBSP
'\x{AD}'. // Soft-hyphen
'\x{2000}-\x{200F}'. // Various space characters
'\x{2028}-\x{202F}'. // Bidirectional text overrides
'\x{205F}-\x{206F}'. // Various text hinting characters
'\x{FEFF}'. // Byte order mark
'\x{FF01}-\x{FF60}'. // Full-width latin
'\x{FFF9}-\x{FFFD}'. // Replacement characters
'\x{0}]/u', // NULL byte
$name)) {
return t('The username contains an illegal character.');
}
if (strpos($name, '@') !== FALSE && !eregi('@([0-9a-z](-?[0-9a-z])*.)+[a-z]{2}([zmuvtg]|fo|me)?$', $name)) return t('The username is not a valid authentication ID.');
if (strlen($name) > USERNAME_MAX_LENGTH) return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}
function user_validate_mail($mail) {
if (!$mail) return t('You must enter an e-mail address.');
if (!valid_email_address($mail)) {
return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
}
}
function user_validate_picture(&$form, &$form_state) {
form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
}
}
}
/**
* Generate a random alphanumeric password.
*/
function user_password($length = 10) {
// This variable contains the list of allowable characters for the
// password. Note that the number 0 and the letter 'O' have been
// removed to avoid confusion between the two. The same is true
// Zero-based count of characters in the allowable list:
$len = strlen($allowable_characters) - 1;
// Declare the password as a blank string.
$pass = '';
// Loop the number of times specified by $length.
for ($i = 0; $i < $length; $i++) {
// Each iteration, pick a random character from the
// allowable string and append it to the password:
$pass .= $allowable_characters[mt_rand(0, $len)];
}
return $pass;
}
/**
* Determine whether the user has a given privilege.
*
* @param $string
* The permission, such as "administer nodes", being checked for.
* @param $account
* (optional) The account to check, if not given use currently logged in user.
* @param $reset
* (optional) Resets the user's permissions cache, which will result in a
* recalculation of the user's permissions. This is necessary to support
* dynamically added user roles.
*
* @return
* Boolean TRUE if the current user has the requested permission.
*
* All permission checks in Drupal should go through this function. This
* way, we guarantee consistent behavior, and ensure that the superuser
* can perform all actions.
*/
function user_access($string, $account = NULL, $reset = FALSE) {
global $user;
static $perm = array();
if ($reset) {
unset($perm);
}
if (is_null($account)) {
$account = $user;
}
// User #1 has all privileges:
if ($account->uid == 1) {
return TRUE;
}
// To reduce the number of SQL queries, we cache the user's permissions
// in a static variable.
if (!isset($perm[$account->uid])) {
$result = db_query("SELECT p.perm FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (". db_placeholders($account->roles) .")", array_keys($account->roles));
$perms = array();
while ($row = db_fetch_object($result)) {
$perms += array_flip(explode(', ', $row->perm));
}
$perm[$account->uid] = $perms;
}
return isset($perm[$account->uid][$string]);
}
/**
* Checks for usernames blocked by user administration.
*
* @return boolean TRUE for blocked users, FALSE for active.
*/
function user_is_blocked($name) {
$deny = db_fetch_object(db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name));
return $deny;
}
function user_fields() {
static $fields;
if (!$fields) {
$result = db_query('SELECT * FROM {users} WHERE uid = 1');
if ($field = db_fetch_array($result)) {
$fields = array_keys($field);
}
else {
// Make sure we return the default fields at least.
if ($skip_access_check || user_access('access user profiles')) {
return t('Users');
}
case 'search':
if (user_access('access user profiles')) {
$find = array();
// Replace wildcards with MySQL/PostgreSQL wildcards.
$keys = preg_replace('!\*+!', '%', $keys);
if (user_access('administer users')) {
// Administrators can also search in the otherwise private email field.
$result = pager_query("SELECT name, uid, mail FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%') OR LOWER(mail) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys, $keys);
$form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
$form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));
// Retrieve a list of new users who have subsequently accessed the site successfully.
$result = db_query_range('SELECT uid, name FROM {users} WHERE status != 0 AND access != 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5));
// Perform database queries to gather online user lists. We use s.timestamp
// rather than u.access because it is much faster.
$anonymous_count = sess_count($interval);
$authenticated_users = db_query('SELECT DISTINCT u.uid, u.name, s.timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
* A FAPI validate handler. Sets an error if supplied username has been blocked
* or denied access.
*/
function user_login_name_validate($form, &$form_state) {
if (isset($form_state['values']['name'])) {
if (user_is_blocked($form_state['values']['name'])) {
// blocked in user administration
form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
}
else if (drupal_is_denied('user', $form_state['values']['name'])) {
// denied by access controls
form_set_error('name', t('The name %name is a reserved username.', array('%name' => $form_state['values']['name'])));
}
}
}
/**
* A validate handler on the login form. Check supplied username/password
* against local users table. If successful, sets the global $user object.
*/
function user_login_authenticate_validate($form, &$form_state) {
user_authenticate($form_state['values']);
}
/**
* A validate handler on the login form. Should be the last validator. Sets an
* error if user has not been authenticated yet.
*/
function user_login_final_validate($form, &$form_state) {
global $user;
if (!$user->uid) {
form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
}
}
/**
* Try to log in the user locally.
*
* @param $form_values
* Form values with at least 'name' and 'pass' keys, as well as anything else
* which should be passed along to hook_user op 'login'.
*
* @return
* A $user object, if successful.
*/
function user_authenticate($form_values = array()) {
global $user;
// Name and pass keys are required.
if (!empty($form_values['name']) && !empty($form_values['pass']) &&
'#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
$form['picture']['picture_delete'] = array('#type' => 'checkbox', '#title' => t('Delete picture'), '#description' => t('Check this box to delete your current picture.'));
if ($admin_setting = variable_get('user_mail_'. $key, FALSE)) {
// An admin setting overrides the default string.
return strtr($admin_setting, $variables);
}
else {
// No override, return default string.
switch ($key) {
case 'register_no_approval_required_subject':
return t('Account details for !username at !site', $variables, $langcode);
case 'register_no_approval_required_body':
return t("!username,\n\nThank you for registering at !site. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n-- !site team", $variables, $langcode);
case 'register_admin_created_subject':
return t('An administrator created an account for you at !site', $variables, $langcode);
case 'register_admin_created_body':
return t("!username,\n\nA site administrator at !site has created an account for you. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n-- !site team", $variables, $langcode);
case 'register_pending_approval_subject':
case 'pending_approval_admin_subject':
return t('Account details for !username at !site (pending admin approval)', $variables, $langcode);
case 'register_pending_approval_body':
return t("!username,\n\nThank you for registering at !site. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.\n\n\n-- !site team", $variables, $langcode);
case 'register_pending_approval_admin_body':
return t("!username has applied for an account.\n\n!edit_uri", $variables, $langcode);
case 'password_reset_subject':
return t('Replacement login information for !username at !site', $variables, $langcode);
case 'password_reset_body':
return t("!username,\n\nA request to reset the password for your account has been made at !site.\n\nYou may now log in to !uri_brief by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once. It expires after one day and nothing will happen if it's not used.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.", $variables, $langcode);
case 'status_activated_subject':
return t('Account details for !username at !site (approved)', $variables, $langcode);
case 'status_activated_body':
return t("!username,\n\nYour account at !site has been activated.\n\nYou may now log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\nOnce you have set your own password, you will be able to log in to !login_uri in the future using:\n\nusername: !username\n", $variables, $langcode);
case 'status_blocked_subject':
return t('Account details for !username at !site (blocked)', $variables, $langcode);
case 'status_blocked_body':
return t("!username,\n\nYour account on !site has been blocked.", $variables, $langcode);
case 'status_deleted_subject':
return t('Account details for !username at !site (deleted)', $variables, $langcode);
case 'status_deleted_body':
return t("!username,\n\nYour account on !site has been deleted.", $variables, $langcode);
}
}
}
/*** Administrative features ***********************************************/
/**
* Retrieve an array of roles matching specified conditions.
*
* @param $membersonly
* Set this to TRUE to exclude the 'anonymous' role.
* @param $permission
* A string containing a permission. If set, only roles containing that
* permission are returned.
*
* @return
* An associative array with the role id as the key and the role name as
* value.
*/
function user_roles($membersonly = FALSE, $permission = NULL) {
// System roles take the first two positions.
$roles = array(
DRUPAL_ANONYMOUS_RID => NULL,
DRUPAL_AUTHENTICATED_RID => NULL,
);
if (!empty($permission)) {
$result = db_query("SELECT r.* FROM {role} r INNER JOIN {permission} p ON r.rid = p.rid WHERE p.perm LIKE '%%%s%%' ORDER BY r.name", $permission);
}
else {
$result = db_query('SELECT * FROM {role} ORDER BY name');
}
while ($role = db_fetch_object($result)) {
switch ($role->rid) {
// We only translate the built in role names
case DRUPAL_ANONYMOUS_RID:
if (!$membersonly) {
$roles[$role->rid] = t($role->name);
}
break;
case DRUPAL_AUTHENTICATED_RID:
$roles[$role->rid] = t($role->name);
break;
default:
$roles[$role->rid] = $role->name;
}
}
// Filter to remove unmatched system roles.
return array_filter($roles);
}
/**
* Implementation of hook_user_operations().
*/
function user_user_operations($form_state = array()) {
t('Are you sure you want to delete these users?'),
'admin/user/user', t('This action cannot be undone.'),
t('Delete all'), t('Cancel'));
}
function user_multiple_delete_confirm_submit($form, &$form_state) {
if ($form_state['values']['confirm']) {
foreach ($form_state['values']['accounts'] as $uid => $value) {
user_delete($form_state['values'], $uid);
}
drupal_set_message(t('The users have been deleted.'));
}
$form_state['redirect'] = 'admin/user/user';
return;
}
/**
* Implementation of hook_help().
*/
function user_help($path, $arg) {
global $user;
switch ($path) {
case 'admin/help#user':
$output = '<p>'. t('The user module allows users to register, login, and log out. Users benefit from being able to sign on because it associates content they create with their account and allows various permissions to be set for their roles. The user module supports user roles which establish fine grained permissions allowing each role to do only what the administrator wants them to. Each user is assigned to one or more roles. By default there are two roles <em>anonymous</em> - a user who has not logged in, and <em>authenticated</em> a user who has signed up and who has been authorized.') .'</p>';
$output .= '<p>'. t("Users can use their own name or handle and can specify personal configuration settings through their individual <em>My account</em> page. Users must authenticate by supplying a local username and password or through their OpenID, an optional and secure method for logging into many websites with a single username and password. In some configurations, users may authenticate using a username and password from another Drupal site, or through some other site-specific mechanism.") .'</p>';
$output .= '<p>'. t('A visitor accessing your website is assigned a unique ID, or session ID, which is stored in a cookie. The cookie does not contain personal information, but acts as a key to retrieve information from your site. Users should have cookies enabled in their web browser when using your site.') .'</p>';
$output .= '<p>'. t('For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/handbook/modules/user/')) .'</p>';
return $output;
case 'admin/user/user':
return '<p>'. t('Drupal allows users to register, login, log out, maintain user profiles, etc. Users of the site may not use their own names to post content until they have signed up for a user account.') .'</p>';
case 'admin/user/user/create':
case 'admin/user/user/account/create':
return '<p>'. t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") .'</p>';
case 'admin/user/rules':
return '<p>'. t('Set up username and e-mail address access rules for new <em>and</em> existing accounts (currently logged in accounts will not be logged out). If a username or e-mail address for an account matches any deny rule, but not an allow rule, then the account will not be allowed to be created or to log in. A host rule is effective for every page view, not just registrations.') .'</p>';
case 'admin/user/permissions':
return '<p>'. t('Permissions let you control what users can do on your site. Each user role (defined on the <a href="@role">user roles page</a>) has its own set of permissions. For example, you could give users classified as "Administrators" permission to "administer nodes" but deny this power to ordinary, "authenticated" users. You can use permissions to reveal new features to privileged users (those with subscriptions, for example). Permissions also allow trusted users to share the administrative burden of running a busy site.', array('@role' => url('admin/user/roles'))) .'</p>';
case 'admin/user/roles':
return t('<p>Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined in <a href="@permissions">user permissions</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the <em>role names</em> of the various roles. To delete a role choose "edit".</p><p>By default, Drupal comes with two user roles:</p>
<ul>
<li>Anonymous user: this role is used for users that don\'t have a user account or that are not authenticated.</li>
<li>Authenticated user: this role is automatically granted to all logged in users.</li>
return '<p>'. t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') .'</p>';
}
}
/**
* Retrieve a list of all user setting/information categories and sort them by weight.
*/
function _user_categories($account) {
$categories = array();
foreach (module_list() as $module) {
if ($data = module_invoke($module, 'user', 'categories', NULL, $account, '')) {
'tooShort' => t('It is recommended to choose a password that contains at least six characters. It should include numbers, punctuation, and both upper and lowercase letters.'),
'needsMoreVariation' => t('The password does not include enough variation to be secure. Try:'),
'addLetters' => t('Adding both upper and lowercase letters.'),
'addNumbers' => t('Adding numbers.'),
'addPunctuation' => t('Adding punctuation.'),
'sameAsUsername' => t('It is recommended to choose a password different from the username.'),
// Add plain text password into user account to generate mail tokens.
$account->password = $pass;
if ($admin && !$notify) {
drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
}
else if (!variable_get('user_email_verification', TRUE) && $account->status && !$admin) {
// No e-mail verification is required, create new user account, and login
drupal_set_message(t('Password and further instructions have been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
}
else {
drupal_set_message(t('Your password and further instructions have been sent to your e-mail address.'));
$form_state['redirect'] = '';
return;
}
}
else {
// Create new user account, administrator approval required.
drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your e-mail address.'));
$form_state['redirect'] = '';
return;
}
}
}
/**
* Form builder; The user registration form.
*
* @ingroup forms
* @see user_register_validate()
* @see user_register_submit()
*/
function user_register() {
global $user;
$admin = user_access('administer users');
// If we aren't admin but already logged on, go to the user page instead.