' . t('About') . ''; $output .= '
' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles (used to classify users) and permissions associated with those roles. For more information, see the online handbook entry for User module.', array('@user' => 'http://drupal.org/handbook/modules/user')) . '
'; $output .= '' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '
'; case 'admin/config/people/permissions': return '' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the Roles page to create a role). Two important roles to consider are Authenticated Users and Administrators. Any permissions granted to the Authenticated Users role will be given to any user who can log into your site. You can make any role the Administrator role for the site, meaning this will be granted all new permissions automatically. You can do this on the User Settings page. You should be careful to ensure that only trusted users are given this access and level of control of your site.', array('@role' => url('admin/config/people/roles'), '@settings' => url('admin/config/people/accounts'))) . '
'; case 'admin/config/people/roles': $output = '' . t('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 user permissions. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the role names of the various roles. To delete a role choose "edit".', array('@permissions' => url('admin/config/people/permissions'))) . '
'; $output .= ''. t('By default, Drupal comes with two user roles:') . '
'; $output .= '' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '
'; case 'admin/config/people/accounts/display': return '' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '
'; case 'admin/people/search': return '' . 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".') . '
'; } } /** * Invokes hook_user() in every module. * * We cannot use module_invoke() for this, because the arguments need to * be passed by reference. */ function user_module_invoke($type, &$edit, $account, $category = NULL) { foreach (module_implements('user_' . $type) as $module) { $function = $module . '_user_' . $type; $function($edit, $account, $category); } } /** * Implements hook_theme(). */ function user_theme() { return array( 'user_picture' => array( 'variables' => array('account' => NULL), 'template' => 'user-picture', ), 'user_profile' => array( 'render element' => 'elements', 'template' => 'user-profile', 'file' => 'user.pages.inc', ), 'user_profile_category' => array( 'render element' => 'element', 'template' => 'user-profile-category', 'file' => 'user.pages.inc', ), 'user_profile_item' => array( 'render element' => 'element', 'template' => 'user-profile-item', 'file' => 'user.pages.inc', ), 'user_list' => array( 'variables' => array('users' => NULL, 'title' => NULL), ), 'user_admin_permissions' => array( 'render element' => 'form', 'file' => 'user.admin.inc', ), 'user_admin_new_role' => array( 'render element' => 'form', 'file' => 'user.admin.inc', ), 'user_filters' => array( 'render element' => 'form', 'file' => 'user.admin.inc', ), 'user_signature' => array( 'variables' => array('signature' => NULL), ), ); } /** * Implements hook_entity_info(). */ function user_entity_info() { $return = array( 'user' => array( 'label' => t('User'), 'controller class' => 'UserController', 'base table' => 'users', 'fieldable' => TRUE, 'object keys' => array( 'id' => 'uid', ), 'bundles' => array( 'user' => array( 'label' => t('User'), 'admin' => array( 'path' => 'admin/config/people/accounts', 'access arguments' => array('administer users'), ), ), ), 'view modes' => array( 'full' => array( 'label' => t('User account'), ), ), ), ); return $return; } /** * Implements hook_field_extra_fields(). */ function user_field_extra_fields() { $return['user']['user'] = array( 'account' => array( 'label' => 'User name and password', 'description' => t('User module account form elements'), 'weight' => -10, ), 'timezone' => array( 'label' => 'Timezone', 'description' => t('User module timezone form element.'), 'weight' => 6, ), 'summary' => array( 'label' => 'History', 'description' => t('User module history view element.'), 'weight' => 5, ), ); return $return; } function user_external_load($authname) { $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField(); if ($uid) { return user_load($uid); } else { return FALSE; } } /** * Load multiple users based on certain conditions. * * This function should be used whenever you need to load more than one user * from the database. Users are loaded into memory and will not require * database access if loaded again during the same page request. * * @param $uids * An array of user IDs. * @param $conditions * An array of conditions to match against the {users} table. These * should be supplied in the form array('field_name' => 'field_value'). * @param $reset * A boolean indicating that the internal cache should be reset. Use this if * loading a user object which has been altered during the page request. * @return * An array of user objects, indexed by uid. * * @see entity_load() * @see user_load() * @see user_load_by_mail() * @see user_load_by_name() */ function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) { return entity_load('user', $uids, $conditions, $reset); } /** * Controller class for users. * * This extends the DrupalDefaultEntityController class, adding required * special handling for user objects. */ class UserController extends DrupalDefaultEntityController { function attachLoad(&$queried_users) { // Build an array of user picture IDs so that these can be fetched later. $picture_fids = array(); foreach ($queried_users as $key => $record) { $picture_fids[] = $record->picture; $queried_users[$key] = drupal_unpack($record); $queried_users[$key]->roles = array(); if ($record->uid) { $queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; } else { $queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user'; } } // Add any additional roles from the database. $result = db_query('SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids)', array(':uids' => array_keys($queried_users))); foreach ($result as $record) { $queried_users[$record->uid]->roles[$record->rid] = $record->name; } // Add the full file objects for user pictures if enabled. if (!empty($picture_fids) && variable_get('user_pictures', 1) == 1) { $pictures = file_load_multiple($picture_fids); foreach ($queried_users as $account) { if (!empty($account->picture) && isset($pictures[$account->picture])) { $account->picture = $pictures[$account->picture]; } else { $account->picture = NULL; } } } // Call the default attachLoad() method. This will add fields and call // hook_user_load(). parent::attachLoad($queried_users); } } /** * Fetch a user object. * * @param $uid * Integer specifying the user id. * @param $reset * A boolean indicating that the internal cache should be reset. * @return * A fully-loaded $user object upon successful user load or FALSE if user * cannot be loaded. * * @see user_load_multiple() */ function user_load($uid, $reset = FALSE) { $users = user_load_multiple(array($uid), array(), $reset); return reset($users); } /** * Fetch a user object by email address. * * @param $mail * String with the account's e-mail address. * @return * A fully-loaded $user object upon successful user load or FALSE if user * cannot be loaded. * * @see user_load_multiple() */ function user_load_by_mail($mail) { $users = user_load_multiple(array(), array('mail' => $mail)); return reset($users); } /** * Fetch a user object by account name. * * @param $name * String with the account's user name. * @return * A fully-loaded $user object upon successful user load or FALSE if user * cannot be loaded. * * @see user_load_multiple() */ function user_load_by_name($name) { $users = user_load_multiple(array(), array('name' => $name)); return reset($users); } /** * Save changes to a user account or add a new user. * * @param $account * (optional) The user object to modify or add. If you want to modify * an existing user account, you will need to ensure that (a) $account * is an object, and (b) you have set $account->uid to the numeric * user ID of the user account you wish to modify. If you * want to create a new user account, you can set $account->is_new to * TRUE or omit the $account->uid field. * @param $edit * An array of fields and values to save. For example array('name' * => 'My name'). Keys that do not belong to columns in the user-related * tables are added to the a serialized array in the 'data' column * and will be loaded in the $user->data array by user_load(). * Setting a field to NULL deletes it from the data column, if you are * modifying an existing user account. * @param $category * (optional) The category for storing profile information in. * * @return * A fully-loaded $user object upon successful save or FALSE if the save failed. */ function user_save($account, $edit = array(), $category = 'account') { $transaction = db_transaction(); try { $table = drupal_get_schema('users'); $user_fields = $table['fields']; if (!empty($edit['pass'])) { // Allow alternate password hashing schemes. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc'); $edit['pass'] = user_hash_password(trim($edit['pass'])); // Abort if the hashing failed and returned FALSE. if (!$edit['pass']) { return FALSE; } } else { // Avoid overwriting an existing password with a blank password. unset($edit['pass']); } // Get the fields form so we can recognize the fields in the $edit // form that should not go into the serialized data array. $field_form = array(); $field_form_state = array(); $edit = (object) $edit; field_attach_form('user', $edit, $field_form, $field_form_state); // Presave fields. field_attach_presave('user', $edit); $edit = (array) $edit; if (!isset($account->is_new)) { $account->is_new = empty($account->uid); } user_module_invoke('presave', $edit, $account, $category); if (is_object($account) && !$account->is_new) { $data = unserialize(db_query('SELECT data FROM {users} WHERE uid = :uid', array(':uid' => $account->uid))->fetchField()); // Consider users edited by an administrator as logged in, if they haven't // already, so anonymous users can view the profile (if allowed). if (empty($edit['access']) && empty($account->access) && user_access('administer users')) { $edit['access'] = REQUEST_TIME; } foreach ($edit as $key => $value) { // Form fields that don't pertain to the users, user_roles, or // Field API are automatically serialized into the users.data // column. if (!in_array($key, array('roles', 'is_new')) && empty($user_fields[$key]) && empty($field_form[$key])) { if ($value === NULL) { unset($data[$key]); } else { $data[$key] = $value; } } } // Process picture uploads. if (!empty($edit['picture']->fid)) { $picture = $edit['picture']; // If the picture is a temporary file move it to its final location and // make it permanent. if (($picture->status & FILE_STATUS_PERMANENT) == 0) { $info = image_get_info($picture->uri); $picture_directory = variable_get('file_default_scheme', 'public') . '://' . variable_get('user_picture_path', 'pictures'); // Prepare the pictures directory. file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY); $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '.' . $info['extension']); if ($picture = file_move($picture, $destination, FILE_EXISTS_REPLACE)) { $picture->status |= FILE_STATUS_PERMANENT; $edit['picture'] = file_save($picture); } } } $edit['picture'] = empty($edit['picture']->fid) ? 0 : $edit['picture']->fid; $edit['data'] = $data; // Do not allow 'uid' to be changed. $edit['uid'] = $account->uid; // Save changes to the user table. $success = drupal_write_record('users', $edit, 'uid'); if ($success === FALSE) { // The query failed - better to abort the save than risk further // data loss. return FALSE; } // If the picture changed or was unset, remove the old one. This step needs // to occur after updating the {users} record so that user_file_references() // doesn't report it in use and block the deletion. if (!empty($account->picture->fid) && ($edit['picture'] != $account->picture->fid)) { file_delete($account->picture); } // Reload user roles if provided. if (isset($edit['roles']) && is_array($edit['roles'])) { db_delete('users_roles') ->condition('uid', $account->uid) ->execute(); $query = db_insert('users_roles')->fields(array('uid', 'rid')); foreach (array_keys($edit['roles']) as $rid) { if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $query->values(array( 'uid' => $account->uid, 'rid' => $rid, )); } } $query->execute(); } // Delete a blocked user's sessions to kick them if they are online. if (isset($edit['status']) && $edit['status'] == 0) { drupal_session_destroy_uid($account->uid); } // If the password changed, delete all open sessions and recreate // the current one. if (!empty($edit['pass'])) { drupal_session_destroy_uid($account->uid); if ($account->uid == $GLOBALS['user']->uid) { drupal_session_regenerate(); } } // Save Field data. $object = (object) $edit; field_attach_update('user', $object); // Refresh user object. $user = user_load($account->uid, TRUE); // Send emails after we have the new user object. if (isset($edit['status']) && $edit['status'] != $account->status) { // The user's status is changing; conditionally send notification email. $op = $edit['status'] == 1 ? 'status_activated' : 'status_blocked'; _user_mail_notify($op, $user); } user_module_invoke('update', $edit, $user, $category); } else { // Allow 'uid' to be set by the caller. There is no danger of writing an // existing user as drupal_write_record will do an INSERT. if (empty($edit['uid'])) { $edit['uid'] = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField()); } // Allow 'created' to be set by the caller. if (!isset($edit['created'])) { $edit['created'] = REQUEST_TIME; } // Consider users created by an administrator as already logged in, so // anonymous users can view the profile (if allowed). if (empty($edit['access']) && user_access('administer users')) { $edit['access'] = REQUEST_TIME; } $edit['mail'] = trim($edit['mail']); $success = drupal_write_record('users', $edit); if ($success === FALSE) { // On a failed INSERT some other existing user's uid may be returned. // We must abort to avoid overwriting their account. return FALSE; } // Build the initial user object. $user = user_load($edit['uid'], TRUE); $object = (object) $edit; field_attach_insert('user', $object); user_module_invoke('insert', $edit, $user, $category); // Note, we wait with saving the data column to prevent module-handled // fields from being saved there. $data = array(); foreach ($edit as $key => $value) { // Form fields that don't pertain to the users, user_roles, or // Field API are automatically serialized into the user.data // column. if ((!in_array($key, array('roles', 'is_new'))) && (empty($user_fields[$key]) && empty($field_form[$key])) && ($value !== NULL)) { $data[$key] = $value; } } if (!empty($data)) { $data_array = array('uid' => $user->uid, 'data' => $data); drupal_write_record('users', $data_array, 'uid'); } // Save user roles (delete just to be safe). if (isset($edit['roles']) && is_array($edit['roles'])) { db_delete('users_roles') ->condition('uid', $edit['uid']) ->execute(); $query = db_insert('users_roles')->fields(array('uid', 'rid')); foreach (array_keys($edit['roles']) as $rid) { if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $query->values(array( 'uid' => $edit['uid'], 'rid' => $rid, )); } } $query->execute(); } // Build the finished user object. $user = user_load($edit['uid'], TRUE); } return $user; } catch (Exception $e) { $transaction->rollback('user', $e->getMessage(), array(), WATCHDOG_ERROR); } } /** * Verify the syntax of the given name. */ function user_validate_name($name) { if (!$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 (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $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}-\x{1F}]/u', // NULL byte and control characters $name)) { return t('The username contains an illegal character.'); } if (drupal_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) { $mail = trim($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) { // If required, validate the uploaded picture. $validators = array( 'file_validate_is_image' => array(), 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')), 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024), ); // Save the file as a temporary file. $file = file_save_upload('picture_upload', $validators); if ($file === FALSE) { 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')))); } elseif ($file !== NULL) { $form_state['values']['picture_upload'] = $file; } } /** * 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 // of 'I', 1, and 'l'. $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // 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 the permissions for one or more roles. * * @param $roles * An array whose keys are the role IDs of interest, such as $user->roles. * * @return * An array indexed by role ID. Each value is an array whose keys are the * permission strings for the given role ID. */ function user_role_permissions($roles = array()) { $cache = &drupal_static(__FUNCTION__, array()); $role_permissions = $fetch = array(); if ($roles) { foreach ($roles as $rid => $name) { if (isset($cache[$rid])) { $role_permissions[$rid] = $cache[$rid]; } else { // Add this rid to the list of those needing to be fetched. $fetch[] = $rid; // Prepare in case no permissions are returned. $cache[$rid] = array(); } } if ($fetch) { // Get from the database permissions that were not in the static variable. // Only role IDs with at least one permission assigned will return rows. $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch)); foreach ($result as $row) { $cache[$row->rid][$row->permission] = TRUE; } foreach ($fetch as $rid) { // For every rid, we know we at least assigned an empty array. $role_permissions[$rid] = $cache[$rid]; } } } return $role_permissions; } /** * 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. * * @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) { global $user; if (!isset($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. // Use the advanced drupal_static() pattern, since this is called very often. static $drupal_static_fast; if (!isset($drupal_static_fast)) { $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__); } $perm = &$drupal_static_fast['perm']; if (!isset($perm[$account->uid])) { $role_permissions = user_role_permissions($account->roles); $perms = array(); foreach ($role_permissions as $one_role) { $perms += $one_role; } $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_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER(:name)", array(':name' => $name))->fetchObject(); return $deny; } /** * Implements hook_permission(). */ function user_permission() { return array( 'administer permissions' => array( 'title' => t('Administer permissions'), 'description' => drupal_placeholder(array('text' => t('Warning: Give to trusted roles only; this permission has security implications.'))), ), 'administer users' => array( 'title' => t('Administer users'), 'description' => drupal_placeholder(array('text' => t('Warning: Give to trusted roles only; this permission has security implications.'))), ), 'access user profiles' => array( 'title' => t('View user profiles'), ), 'change own username' => array( 'title' => t('Change own username'), ), 'cancel account' => array( 'title' => t('Cancel own user account'), 'description' => t('Note: content may be kept, unpublished, deleted or transfered to the %anonymous-name user depending on the configured user settings.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')), '@user-settings-url' => url('admin/config/people/accounts'))), ), 'select account cancellation method' => array( 'title' => t('Select method for cancelling own account'), 'description' => drupal_placeholder(array('text' => t('Warning: Give to trusted roles only; this permission has security implications.'))), ), ); } /** * Implements hook_file_download(). * * Ensure that user pictures (avatars) are always downloadable. */ function user_file_download($uri) { if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) { $info = image_get_info($uri); return array('Content-Type' => $info['mime_type']); } } /** * Implements hook_file_references(). */ function user_file_references($file) { // Determine if the file is used by this module. $file_used = (bool) db_query_range('SELECT 1 FROM {users} WHERE picture = :fid', 0, 1, array(':fid' => $file->fid))->fetchField(); if ($file_used) { // Return the name of the module and how many references it has to the file. return array('user' => $count); } } /** * Implements hook_file_delete(). */ function user_file_delete($file) { // Remove any references to the file. db_update('users') ->fields(array('picture' => 0)) ->condition('picture', $file->fid) ->execute(); } /** * Implements hook_search_info(). */ function user_search_info() { return array( 'title' => 'Users', ); } /** * Implements hook_search_access(). */ function user_search_access() { return user_access('access user profiles'); } /** * Implements hook_search_execute(). */ function user_search_execute($keys = NULL) { $find = array(); // Replace wildcards with MySQL/PostgreSQL wildcards. $keys = preg_replace('!\*+!', '%', $keys); $query = db_select('users')->extend('PagerDefault'); $query->fields('users', array('name', 'uid', 'mail')); if (user_access('administer users')) { // Administrators can also search in the otherwise private email field. $query->condition(db_or()-> where('LOWER(name) LIKE LOWER(:name)', array(':name' => "%$keys%"))-> where('LOWER(mail) LIKE LOWER(:mail)', array(':mail' => "%$keys%"))); } else { $query->where('LOWER(name) LIKE LOWER(:name)', array(':name' => "%$keys%")); } $result = $query ->limit(15) ->execute(); foreach ($result as $account) { $find[] = array('title' => $account->name . ' (' . $account->mail . ')', 'link' => url('user/' . $account->uid, array('absolute' => TRUE))); } return $find; } /** * Implements hook_element_info(). */ function user_element_info() { $types['user_profile_category'] = array( '#theme_wrappers' => array('user_profile_category'), ); $types['user_profile_item'] = array( '#theme' => 'user_profile_item', ); return $types; } /** * Implements hook_user_view(). */ function user_user_view($account) { $account->content['user_picture'] = array( '#markup' => theme('user_picture', array('account' => $account)), '#weight' => -10, ); if (!isset($account->content['summary'])) { $account->content['summary'] = array(); } $account->content['summary'] += array( '#type' => 'user_profile_category', '#attributes' => array('class' => array('user-member')), '#weight' => 5, '#title' => t('History'), ); $account->content['summary']['member_for'] = array( '#type' => 'user_profile_item', '#title' => t('Member for'), '#markup' => format_interval(REQUEST_TIME - $account->created), ); } /** * Helper function to add default user account fields to user registration and edit form. */ function user_account_form(&$form, &$form_state) { global $user; $account = $form['#user']; $register = ($form['#user']->uid > 0 ? FALSE : TRUE); $admin = user_access('administer users'); $form['#validate'][] = 'user_account_form_validate'; // Account information. $form['account'] = array( '#type' => 'fieldset', '#title' => t('Account information'), '#weight' => -10, ); // Only show name field on registration form or user can change own username. $form['account']['name'] = array( '#type' => 'textfield', '#title' => t('Username'), '#maxlength' => USERNAME_MAX_LENGTH, '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'), '#required' => TRUE, '#attributes' => array('class' => array('username')), '#default_value' => (!$register ? $account->name : ''), '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin), ); $form['account']['mail'] = array( '#type' => 'textfield', '#title' => t('E-mail address'), '#maxlength' => EMAIL_MAX_LENGTH, '#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.'), '#required' => TRUE, '#default_value' => (!$register ? $account->mail : ''), ); // Display password field only for existing users or when user is allowed to // assign a password during registration. if (!$register) { $form['account']['pass'] = array( '#type' => 'password_confirm', '#size' => 25, '#description' => t('To change the current user password, enter the new password in both fields.'), ); } elseif (!variable_get('user_email_verification', TRUE) || $admin) { $form['account']['pass'] = array( '#type' => 'password_confirm', '#size' => 25, '#description' => t('Provide a password for the new account in both fields.'), '#required' => TRUE, ); } if ($admin) { $status = (isset($account->status) ? $account->status : 1); } else { $status = (variable_get('user_register', 1) == 1); } $form['account']['status'] = array( '#type' => 'radios', '#title' => t('Status'), '#default_value' => $status, '#options' => array(t('Blocked'), t('Active')), '#access' => $admin, ); $roles = user_roles(TRUE); // The disabled checkbox subelement for the 'authenticated user' role // must be generated separately and added to the checkboxes element, // because of a limitation in Form API not supporting a single disabled // checkbox within a set of checkboxes. // @todo This should be solved more elegantly. See issue #119038. $checkbox_authenticated = array( '#type' => 'checkbox', '#title' => $roles[DRUPAL_AUTHENTICATED_RID], '#default_value' => TRUE, '#disabled' => TRUE, ); unset($roles[DRUPAL_AUTHENTICATED_RID]); $form['account']['roles'] = array( '#type' => 'checkboxes', '#title' => t('Roles'), '#default_value' => (!$register && isset($account->roles) ? array_keys($account->roles) : array()), '#options' => $roles, '#access' => $roles && user_access('administer permissions'), DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated, ); $form['account']['notify'] = array( '#type' => 'checkbox', '#title' => t('Notify user of new account'), '#access' => $register && $admin, ); // Signature. $form['signature_settings'] = array( '#type' => 'fieldset', '#title' => t('Signature settings'), '#weight' => 1, '#access' => (!$register && variable_get('user_signatures', 0)), ); $form['signature_settings']['signature'] = array( '#type' => 'textarea', '#title' => t('Signature'), '#default_value' => isset($account->signature) ? $account->signature : '', '#description' => t('Your signature will be publicly displayed at the end of your comments.'), ); // Picture/avatar. $form['picture'] = array( '#type' => 'fieldset', '#title' => t('Picture'), '#weight' => 1, '#access' => (!$register && variable_get('user_pictures', 0)), ); $form['picture']['picture'] = array( '#type' => 'value', '#value' => isset($account->picture) ? $account->picture : NULL, ); $form['picture']['picture_current'] = array( '#markup' => theme('user_picture', array('account' => $account)), ); $form['picture']['picture_delete'] = array( '#type' => 'checkbox', '#title' => t('Delete picture'), '#access' => !empty($account->picture->fid), '#description' => t('Check this box to delete your current picture.'), ); $form['picture']['picture_upload'] = array( '#type' => 'file', '#title' => t('Upload picture'), '#size' => 48, '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions pixels and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'), '%size' => variable_get('user_picture_file_size', '30'))) . ' ' . variable_get('user_picture_guidelines', ''), ); $form['#validate'][] = 'user_validate_picture'; } /** * Form validation handler for user_account_form(). */ function user_account_form_validate($form, &$form_state) { if ($form['#user_category'] == 'account' || $form['#user_category'] == 'register') { $account = $form['#user']; // Validate new or changing username. if (isset($form_state['values']['name'])) { if ($error = user_validate_name($form_state['values']['name'])) { form_set_error('name', $error); } elseif ((bool) db_query_range("SELECT 1 FROM {users} WHERE uid <> :uid AND LOWER(name) = LOWER(:name)", 0, 1, array(':uid' => $account->uid, ':name' => $form_state['values']['name']))->fetchField()) { form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name']))); } } // Validate the e-mail address, and check if it is taken by an existing user. if ($error = user_validate_mail($form_state['values']['mail'])) { form_set_error('mail', $error); } elseif ((bool) db_query_range("SELECT 1 FROM {users} WHERE uid <> :uid AND LOWER(mail) = LOWER(:mail)", 0, 1, array(':uid' => $account->uid, ':mail' => $form_state['values']['mail']))->fetchField()) { // Format error message dependent on whether the user is logged in or not. if ($GLOBALS['user']->uid) { form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $form_state['values']['mail']))); } else { form_set_error('mail', t('The e-mail address %email is already registered. Have you forgotten your password?', array('%email' => $form_state['values']['mail'], '@password' => url('user/password')))); } } // Make sure the signature isn't longer than the size of the database field. // Signatures are disabled by default, so make sure it exists first. if (isset($form_state['values']['signature'])) { $user_schema = drupal_get_schema('users'); if (drupal_strlen($form_state['values']['signature']) > $user_schema['fields']['signature']['length']) { form_set_error('signature', t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length']))); } } } } /** * Implements hook_user_presave(). */ function user_user_presave(&$edit, $account, $category) { if ($category == 'account' || $category == 'register') { if (!empty($edit['picture_upload'])) { $edit['picture'] = $edit['picture_upload']; } // Delete picture if requested, and if no replacement picture was given. elseif (!empty($edit['picture_delete'])) { $edit['picture'] = NULL; } // Remove these values so they don't end up serialized in the data field. $edit['picture_upload'] = NULL; $edit['picture_delete'] = NULL; // Prepare user roles. if (isset($edit['roles'])) { $edit['roles'] = array_filter($edit['roles']); } } } /** * Implements hook_user_categories(). */ function user_user_categories() { return array(array( 'name' => 'account', 'title' => t('Account settings'), 'weight' => 1, )); } function user_login_block($form) { $form['#action'] = url($_GET['q'], array('query' => drupal_get_destination())); $form['#id'] = 'user-login-form'; $form['#validate'] = user_login_default_validators(); $form['#submit'][] = 'user_login_submit'; $form['name'] = array('#type' => 'textfield', '#title' => t('Username'), '#maxlength' => USERNAME_MAX_LENGTH, '#size' => 15, '#required' => TRUE, ); $form['pass'] = array('#type' => 'password', '#title' => t('Password'), '#maxlength' => 60, '#size' => 15, '#required' => TRUE, ); $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), ); $items = array(); if (variable_get('user_register', 1)) { $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.')))); } $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.')))); $form['links'] = array('#markup' => theme('item_list', array('items' => $items))); return $form; } /** * Implements hook_block_info(). */ function user_block_info() { global $user; $blocks['login']['info'] = t('User login'); // Not worth caching. $blocks['login']['cache'] = DRUPAL_NO_CACHE; $blocks['new']['info'] = t('Who\'s new'); // Too dynamic to cache. $blocks['online']['info'] = t('Who\'s online'); $blocks['online']['cache'] = DRUPAL_NO_CACHE; return $blocks; } /** * Implements hook_block_configure(). */ function user_block_configure($delta = '') { global $user; switch ($delta) { case 'new': $form['user_block_whois_new_count'] = array( '#type' => 'select', '#title' => t('Number of users to display'), '#default_value' => variable_get('user_block_whois_new_count', 5), '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), ); return $form; case 'online': $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval'); $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.')); return $form; } } /** * Implements hook_block_save(). */ function user_block_save($delta = '', $edit = array()) { global $user; switch ($delta) { case 'new': variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']); break; case 'online': variable_set('user_block_seconds_online', $edit['user_block_seconds_online']); variable_set('user_block_max_list_count', $edit['user_block_max_list_count']); break; } } /** * Implements hook_block_view(). */ function user_block_view($delta = '') { global $user; $block = array(); switch ($delta) { case 'login': // For usability's sake, avoid showing two login forms on one page. if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) { $block['subject'] = t('User login'); $block['content'] = drupal_get_form('user_login_block'); } return $block; case 'new': if (user_access('access content')) { // Retrieve a list of new users who have subsequently accessed the site successfully. $items = 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))->fetchAll(); $output = theme('user_list', array('users' => $items)); $block['subject'] = t('Who\'s new'); $block['content'] = $output; } return $block; case 'online': if (user_access('access content')) { // Count users active within the defined period. $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900); // Perform database queries to gather online user lists. We use s.timestamp // rather than u.access because it is much faster. $authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField(); $output = format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.'); // Display a list of currently online users. $max_users = variable_get('user_block_max_list_count', 10); if ($authenticated_count && $max_users) { $items = db_query_range('SELECT u.uid, u.name, MAX(s.timestamp) AS max_timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= :interval AND s.uid > 0 GROUP BY u.uid, u.name ORDER BY max_timestamp DESC', 0, $max_users, array(':interval' => $interval))->fetchAll(); $output .= theme('user_list', array('users' => $items)); } $block['subject'] = t('Who\'s online'); $block['content'] = $output; } return $block; } } /** * Process variables for user-picture.tpl.php. * * The $variables array contains the following arguments: * - $account: A user, node or comment object with 'name', 'uid' and 'picture' * fields. * * @see user-picture.tpl.php */ function template_preprocess_user_picture(&$variables) { $variables['user_picture'] = ''; if (variable_get('user_pictures', 0)) { $account = $variables['account']; if (!empty($account->picture)) { // @TODO: Ideally this function would only be passed file objects, but // since there's a lot of legacy code that JOINs the {users} table to // {node} or {comments} and passes the results into this function if we // a numeric value in the picture field we'll assume it's a file id // and load it for them. Once we've got user_load_multiple() and // comment_load_multiple() functions the user module will be able to load // the picture files in mass during the object's load process. if (is_numeric($account->picture)) { $account->picture = file_load($account->picture); } if (!empty($account->picture->uri)) { $filepath = $account->picture->uri; } } elseif (variable_get('user_picture_default', '')) { $filepath = variable_get('user_picture_default', ''); } if (isset($filepath)) { $alt = t("@user's picture", array('@user' => format_username($account))); if (module_exists('image') && $style = variable_get('user_picture_style', '')) { $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt, 'attributes' => array(), 'getsize' => FALSE)); } else { $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt, 'attributes' => array(), 'getsize' => FALSE)); } if (!empty($account->uid) && user_access('access user profiles')) { $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE); $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes); } } } } /** * Make a list of users. * * @param $variables * An associative array containing: * - users: An array with user objects. Should contain at least the name and * uid. * - title: (optional) Title to pass on to theme_item_list(). * * @ingroup themeable */ function theme_user_list($variables) { $users = $variables['users']; $title = $variables['title']; if (!empty($users)) { foreach ($users as $user) { $items[] = theme('username', array('account' => $user)); } } return theme('item_list', array('items' => $items, 'title' => $title)); } function user_is_anonymous() { // Menu administrators can see items for anonymous when administering. return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']); } function user_is_logged_in() { return (bool)$GLOBALS['user']->uid; } function user_register_access() { return user_is_anonymous() && variable_get('user_register', 1); } function user_view_access($account) { return $account && $account->uid && ( // Always let users view their own profile. ($GLOBALS['user']->uid == $account->uid) || // Administrators can view all accounts. user_access('administer users') || // The user is not blocked and logged in at least once. ($account->access && $account->status && user_access('access user profiles')) ); } /** * Access callback for user account editing. */ function user_edit_access($account) { return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0; } /** * Menu access callback; limit access to account cancellation pages. * * Limit access to users with the 'cancel account' permission or administrative * users, and prevent the anonymous user from cancelling the account. */ function user_cancel_access($account) { return ((($GLOBALS['user']->uid == $account->uid) && user_access('cancel account')) || user_access('administer users')) && $account->uid > 0; } function user_load_self($arg) { $arg[1] = user_load($GLOBALS['user']->uid); return $arg; } /** * Implements hook_menu(). */ function user_menu() { $items['user/autocomplete'] = array( 'title' => 'User autocomplete', 'page callback' => 'user_autocomplete', 'access callback' => 'user_access', 'access arguments' => array('access user profiles'), 'type' => MENU_CALLBACK, 'file' => 'user.pages.inc', ); // Registration and login pages. $items['user'] = array( 'title' => 'User account', 'page callback' => 'user_page', 'access callback' => TRUE, 'type' => MENU_CALLBACK, 'file' => 'user.pages.inc', ); $items['user/login'] = array( 'title' => 'Log in', 'access callback' => 'user_is_anonymous', 'type' => MENU_DEFAULT_LOCAL_TASK, ); $items['user/register'] = array( 'title' => 'Create new account', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_register_form'), 'access callback' => 'user_register_access', 'type' => MENU_LOCAL_TASK, ); $items['user/password'] = array( 'title' => 'Request new password', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_pass'), 'access callback' => 'user_is_anonymous', 'type' => MENU_LOCAL_TASK, 'file' => 'user.pages.inc', ); $items['user/reset/%/%/%'] = array( 'title' => 'Reset password', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_pass_reset', 2, 3, 4), 'access callback' => TRUE, 'type' => MENU_CALLBACK, 'file' => 'user.pages.inc', ); $items['user/logout'] = array( 'title' => 'Log out', 'access callback' => 'user_is_logged_in', 'page callback' => 'user_logout', 'weight' => 10, 'menu_name' => 'user-menu', 'file' => 'user.pages.inc', ); // User listing pages. $items['admin/people'] = array( 'title' => 'People', 'page callback' => 'user_admin', 'page arguments' => array('list'), 'access arguments' => array('administer users'), 'position' => 'left', 'weight' => -4, 'file' => 'user.admin.inc', ); $items['admin/people/people'] = array( 'title' => 'List', 'description' => 'Find and manage people interacting with your site.', 'access arguments' => array('administer users'), 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10, 'file' => 'user.admin.inc', ); $items['admin/people/create'] = array( 'title' => 'Add user', 'page arguments' => array('create'), 'access arguments' => array('administer users'), 'type' => MENU_LOCAL_ACTION, ); // Administration pages. $items['admin/config/people'] = array( 'title' => 'People and permissions', 'description' => 'Configure user accounts, roles and permissions.', 'position' => 'right', 'page callback' => 'system_admin_menu_block_page', 'access arguments' => array('access administration pages'), 'file' => 'system.admin.inc', 'file path' => drupal_get_path('module', 'system'), ); $items['admin/config/people/accounts'] = array( 'title' => 'Account settings', 'description' => 'Configure default behavior of users, including registration requirements, e-mails, and user pictures.', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_admin_settings'), 'access arguments' => array('administer users'), 'file' => 'user.admin.inc', 'weight' => -10, ); $items['admin/config/people/accounts/settings'] = array( 'title' => 'Settings', 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10, ); // Permission administration pages. $items['admin/config/people/roles'] = array( 'title' => 'Roles', 'description' => 'List, edit, or add user roles.', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_admin_new_role'), 'access arguments' => array('administer permissions'), 'file' => 'user.admin.inc', 'weight' => -9, ); $items['admin/config/people/roles/edit'] = array( 'title' => 'Edit role', 'page arguments' => array('user_admin_role'), 'access arguments' => array('administer permissions'), 'type' => MENU_CALLBACK, ); $items['admin/config/people/permissions'] = array( 'title' => 'Permissions', 'description' => 'Determine access to features by selecting permissions for roles.', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_admin_permissions'), 'access arguments' => array('administer permissions'), 'file' => 'user.admin.inc', 'weight' => -8, ); $items['user/%user_uid_optional'] = array( 'title' => 'My account', 'title callback' => 'user_page_title', 'title arguments' => array(1), 'page callback' => 'user_view', 'page arguments' => array(1), 'access callback' => 'user_view_access', 'access arguments' => array(1), 'weight' => -10, 'menu_name' => 'user-menu', 'file' => 'user.pages.inc', ); $items['user/%user/view'] = array( 'title' => 'View', 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10, ); $items['user/%user/cancel'] = array( 'title' => 'Cancel account', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_cancel_confirm_form', 1), 'access callback' => 'user_cancel_access', 'access arguments' => array(1), 'type' => MENU_CALLBACK, 'file' => 'user.pages.inc', ); $items['user/%user/cancel/confirm/%/%'] = array( 'title' => 'Confirm account cancellation', 'page callback' => 'user_cancel_confirm', 'page arguments' => array(1, 4, 5), 'access callback' => 'user_cancel_access', 'access arguments' => array(1), 'type' => MENU_CALLBACK, 'file' => 'user.pages.inc', ); $items['user/%user/edit'] = array( 'title' => 'Edit', 'page callback' => 'drupal_get_form', 'page arguments' => array('user_profile_form', 1), 'access callback' => 'user_edit_access', 'access arguments' => array(1), 'type' => MENU_LOCAL_TASK, 'file' => 'user.pages.inc', ); $items['user/%user_category/edit/account'] = array( 'title' => 'Account', 'type' => MENU_DEFAULT_LOCAL_TASK, 'load arguments' => array('%map', '%index'), ); if (($categories = _user_categories()) && (count($categories) > 1)) { foreach ($categories as $key => $category) { // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK. if ($category['name'] != 'account') { $items['user/%user_category/edit/' . $category['name']] = array( 'title callback' => 'check_plain', 'title arguments' => array($category['title']), 'page callback' => 'drupal_get_form', 'page arguments' => array('user_profile_form', 1, 3), 'access callback' => isset($category['access callback']) ? $category['access callback'] : 'user_edit_access', 'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(1), 'type' => MENU_LOCAL_TASK, 'weight' => $category['weight'], 'load arguments' => array('%map', '%index'), 'tab_parent' => 'user/%/edit', 'file' => 'user.pages.inc', ); } } } return $items; } /** * Implements hook_init(). */ function user_init() { drupal_add_css(drupal_get_path('module', 'user') . '/user.css'); } /** * Load either a specified or the current user account. * * @param $uid * An optional user ID of the user to load. If not provided, the current * user's ID will be used. * @return * A fully-loaded $user object upon successful user load, FALSE if user * cannot be loaded. * * @see user_load() */ function user_uid_optional_load($uid = NULL) { if (!isset($uid)) { $uid = $GLOBALS['user']->uid; } return user_load($uid); } /** * Return a user object after checking if any profile category in the path exists. */ function user_category_load($uid, &$map, $index) { static $user_categories, $accounts; // Cache $account - this load function will get called for each profile tab. if (!isset($accounts[$uid])) { $accounts[$uid] = user_load($uid); } $valid = TRUE; if ($account = $accounts[$uid]) { // Since the path is like user/%/edit/category_name, the category name will // be at a position 2 beyond the index corresponding to the % wildcard. $category_index = $index + 2; // Valid categories may contain slashes, and hence need to be imploded. $category_path = implode('/', array_slice($map, $category_index)); if ($category_path) { // Check that the requested category exists. $valid = FALSE; if (!isset($user_categories)) { $user_categories = _user_categories(); } foreach ($user_categories as $category) { if ($category['name'] == $category_path) { $valid = TRUE; // Truncate the map array in case the category name had slashes. $map = array_slice($map, 0, $category_index); // Assign the imploded category name to the last map element. $map[$category_index] = $category_path; break; } } } } return $valid ? $account : FALSE; } /** * Returns the user id of the currently logged in user. */ function user_uid_optional_to_arg($arg) { // Give back the current user uid when called from eg. tracker, aka. // with an empty arg. Also use the current user uid when called from // the menu with a % for the current account link. return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg; } /** * Menu item title callback - use the user name. */ function user_page_title($account) { return format_username($account); } /** * Discover which external authentication module(s) authenticated a username. * * @param $authname * A username used by an external authentication module. * @return * An associative array with module as key and username as value. */ function user_get_authmaps($authname = NULL) { $authmaps = db_query("SELECT authname, module FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchAllKeyed(); return count($authmaps) ? $authmaps : 0; } /** * Save mappings of which external authentication module(s) authenticated * a user. Maps external usernames to user ids in the users table. * * @param $account * A user object. * @param $authmaps * An associative array with a compound key and the username as the value. * The key is made up of 'authname_' plus the name of the external authentication * module. * @see user_external_login_register() */ function user_set_authmaps($account, $authmaps) { foreach ($authmaps as $key => $value) { $module = explode('_', $key, 2); if ($value) { db_merge('authmap') ->key(array( 'uid' => $account->uid, 'module' => $module[1], )) ->fields(array('authname' => $value)) ->execute(); } else { db_delete('authmap') ->condition('uid', $account->uid) ->condition('module', $module[1]) ->execute(); } } } /** * Form builder; the main user login form. * * @ingroup forms */ function user_login($form, &$form_state) { global $user; // If we are already logged on, go to the user page instead. if ($user->uid) { drupal_goto('user/' . $user->uid); } // Display login form: $form['name'] = array('#type' => 'textfield', '#title' => t('Username'), '#size' => 60, '#maxlength' => USERNAME_MAX_LENGTH, '#required' => TRUE, ); $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal'))); $form['pass'] = array('#type' => 'password', '#title' => t('Password'), '#description' => t('Enter the password that accompanies your username.'), '#required' => TRUE, ); $form['#validate'] = user_login_default_validators(); $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2); return $form; } /** * Set up a series for validators which check for blocked users, * then authenticate against local database, then return an error if * authentication fails. Distributed authentication modules are welcome * to use hook_form_alter() to change this series in order to * authenticate against their user database instead of the local users * table. If a distributed authentication module is successful, it * should set $form_state['uid'] to a user ID. * * We use three validators instead of one since external authentication * modules usually only need to alter the second validator. * * @see user_login_name_validate() * @see user_login_authenticate_validate() * @see user_login_final_validate() * @return array * A simple list of validate functions. */ function user_login_default_validators() { return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate'); } /** * A FAPI validate handler. Sets an error if supplied username has been blocked. */ function user_login_name_validate($form, &$form_state) { if (isset($form_state['values']['name']) && 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']))); } } /** * A validate handler on the login form. Check supplied username/password * against local users table. If successful, $form_state['uid'] * is set to the matching user ID. */ function user_login_authenticate_validate($form, &$form_state) { $password = trim($form_state['values']['pass']); if (!empty($form_state['values']['name']) && !empty($password)) { // Do not allow any login from the current user's IP if the limit has been // reached. Default is 50 failed attempts allowed in one hour. This is // independent of the per-user limit to catch attempts from one IP to log // in to many different user accounts. We have a reasonably high limit // since there may be only one apparent IP for all users at an institution. if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) { $form_state['flood_control_triggered'] = 'ip'; return; } $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject(); if ($account) { if (variable_get('user_failed_login_identifier_uid_only', FALSE)) { // Register flood events based on the uid only, so they apply for any // IP address. This is the most secure option. $identifier = $account->uid; } else { // The default identifier is a combination of uid and IP address. This // is less secure but more resistant to denial-of-service attacks that // could lock out all users with public user names. $identifier = $account->uid . '-' . ip_address(); } $form_state['flood_control_user_identifier'] = $identifier; // Don't allow login if the limit for this user has been reached. // Default is to allow 5 failed attempts every 6 hours. if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) { $form_state['flood_control_triggered'] = 'user'; return; } } // We are not limited by flood control, so try to authenticate. // Set $form_state['uid'] as a flag for user_login_final_validate(). $form_state['uid'] = user_authenticate($form_state['values']['name'], $password); } } /** * The final validation handler on the login form. * * Sets a form error if user has not been authenticated, or if too many * logins have been attempted. This validation function should always * be the last one. */ function user_login_final_validate($form, &$form_state) { if (empty($form_state['uid'])) { // Always register an IP-based failed login event. flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600)); // Register a per-user failed login event. if (isset($form_state['flood_control_user_identifier'])) { flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']); } if (isset($form_state['flood_control_triggered'])) { if ($form_state['flood_control_triggered'] == 'user') { form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Please try again later, or request a new password.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Please try again later, or request a new password.', array('@url' => url('user/password')))); } else { // We did not find a uid, so the limit is IP-based. form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Please try again later, or request a new password.', array('@url' => url('user/password')))); } } else { form_set_error('name', t('Sorry, unrecognized username or password. Have you forgotten your password?', array('@password' => url('user/password')))); watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name'])); } } elseif (isset($form_state['flood_control_user_identifier'])) { // Clear past failures for this user so as not to block a user who might // log in and out more than once in an hour. flood_clear_event('failed_login_attempt_user', $form_state['flood_control_user_identifier']); } } /** * Try to validate the user's login credentials locally. * * @param $name * User name to authenticate. * @param $password * A plain-text password, such as trimmed text from form values. * @return * The user's uid on success, or FALSE on failure to authenticate. */ function user_authenticate($name, $password) { $uid = FALSE; if (!empty($name) && !empty($password)) { $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $name))->fetchObject(); if ($account) { // Allow alternate password hashing schemes. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc'); if (user_check_password($password, $account)) { // Successful authentication. $uid = $account->uid; // Update user to new password scheme if needed. if (user_needs_new_hash($account)) { $new_hash = user_hash_password($password); if ($new_hash) { db_update('users') ->fields(array('pass' => $new_hash)) ->condition('uid', $account->uid) ->execute(); } } } } } return $uid; } /** * Finalize the login process. Must be called when logging in a user. * * The function records a watchdog message about the new session, saves the * login timestamp, calls hook_user op 'login' and generates a new session. * */ function user_login_finalize(&$edit = array()) { global $user; watchdog('user', 'Session opened for %name.', array('%name' => $user->name)); // Update the user table timestamp noting user has logged in. // This is also used to invalidate one-time login links. $user->login = REQUEST_TIME; db_update('users') ->fields(array('login' => $user->login)) ->condition('uid', $user->uid) ->execute(); // Regenerate the session ID to prevent against session fixation attacks. // This is called before hook_user in case one of those functions fails // or incorrectly does a redirect which would leave the old session in place. drupal_session_regenerate(); user_module_invoke('login', $edit, $user); } /** * Submit handler for the login form. Load $user object and perform standard login * tasks. The user is then redirected to the My Account page. Setting the * destination in the query string overrides the redirect. */ function user_login_submit($form, &$form_state) { global $user; $user = user_load($form_state['uid']); user_login_finalize(); $form_state['redirect'] = 'user/' . $user->uid; } /** * Helper function for authentication modules. Either logs in or registers * the current user, based on username. Either way, the global $user object is * populated and login tasks are performed. */ function user_external_login_register($name, $module) { $account = user_load_by_name($name); if (!$account->uid) { // Register this new user. $userinfo = array( 'name' => $name, 'pass' => user_password(), 'init' => $name, 'status' => 1, 'access' => REQUEST_TIME ); $account = user_save(drupal_anonymous_user(), $userinfo); // Terminate if an error occurred during user_save(). if (!$account) { drupal_set_message(t("Error saving user account."), 'error'); return; } user_set_authmaps($account, array("authname_$module" => $name)); } // Log user in. $form_state['uid'] = $account->uid; user_login_submit(array(), $form_state); } function user_pass_reset_url($account) { $timestamp = REQUEST_TIME; return url("user/reset/$account->uid/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE)); } /** * Generate a URL to confirm an account cancellation request. * * @see user_mail_tokens() * @see user_cancel_confirm() */ function user_cancel_url($account) { $timestamp = REQUEST_TIME; return url("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE)); } function user_pass_rehash($password, $timestamp, $login) { return md5($timestamp . $password . $login); } /** * Cancel a user account. * * Since the user cancellation process needs to be run in a batch, either * Form API will invoke it, or batch_process() needs to be invoked after calling * this function and should define the path to redirect to. * * @param $edit * An array of submitted form values. * @param $uid * The user ID of the user account to cancel. * @param $method * The account cancellation method to use. * * @see _user_cancel() */ function user_cancel($edit, $uid, $method) { global $user; $account = user_load($uid); if (!$account) { drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error'); watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR); return; } // Initialize batch (to set title). $batch = array( 'title' => t('Cancelling account'), 'operations' => array(), ); batch_set($batch); // Allow modules to add further sets to this batch. module_invoke_all('user_cancel', $edit, $account, $method); // Finish the batch and actually cancel the account. $batch = array( 'title' => t('Cancelling user account'), 'operations' => array( array('_user_cancel', array($edit, $account, $method)), ), ); batch_set($batch); // Batch processing is either handled via Form API or has to be invoked // manually. } /** * Last batch processing step for cancelling a user account. * * Since batch and session API require a valid user account, the actual * cancellation of a user account needs to happen last. * * @see user_cancel() */ function _user_cancel($edit, $account, $method) { global $user; switch ($method) { case 'user_cancel_block': case 'user_cancel_block_unpublish': default: // Send account blocked notification if option was checked. if (!empty($edit['user_cancel_notify'])) { _user_mail_notify('status_blocked', $account); } db_update('users') ->fields(array('status' => 0)) ->condition('uid', $account->uid) ->execute(); drupal_set_message(t('%name has been disabled.', array('%name' => $account->name))); watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE); break; case 'user_cancel_reassign': case 'user_cancel_delete': // Send account canceled notification if option was checked. if (!empty($edit['user_cancel_notify'])) { _user_mail_notify('status_canceled', $account); } db_delete('users') ->condition('uid', $account->uid) ->execute(); db_delete('users_roles') ->condition('uid', $account->uid) ->execute(); db_delete('authmap') ->condition('uid', $account->uid) ->execute(); drupal_set_message(t('%name has been deleted.', array('%name' => $account->name))); watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE); break; } // After cancelling account, ensure that user is logged out. if ($account->uid == $user->uid) { // Destroy the current session, and reset $user to the anonymous user. session_destroy(); } else { drupal_session_destroy_uid($account->uid); } // Clear the cache for anonymous users. cache_clear_all(); } /** * Generate an array for rendering the given user. * * When viewing a user profile, the $page array contains: * * - $page['content']['Profile Category']: * Profile categories keyed by their human-readable names. * - $page['content']['Profile Category']['profile_machine_name']: * Profile fields keyed by their machine-readable names. * - $page['content']['user_picture']: * User's rendered picture. * - $page['content']['summary']: * Contains the default "History" profile data for a user. * - $page['content']['#account']: * The user account of the profile being viewed. * * To theme user profiles, copy modules/user/user-profile.tpl.php * to your theme directory, and edit it as instructed in that file's comments. * * @param $account * A user object. * @param $view_mode * View mode, e.g. 'full'. * * @return * An array as expected by drupal_render(). */ function user_view($account, $view_mode = 'full') { // Retrieve all profile fields and attach to $account->content. user_build_content($account, $view_mode); $build = $account->content; // We don't need duplicate rendering info in account->content. unset($account->content); $build += array( '#theme' => 'user_profile', '#account' => $account, '#view_mode' => $view_mode, ); // Allow modules to modify the structured user. drupal_alter('user_view', $build); return $build; } /** * Builds a structured array representing the profile content. * * @param $account * A user object. * @param $view_mode * View mode, e.g. 'full'. */ function user_build_content($account, $view_mode = 'full') { // Remove previously built content, if exists. $account->content = array(); // Build fields content. field_attach_prepare_view('user', array($account->uid => $account), $view_mode); $account->content += field_attach_view('user', $account, $view_mode); // Populate $account->content with a render() array. module_invoke_all('user_view', $account, $view_mode); } /** * Implements hook_mail(). */ function user_mail($key, &$message, $params) { $language = $message['language']; $variables = array('user' => $params['account']); $message['subject'] .= _user_mail_text($key . '_subject', $language, $variables); $message['body'][] = _user_mail_text($key . '_body', $language, $variables); } /** * Returns a mail string for a variable name. * * Used by user_mail() and the settings forms to retrieve strings. */ function _user_mail_text($key, $language = NULL, $variables = array()) { $langcode = isset($language) ? $language->language : NULL; if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) { // An admin setting overrides the default string. $text = $admin_setting; } else { // No override, return default string. switch ($key) { case 'register_no_approval_required_subject': $text = t('Account details for [user:name] at [site:name]', array(), array('langcode' => $langcode)); break; case 'register_no_approval_required_body': $text = t("[user:name], Thank you for registering at [site:name]. You may now log in to [site:login-url] using the following username and password: username: [user:name] password: [user:password] You may also log in by clicking on this link or copying and pasting it in your browser: [user:one-time-login-url] This is a one-time login, so it can be used only once. After logging in, you will be redirected to [user:edit-url] so you can change your password. -- [site:name] team", array(), array('langcode' => $langcode)); break; case 'register_admin_created_subject': $text = t('An administrator created an account for you at [site:name]', array(), array('langcode' => $langcode)); break; case 'register_admin_created_body': $text = t("[user:name], A site administrator at [site:name] has created an account for you. You may now log in to [site:login-url] using the following username and password: username: [user:name] password: [user:password] You may also log in by clicking on this link or copying and pasting it in your browser: [user:one-time-login-url] This is a one-time login, so it can be used only once. After logging in, you will be redirected to [user:edit-url] so you can change your password. -- [site:name] team", array(), array('langcode' => $langcode)); break; case 'register_pending_approval_subject': case 'register_pending_approval_admin_subject': $text = t('Account details for [user:name] at [site:name] (pending admin approval)', array(), array('langcode' => $langcode)); break; case 'register_pending_approval_body': $text = t("[user:name], Thank you for registering at [site:name]. 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. -- [site:name] team", array(), array('langcode' => $langcode)); break; case 'register_pending_approval_admin_body': $text = t("[user:name] has applied for an account. [user:edit-url]", array(), array('langcode' => $langcode)); break; case 'password_reset_subject': $text = t('Replacement login information for [user:name] at [site:name]', array(), array('langcode' => $langcode)); break; case 'password_reset_body': $text = t("[user:name], A request to reset the password for your account has been made at [site:name]. You may now log in to [site:uri-brief] by clicking on this link or copying and pasting it in your browser: [user:one-time-login-url] This 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. After logging in, you will be redirected to [user:edit-url] so you can change your password.", array(), array('langcode' => $langcode)); break; case 'status_activated_subject': $text = t('Account details for [user:name] at [site:name] (approved)', array(), array('langcode' => $langcode)); break; case 'status_activated_body': $text = t("[user:name], Your account at [site:name] has been activated. You may now log in by clicking on this link or copying and pasting it in your browser: [site:login-url] This is a one-time login, so it can be used only once. After logging in, you will be redirected to [user:edit-url] so you can change your password. Once you have set your own password, you will be able to log in to [site:login-url] in the future using: username: [user:name]", array(), array('langcode' => $langcode)); break; case 'status_blocked_subject': $text = t('Account details for [user:name] at [site:name] (blocked)', array(), array('langcode' => $langcode)); break; case 'status_blocked_body': $text = t("[user:name],\n\nYour account on [site:name] has been blocked.", array(), array('langcode' => $langcode)); break; case 'cancel_confirm_subject': $text = t('Account cancellation request for [user:name] at [site:name]', array(), array('langcode' => $langcode)); break; case 'cancel_confirm_body': $text = t("[user:name], A request to cancel your account has been made at [site:name]. You may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser: [user:cancel-url] NOTE: The cancellation of your account is not reversible. This link expires in one day and nothing will happen if it is not used.", array(), array('langcode' => $langcode)); break; case 'status_canceled_subject': $text = t('Account details for [user:name] at [site:name] (canceled)', array(), array('langcode' => $langcode)); break; case 'status_canceled_body': $text = t("[user:name], Your account on [site:name] has been canceled.", array(), array('langcode' => $langcode)); break; } } return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens')); } /** * Token callback to add unsafe tokens for user mails. * * @see user_mail() */ function user_mail_tokens(&$replacements, $data, $options) { if (isset($data['user'])) { $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']); $replacements['[user:cancel-url]'] = user_cancel_url($data['user']); if (isset($data['user']->password) && !empty($data['user']->password)) { $replacements['[user:password]'] = $data['user']->password; } } } /*** 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 {role_permission} p ON r.rid = p.rid WHERE p.permission = :permission ORDER BY r.name", array(':permission' => $permission)); } else { $result = db_query('SELECT * FROM {role} ORDER BY name'); } foreach ($result as $role) { 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); } /** * Fetch a user role from database. * * @param $role * A string with the role name, or an integer with the role ID. * @return * A fully-loaded role object if a role with the given name or ID * exists, FALSE otherwise. */ function user_role_load($role) { $field = is_int($role) ? 'rid' : 'name'; return db_select('role', 'r') ->fields('r') ->condition($field, $role) ->execute() ->fetchObject(); } /** * Save a user role to the database. * * @param $role * A role object to modify or add. If $role->rid is not specified, a new * role will be created. * @return * Status constant indicating if role was created or updated. * Failure to write the user role record will return FALSE. Otherwise. * SAVED_NEW or SAVED_UPDATED is returned depending on the operation * performed. */ function user_role_save($role) { if ($role->name) { // Prevent leading and trailing spaces in role names. $role->name = trim($role->name); } if (!empty($role->rid) && $role->name) { $status = drupal_write_record('role', $role, 'rid'); module_invoke_all('user_role_update', $role); } else { $status = drupal_write_record('role', $role); module_invoke_all('user_role_insert', $role); } // Clear the user access cache. drupal_static_reset('user_access'); drupal_static_reset('user_role_permissions'); return $status; } /** * Delete a user role from database. * * @param $role * A string with the role name, or an integer with the role ID. */ function user_role_delete($role) { $role = user_role_load($role); db_delete('role') ->condition('rid', $role->rid) ->execute(); db_delete('role_permission') ->condition('rid', $role->rid) ->execute(); // Update the users who have this role set: db_delete('users_roles') ->condition('rid', $role->rid) ->execute(); module_invoke_all('user_role_delete', $role); // Clear the user access cache. drupal_static_reset('user_access'); drupal_static_reset('user_role_permissions'); } /** * Change permissions for a user role. * * This function may be used to grant and revoke multiple permissions at once. * For example, when a form exposes checkboxes to configure permissions for a * role, the submitted values may be directly passed on in a form submit * handler. * * @param $rid * The ID of a user role to alter. * @param $permissions * An array of permissions, where the key holds the permission name and the * value is an integer or boolean that determines whether to grant or revoke * the permission: * @code * array( * 'administer nodes' => 0, * 'access user profiles' => 1, * ) * @endcode * Existing permissions are not changed, unless specified in $permissions. * * @see user_role_grant_permissions() * @see user_role_revoke_permissions() */ function user_role_change_permissions($rid, array $permissions = array()) { // Grant new permissions for the role. $grant = array_filter($permissions); if (!empty($grant)) { user_role_grant_permissions($rid, array_keys($grant)); } // Revoke permissions for the role. $revoke = array_diff_assoc($permissions, $grant); if (!empty($revoke)) { user_role_revoke_permissions($rid, array_keys($revoke)); } } /** * Grant permissions to a user role. * * @param $rid * The ID of a user role to alter. * @param $permissions * A list of permission names to grant. * * @see user_role_change_permissions() * @see user_role_revoke_permissions() */ function user_role_grant_permissions($rid, array $permissions = array()) { // Grant new permissions for the role. foreach ($permissions as $name) { db_merge('role_permission') ->key(array( 'rid' => $rid, 'permission' => $name, )) ->execute(); } // Clear the user access cache. drupal_static_reset('user_access'); drupal_static_reset('user_role_permissions'); } /** * Revoke permissions from a user role. * * @param $rid * The ID of a user role to alter. * @param $permissions * A list of permission names to revoke. * * @see user_role_change_permissions() * @see user_role_grant_permissions() */ function user_role_revoke_permissions($rid, array $permissions = array()) { // Revoke permissions for the role. db_delete('role_permission') ->condition('rid', $rid) ->condition('permission', $permissions, 'IN') ->execute(); // Clear the user access cache. drupal_static_reset('user_access'); drupal_static_reset('user_role_permissions'); } /** * Implements hook_user_operations(). */ function user_user_operations($form = array(), $form_state = array()) { $operations = array( 'unblock' => array( 'label' => t('Unblock the selected users'), 'callback' => 'user_user_operations_unblock', ), 'block' => array( 'label' => t('Block the selected users'), 'callback' => 'user_user_operations_block', ), 'cancel' => array( 'label' => t('Cancel the selected user accounts'), ), ); if (user_access('administer permissions')) { $roles = user_roles(TRUE); unset($roles[DRUPAL_AUTHENTICATED_RID]); // Can't edit authenticated role. $add_roles = array(); foreach ($roles as $key => $value) { $add_roles['add_role-' . $key] = $value; } $remove_roles = array(); foreach ($roles as $key => $value) { $remove_roles['remove_role-' . $key] = $value; } if (count($roles)) { $role_operations = array( t('Add a role to the selected users') => array( 'label' => $add_roles, ), t('Remove a role from the selected users') => array( 'label' => $remove_roles, ), ); $operations += $role_operations; } } // If the form has been posted, we need to insert the proper data for // role editing if necessary. if (!empty($form_state['submitted'])) { $operation_rid = explode('-', $form_state['values']['operation']); $operation = $operation_rid[0]; if ($operation == 'add_role' || $operation == 'remove_role') { $rid = $operation_rid[1]; if (user_access('administer permissions')) { $operations[$form_state['values']['operation']] = array( 'callback' => 'user_multiple_role_edit', 'callback arguments' => array($operation, $rid), ); } else { watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING); return; } } } return $operations; } /** * Callback function for admin mass unblocking users. */ function user_user_operations_unblock($accounts) { $accounts = user_load_multiple($accounts); foreach ($accounts as $account) { // Skip unblocking user if they are already unblocked. if ($account !== FALSE && $account->status == 0) { user_save($account, array('status' => 1)); } } } /** * Callback function for admin mass blocking users. */ function user_user_operations_block($accounts) { $accounts = user_load_multiple($accounts); foreach ($accounts as $account) { // Skip blocking user if they are already blocked. if ($account !== FALSE && $account->status == 1) { user_save($account, array('status' => 0)); } } } /** * Callback function for admin mass adding/deleting a user role. */ function user_multiple_role_edit($accounts, $operation, $rid) { // The role name is not necessary as user_save() will reload the user // object, but some modules' hook_user() may look at this first. $role_name = db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $rid))->fetchField(); switch ($operation) { case 'add_role': $accounts = user_load_multiple($accounts); foreach ($accounts as $account) { // Skip adding the role to the user if they already have it. if ($account !== FALSE && !isset($account->roles[$rid])) { $roles = $account->roles + array($rid => $role_name); user_save($account, array('roles' => $roles)); } } break; case 'remove_role': $accounts = user_load_multiple($accounts); foreach ($accounts as $account) { // Skip removing the role from the user if they already don't have it. if ($account !== FALSE && isset($account->roles[$rid])) { $roles = array_diff($account->roles, array($rid => $role_name)); user_save($account, array('roles' => $roles)); } } break; } } function user_multiple_cancel_confirm($form, &$form_state) { $edit = $form_state['input']; $form['accounts'] = array('#prefix' => '